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.

277400 lines
7.4MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. #ifdef __MINGW32__
  68. #define JUCE_MINGW 1
  69. #endif
  70. /** If defined, this indicates that the processor is little-endian. */
  71. #define JUCE_LITTLE_ENDIAN 1
  72. #define JUCE_INTEL 1
  73. #endif
  74. #if JUCE_MAC
  75. #ifndef NDEBUG
  76. #define JUCE_DEBUG 1
  77. #endif
  78. #ifdef __LITTLE_ENDIAN__
  79. #define JUCE_LITTLE_ENDIAN 1
  80. #else
  81. #define JUCE_BIG_ENDIAN 1
  82. #endif
  83. #if defined (__ppc__) || defined (__ppc64__)
  84. #define JUCE_PPC 1
  85. #else
  86. #define JUCE_INTEL 1
  87. #endif
  88. #ifdef __LP64__
  89. #define JUCE_64BIT 1
  90. #else
  91. #define JUCE_32BIT 1
  92. #endif
  93. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  94. #error "Building for OSX 10.3 is no longer supported!"
  95. #endif
  96. #ifndef MAC_OS_X_VERSION_10_5
  97. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /*** End of inlined file: juce_TargetPlatform.h ***/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /*** Start of inlined file: juce_Config.h ***/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  152. project settings, but if you define this value, you can override this to force
  153. it to be true or false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 0
  157. #endif
  158. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  159. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. #define JUCE_LOG_ASSERTIONS 0
  167. #endif
  168. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  169. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  170. on your Windows build machine.
  171. See the comments in the ASIOAudioIODevice class's header file for more
  172. info about this.
  173. */
  174. #ifndef JUCE_ASIO
  175. #define JUCE_ASIO 0
  176. #endif
  177. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  178. */
  179. #ifndef JUCE_WASAPI
  180. #define JUCE_WASAPI 0
  181. #endif
  182. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  183. */
  184. #ifndef JUCE_DIRECTSOUND
  185. #define JUCE_DIRECTSOUND 1
  186. #endif
  187. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  192. #ifndef JUCE_JACK
  193. #define JUCE_JACK 0
  194. #endif
  195. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  196. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  197. installed, and its header files will need to be on your include path.
  198. */
  199. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  200. #define JUCE_QUICKTIME 0
  201. #endif
  202. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  203. #undef JUCE_QUICKTIME
  204. #endif
  205. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  206. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  207. */
  208. #ifndef JUCE_OPENGL
  209. #define JUCE_OPENGL 1
  210. #endif
  211. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  212. If your app doesn't need to read FLAC files, you might want to disable this to
  213. reduce the size of your codebase and build time.
  214. */
  215. #ifndef JUCE_USE_FLAC
  216. #define JUCE_USE_FLAC 1
  217. #endif
  218. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  219. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_OGGVORBIS
  223. #define JUCE_USE_OGGVORBIS 1
  224. #endif
  225. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  226. Unless you're using CD-burning, you should probably turn this flag off to
  227. reduce code size.
  228. */
  229. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  230. #define JUCE_USE_CDBURNER 0
  231. #endif
  232. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-reading, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #ifndef JUCE_USE_CDREADER
  237. #define JUCE_USE_CDREADER 0
  238. #endif
  239. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  240. */
  241. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  242. #define JUCE_USE_CAMERA 0
  243. #endif
  244. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  245. gets repainted will flash in a random colour, so that you can check exactly how much and how
  246. often your components are being drawn.
  247. */
  248. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  249. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  250. #endif
  251. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  252. Unless you specifically want to disable this, it's best to leave this option turned on.
  253. */
  254. #ifndef JUCE_USE_XINERAMA
  255. #define JUCE_USE_XINERAMA 1
  256. #endif
  257. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  258. turned on unless you have a good reason to disable it.
  259. */
  260. #ifndef JUCE_USE_XSHM
  261. #define JUCE_USE_XSHM 1
  262. #endif
  263. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  264. */
  265. #ifndef JUCE_USE_XRENDER
  266. #define JUCE_USE_XRENDER 0
  267. #endif
  268. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  269. unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XCURSOR
  272. #define JUCE_USE_XCURSOR 1
  273. #endif
  274. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  275. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  276. you're building a plugin hosting app.
  277. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  278. */
  279. #ifndef JUCE_PLUGINHOST_VST
  280. #define JUCE_PLUGINHOST_VST 0
  281. #endif
  282. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  283. of course, and should only be enabled if you're building a plugin hosting app.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. #define JUCE_PLUGINHOST_AU 0
  288. #endif
  289. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  290. This should be enabled if you're writing a console application.
  291. */
  292. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  293. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  294. #endif
  295. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  296. If you're not using any embedded web-pages, turning this off may reduce your code size.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  302. Carbon isn't required for a normal app, but may be needed by specialised classes like
  303. plugin-hosts, which support older APIs.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  309. You might need to tweak this if you're linking to an external zlib library in your app,
  310. but for normal apps, this option should be left alone.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  334. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  341. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  342. #undef JUCE_QUICKTIME
  343. #define JUCE_QUICKTIME 0
  344. #undef JUCE_OPENGL
  345. #define JUCE_OPENGL 0
  346. #undef JUCE_USE_CDBURNER
  347. #define JUCE_USE_CDBURNER 0
  348. #undef JUCE_USE_CDREADER
  349. #define JUCE_USE_CDREADER 0
  350. #undef JUCE_WEB_BROWSER
  351. #define JUCE_WEB_BROWSER 0
  352. #undef JUCE_PLUGINHOST_AU
  353. #define JUCE_PLUGINHOST_AU 0
  354. #undef JUCE_PLUGINHOST_VST
  355. #define JUCE_PLUGINHOST_VST 0
  356. #endif
  357. #endif
  358. /*** End of inlined file: juce_Config.h ***/
  359. // FORCE_AMALGAMATOR_INCLUDE
  360. #ifndef JUCE_BUILD_CORE
  361. #define JUCE_BUILD_CORE 1
  362. #endif
  363. #ifndef JUCE_BUILD_MISC
  364. #define JUCE_BUILD_MISC 1
  365. #endif
  366. #ifndef JUCE_BUILD_GUI
  367. #define JUCE_BUILD_GUI 1
  368. #endif
  369. #ifndef JUCE_BUILD_NATIVE
  370. #define JUCE_BUILD_NATIVE 1
  371. #endif
  372. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  373. #undef JUCE_BUILD_MISC
  374. #undef JUCE_BUILD_GUI
  375. #endif
  376. //==============================================================================
  377. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  378. #if JUCE_WINDOWS
  379. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  380. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  381. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #ifndef STRICT
  383. #define STRICT 1
  384. #endif
  385. #undef WIN32_LEAN_AND_MEAN
  386. #define WIN32_LEAN_AND_MEAN 1
  387. #if JUCE_MSVC
  388. #pragma warning (push)
  389. #pragma warning (disable : 4100 4201 4514 4312 4995)
  390. #endif
  391. #define _WIN32_WINNT 0x0500
  392. #define _UNICODE 1
  393. #define UNICODE 1
  394. #ifndef _WIN32_IE
  395. #define _WIN32_IE 0x0400
  396. #endif
  397. #include <windows.h>
  398. #include <windowsx.h>
  399. #include <commdlg.h>
  400. #include <shellapi.h>
  401. #include <mmsystem.h>
  402. #include <vfw.h>
  403. #include <tchar.h>
  404. #include <stddef.h>
  405. #include <ctime>
  406. #include <wininet.h>
  407. #include <nb30.h>
  408. #include <iphlpapi.h>
  409. #include <mapi.h>
  410. #include <float.h>
  411. #include <process.h>
  412. #include <Exdisp.h>
  413. #include <exdispid.h>
  414. #include <shlobj.h>
  415. #if ! JUCE_MINGW
  416. #include <crtdbg.h>
  417. #include <comutil.h>
  418. #endif
  419. #if JUCE_OPENGL
  420. #include <gl/gl.h>
  421. #endif
  422. #undef PACKED
  423. #if JUCE_ASIO
  424. /*
  425. This is very frustrating - we only need to use a handful of definitions from
  426. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  427. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  428. implementation...
  429. ..unfortunately that would break Steinberg's license agreement for use of
  430. their SDK, so I'm not allowed to do this.
  431. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  432. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  433. (see www.steinberg.net/Steinberg/Developers.asp).
  434. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  435. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  436. if you prefer). Make sure that your header search path will find the
  437. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  438. files are actually needed - so to simplify things, you could just copy
  439. these into your JUCE directory).
  440. If you're compiling and you get an error here because you don't have the
  441. ASIO SDK installed, you can disable ASIO support by commenting-out the
  442. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  443. */
  444. #include "iasiodrv.h"
  445. #endif
  446. #if JUCE_USE_CDBURNER
  447. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  448. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  449. flag in juce_Config.h to avoid these includes.
  450. */
  451. #include <imapi.h>
  452. #include <imapierror.h>
  453. #endif
  454. #if JUCE_USE_CAMERA
  455. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  456. These files are provided in the normal Windows SDK, but some Microsoft plonker
  457. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  458. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  459. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  460. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  461. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  462. The dummy file just needs to contain the following content:
  463. #define __IDxtCompositor_INTERFACE_DEFINED__
  464. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  465. #define __IDxtJpeg_INTERFACE_DEFINED__
  466. #define __IDxtKey_INTERFACE_DEFINED__
  467. ..and that should be enough to convince qedit.h that you have the SDK!
  468. */
  469. #include <dshow.h>
  470. #include <qedit.h>
  471. #include <dshowasf.h>
  472. #endif
  473. #if JUCE_WASAPI
  474. #include <MMReg.h>
  475. #include <mmdeviceapi.h>
  476. #include <Audioclient.h>
  477. #include <Avrt.h>
  478. #include <functiondiscoverykeys.h>
  479. #endif
  480. #if JUCE_QUICKTIME
  481. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  482. add its header directory to your include path.
  483. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  484. flag in juce_Config.h
  485. */
  486. #include <Movies.h>
  487. #include <QTML.h>
  488. #include <QuickTimeComponents.h>
  489. #include <MediaHandlers.h>
  490. #include <ImageCodec.h>
  491. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  492. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  493. your include search path to make these import statements work.
  494. */
  495. #import <QTOLibrary.dll>
  496. #import <QTOControl.dll>
  497. #endif
  498. #if JUCE_MSVC
  499. #pragma warning (pop)
  500. #endif
  501. /** A simple COM smart pointer.
  502. Avoids having to include ATL just to get one of these.
  503. */
  504. template <class ComClass>
  505. class ComSmartPtr
  506. {
  507. public:
  508. ComSmartPtr() throw() : p (0) {}
  509. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  510. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  511. ~ComSmartPtr() { if (p != 0) p->Release(); }
  512. operator ComClass*() const throw() { return p; }
  513. ComClass& operator*() const throw() { return *p; }
  514. ComClass** operator&() throw() { return &p; }
  515. ComClass* operator->() const throw() { return p; }
  516. ComClass* operator= (ComClass* const newP)
  517. {
  518. if (newP != 0) newP->AddRef();
  519. if (p != 0) p->Release();
  520. p = newP;
  521. return newP;
  522. }
  523. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  524. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  525. {
  526. #ifndef __MINGW32__
  527. operator= (0);
  528. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  529. #else
  530. return S_FALSE;
  531. #endif
  532. }
  533. private:
  534. ComClass* p;
  535. };
  536. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  537. */
  538. template <class ComClass>
  539. class ComBaseClassHelper : public ComClass
  540. {
  541. public:
  542. ComBaseClassHelper() : refCount (1) {}
  543. virtual ~ComBaseClassHelper() {}
  544. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  545. {
  546. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  547. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  548. *result = 0;
  549. return E_NOINTERFACE;
  550. }
  551. ULONG __stdcall AddRef() { return ++refCount; }
  552. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  553. protected:
  554. int refCount;
  555. };
  556. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  557. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  558. #elif JUCE_LINUX
  559. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  560. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  561. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. /*
  563. This file wraps together all the linux-specific headers, so
  564. that we can include them all just once, and compile all our
  565. platform-specific stuff in one big lump, keeping it out of the
  566. way of the rest of the codebase.
  567. */
  568. #include <sched.h>
  569. #include <pthread.h>
  570. #include <sys/time.h>
  571. #include <errno.h>
  572. #include <sys/stat.h>
  573. #include <sys/dir.h>
  574. #include <sys/ptrace.h>
  575. #include <sys/vfs.h>
  576. #include <sys/wait.h>
  577. #include <fnmatch.h>
  578. #include <utime.h>
  579. #include <pwd.h>
  580. #include <fcntl.h>
  581. #include <dlfcn.h>
  582. #include <netdb.h>
  583. #include <arpa/inet.h>
  584. #include <netinet/in.h>
  585. #include <sys/types.h>
  586. #include <sys/ioctl.h>
  587. #include <sys/socket.h>
  588. #include <linux/if.h>
  589. #include <sys/sysinfo.h>
  590. #include <sys/file.h>
  591. #include <signal.h>
  592. /* Got a build error here? You'll need to install the freetype library...
  593. The name of the package to install is "libfreetype6-dev".
  594. */
  595. #include <ft2build.h>
  596. #include FT_FREETYPE_H
  597. #include <X11/Xlib.h>
  598. #include <X11/Xatom.h>
  599. #include <X11/Xresource.h>
  600. #include <X11/Xutil.h>
  601. #include <X11/Xmd.h>
  602. #include <X11/keysym.h>
  603. #include <X11/cursorfont.h>
  604. #if JUCE_USE_XINERAMA
  605. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  606. #include <X11/extensions/Xinerama.h>
  607. #endif
  608. #if JUCE_USE_XSHM
  609. #include <X11/extensions/XShm.h>
  610. #include <sys/shm.h>
  611. #include <sys/ipc.h>
  612. #endif
  613. #if JUCE_USE_XRENDER
  614. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  615. #include <X11/extensions/Xrender.h>
  616. #include <X11/extensions/Xcomposite.h>
  617. #endif
  618. #if JUCE_USE_XCURSOR
  619. // If you're missing this header, try installing the libxcursor-dev package
  620. #include <X11/Xcursor/Xcursor.h>
  621. #endif
  622. #if JUCE_OPENGL
  623. /* Got an include error here?
  624. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  625. and "freeglut3-dev".
  626. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  627. want to disable it.
  628. */
  629. #include <GL/glx.h>
  630. #endif
  631. #undef KeyPress
  632. #if JUCE_ALSA
  633. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  634. not got your paths set up correctly to find its header files.
  635. The package you need to install to get ASLA support is "libasound2-dev".
  636. If you don't have the ALSA library and don't want to build Juce with audio support,
  637. just disable the JUCE_ALSA flag in juce_Config.h
  638. */
  639. #include <alsa/asoundlib.h>
  640. #endif
  641. #if JUCE_JACK
  642. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  643. installed, or you've not got your paths set up correctly to find its header files.
  644. The package you need to install to get JACK support is "libjack-dev".
  645. If you don't have the jack-audio-connection-kit library and don't want to build
  646. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  647. */
  648. #include <jack/jack.h>
  649. //#include <jack/transport.h>
  650. #endif
  651. #undef SIZEOF
  652. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  653. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  654. #elif JUCE_MAC || JUCE_IPHONE
  655. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  656. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  657. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. /*
  659. This file wraps together all the mac-specific code, so that
  660. we can include all the native headers just once, and compile all our
  661. platform-specific stuff in one big lump, keeping it out of the way of
  662. the rest of the codebase.
  663. */
  664. #define USE_COREGRAPHICS_RENDERING 1
  665. #if JUCE_IPHONE
  666. #import <Foundation/Foundation.h>
  667. #import <UIKit/UIKit.h>
  668. #import <AudioToolbox/AudioToolbox.h>
  669. #import <AVFoundation/AVFoundation.h>
  670. #import <CoreData/CoreData.h>
  671. #import <MobileCoreServices/MobileCoreServices.h>
  672. #import <QuartzCore/QuartzCore.h>
  673. #include <sys/fcntl.h>
  674. #if JUCE_OPENGL
  675. #include <OpenGLES/ES1/gl.h>
  676. #include <OpenGLES/ES1/glext.h>
  677. #endif
  678. #else
  679. #import <Cocoa/Cocoa.h>
  680. #import <CoreAudio/HostTime.h>
  681. #import <CoreAudio/AudioHardware.h>
  682. #import <CoreMIDI/MIDIServices.h>
  683. #import <QTKit/QTKit.h>
  684. #import <WebKit/WebKit.h>
  685. #import <DiscRecording/DiscRecording.h>
  686. #import <IOKit/IOKitLib.h>
  687. #import <IOKit/IOCFPlugIn.h>
  688. #import <IOKit/hid/IOHIDLib.h>
  689. #import <IOKit/hid/IOHIDKeys.h>
  690. #import <IOKit/pwr_mgt/IOPMLib.h>
  691. #include <Carbon/Carbon.h>
  692. #include <sys/dir.h>
  693. #endif
  694. #include <sys/socket.h>
  695. #include <sys/sysctl.h>
  696. #include <sys/stat.h>
  697. #include <sys/param.h>
  698. #include <sys/mount.h>
  699. #include <fnmatch.h>
  700. #include <utime.h>
  701. #include <dlfcn.h>
  702. #include <ifaddrs.h>
  703. #include <net/if_dl.h>
  704. #include <mach/mach_time.h>
  705. #if MACOS_10_4_OR_EARLIER
  706. #include <GLUT/glut.h>
  707. #endif
  708. #if ! CGFLOAT_DEFINED
  709. #define CGFloat float
  710. #endif
  711. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  712. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  713. #else
  714. #error "Unknown platform!"
  715. #endif
  716. #endif
  717. //==============================================================================
  718. #define DONT_SET_USING_JUCE_NAMESPACE 1
  719. #undef max
  720. #undef min
  721. #define NO_DUMMY_DECL
  722. #if JUCE_BUILD_NATIVE
  723. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  724. #endif
  725. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  726. #pragma warning (disable: 4309 4305)
  727. #endif
  728. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  729. BEGIN_JUCE_NAMESPACE
  730. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  731. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  732. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. /**
  734. Creates a floating carbon window that can be used to hold a carbon UI.
  735. This is a handy class that's designed to be inlined where needed, e.g.
  736. in the audio plugin hosting code.
  737. */
  738. class CarbonViewWrapperComponent : public Component,
  739. public ComponentMovementWatcher,
  740. public Timer
  741. {
  742. public:
  743. CarbonViewWrapperComponent()
  744. : ComponentMovementWatcher (this),
  745. wrapperWindow (0),
  746. embeddedView (0),
  747. recursiveResize (false)
  748. {
  749. }
  750. virtual ~CarbonViewWrapperComponent()
  751. {
  752. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  753. }
  754. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  755. virtual void removeView (HIViewRef embeddedView) = 0;
  756. virtual void mouseDown (int, int) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] =
  790. {
  791. { kEventClassWindow, kEventWindowGetClickActivation },
  792. { kEventClassWindow, kEventWindowHandleDeactivate },
  793. { kEventClassWindow, kEventWindowBoundsChanging },
  794. { kEventClassMouse, kEventMouseDown },
  795. { kEventClassMouse, kEventMouseMoved },
  796. { kEventClassMouse, kEventMouseDragged },
  797. { kEventClassMouse, kEventMouseUp},
  798. { kEventClassWindow, kEventWindowDrawContent },
  799. { kEventClassWindow, kEventWindowShown },
  800. { kEventClassWindow, kEventWindowHidden }
  801. };
  802. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  803. InstallWindowEventHandler (wrapperWindow, upp,
  804. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  805. windowEventTypes, this, &eventHandlerRef);
  806. setOurSizeToEmbeddedViewSize();
  807. setEmbeddedWindowToOurSize();
  808. creationTime = Time::getCurrentTime();
  809. }
  810. }
  811. void deleteWindow()
  812. {
  813. removeView (embeddedView);
  814. embeddedView = 0;
  815. if (wrapperWindow != 0)
  816. {
  817. RemoveEventHandler (eventHandlerRef);
  818. DisposeWindow (wrapperWindow);
  819. wrapperWindow = 0;
  820. }
  821. }
  822. void setOurSizeToEmbeddedViewSize()
  823. {
  824. int w, h;
  825. if (getEmbeddedViewSize (w, h))
  826. {
  827. if (w != getWidth() || h != getHeight())
  828. {
  829. startTimer (50);
  830. setSize (w, h);
  831. if (getParentComponent() != 0)
  832. getParentComponent()->setSize (w, h);
  833. }
  834. else
  835. {
  836. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  837. }
  838. }
  839. else
  840. {
  841. stopTimer();
  842. }
  843. }
  844. void setEmbeddedWindowToOurSize()
  845. {
  846. if (! recursiveResize)
  847. {
  848. recursiveResize = true;
  849. if (embeddedView != 0)
  850. {
  851. HIRect r;
  852. r.origin.x = 0;
  853. r.origin.y = 0;
  854. r.size.width = (float) getWidth();
  855. r.size.height = (float) getHeight();
  856. HIViewSetFrame (embeddedView, &r);
  857. }
  858. if (wrapperWindow != 0)
  859. {
  860. Rect wr;
  861. wr.left = getScreenX();
  862. wr.top = getScreenY();
  863. wr.right = wr.left + getWidth();
  864. wr.bottom = wr.top + getHeight();
  865. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  866. ShowWindow (wrapperWindow);
  867. }
  868. recursiveResize = false;
  869. }
  870. }
  871. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  872. {
  873. setEmbeddedWindowToOurSize();
  874. }
  875. void componentPeerChanged()
  876. {
  877. deleteWindow();
  878. createWindow();
  879. }
  880. void componentVisibilityChanged (Component&)
  881. {
  882. if (isShowing())
  883. createWindow();
  884. else
  885. deleteWindow();
  886. setEmbeddedWindowToOurSize();
  887. }
  888. static void recursiveHIViewRepaint (HIViewRef view)
  889. {
  890. HIViewSetNeedsDisplay (view, true);
  891. HIViewRef child = HIViewGetFirstSubview (view);
  892. while (child != 0)
  893. {
  894. recursiveHIViewRepaint (child);
  895. child = HIViewGetNextView (child);
  896. }
  897. }
  898. void timerCallback()
  899. {
  900. setOurSizeToEmbeddedViewSize();
  901. // To avoid strange overpainting problems when the UI is first opened, we'll
  902. // repaint it a few times during the first second that it's on-screen..
  903. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  904. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  905. }
  906. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  907. EventRef event)
  908. {
  909. switch (GetEventKind (event))
  910. {
  911. case kEventWindowHandleDeactivate:
  912. ActivateWindow (wrapperWindow, TRUE);
  913. break;
  914. case kEventWindowGetClickActivation:
  915. {
  916. getTopLevelComponent()->toFront (false);
  917. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  918. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  919. sizeof (ClickActivationResult), &howToHandleClick);
  920. HIViewSetNeedsDisplay (embeddedView, true);
  921. }
  922. break;
  923. }
  924. return noErr;
  925. }
  926. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  927. EventRef event, void* userData)
  928. {
  929. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  930. }
  931. protected:
  932. WindowRef wrapperWindow;
  933. HIViewRef embeddedView;
  934. bool recursiveResize;
  935. Time creationTime;
  936. EventHandlerRef eventHandlerRef;
  937. };
  938. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  939. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  940. END_JUCE_NAMESPACE
  941. #endif
  942. #define JUCE_AMALGAMATED_TEMPLATE 1
  943. //==============================================================================
  944. #if JUCE_BUILD_CORE
  945. /*** Start of inlined file: juce_FileLogger.cpp ***/
  946. BEGIN_JUCE_NAMESPACE
  947. FileLogger::FileLogger (const File& logFile_,
  948. const String& welcomeMessage,
  949. const int maxInitialFileSizeBytes)
  950. : logFile (logFile_)
  951. {
  952. if (maxInitialFileSizeBytes >= 0)
  953. trimFileSize (maxInitialFileSizeBytes);
  954. if (! logFile_.exists())
  955. {
  956. // do this so that the parent directories get created..
  957. logFile_.create();
  958. }
  959. logStream = logFile_.createOutputStream (256);
  960. jassert (logStream != 0);
  961. String welcome;
  962. welcome << "\r\n**********************************************************\r\n"
  963. << welcomeMessage
  964. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  965. << "\r\n";
  966. logMessage (welcome);
  967. }
  968. FileLogger::~FileLogger()
  969. {
  970. }
  971. void FileLogger::logMessage (const String& message)
  972. {
  973. if (logStream != 0)
  974. {
  975. DBG (message);
  976. const ScopedLock sl (logLock);
  977. (*logStream) << message << "\r\n";
  978. logStream->flush();
  979. }
  980. }
  981. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  982. {
  983. if (maxFileSizeBytes <= 0)
  984. {
  985. logFile.deleteFile();
  986. }
  987. else
  988. {
  989. const int64 fileSize = logFile.getSize();
  990. if (fileSize > maxFileSizeBytes)
  991. {
  992. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  993. jassert (in != 0);
  994. if (in != 0)
  995. {
  996. in->setPosition (fileSize - maxFileSizeBytes);
  997. String content;
  998. {
  999. MemoryBlock contentToSave;
  1000. contentToSave.setSize (maxFileSizeBytes + 4);
  1001. contentToSave.fillWith (0);
  1002. in->read (contentToSave.getData(), maxFileSizeBytes);
  1003. in = 0;
  1004. content = contentToSave.toString();
  1005. }
  1006. int newStart = 0;
  1007. while (newStart < fileSize
  1008. && content[newStart] != '\n'
  1009. && content[newStart] != '\r')
  1010. ++newStart;
  1011. logFile.deleteFile();
  1012. logFile.appendText (content.substring (newStart), false, false);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1018. const String& logFileName,
  1019. const String& welcomeMessage,
  1020. const int maxInitialFileSizeBytes)
  1021. {
  1022. #if JUCE_MAC
  1023. File logFile ("~/Library/Logs");
  1024. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1025. .getChildFile (logFileName);
  1026. #else
  1027. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1028. if (logFile.isDirectory())
  1029. {
  1030. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1031. .getChildFile (logFileName);
  1032. }
  1033. #endif
  1034. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1035. }
  1036. END_JUCE_NAMESPACE
  1037. /*** End of inlined file: juce_FileLogger.cpp ***/
  1038. /*** Start of inlined file: juce_Logger.cpp ***/
  1039. BEGIN_JUCE_NAMESPACE
  1040. Logger::Logger()
  1041. {
  1042. }
  1043. Logger::~Logger()
  1044. {
  1045. }
  1046. Logger* Logger::currentLogger = 0;
  1047. void Logger::setCurrentLogger (Logger* const newLogger,
  1048. const bool deleteOldLogger)
  1049. {
  1050. Logger* const oldLogger = currentLogger;
  1051. currentLogger = newLogger;
  1052. if (deleteOldLogger)
  1053. delete oldLogger;
  1054. }
  1055. void Logger::writeToLog (const String& message)
  1056. {
  1057. if (currentLogger != 0)
  1058. currentLogger->logMessage (message);
  1059. else
  1060. outputDebugString (message);
  1061. }
  1062. #if JUCE_LOG_ASSERTIONS
  1063. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1064. {
  1065. String m ("JUCE Assertion failure in ");
  1066. m << filename << ", line " << lineNum;
  1067. Logger::writeToLog (m);
  1068. }
  1069. #endif
  1070. END_JUCE_NAMESPACE
  1071. /*** End of inlined file: juce_Logger.cpp ***/
  1072. /*** Start of inlined file: juce_Random.cpp ***/
  1073. BEGIN_JUCE_NAMESPACE
  1074. Random::Random (const int64 seedValue) throw()
  1075. : seed (seedValue)
  1076. {
  1077. }
  1078. Random::~Random() throw()
  1079. {
  1080. }
  1081. void Random::setSeed (const int64 newSeed) throw()
  1082. {
  1083. seed = newSeed;
  1084. }
  1085. void Random::combineSeed (const int64 seedValue) throw()
  1086. {
  1087. seed ^= nextInt64() ^ seedValue;
  1088. }
  1089. void Random::setSeedRandomly()
  1090. {
  1091. combineSeed ((int64) (pointer_sized_int) this);
  1092. combineSeed (Time::getMillisecondCounter());
  1093. combineSeed (Time::getHighResolutionTicks());
  1094. combineSeed (Time::getHighResolutionTicksPerSecond());
  1095. combineSeed (Time::currentTimeMillis());
  1096. }
  1097. int Random::nextInt() throw()
  1098. {
  1099. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1100. return (int) (seed >> 16);
  1101. }
  1102. int Random::nextInt (const int maxValue) throw()
  1103. {
  1104. jassert (maxValue > 0);
  1105. return (nextInt() & 0x7fffffff) % maxValue;
  1106. }
  1107. int64 Random::nextInt64() throw()
  1108. {
  1109. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1110. }
  1111. bool Random::nextBool() throw()
  1112. {
  1113. return (nextInt() & 0x80000000) != 0;
  1114. }
  1115. float Random::nextFloat() throw()
  1116. {
  1117. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1118. }
  1119. double Random::nextDouble() throw()
  1120. {
  1121. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1122. }
  1123. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1124. {
  1125. BigInteger n;
  1126. do
  1127. {
  1128. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1129. }
  1130. while (n >= maximumValue);
  1131. return n;
  1132. }
  1133. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1134. {
  1135. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1136. while ((startBit & 31) != 0 && numBits > 0)
  1137. {
  1138. arrayToChange.setBit (startBit++, nextBool());
  1139. --numBits;
  1140. }
  1141. while (numBits >= 32)
  1142. {
  1143. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1144. startBit += 32;
  1145. numBits -= 32;
  1146. }
  1147. while (--numBits >= 0)
  1148. arrayToChange.setBit (startBit + numBits, nextBool());
  1149. }
  1150. Random& Random::getSystemRandom() throw()
  1151. {
  1152. static Random sysRand (1);
  1153. return sysRand;
  1154. }
  1155. END_JUCE_NAMESPACE
  1156. /*** End of inlined file: juce_Random.cpp ***/
  1157. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1158. BEGIN_JUCE_NAMESPACE
  1159. RelativeTime::RelativeTime (const double seconds_) throw()
  1160. : seconds (seconds_)
  1161. {
  1162. }
  1163. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1164. : seconds (other.seconds)
  1165. {
  1166. }
  1167. RelativeTime::~RelativeTime() throw()
  1168. {
  1169. }
  1170. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1171. {
  1172. return RelativeTime (milliseconds * 0.001);
  1173. }
  1174. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1175. {
  1176. return RelativeTime (milliseconds * 0.001);
  1177. }
  1178. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1179. {
  1180. return RelativeTime (numberOfMinutes * 60.0);
  1181. }
  1182. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1183. {
  1184. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1185. }
  1186. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1187. {
  1188. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1189. }
  1190. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1191. {
  1192. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1193. }
  1194. int64 RelativeTime::inMilliseconds() const throw()
  1195. {
  1196. return (int64)(seconds * 1000.0);
  1197. }
  1198. double RelativeTime::inMinutes() const throw()
  1199. {
  1200. return seconds / 60.0;
  1201. }
  1202. double RelativeTime::inHours() const throw()
  1203. {
  1204. return seconds / (60.0 * 60.0);
  1205. }
  1206. double RelativeTime::inDays() const throw()
  1207. {
  1208. return seconds / (60.0 * 60.0 * 24.0);
  1209. }
  1210. double RelativeTime::inWeeks() const throw()
  1211. {
  1212. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1213. }
  1214. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1215. {
  1216. if (seconds < 0.001 && seconds > -0.001)
  1217. return returnValueForZeroTime;
  1218. String result;
  1219. if (seconds < 0)
  1220. result = "-";
  1221. int fieldsShown = 0;
  1222. int n = abs ((int) inWeeks());
  1223. if (n > 0)
  1224. {
  1225. result << n << ((n == 1) ? TRANS(" week ")
  1226. : TRANS(" weeks "));
  1227. ++fieldsShown;
  1228. }
  1229. n = abs ((int) inDays()) % 7;
  1230. if (n > 0)
  1231. {
  1232. result << n << ((n == 1) ? TRANS(" day ")
  1233. : TRANS(" days "));
  1234. ++fieldsShown;
  1235. }
  1236. if (fieldsShown < 2)
  1237. {
  1238. n = abs ((int) inHours()) % 24;
  1239. if (n > 0)
  1240. {
  1241. result << n << ((n == 1) ? TRANS(" hr ")
  1242. : TRANS(" hrs "));
  1243. ++fieldsShown;
  1244. }
  1245. if (fieldsShown < 2)
  1246. {
  1247. n = abs ((int) inMinutes()) % 60;
  1248. if (n > 0)
  1249. {
  1250. result << n << ((n == 1) ? TRANS(" min ")
  1251. : TRANS(" mins "));
  1252. ++fieldsShown;
  1253. }
  1254. if (fieldsShown < 2)
  1255. {
  1256. n = abs ((int) inSeconds()) % 60;
  1257. if (n > 0)
  1258. {
  1259. result << n << ((n == 1) ? TRANS(" sec ")
  1260. : TRANS(" secs "));
  1261. ++fieldsShown;
  1262. }
  1263. if (fieldsShown < 1)
  1264. {
  1265. n = abs ((int) inMilliseconds()) % 1000;
  1266. if (n > 0)
  1267. {
  1268. result << n << TRANS(" ms");
  1269. ++fieldsShown;
  1270. }
  1271. }
  1272. }
  1273. }
  1274. }
  1275. return result.trimEnd();
  1276. }
  1277. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1278. {
  1279. seconds = other.seconds;
  1280. return *this;
  1281. }
  1282. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1283. {
  1284. return seconds == other.seconds;
  1285. }
  1286. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1287. {
  1288. return seconds != other.seconds;
  1289. }
  1290. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1291. {
  1292. return seconds > other.seconds;
  1293. }
  1294. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1295. {
  1296. return seconds < other.seconds;
  1297. }
  1298. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1299. {
  1300. return seconds >= other.seconds;
  1301. }
  1302. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1303. {
  1304. return seconds <= other.seconds;
  1305. }
  1306. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1307. {
  1308. return RelativeTime (seconds + timeToAdd.seconds);
  1309. }
  1310. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1311. {
  1312. return RelativeTime (seconds - timeToSubtract.seconds);
  1313. }
  1314. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1315. {
  1316. return RelativeTime (seconds + secondsToAdd);
  1317. }
  1318. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1319. {
  1320. return RelativeTime (seconds - secondsToSubtract);
  1321. }
  1322. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1323. {
  1324. seconds += timeToAdd.seconds;
  1325. return *this;
  1326. }
  1327. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1328. {
  1329. seconds -= timeToSubtract.seconds;
  1330. return *this;
  1331. }
  1332. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1333. {
  1334. seconds += secondsToAdd;
  1335. return *this;
  1336. }
  1337. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1338. {
  1339. seconds -= secondsToSubtract;
  1340. return *this;
  1341. }
  1342. END_JUCE_NAMESPACE
  1343. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1344. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1345. BEGIN_JUCE_NAMESPACE
  1346. SystemStats::CPUFlags SystemStats::cpuFlags;
  1347. const String SystemStats::getJUCEVersion()
  1348. {
  1349. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1350. + "." + String (JUCE_MINOR_VERSION)
  1351. + "." + String (JUCE_BUILDNUMBER);
  1352. }
  1353. const StringArray SystemStats::getMACAddressStrings()
  1354. {
  1355. int64 macAddresses [16];
  1356. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1357. StringArray s;
  1358. for (int i = 0; i < numAddresses; ++i)
  1359. {
  1360. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1361. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1362. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1363. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1364. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1365. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1366. }
  1367. return s;
  1368. }
  1369. static bool juceInitialisedNonGUI = false;
  1370. #if JUCE_DEBUG
  1371. template <typename Type>
  1372. static void juce_testAtomicType (Type)
  1373. {
  1374. Atomic<Type> a, b;
  1375. a.set ((Type) 10);
  1376. a += (Type) 15;
  1377. a.memoryBarrier();
  1378. a -= (Type) 5;
  1379. ++a;
  1380. ++a;
  1381. --a;
  1382. a.memoryBarrier();
  1383. /* These are some simple test cases to check the atomics - let me know
  1384. if any of these assertions fail on your system!
  1385. */
  1386. jassert (a.get() == (Type) 21);
  1387. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1388. jassert (a.get() == (Type) 21);
  1389. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1390. jassert (a.get() == (Type) 101);
  1391. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1392. jassert (a.get() == (Type) 101);
  1393. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1394. jassert (a.get() == (Type) 200);
  1395. jassert (a.exchange ((Type) 300) == (Type) 200);
  1396. jassert (a.get() == (Type) 300);
  1397. b = a;
  1398. jassert (b.get() == a.get());
  1399. }
  1400. static void juce_testAtomics()
  1401. {
  1402. juce_testAtomicType ((int) 0);
  1403. juce_testAtomicType ((unsigned int) 0);
  1404. juce_testAtomicType ((int32) 0);
  1405. juce_testAtomicType ((uint32) 0);
  1406. juce_testAtomicType ((long) 0);
  1407. juce_testAtomicType ((void*) 0);
  1408. juce_testAtomicType ((int*) 0);
  1409. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1410. juce_testAtomicType ((int64) 0);
  1411. juce_testAtomicType ((uint64) 0);
  1412. #endif
  1413. }
  1414. #endif
  1415. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1416. {
  1417. if (! juceInitialisedNonGUI)
  1418. {
  1419. #if JUCE_MAC || JUCE_IPHONE
  1420. const ScopedAutoReleasePool pool;
  1421. #endif
  1422. #if JUCE_DEBUG
  1423. {
  1424. // Some simple test code to keep an eye on things and make sure these functions
  1425. // work ok on all platforms. Let me know if any of these assertions fail!
  1426. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1427. static_jassert (sizeof (int8) == 1);
  1428. static_jassert (sizeof (uint8) == 1);
  1429. static_jassert (sizeof (int16) == 2);
  1430. static_jassert (sizeof (uint16) == 2);
  1431. static_jassert (sizeof (int32) == 4);
  1432. static_jassert (sizeof (uint32) == 4);
  1433. static_jassert (sizeof (int64) == 8);
  1434. static_jassert (sizeof (uint64) == 8);
  1435. char a1[7];
  1436. jassert (numElementsInArray(a1) == 7);
  1437. int a2[3];
  1438. jassert (numElementsInArray(a2) == 3);
  1439. juce_testAtomics();
  1440. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1441. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1442. // Some quick stream tests..
  1443. int randomInt = Random::getSystemRandom().nextInt();
  1444. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1445. double randomDouble = Random::getSystemRandom().nextDouble();
  1446. String randomString;
  1447. for (int i = 50; --i >= 0;)
  1448. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1449. MemoryOutputStream mo;
  1450. mo.writeInt (randomInt);
  1451. mo.writeIntBigEndian (randomInt);
  1452. mo.writeCompressedInt (randomInt);
  1453. mo.writeString (randomString);
  1454. mo.writeInt64 (randomInt64);
  1455. mo.writeInt64BigEndian (randomInt64);
  1456. mo.writeDouble (randomDouble);
  1457. mo.writeDoubleBigEndian (randomDouble);
  1458. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1459. jassert (mi.readInt() == randomInt);
  1460. jassert (mi.readIntBigEndian() == randomInt);
  1461. jassert (mi.readCompressedInt() == randomInt);
  1462. jassert (mi.readString() == randomString);
  1463. jassert (mi.readInt64() == randomInt64);
  1464. jassert (mi.readInt64BigEndian() == randomInt64);
  1465. jassert (mi.readDouble() == randomDouble);
  1466. jassert (mi.readDoubleBigEndian() == randomDouble);
  1467. }
  1468. #endif
  1469. // Now the real initialisation..
  1470. juceInitialisedNonGUI = true;
  1471. DBG (SystemStats::getJUCEVersion());
  1472. SystemStats::initialiseStats();
  1473. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1474. }
  1475. }
  1476. #if JUCE_WINDOWS
  1477. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1478. #endif
  1479. #if JUCE_DEBUG
  1480. extern void juce_CheckForDanglingStreams();
  1481. #endif
  1482. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1483. {
  1484. if (juceInitialisedNonGUI)
  1485. {
  1486. #if JUCE_MAC || JUCE_IPHONE
  1487. const ScopedAutoReleasePool pool;
  1488. #endif
  1489. #if JUCE_WINDOWS
  1490. // need to shut down sockets if they were used..
  1491. juce_shutdownWin32Sockets();
  1492. #endif
  1493. LocalisedStrings::setCurrentMappings (0);
  1494. Thread::stopAllThreads (3000);
  1495. #if JUCE_DEBUG
  1496. juce_CheckForDanglingStreams();
  1497. #endif
  1498. juceInitialisedNonGUI = false;
  1499. }
  1500. }
  1501. #ifdef JUCE_DLL
  1502. void* juce_Malloc (const int size)
  1503. {
  1504. return malloc (size);
  1505. }
  1506. void* juce_Calloc (const int size)
  1507. {
  1508. return calloc (1, size);
  1509. }
  1510. void* juce_Realloc (void* const block, const int size)
  1511. {
  1512. return realloc (block, size);
  1513. }
  1514. void juce_Free (void* const block)
  1515. {
  1516. free (block);
  1517. }
  1518. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1519. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1520. {
  1521. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1522. }
  1523. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1524. {
  1525. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1526. }
  1527. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1528. {
  1529. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1530. }
  1531. void juce_DebugFree (void* const block)
  1532. {
  1533. _free_dbg (block, _NORMAL_BLOCK);
  1534. }
  1535. #endif
  1536. #endif
  1537. END_JUCE_NAMESPACE
  1538. /*** End of inlined file: juce_SystemStats.cpp ***/
  1539. /*** Start of inlined file: juce_Time.cpp ***/
  1540. #if JUCE_MSVC
  1541. #pragma warning (push)
  1542. #pragma warning (disable: 4514)
  1543. #endif
  1544. #ifndef JUCE_WINDOWS
  1545. #include <sys/time.h>
  1546. #else
  1547. #include <ctime>
  1548. #endif
  1549. #include <sys/timeb.h>
  1550. #if JUCE_MSVC
  1551. #pragma warning (pop)
  1552. #ifdef _INC_TIME_INL
  1553. #define USE_NEW_SECURE_TIME_FNS
  1554. #endif
  1555. #endif
  1556. BEGIN_JUCE_NAMESPACE
  1557. namespace TimeHelpers
  1558. {
  1559. static struct tm millisToLocal (const int64 millis) throw()
  1560. {
  1561. struct tm result;
  1562. const int64 seconds = millis / 1000;
  1563. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1564. {
  1565. // use extended maths for dates beyond 1970 to 2037..
  1566. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1567. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1568. const int days = (int) (jdm / literal64bit (86400));
  1569. const int a = 32044 + days;
  1570. const int b = (4 * a + 3) / 146097;
  1571. const int c = a - (b * 146097) / 4;
  1572. const int d = (4 * c + 3) / 1461;
  1573. const int e = c - (d * 1461) / 4;
  1574. const int m = (5 * e + 2) / 153;
  1575. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1576. result.tm_mon = m + 2 - 12 * (m / 10);
  1577. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1578. result.tm_wday = (days + 1) % 7;
  1579. result.tm_yday = -1;
  1580. int t = (int) (jdm % literal64bit (86400));
  1581. result.tm_hour = t / 3600;
  1582. t %= 3600;
  1583. result.tm_min = t / 60;
  1584. result.tm_sec = t % 60;
  1585. result.tm_isdst = -1;
  1586. }
  1587. else
  1588. {
  1589. time_t now = static_cast <time_t> (seconds);
  1590. #if JUCE_WINDOWS
  1591. #ifdef USE_NEW_SECURE_TIME_FNS
  1592. if (now >= 0 && now <= 0x793406fff)
  1593. localtime_s (&result, &now);
  1594. else
  1595. zeromem (&result, sizeof (result));
  1596. #else
  1597. result = *localtime (&now);
  1598. #endif
  1599. #else
  1600. // more thread-safe
  1601. localtime_r (&now, &result);
  1602. #endif
  1603. }
  1604. return result;
  1605. }
  1606. static int extendedModulo (const int64 value, const int modulo) throw()
  1607. {
  1608. return (int) (value >= 0 ? (value % modulo)
  1609. : (value - ((value / modulo) + 1) * modulo));
  1610. }
  1611. static uint32 lastMSCounterValue = 0;
  1612. }
  1613. Time::Time() throw()
  1614. : millisSinceEpoch (0)
  1615. {
  1616. }
  1617. Time::Time (const Time& other) throw()
  1618. : millisSinceEpoch (other.millisSinceEpoch)
  1619. {
  1620. }
  1621. Time::Time (const int64 ms) throw()
  1622. : millisSinceEpoch (ms)
  1623. {
  1624. }
  1625. Time::Time (const int year,
  1626. const int month,
  1627. const int day,
  1628. const int hours,
  1629. const int minutes,
  1630. const int seconds,
  1631. const int milliseconds,
  1632. const bool useLocalTime) throw()
  1633. {
  1634. jassert (year > 100); // year must be a 4-digit version
  1635. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1636. {
  1637. // use extended maths for dates beyond 1970 to 2037..
  1638. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1639. : 0;
  1640. const int a = (13 - month) / 12;
  1641. const int y = year + 4800 - a;
  1642. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1643. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1644. - 32045;
  1645. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1646. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1647. + milliseconds;
  1648. }
  1649. else
  1650. {
  1651. struct tm t;
  1652. t.tm_year = year - 1900;
  1653. t.tm_mon = month;
  1654. t.tm_mday = day;
  1655. t.tm_hour = hours;
  1656. t.tm_min = minutes;
  1657. t.tm_sec = seconds;
  1658. t.tm_isdst = -1;
  1659. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1660. if (millisSinceEpoch < 0)
  1661. millisSinceEpoch = 0;
  1662. else
  1663. millisSinceEpoch += milliseconds;
  1664. }
  1665. }
  1666. Time::~Time() throw()
  1667. {
  1668. }
  1669. Time& Time::operator= (const Time& other) throw()
  1670. {
  1671. millisSinceEpoch = other.millisSinceEpoch;
  1672. return *this;
  1673. }
  1674. int64 Time::currentTimeMillis() throw()
  1675. {
  1676. static uint32 lastCounterResult = 0xffffffff;
  1677. static int64 correction = 0;
  1678. const uint32 now = getMillisecondCounter();
  1679. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1680. if (now < lastCounterResult)
  1681. {
  1682. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1683. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1684. {
  1685. // get the time once using normal library calls, and store the difference needed to
  1686. // turn the millisecond counter into a real time.
  1687. #if JUCE_WINDOWS
  1688. struct _timeb t;
  1689. #ifdef USE_NEW_SECURE_TIME_FNS
  1690. _ftime_s (&t);
  1691. #else
  1692. _ftime (&t);
  1693. #endif
  1694. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1695. #else
  1696. struct timeval tv;
  1697. struct timezone tz;
  1698. gettimeofday (&tv, &tz);
  1699. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1700. #endif
  1701. }
  1702. }
  1703. lastCounterResult = now;
  1704. return correction + now;
  1705. }
  1706. uint32 juce_millisecondsSinceStartup() throw();
  1707. uint32 Time::getMillisecondCounter() throw()
  1708. {
  1709. const uint32 now = juce_millisecondsSinceStartup();
  1710. if (now < TimeHelpers::lastMSCounterValue)
  1711. {
  1712. // in multi-threaded apps this might be called concurrently, so
  1713. // make sure that our last counter value only increases and doesn't
  1714. // go backwards..
  1715. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1716. TimeHelpers::lastMSCounterValue = now;
  1717. }
  1718. else
  1719. {
  1720. TimeHelpers::lastMSCounterValue = now;
  1721. }
  1722. return now;
  1723. }
  1724. uint32 Time::getApproximateMillisecondCounter() throw()
  1725. {
  1726. jassert (TimeHelpers::lastMSCounterValue != 0);
  1727. return TimeHelpers::lastMSCounterValue;
  1728. }
  1729. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1730. {
  1731. for (;;)
  1732. {
  1733. const uint32 now = getMillisecondCounter();
  1734. if (now >= targetTime)
  1735. break;
  1736. const int toWait = targetTime - now;
  1737. if (toWait > 2)
  1738. {
  1739. Thread::sleep (jmin (20, toWait >> 1));
  1740. }
  1741. else
  1742. {
  1743. // xxx should consider using mutex_pause on the mac as it apparently
  1744. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1745. for (int i = 10; --i >= 0;)
  1746. Thread::yield();
  1747. }
  1748. }
  1749. }
  1750. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1751. {
  1752. return ticks / (double) getHighResolutionTicksPerSecond();
  1753. }
  1754. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1755. {
  1756. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1757. }
  1758. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1759. {
  1760. return Time (currentTimeMillis());
  1761. }
  1762. const String Time::toString (const bool includeDate,
  1763. const bool includeTime,
  1764. const bool includeSeconds,
  1765. const bool use24HourClock) const throw()
  1766. {
  1767. String result;
  1768. if (includeDate)
  1769. {
  1770. result << getDayOfMonth() << ' '
  1771. << getMonthName (true) << ' '
  1772. << getYear();
  1773. if (includeTime)
  1774. result << ' ';
  1775. }
  1776. if (includeTime)
  1777. {
  1778. const int mins = getMinutes();
  1779. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1780. << (mins < 10 ? ":0" : ":") << mins;
  1781. if (includeSeconds)
  1782. {
  1783. const int secs = getSeconds();
  1784. result << (secs < 10 ? ":0" : ":") << secs;
  1785. }
  1786. if (! use24HourClock)
  1787. result << (isAfternoon() ? "pm" : "am");
  1788. }
  1789. return result.trimEnd();
  1790. }
  1791. const String Time::formatted (const String& format) const throw()
  1792. {
  1793. String buffer;
  1794. int bufferSize = 128;
  1795. buffer.preallocateStorage (bufferSize);
  1796. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1797. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1798. {
  1799. bufferSize += 128;
  1800. buffer.preallocateStorage (bufferSize);
  1801. }
  1802. return buffer;
  1803. }
  1804. int Time::getYear() const throw()
  1805. {
  1806. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1807. }
  1808. int Time::getMonth() const throw()
  1809. {
  1810. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1811. }
  1812. int Time::getDayOfMonth() const throw()
  1813. {
  1814. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1815. }
  1816. int Time::getDayOfWeek() const throw()
  1817. {
  1818. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1819. }
  1820. int Time::getHours() const throw()
  1821. {
  1822. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1823. }
  1824. int Time::getHoursInAmPmFormat() const throw()
  1825. {
  1826. const int hours = getHours();
  1827. if (hours == 0)
  1828. return 12;
  1829. else if (hours <= 12)
  1830. return hours;
  1831. else
  1832. return hours - 12;
  1833. }
  1834. bool Time::isAfternoon() const throw()
  1835. {
  1836. return getHours() >= 12;
  1837. }
  1838. int Time::getMinutes() const throw()
  1839. {
  1840. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1841. }
  1842. int Time::getSeconds() const throw()
  1843. {
  1844. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1845. }
  1846. int Time::getMilliseconds() const throw()
  1847. {
  1848. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1849. }
  1850. bool Time::isDaylightSavingTime() const throw()
  1851. {
  1852. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1853. }
  1854. const String Time::getTimeZone() const throw()
  1855. {
  1856. String zone[2];
  1857. #if JUCE_WINDOWS
  1858. _tzset();
  1859. #ifdef USE_NEW_SECURE_TIME_FNS
  1860. {
  1861. char name [128];
  1862. size_t length;
  1863. for (int i = 0; i < 2; ++i)
  1864. {
  1865. zeromem (name, sizeof (name));
  1866. _get_tzname (&length, name, 127, i);
  1867. zone[i] = name;
  1868. }
  1869. }
  1870. #else
  1871. const char** const zonePtr = (const char**) _tzname;
  1872. zone[0] = zonePtr[0];
  1873. zone[1] = zonePtr[1];
  1874. #endif
  1875. #else
  1876. tzset();
  1877. const char** const zonePtr = (const char**) tzname;
  1878. zone[0] = zonePtr[0];
  1879. zone[1] = zonePtr[1];
  1880. #endif
  1881. if (isDaylightSavingTime())
  1882. {
  1883. zone[0] = zone[1];
  1884. if (zone[0].length() > 3
  1885. && zone[0].containsIgnoreCase ("daylight")
  1886. && zone[0].contains ("GMT"))
  1887. zone[0] = "BST";
  1888. }
  1889. return zone[0].substring (0, 3);
  1890. }
  1891. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1892. {
  1893. return getMonthName (getMonth(), threeLetterVersion);
  1894. }
  1895. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1896. {
  1897. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1898. }
  1899. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1900. {
  1901. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1902. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1903. monthNumber %= 12;
  1904. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1905. : longMonthNames [monthNumber]);
  1906. }
  1907. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1908. {
  1909. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1910. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1911. day %= 7;
  1912. return TRANS (threeLetterVersion ? shortDayNames [day]
  1913. : longDayNames [day]);
  1914. }
  1915. END_JUCE_NAMESPACE
  1916. /*** End of inlined file: juce_Time.cpp ***/
  1917. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1918. BEGIN_JUCE_NAMESPACE
  1919. BigInteger::BigInteger()
  1920. : numValues (4),
  1921. highestBit (-1),
  1922. negative (false)
  1923. {
  1924. values.calloc (numValues + 1);
  1925. }
  1926. BigInteger::BigInteger (const int value)
  1927. : numValues (4),
  1928. highestBit (31),
  1929. negative (value < 0)
  1930. {
  1931. values.calloc (numValues + 1);
  1932. values[0] = abs (value);
  1933. highestBit = getHighestBit();
  1934. }
  1935. BigInteger::BigInteger (int64 value)
  1936. : numValues (4),
  1937. highestBit (63),
  1938. negative (value < 0)
  1939. {
  1940. values.calloc (numValues + 1);
  1941. if (value < 0)
  1942. value = -value;
  1943. values[0] = (unsigned int) value;
  1944. values[1] = (unsigned int) (value >> 32);
  1945. highestBit = getHighestBit();
  1946. }
  1947. BigInteger::BigInteger (const unsigned int value)
  1948. : numValues (4),
  1949. highestBit (31),
  1950. negative (false)
  1951. {
  1952. values.calloc (numValues + 1);
  1953. values[0] = value;
  1954. highestBit = getHighestBit();
  1955. }
  1956. BigInteger::BigInteger (const BigInteger& other)
  1957. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1958. highestBit (other.getHighestBit()),
  1959. negative (other.negative)
  1960. {
  1961. values.malloc (numValues + 1);
  1962. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1963. }
  1964. BigInteger::~BigInteger()
  1965. {
  1966. }
  1967. void BigInteger::swapWith (BigInteger& other) throw()
  1968. {
  1969. values.swapWith (other.values);
  1970. swapVariables (numValues, other.numValues);
  1971. swapVariables (highestBit, other.highestBit);
  1972. swapVariables (negative, other.negative);
  1973. }
  1974. BigInteger& BigInteger::operator= (const BigInteger& other)
  1975. {
  1976. if (this != &other)
  1977. {
  1978. highestBit = other.getHighestBit();
  1979. numValues = jmax (4, (highestBit >> 5) + 1);
  1980. negative = other.negative;
  1981. values.malloc (numValues + 1);
  1982. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1983. }
  1984. return *this;
  1985. }
  1986. void BigInteger::ensureSize (const int numVals)
  1987. {
  1988. if (numVals + 2 >= numValues)
  1989. {
  1990. int oldSize = numValues;
  1991. numValues = ((numVals + 2) * 3) / 2;
  1992. values.realloc (numValues + 1);
  1993. while (oldSize < numValues)
  1994. values [oldSize++] = 0;
  1995. }
  1996. }
  1997. bool BigInteger::operator[] (const int bit) const throw()
  1998. {
  1999. return bit <= highestBit && bit >= 0
  2000. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2001. }
  2002. int BigInteger::toInteger() const throw()
  2003. {
  2004. const int n = (int) (values[0] & 0x7fffffff);
  2005. return negative ? -n : n;
  2006. }
  2007. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2008. {
  2009. BigInteger r;
  2010. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2011. r.ensureSize (numBits >> 5);
  2012. r.highestBit = numBits;
  2013. int i = 0;
  2014. while (numBits > 0)
  2015. {
  2016. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2017. numBits -= 32;
  2018. startBit += 32;
  2019. }
  2020. r.highestBit = r.getHighestBit();
  2021. return r;
  2022. }
  2023. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2024. {
  2025. if (numBits > 32)
  2026. {
  2027. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2028. numBits = 32;
  2029. }
  2030. numBits = jmin (numBits, highestBit + 1 - startBit);
  2031. if (numBits <= 0)
  2032. return 0;
  2033. const int pos = startBit >> 5;
  2034. const int offset = startBit & 31;
  2035. const int endSpace = 32 - numBits;
  2036. uint32 n = ((uint32) values [pos]) >> offset;
  2037. if (offset > endSpace)
  2038. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2039. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2040. }
  2041. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2042. {
  2043. if (numBits > 32)
  2044. {
  2045. jassertfalse;
  2046. numBits = 32;
  2047. }
  2048. for (int i = 0; i < numBits; ++i)
  2049. {
  2050. setBit (startBit + i, (valueToSet & 1) != 0);
  2051. valueToSet >>= 1;
  2052. }
  2053. }
  2054. void BigInteger::clear()
  2055. {
  2056. if (numValues > 16)
  2057. {
  2058. numValues = 4;
  2059. values.calloc (numValues + 1);
  2060. }
  2061. else
  2062. {
  2063. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2064. }
  2065. highestBit = -1;
  2066. negative = false;
  2067. }
  2068. void BigInteger::setBit (const int bit)
  2069. {
  2070. if (bit >= 0)
  2071. {
  2072. if (bit > highestBit)
  2073. {
  2074. ensureSize (bit >> 5);
  2075. highestBit = bit;
  2076. }
  2077. values [bit >> 5] |= (1 << (bit & 31));
  2078. }
  2079. }
  2080. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2081. {
  2082. if (shouldBeSet)
  2083. setBit (bit);
  2084. else
  2085. clearBit (bit);
  2086. }
  2087. void BigInteger::clearBit (const int bit) throw()
  2088. {
  2089. if (bit >= 0 && bit <= highestBit)
  2090. values [bit >> 5] &= ~(1 << (bit & 31));
  2091. }
  2092. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2093. {
  2094. while (--numBits >= 0)
  2095. setBit (startBit++, shouldBeSet);
  2096. }
  2097. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2098. {
  2099. if (bit >= 0)
  2100. shiftBits (1, bit);
  2101. setBit (bit, shouldBeSet);
  2102. }
  2103. bool BigInteger::isZero() const throw()
  2104. {
  2105. return getHighestBit() < 0;
  2106. }
  2107. bool BigInteger::isOne() const throw()
  2108. {
  2109. return getHighestBit() == 0 && ! negative;
  2110. }
  2111. bool BigInteger::isNegative() const throw()
  2112. {
  2113. return negative && ! isZero();
  2114. }
  2115. void BigInteger::setNegative (const bool neg) throw()
  2116. {
  2117. negative = neg;
  2118. }
  2119. void BigInteger::negate() throw()
  2120. {
  2121. negative = (! negative) && ! isZero();
  2122. }
  2123. int BigInteger::countNumberOfSetBits() const throw()
  2124. {
  2125. int total = 0;
  2126. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2127. {
  2128. unsigned int n = values[i];
  2129. if (n == 0xffffffff)
  2130. {
  2131. total += 32;
  2132. }
  2133. else
  2134. {
  2135. while (n != 0)
  2136. {
  2137. total += (n & 1);
  2138. n >>= 1;
  2139. }
  2140. }
  2141. }
  2142. return total;
  2143. }
  2144. int BigInteger::getHighestBit() const throw()
  2145. {
  2146. for (int i = highestBit + 1; --i >= 0;)
  2147. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2148. return i;
  2149. return -1;
  2150. }
  2151. int BigInteger::findNextSetBit (int i) const throw()
  2152. {
  2153. for (; i <= highestBit; ++i)
  2154. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2155. return i;
  2156. return -1;
  2157. }
  2158. int BigInteger::findNextClearBit (int i) const throw()
  2159. {
  2160. for (; i <= highestBit; ++i)
  2161. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2162. break;
  2163. return i;
  2164. }
  2165. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2166. {
  2167. if (other.isNegative())
  2168. return operator-= (-other);
  2169. if (isNegative())
  2170. {
  2171. if (compareAbsolute (other) < 0)
  2172. {
  2173. BigInteger temp (*this);
  2174. temp.negate();
  2175. *this = other;
  2176. operator-= (temp);
  2177. }
  2178. else
  2179. {
  2180. negate();
  2181. operator-= (other);
  2182. negate();
  2183. }
  2184. }
  2185. else
  2186. {
  2187. if (other.highestBit > highestBit)
  2188. highestBit = other.highestBit;
  2189. ++highestBit;
  2190. const int numInts = (highestBit >> 5) + 1;
  2191. ensureSize (numInts);
  2192. int64 remainder = 0;
  2193. for (int i = 0; i <= numInts; ++i)
  2194. {
  2195. if (i < numValues)
  2196. remainder += values[i];
  2197. if (i < other.numValues)
  2198. remainder += other.values[i];
  2199. values[i] = (unsigned int) remainder;
  2200. remainder >>= 32;
  2201. }
  2202. jassert (remainder == 0);
  2203. highestBit = getHighestBit();
  2204. }
  2205. return *this;
  2206. }
  2207. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2208. {
  2209. if (other.isNegative())
  2210. return operator+= (-other);
  2211. if (! isNegative())
  2212. {
  2213. if (compareAbsolute (other) < 0)
  2214. {
  2215. BigInteger temp (other);
  2216. swapWith (temp);
  2217. operator-= (temp);
  2218. negate();
  2219. return *this;
  2220. }
  2221. }
  2222. else
  2223. {
  2224. negate();
  2225. operator+= (other);
  2226. negate();
  2227. return *this;
  2228. }
  2229. const int numInts = (highestBit >> 5) + 1;
  2230. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2231. int64 amountToSubtract = 0;
  2232. for (int i = 0; i <= numInts; ++i)
  2233. {
  2234. if (i <= maxOtherInts)
  2235. amountToSubtract += (int64) other.values[i];
  2236. if (values[i] >= amountToSubtract)
  2237. {
  2238. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2239. amountToSubtract = 0;
  2240. }
  2241. else
  2242. {
  2243. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2244. values[i] = (unsigned int) n;
  2245. amountToSubtract = 1;
  2246. }
  2247. }
  2248. return *this;
  2249. }
  2250. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2251. {
  2252. BigInteger total;
  2253. highestBit = getHighestBit();
  2254. const bool wasNegative = isNegative();
  2255. setNegative (false);
  2256. for (int i = 0; i <= highestBit; ++i)
  2257. {
  2258. if (operator[](i))
  2259. {
  2260. BigInteger n (other);
  2261. n.setNegative (false);
  2262. n <<= i;
  2263. total += n;
  2264. }
  2265. }
  2266. total.setNegative (wasNegative ^ other.isNegative());
  2267. swapWith (total);
  2268. return *this;
  2269. }
  2270. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2271. {
  2272. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2273. const int divHB = divisor.getHighestBit();
  2274. const int ourHB = getHighestBit();
  2275. if (divHB < 0 || ourHB < 0)
  2276. {
  2277. // division by zero
  2278. remainder.clear();
  2279. clear();
  2280. }
  2281. else
  2282. {
  2283. const bool wasNegative = isNegative();
  2284. swapWith (remainder);
  2285. remainder.setNegative (false);
  2286. clear();
  2287. BigInteger temp (divisor);
  2288. temp.setNegative (false);
  2289. int leftShift = ourHB - divHB;
  2290. temp <<= leftShift;
  2291. while (leftShift >= 0)
  2292. {
  2293. if (remainder.compareAbsolute (temp) >= 0)
  2294. {
  2295. remainder -= temp;
  2296. setBit (leftShift);
  2297. }
  2298. if (--leftShift >= 0)
  2299. temp >>= 1;
  2300. }
  2301. negative = wasNegative ^ divisor.isNegative();
  2302. remainder.setNegative (wasNegative);
  2303. }
  2304. }
  2305. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2306. {
  2307. BigInteger remainder;
  2308. divideBy (other, remainder);
  2309. return *this;
  2310. }
  2311. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2312. {
  2313. // this operation doesn't take into account negative values..
  2314. jassert (isNegative() == other.isNegative());
  2315. if (other.highestBit >= 0)
  2316. {
  2317. ensureSize (other.highestBit >> 5);
  2318. int n = (other.highestBit >> 5) + 1;
  2319. while (--n >= 0)
  2320. values[n] |= other.values[n];
  2321. if (other.highestBit > highestBit)
  2322. highestBit = other.highestBit;
  2323. highestBit = getHighestBit();
  2324. }
  2325. return *this;
  2326. }
  2327. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2328. {
  2329. // this operation doesn't take into account negative values..
  2330. jassert (isNegative() == other.isNegative());
  2331. int n = numValues;
  2332. while (n > other.numValues)
  2333. values[--n] = 0;
  2334. while (--n >= 0)
  2335. values[n] &= other.values[n];
  2336. if (other.highestBit < highestBit)
  2337. highestBit = other.highestBit;
  2338. highestBit = getHighestBit();
  2339. return *this;
  2340. }
  2341. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2342. {
  2343. // this operation will only work with the absolute values
  2344. jassert (isNegative() == other.isNegative());
  2345. if (other.highestBit >= 0)
  2346. {
  2347. ensureSize (other.highestBit >> 5);
  2348. int n = (other.highestBit >> 5) + 1;
  2349. while (--n >= 0)
  2350. values[n] ^= other.values[n];
  2351. if (other.highestBit > highestBit)
  2352. highestBit = other.highestBit;
  2353. highestBit = getHighestBit();
  2354. }
  2355. return *this;
  2356. }
  2357. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2358. {
  2359. BigInteger remainder;
  2360. divideBy (divisor, remainder);
  2361. swapWith (remainder);
  2362. return *this;
  2363. }
  2364. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2365. {
  2366. shiftBits (numBitsToShift, 0);
  2367. return *this;
  2368. }
  2369. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2370. {
  2371. return operator<<= (-numBitsToShift);
  2372. }
  2373. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2374. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2375. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2376. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2377. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2378. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2379. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2380. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2381. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2382. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2383. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2384. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2385. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2386. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2387. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2388. int BigInteger::compare (const BigInteger& other) const throw()
  2389. {
  2390. if (isNegative() == other.isNegative())
  2391. {
  2392. const int absComp = compareAbsolute (other);
  2393. return isNegative() ? -absComp : absComp;
  2394. }
  2395. else
  2396. {
  2397. return isNegative() ? -1 : 1;
  2398. }
  2399. }
  2400. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2401. {
  2402. const int h1 = getHighestBit();
  2403. const int h2 = other.getHighestBit();
  2404. if (h1 > h2)
  2405. return 1;
  2406. else if (h1 < h2)
  2407. return -1;
  2408. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2409. if (values[i] != other.values[i])
  2410. return (values[i] > other.values[i]) ? 1 : -1;
  2411. return 0;
  2412. }
  2413. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2414. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2415. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2416. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2417. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2418. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2419. void BigInteger::shiftBits (int bits, const int startBit)
  2420. {
  2421. if (highestBit < 0)
  2422. return;
  2423. if (startBit > 0)
  2424. {
  2425. if (bits < 0)
  2426. {
  2427. // right shift
  2428. for (int i = startBit; i <= highestBit; ++i)
  2429. setBit (i, operator[] (i - bits));
  2430. highestBit = getHighestBit();
  2431. }
  2432. else if (bits > 0)
  2433. {
  2434. // left shift
  2435. for (int i = highestBit + 1; --i >= startBit;)
  2436. setBit (i + bits, operator[] (i));
  2437. while (--bits >= 0)
  2438. clearBit (bits + startBit);
  2439. }
  2440. }
  2441. else
  2442. {
  2443. if (bits < 0)
  2444. {
  2445. // right shift
  2446. bits = -bits;
  2447. if (bits > highestBit)
  2448. {
  2449. clear();
  2450. }
  2451. else
  2452. {
  2453. const int wordsToMove = bits >> 5;
  2454. int top = 1 + (highestBit >> 5) - wordsToMove;
  2455. highestBit -= bits;
  2456. if (wordsToMove > 0)
  2457. {
  2458. int i;
  2459. for (i = 0; i < top; ++i)
  2460. values [i] = values [i + wordsToMove];
  2461. for (i = 0; i < wordsToMove; ++i)
  2462. values [top + i] = 0;
  2463. bits &= 31;
  2464. }
  2465. if (bits != 0)
  2466. {
  2467. const int invBits = 32 - bits;
  2468. --top;
  2469. for (int i = 0; i < top; ++i)
  2470. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2471. values[top] = (values[top] >> bits);
  2472. }
  2473. highestBit = getHighestBit();
  2474. }
  2475. }
  2476. else if (bits > 0)
  2477. {
  2478. // left shift
  2479. ensureSize (((highestBit + bits) >> 5) + 1);
  2480. const int wordsToMove = bits >> 5;
  2481. int top = 1 + (highestBit >> 5);
  2482. highestBit += bits;
  2483. if (wordsToMove > 0)
  2484. {
  2485. int i;
  2486. for (i = top; --i >= 0;)
  2487. values [i + wordsToMove] = values [i];
  2488. for (i = 0; i < wordsToMove; ++i)
  2489. values [i] = 0;
  2490. bits &= 31;
  2491. }
  2492. if (bits != 0)
  2493. {
  2494. const int invBits = 32 - bits;
  2495. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2496. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2497. values [wordsToMove] = values [wordsToMove] << bits;
  2498. }
  2499. highestBit = getHighestBit();
  2500. }
  2501. }
  2502. }
  2503. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2504. {
  2505. while (! m->isZero())
  2506. {
  2507. if (n->compareAbsolute (*m) > 0)
  2508. swapVariables (m, n);
  2509. *m -= *n;
  2510. }
  2511. return *n;
  2512. }
  2513. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2514. {
  2515. BigInteger m (*this);
  2516. while (! n.isZero())
  2517. {
  2518. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2519. return simpleGCD (&m, &n);
  2520. BigInteger temp1 (m), temp2;
  2521. temp1.divideBy (n, temp2);
  2522. m = n;
  2523. n = temp2;
  2524. }
  2525. return m;
  2526. }
  2527. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2528. {
  2529. BigInteger exp (exponent);
  2530. exp %= modulus;
  2531. BigInteger value (1);
  2532. swapWith (value);
  2533. value %= modulus;
  2534. while (! exp.isZero())
  2535. {
  2536. if (exp [0])
  2537. {
  2538. operator*= (value);
  2539. operator%= (modulus);
  2540. }
  2541. value *= value;
  2542. value %= modulus;
  2543. exp >>= 1;
  2544. }
  2545. }
  2546. void BigInteger::inverseModulo (const BigInteger& modulus)
  2547. {
  2548. if (modulus.isOne() || modulus.isNegative())
  2549. {
  2550. clear();
  2551. return;
  2552. }
  2553. if (isNegative() || compareAbsolute (modulus) >= 0)
  2554. operator%= (modulus);
  2555. if (isOne())
  2556. return;
  2557. if (! (*this)[0])
  2558. {
  2559. // not invertible
  2560. clear();
  2561. return;
  2562. }
  2563. BigInteger a1 (modulus);
  2564. BigInteger a2 (*this);
  2565. BigInteger b1 (modulus);
  2566. BigInteger b2 (1);
  2567. while (! a2.isOne())
  2568. {
  2569. BigInteger temp1, temp2, multiplier (a1);
  2570. multiplier.divideBy (a2, temp1);
  2571. temp1 = a2;
  2572. temp1 *= multiplier;
  2573. temp2 = a1;
  2574. temp2 -= temp1;
  2575. a1 = a2;
  2576. a2 = temp2;
  2577. temp1 = b2;
  2578. temp1 *= multiplier;
  2579. temp2 = b1;
  2580. temp2 -= temp1;
  2581. b1 = b2;
  2582. b2 = temp2;
  2583. }
  2584. while (b2.isNegative())
  2585. b2 += modulus;
  2586. b2 %= modulus;
  2587. swapWith (b2);
  2588. }
  2589. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2590. {
  2591. return stream << value.toString (10);
  2592. }
  2593. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2594. {
  2595. String s;
  2596. BigInteger v (*this);
  2597. if (base == 2 || base == 8 || base == 16)
  2598. {
  2599. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2600. static const char* const hexDigits = "0123456789abcdef";
  2601. for (;;)
  2602. {
  2603. const int remainder = v.getBitRangeAsInt (0, bits);
  2604. v >>= bits;
  2605. if (remainder == 0 && v.isZero())
  2606. break;
  2607. s = String::charToString (hexDigits [remainder]) + s;
  2608. }
  2609. }
  2610. else if (base == 10)
  2611. {
  2612. const BigInteger ten (10);
  2613. BigInteger remainder;
  2614. for (;;)
  2615. {
  2616. v.divideBy (ten, remainder);
  2617. if (remainder.isZero() && v.isZero())
  2618. break;
  2619. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2620. }
  2621. }
  2622. else
  2623. {
  2624. jassertfalse; // can't do the specified base!
  2625. return String::empty;
  2626. }
  2627. s = s.paddedLeft ('0', minimumNumCharacters);
  2628. return isNegative() ? "-" + s : s;
  2629. }
  2630. void BigInteger::parseString (const String& text, const int base)
  2631. {
  2632. clear();
  2633. const juce_wchar* t = text;
  2634. if (base == 2 || base == 8 || base == 16)
  2635. {
  2636. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2637. for (;;)
  2638. {
  2639. const juce_wchar c = *t++;
  2640. const int digit = CharacterFunctions::getHexDigitValue (c);
  2641. if (((unsigned int) digit) < (unsigned int) base)
  2642. {
  2643. operator<<= (bits);
  2644. operator+= (digit);
  2645. }
  2646. else if (c == 0)
  2647. {
  2648. break;
  2649. }
  2650. }
  2651. }
  2652. else if (base == 10)
  2653. {
  2654. const BigInteger ten ((unsigned int) 10);
  2655. for (;;)
  2656. {
  2657. const juce_wchar c = *t++;
  2658. if (c >= '0' && c <= '9')
  2659. {
  2660. operator*= (ten);
  2661. operator+= ((int) (c - '0'));
  2662. }
  2663. else if (c == 0)
  2664. {
  2665. break;
  2666. }
  2667. }
  2668. }
  2669. setNegative (text.trimStart().startsWithChar ('-'));
  2670. }
  2671. const MemoryBlock BigInteger::toMemoryBlock() const
  2672. {
  2673. const int numBytes = (getHighestBit() + 8) >> 3;
  2674. MemoryBlock mb ((size_t) numBytes);
  2675. for (int i = 0; i < numBytes; ++i)
  2676. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2677. return mb;
  2678. }
  2679. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2680. {
  2681. clear();
  2682. for (int i = (int) data.getSize(); --i >= 0;)
  2683. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2684. }
  2685. END_JUCE_NAMESPACE
  2686. /*** End of inlined file: juce_BigInteger.cpp ***/
  2687. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2688. BEGIN_JUCE_NAMESPACE
  2689. MemoryBlock::MemoryBlock() throw()
  2690. : size (0)
  2691. {
  2692. }
  2693. MemoryBlock::MemoryBlock (const size_t initialSize,
  2694. const bool initialiseToZero) throw()
  2695. {
  2696. if (initialSize > 0)
  2697. {
  2698. size = initialSize;
  2699. data.allocate (initialSize, initialiseToZero);
  2700. }
  2701. else
  2702. {
  2703. size = 0;
  2704. }
  2705. }
  2706. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2707. : size (other.size)
  2708. {
  2709. if (size > 0)
  2710. {
  2711. jassert (other.data != 0);
  2712. data.malloc (size);
  2713. memcpy (data, other.data, size);
  2714. }
  2715. }
  2716. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2717. const size_t sizeInBytes) throw()
  2718. : size (jmax ((size_t) 0, sizeInBytes))
  2719. {
  2720. jassert (sizeInBytes >= 0);
  2721. if (size > 0)
  2722. {
  2723. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2724. data.malloc (size);
  2725. if (dataToInitialiseFrom != 0)
  2726. memcpy (data, dataToInitialiseFrom, size);
  2727. }
  2728. }
  2729. MemoryBlock::~MemoryBlock() throw()
  2730. {
  2731. jassert (size >= 0); // should never happen
  2732. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2733. }
  2734. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2735. {
  2736. if (this != &other)
  2737. {
  2738. setSize (other.size, false);
  2739. memcpy (data, other.data, size);
  2740. }
  2741. return *this;
  2742. }
  2743. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2744. {
  2745. return matches (other.data, other.size);
  2746. }
  2747. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2748. {
  2749. return ! operator== (other);
  2750. }
  2751. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2752. {
  2753. return size == dataSize
  2754. && memcmp (data, dataToCompare, size) == 0;
  2755. }
  2756. // this will resize the block to this size
  2757. void MemoryBlock::setSize (const size_t newSize,
  2758. const bool initialiseToZero) throw()
  2759. {
  2760. if (size != newSize)
  2761. {
  2762. if (newSize <= 0)
  2763. {
  2764. data.free();
  2765. size = 0;
  2766. }
  2767. else
  2768. {
  2769. if (data != 0)
  2770. {
  2771. data.realloc (newSize);
  2772. if (initialiseToZero && (newSize > size))
  2773. zeromem (data + size, newSize - size);
  2774. }
  2775. else
  2776. {
  2777. data.allocate (newSize, initialiseToZero);
  2778. }
  2779. size = newSize;
  2780. }
  2781. }
  2782. }
  2783. void MemoryBlock::ensureSize (const size_t minimumSize,
  2784. const bool initialiseToZero) throw()
  2785. {
  2786. if (size < minimumSize)
  2787. setSize (minimumSize, initialiseToZero);
  2788. }
  2789. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2790. {
  2791. swapVariables (size, other.size);
  2792. data.swapWith (other.data);
  2793. }
  2794. void MemoryBlock::fillWith (const uint8 value) throw()
  2795. {
  2796. memset (data, (int) value, size);
  2797. }
  2798. void MemoryBlock::append (const void* const srcData,
  2799. const size_t numBytes) throw()
  2800. {
  2801. if (numBytes > 0)
  2802. {
  2803. const size_t oldSize = size;
  2804. setSize (size + numBytes);
  2805. memcpy (data + oldSize, srcData, numBytes);
  2806. }
  2807. }
  2808. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2809. {
  2810. const char* d = static_cast<const char*> (src);
  2811. if (offset < 0)
  2812. {
  2813. d -= offset;
  2814. num -= offset;
  2815. offset = 0;
  2816. }
  2817. if (offset + num > size)
  2818. num = size - offset;
  2819. if (num > 0)
  2820. memcpy (data + offset, d, num);
  2821. }
  2822. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2823. {
  2824. char* d = static_cast<char*> (dst);
  2825. if (offset < 0)
  2826. {
  2827. zeromem (d, -offset);
  2828. d -= offset;
  2829. num += offset;
  2830. offset = 0;
  2831. }
  2832. if (offset + num > size)
  2833. {
  2834. const size_t newNum = size - offset;
  2835. zeromem (d + newNum, num - newNum);
  2836. num = newNum;
  2837. }
  2838. if (num > 0)
  2839. memcpy (d, data + offset, num);
  2840. }
  2841. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2842. {
  2843. if (startByte < 0)
  2844. {
  2845. numBytesToRemove += startByte;
  2846. startByte = 0;
  2847. }
  2848. if (startByte + numBytesToRemove >= size)
  2849. {
  2850. setSize (startByte);
  2851. }
  2852. else if (numBytesToRemove > 0)
  2853. {
  2854. memmove (data + startByte,
  2855. data + startByte + numBytesToRemove,
  2856. size - (startByte + numBytesToRemove));
  2857. setSize (size - numBytesToRemove);
  2858. }
  2859. }
  2860. const String MemoryBlock::toString() const throw()
  2861. {
  2862. return String (static_cast <const char*> (getData()), size);
  2863. }
  2864. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2865. {
  2866. int res = 0;
  2867. size_t byte = bitRangeStart >> 3;
  2868. int offsetInByte = (int) bitRangeStart & 7;
  2869. size_t bitsSoFar = 0;
  2870. while (numBits > 0 && (size_t) byte < size)
  2871. {
  2872. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2873. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2874. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2875. bitsSoFar += bitsThisTime;
  2876. numBits -= bitsThisTime;
  2877. ++byte;
  2878. offsetInByte = 0;
  2879. }
  2880. return res;
  2881. }
  2882. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2883. {
  2884. size_t byte = bitRangeStart >> 3;
  2885. int offsetInByte = (int) bitRangeStart & 7;
  2886. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2887. while (numBits > 0 && (size_t) byte < size)
  2888. {
  2889. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2890. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2891. const unsigned int tempBits = bitsToSet << offsetInByte;
  2892. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2893. ++byte;
  2894. numBits -= bitsThisTime;
  2895. bitsToSet >>= bitsThisTime;
  2896. mask >>= bitsThisTime;
  2897. offsetInByte = 0;
  2898. }
  2899. }
  2900. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2901. {
  2902. ensureSize (hex.length() >> 1);
  2903. char* dest = data;
  2904. int i = 0;
  2905. for (;;)
  2906. {
  2907. int byte = 0;
  2908. for (int loop = 2; --loop >= 0;)
  2909. {
  2910. byte <<= 4;
  2911. for (;;)
  2912. {
  2913. const juce_wchar c = hex [i++];
  2914. if (c >= '0' && c <= '9')
  2915. {
  2916. byte |= c - '0';
  2917. break;
  2918. }
  2919. else if (c >= 'a' && c <= 'z')
  2920. {
  2921. byte |= c - ('a' - 10);
  2922. break;
  2923. }
  2924. else if (c >= 'A' && c <= 'Z')
  2925. {
  2926. byte |= c - ('A' - 10);
  2927. break;
  2928. }
  2929. else if (c == 0)
  2930. {
  2931. setSize (static_cast <size_t> (dest - data));
  2932. return;
  2933. }
  2934. }
  2935. }
  2936. *dest++ = (char) byte;
  2937. }
  2938. }
  2939. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2940. const String MemoryBlock::toBase64Encoding() const throw()
  2941. {
  2942. const size_t numChars = ((size << 3) + 5) / 6;
  2943. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2944. const int initialLen = destString.length();
  2945. destString.preallocateStorage (initialLen + 2 + numChars);
  2946. juce_wchar* d = destString;
  2947. d += initialLen;
  2948. *d++ = '.';
  2949. for (size_t i = 0; i < numChars; ++i)
  2950. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2951. *d++ = 0;
  2952. return destString;
  2953. }
  2954. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2955. {
  2956. const int startPos = s.indexOfChar ('.') + 1;
  2957. if (startPos <= 0)
  2958. return false;
  2959. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2960. setSize (numBytesNeeded, true);
  2961. const int numChars = s.length() - startPos;
  2962. const juce_wchar* srcChars = s;
  2963. srcChars += startPos;
  2964. int pos = 0;
  2965. for (int i = 0; i < numChars; ++i)
  2966. {
  2967. const char c = (char) srcChars[i];
  2968. for (int j = 0; j < 64; ++j)
  2969. {
  2970. if (encodingTable[j] == c)
  2971. {
  2972. setBitRange (pos, 6, j);
  2973. pos += 6;
  2974. break;
  2975. }
  2976. }
  2977. }
  2978. return true;
  2979. }
  2980. END_JUCE_NAMESPACE
  2981. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2982. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2983. BEGIN_JUCE_NAMESPACE
  2984. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2985. : properties (ignoreCaseOfKeyNames),
  2986. fallbackProperties (0),
  2987. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2988. {
  2989. }
  2990. PropertySet::PropertySet (const PropertySet& other) throw()
  2991. : properties (other.properties),
  2992. fallbackProperties (other.fallbackProperties),
  2993. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2994. {
  2995. }
  2996. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2997. {
  2998. properties = other.properties;
  2999. fallbackProperties = other.fallbackProperties;
  3000. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3001. propertyChanged();
  3002. return *this;
  3003. }
  3004. PropertySet::~PropertySet()
  3005. {
  3006. }
  3007. void PropertySet::clear()
  3008. {
  3009. const ScopedLock sl (lock);
  3010. if (properties.size() > 0)
  3011. {
  3012. properties.clear();
  3013. propertyChanged();
  3014. }
  3015. }
  3016. const String PropertySet::getValue (const String& keyName,
  3017. const String& defaultValue) const throw()
  3018. {
  3019. const ScopedLock sl (lock);
  3020. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3021. if (index >= 0)
  3022. return properties.getAllValues() [index];
  3023. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3024. : defaultValue;
  3025. }
  3026. int PropertySet::getIntValue (const String& keyName,
  3027. const int defaultValue) const throw()
  3028. {
  3029. const ScopedLock sl (lock);
  3030. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3031. if (index >= 0)
  3032. return properties.getAllValues() [index].getIntValue();
  3033. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3034. : defaultValue;
  3035. }
  3036. double PropertySet::getDoubleValue (const String& keyName,
  3037. const double defaultValue) const throw()
  3038. {
  3039. const ScopedLock sl (lock);
  3040. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3041. if (index >= 0)
  3042. return properties.getAllValues()[index].getDoubleValue();
  3043. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3044. : defaultValue;
  3045. }
  3046. bool PropertySet::getBoolValue (const String& keyName,
  3047. const bool defaultValue) const throw()
  3048. {
  3049. const ScopedLock sl (lock);
  3050. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3051. if (index >= 0)
  3052. return properties.getAllValues() [index].getIntValue() != 0;
  3053. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3054. : defaultValue;
  3055. }
  3056. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3057. {
  3058. XmlDocument doc (getValue (keyName));
  3059. return doc.getDocumentElement();
  3060. }
  3061. void PropertySet::setValue (const String& keyName,
  3062. const String& value) throw()
  3063. {
  3064. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3065. if (keyName.isNotEmpty())
  3066. {
  3067. const ScopedLock sl (lock);
  3068. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3069. if (index < 0 || properties.getAllValues() [index] != value)
  3070. {
  3071. properties.set (keyName, value);
  3072. propertyChanged();
  3073. }
  3074. }
  3075. }
  3076. void PropertySet::removeValue (const String& keyName) throw()
  3077. {
  3078. if (keyName.isNotEmpty())
  3079. {
  3080. const ScopedLock sl (lock);
  3081. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3082. if (index >= 0)
  3083. {
  3084. properties.remove (keyName);
  3085. propertyChanged();
  3086. }
  3087. }
  3088. }
  3089. void PropertySet::setValue (const String& keyName, const int value) throw()
  3090. {
  3091. setValue (keyName, String (value));
  3092. }
  3093. void PropertySet::setValue (const String& keyName, const double value) throw()
  3094. {
  3095. setValue (keyName, String (value));
  3096. }
  3097. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3098. {
  3099. setValue (keyName, String (value ? "1" : "0"));
  3100. }
  3101. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3102. {
  3103. setValue (keyName, (xml == 0) ? String::empty
  3104. : xml->createDocument (String::empty, true));
  3105. }
  3106. bool PropertySet::containsKey (const String& keyName) const throw()
  3107. {
  3108. const ScopedLock sl (lock);
  3109. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3110. }
  3111. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3112. {
  3113. const ScopedLock sl (lock);
  3114. fallbackProperties = fallbackProperties_;
  3115. }
  3116. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3117. {
  3118. const ScopedLock sl (lock);
  3119. XmlElement* const xml = new XmlElement (nodeName);
  3120. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3121. {
  3122. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3123. e->setAttribute ("name", properties.getAllKeys()[i]);
  3124. e->setAttribute ("val", properties.getAllValues()[i]);
  3125. }
  3126. return xml;
  3127. }
  3128. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3129. {
  3130. const ScopedLock sl (lock);
  3131. clear();
  3132. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3133. {
  3134. if (e->hasAttribute ("name")
  3135. && e->hasAttribute ("val"))
  3136. {
  3137. properties.set (e->getStringAttribute ("name"),
  3138. e->getStringAttribute ("val"));
  3139. }
  3140. }
  3141. if (properties.size() > 0)
  3142. propertyChanged();
  3143. }
  3144. void PropertySet::propertyChanged()
  3145. {
  3146. }
  3147. END_JUCE_NAMESPACE
  3148. /*** End of inlined file: juce_PropertySet.cpp ***/
  3149. /*** Start of inlined file: juce_Identifier.cpp ***/
  3150. BEGIN_JUCE_NAMESPACE
  3151. StringPool& Identifier::getPool()
  3152. {
  3153. static StringPool pool;
  3154. return pool;
  3155. }
  3156. Identifier::Identifier() throw()
  3157. : name (0)
  3158. {
  3159. }
  3160. Identifier::Identifier (const Identifier& other) throw()
  3161. : name (other.name)
  3162. {
  3163. }
  3164. Identifier& Identifier::operator= (const Identifier& other) throw()
  3165. {
  3166. name = other.name;
  3167. return *this;
  3168. }
  3169. Identifier::Identifier (const String& name_)
  3170. : name (Identifier::getPool().getPooledString (name_))
  3171. {
  3172. /* An Identifier string must be suitable for use as a script variable or XML
  3173. attribute, so it can only contain this limited set of characters.. */
  3174. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3175. }
  3176. Identifier::Identifier (const char* const name_)
  3177. : name (Identifier::getPool().getPooledString (name_))
  3178. {
  3179. /* An Identifier string must be suitable for use as a script variable or XML
  3180. attribute, so it can only contain this limited set of characters.. */
  3181. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3182. }
  3183. Identifier::~Identifier()
  3184. {
  3185. }
  3186. END_JUCE_NAMESPACE
  3187. /*** End of inlined file: juce_Identifier.cpp ***/
  3188. /*** Start of inlined file: juce_Variant.cpp ***/
  3189. BEGIN_JUCE_NAMESPACE
  3190. var::var() throw()
  3191. : type (voidType)
  3192. {
  3193. value.doubleValue = 0;
  3194. }
  3195. var::~var() throw()
  3196. {
  3197. if (type == stringType)
  3198. delete value.stringValue;
  3199. else if (type == objectType && value.objectValue != 0)
  3200. value.objectValue->decReferenceCount();
  3201. }
  3202. const var var::null;
  3203. var::var (const var& valueToCopy)
  3204. : type (valueToCopy.type),
  3205. value (valueToCopy.value)
  3206. {
  3207. if (type == stringType)
  3208. value.stringValue = new String (*(value.stringValue));
  3209. else if (type == objectType && value.objectValue != 0)
  3210. value.objectValue->incReferenceCount();
  3211. }
  3212. var::var (const int value_) throw()
  3213. : type (intType)
  3214. {
  3215. value.intValue = value_;
  3216. }
  3217. var::var (const bool value_) throw()
  3218. : type (boolType)
  3219. {
  3220. value.boolValue = value_;
  3221. }
  3222. var::var (const double value_) throw()
  3223. : type (doubleType)
  3224. {
  3225. value.doubleValue = value_;
  3226. }
  3227. var::var (const String& value_)
  3228. : type (stringType)
  3229. {
  3230. value.stringValue = new String (value_);
  3231. }
  3232. var::var (const char* const value_)
  3233. : type (stringType)
  3234. {
  3235. value.stringValue = new String (value_);
  3236. }
  3237. var::var (const juce_wchar* const value_)
  3238. : type (stringType)
  3239. {
  3240. value.stringValue = new String (value_);
  3241. }
  3242. var::var (DynamicObject* const object)
  3243. : type (objectType)
  3244. {
  3245. value.objectValue = object;
  3246. if (object != 0)
  3247. object->incReferenceCount();
  3248. }
  3249. var::var (MethodFunction method_) throw()
  3250. : type (methodType)
  3251. {
  3252. value.methodValue = method_;
  3253. }
  3254. void var::swapWith (var& other) throw()
  3255. {
  3256. swapVariables (type, other.type);
  3257. swapVariables (value, other.value);
  3258. }
  3259. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3260. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3261. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3262. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3263. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3264. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3265. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3266. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3267. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3268. var::operator int() const
  3269. {
  3270. switch (type)
  3271. {
  3272. case voidType: break;
  3273. case intType: return value.intValue;
  3274. case boolType: return value.boolValue ? 1 : 0;
  3275. case doubleType: return static_cast <int> (value.doubleValue);
  3276. case stringType: return value.stringValue->getIntValue();
  3277. case objectType: break;
  3278. default: jassertfalse; break;
  3279. }
  3280. return 0;
  3281. }
  3282. var::operator bool() const
  3283. {
  3284. switch (type)
  3285. {
  3286. case voidType: break;
  3287. case intType: return value.intValue != 0;
  3288. case boolType: return value.boolValue;
  3289. case doubleType: return value.doubleValue != 0;
  3290. case stringType: return value.stringValue->getIntValue() != 0
  3291. || value.stringValue->trim().equalsIgnoreCase ("true")
  3292. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3293. case objectType: return value.objectValue != 0;
  3294. default: jassertfalse; break;
  3295. }
  3296. return false;
  3297. }
  3298. var::operator float() const
  3299. {
  3300. return (float) operator double();
  3301. }
  3302. var::operator double() const
  3303. {
  3304. switch (type)
  3305. {
  3306. case voidType: break;
  3307. case intType: return value.intValue;
  3308. case boolType: return value.boolValue ? 1.0 : 0.0;
  3309. case doubleType: return value.doubleValue;
  3310. case stringType: return value.stringValue->getDoubleValue();
  3311. case objectType: break;
  3312. default: jassertfalse; break;
  3313. }
  3314. return 0.0;
  3315. }
  3316. const String var::toString() const
  3317. {
  3318. switch (type)
  3319. {
  3320. case voidType: return String::empty;
  3321. case intType: return String (value.intValue);
  3322. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3323. case doubleType: return String (value.doubleValue);
  3324. case stringType: return *(value.stringValue);
  3325. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3326. case methodType: return "Method";
  3327. default: jassertfalse; break;
  3328. }
  3329. return String::empty;
  3330. }
  3331. var::operator const String() const
  3332. {
  3333. return toString();
  3334. }
  3335. DynamicObject* var::getObject() const
  3336. {
  3337. return type == objectType ? value.objectValue : 0;
  3338. }
  3339. bool var::equals (const var& other) const throw()
  3340. {
  3341. switch (type)
  3342. {
  3343. case voidType: return other.isVoid();
  3344. case intType: return value.intValue == static_cast <int> (other);
  3345. case boolType: return value.boolValue == static_cast <bool> (other);
  3346. case doubleType: return value.doubleValue == static_cast <double> (other);
  3347. case stringType: return (*(value.stringValue)) == other.toString();
  3348. case objectType: return value.objectValue == other.getObject();
  3349. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3350. default: jassertfalse; break;
  3351. }
  3352. return false;
  3353. }
  3354. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3355. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3356. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3357. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3358. void var::writeToStream (OutputStream& output) const
  3359. {
  3360. switch (type)
  3361. {
  3362. case voidType: output.writeCompressedInt (0); break;
  3363. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3364. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3365. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3366. case stringType:
  3367. {
  3368. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3369. output.writeCompressedInt (len + 1);
  3370. output.writeByte (5);
  3371. HeapBlock<char> temp (len);
  3372. value.stringValue->copyToUTF8 (temp, len);
  3373. output.write (temp, len);
  3374. break;
  3375. }
  3376. case objectType:
  3377. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3378. default: jassertfalse; break; // Is this a corrupted object?
  3379. }
  3380. }
  3381. const var var::readFromStream (InputStream& input)
  3382. {
  3383. const int numBytes = input.readCompressedInt();
  3384. if (numBytes > 0)
  3385. {
  3386. switch (input.readByte())
  3387. {
  3388. case 1: return var (input.readInt());
  3389. case 2: return var (true);
  3390. case 3: return var (false);
  3391. case 4: return var (input.readDouble());
  3392. case 5:
  3393. {
  3394. MemoryBlock mb;
  3395. input.readIntoMemoryBlock (mb, numBytes - 1);
  3396. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3397. }
  3398. default: input.skipNextBytes (numBytes - 1); break;
  3399. }
  3400. }
  3401. return var::null;
  3402. }
  3403. const var var::operator[] (const Identifier& propertyName) const
  3404. {
  3405. if (type == objectType && value.objectValue != 0)
  3406. return value.objectValue->getProperty (propertyName);
  3407. return var::null;
  3408. }
  3409. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3410. {
  3411. if (type == objectType && value.objectValue != 0)
  3412. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3413. return var::null;
  3414. }
  3415. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3416. {
  3417. if (isMethod())
  3418. {
  3419. DynamicObject* const target = targetObject.getObject();
  3420. if (target != 0)
  3421. return (target->*(value.methodValue)) (arguments, numArguments);
  3422. }
  3423. return var::null;
  3424. }
  3425. const var var::call (const Identifier& method) const
  3426. {
  3427. return invoke (method, 0, 0);
  3428. }
  3429. const var var::call (const Identifier& method, const var& arg1) const
  3430. {
  3431. return invoke (method, &arg1, 1);
  3432. }
  3433. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3434. {
  3435. var args[] = { arg1, arg2 };
  3436. return invoke (method, args, 2);
  3437. }
  3438. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3439. {
  3440. var args[] = { arg1, arg2, arg3 };
  3441. return invoke (method, args, 3);
  3442. }
  3443. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3444. {
  3445. var args[] = { arg1, arg2, arg3, arg4 };
  3446. return invoke (method, args, 4);
  3447. }
  3448. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3449. {
  3450. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3451. return invoke (method, args, 5);
  3452. }
  3453. END_JUCE_NAMESPACE
  3454. /*** End of inlined file: juce_Variant.cpp ***/
  3455. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3456. BEGIN_JUCE_NAMESPACE
  3457. NamedValueSet::NamedValue::NamedValue() throw()
  3458. {
  3459. }
  3460. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3461. : name (name_), value (value_)
  3462. {
  3463. }
  3464. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3465. {
  3466. return name == other.name && value == other.value;
  3467. }
  3468. NamedValueSet::NamedValueSet() throw()
  3469. {
  3470. }
  3471. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3472. : values (other.values)
  3473. {
  3474. }
  3475. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3476. {
  3477. values = other.values;
  3478. return *this;
  3479. }
  3480. NamedValueSet::~NamedValueSet()
  3481. {
  3482. }
  3483. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3484. {
  3485. return values == other.values;
  3486. }
  3487. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3488. {
  3489. return ! operator== (other);
  3490. }
  3491. int NamedValueSet::size() const throw()
  3492. {
  3493. return values.size();
  3494. }
  3495. const var& NamedValueSet::operator[] (const Identifier& name) const
  3496. {
  3497. for (int i = values.size(); --i >= 0;)
  3498. {
  3499. const NamedValue& v = values.getReference(i);
  3500. if (v.name == name)
  3501. return v.value;
  3502. }
  3503. return var::null;
  3504. }
  3505. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3506. {
  3507. const var* v = getItem (name);
  3508. return v != 0 ? *v : defaultReturnValue;
  3509. }
  3510. var* NamedValueSet::getItem (const Identifier& name) const
  3511. {
  3512. for (int i = values.size(); --i >= 0;)
  3513. {
  3514. NamedValue& v = values.getReference(i);
  3515. if (v.name == name)
  3516. return &(v.value);
  3517. }
  3518. return 0;
  3519. }
  3520. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3521. {
  3522. for (int i = values.size(); --i >= 0;)
  3523. {
  3524. NamedValue& v = values.getReference(i);
  3525. if (v.name == name)
  3526. {
  3527. if (v.value == newValue)
  3528. return false;
  3529. v.value = newValue;
  3530. return true;
  3531. }
  3532. }
  3533. values.add (NamedValue (name, newValue));
  3534. return true;
  3535. }
  3536. bool NamedValueSet::contains (const Identifier& name) const
  3537. {
  3538. return getItem (name) != 0;
  3539. }
  3540. bool NamedValueSet::remove (const Identifier& name)
  3541. {
  3542. for (int i = values.size(); --i >= 0;)
  3543. {
  3544. if (values.getReference(i).name == name)
  3545. {
  3546. values.remove (i);
  3547. return true;
  3548. }
  3549. }
  3550. return false;
  3551. }
  3552. const Identifier NamedValueSet::getName (const int index) const
  3553. {
  3554. jassert (((unsigned int) index) < (unsigned int) values.size());
  3555. return values [index].name;
  3556. }
  3557. const var NamedValueSet::getValueAt (const int index) const
  3558. {
  3559. jassert (((unsigned int) index) < (unsigned int) values.size());
  3560. return values [index].value;
  3561. }
  3562. void NamedValueSet::clear()
  3563. {
  3564. values.clear();
  3565. }
  3566. END_JUCE_NAMESPACE
  3567. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3568. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3569. BEGIN_JUCE_NAMESPACE
  3570. DynamicObject::DynamicObject()
  3571. {
  3572. }
  3573. DynamicObject::~DynamicObject()
  3574. {
  3575. }
  3576. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3577. {
  3578. var* const v = properties.getItem (propertyName);
  3579. return v != 0 && ! v->isMethod();
  3580. }
  3581. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3582. {
  3583. return properties [propertyName];
  3584. }
  3585. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3586. {
  3587. properties.set (propertyName, newValue);
  3588. }
  3589. void DynamicObject::removeProperty (const Identifier& propertyName)
  3590. {
  3591. properties.remove (propertyName);
  3592. }
  3593. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3594. {
  3595. return getProperty (methodName).isMethod();
  3596. }
  3597. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3598. const var* parameters,
  3599. int numParameters)
  3600. {
  3601. return properties [methodName].invoke (var (this), parameters, numParameters);
  3602. }
  3603. void DynamicObject::setMethod (const Identifier& name,
  3604. var::MethodFunction methodFunction)
  3605. {
  3606. properties.set (name, var (methodFunction));
  3607. }
  3608. void DynamicObject::clear()
  3609. {
  3610. properties.clear();
  3611. }
  3612. END_JUCE_NAMESPACE
  3613. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3614. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3615. BEGIN_JUCE_NAMESPACE
  3616. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3617. {
  3618. jassert (keyData != 0);
  3619. jassert (keyBytes > 0);
  3620. static const uint32 initialPValues [18] =
  3621. {
  3622. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3623. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3624. 0x9216d5d9, 0x8979fb1b
  3625. };
  3626. static const uint32 initialSValues [4 * 256] =
  3627. {
  3628. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3629. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3630. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3631. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3632. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3633. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3634. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3635. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3636. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3637. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3638. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3639. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3640. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3641. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3642. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3643. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3644. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3645. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3646. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3647. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3648. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3649. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3650. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3651. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3652. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3653. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3654. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3655. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3656. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3657. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3658. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3659. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3660. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3661. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3662. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3663. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3664. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3665. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3666. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3667. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3668. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3669. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3670. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3671. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3672. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3673. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3674. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3675. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3676. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3677. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3678. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3679. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3680. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3681. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3682. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3683. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3684. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3685. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3686. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3687. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3688. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3689. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3690. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3691. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3692. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3693. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3694. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3695. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3696. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3697. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3698. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3699. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3700. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3701. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3702. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3703. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3704. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3705. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3706. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3707. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3708. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3709. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3710. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3711. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3712. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3713. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3714. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3715. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3716. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3717. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3718. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3719. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3720. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3721. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3722. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3723. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3724. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3725. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3726. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3727. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3728. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3729. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3730. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3731. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3732. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3733. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3734. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3735. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3736. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3737. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3738. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3739. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3740. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3741. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3742. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3743. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3744. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3745. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3746. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3747. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3748. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3749. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3750. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3751. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3752. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3753. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3754. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3755. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3756. };
  3757. memcpy (p, initialPValues, sizeof (p));
  3758. int i, j = 0;
  3759. for (i = 4; --i >= 0;)
  3760. {
  3761. s[i].malloc (256);
  3762. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3763. }
  3764. for (i = 0; i < 18; ++i)
  3765. {
  3766. uint32 d = 0;
  3767. for (int k = 0; k < 4; ++k)
  3768. {
  3769. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3770. if (++j >= keyBytes)
  3771. j = 0;
  3772. }
  3773. p[i] = initialPValues[i] ^ d;
  3774. }
  3775. uint32 l = 0, r = 0;
  3776. for (i = 0; i < 18; i += 2)
  3777. {
  3778. encrypt (l, r);
  3779. p[i] = l;
  3780. p[i + 1] = r;
  3781. }
  3782. for (i = 0; i < 4; ++i)
  3783. {
  3784. for (j = 0; j < 256; j += 2)
  3785. {
  3786. encrypt (l, r);
  3787. s[i][j] = l;
  3788. s[i][j + 1] = r;
  3789. }
  3790. }
  3791. }
  3792. BlowFish::BlowFish (const BlowFish& other)
  3793. {
  3794. for (int i = 4; --i >= 0;)
  3795. s[i].malloc (256);
  3796. operator= (other);
  3797. }
  3798. BlowFish& BlowFish::operator= (const BlowFish& other)
  3799. {
  3800. memcpy (p, other.p, sizeof (p));
  3801. for (int i = 4; --i >= 0;)
  3802. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3803. return *this;
  3804. }
  3805. BlowFish::~BlowFish()
  3806. {
  3807. }
  3808. uint32 BlowFish::F (const uint32 x) const throw()
  3809. {
  3810. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3811. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3812. }
  3813. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3814. {
  3815. uint32 l = data1;
  3816. uint32 r = data2;
  3817. for (int i = 0; i < 16; ++i)
  3818. {
  3819. l ^= p[i];
  3820. r ^= F(l);
  3821. swapVariables (l, r);
  3822. }
  3823. data1 = r ^ p[17];
  3824. data2 = l ^ p[16];
  3825. }
  3826. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3827. {
  3828. uint32 l = data1;
  3829. uint32 r = data2;
  3830. for (int i = 17; i > 1; --i)
  3831. {
  3832. l ^= p[i];
  3833. r ^= F(l);
  3834. swapVariables (l, r);
  3835. }
  3836. data1 = r ^ p[0];
  3837. data2 = l ^ p[1];
  3838. }
  3839. END_JUCE_NAMESPACE
  3840. /*** End of inlined file: juce_BlowFish.cpp ***/
  3841. /*** Start of inlined file: juce_MD5.cpp ***/
  3842. BEGIN_JUCE_NAMESPACE
  3843. MD5::MD5()
  3844. {
  3845. zerostruct (result);
  3846. }
  3847. MD5::MD5 (const MD5& other)
  3848. {
  3849. memcpy (result, other.result, sizeof (result));
  3850. }
  3851. MD5& MD5::operator= (const MD5& other)
  3852. {
  3853. memcpy (result, other.result, sizeof (result));
  3854. return *this;
  3855. }
  3856. MD5::MD5 (const MemoryBlock& data)
  3857. {
  3858. ProcessContext context;
  3859. context.processBlock (data.getData(), data.getSize());
  3860. context.finish (result);
  3861. }
  3862. MD5::MD5 (const void* data, const size_t numBytes)
  3863. {
  3864. ProcessContext context;
  3865. context.processBlock (data, numBytes);
  3866. context.finish (result);
  3867. }
  3868. MD5::MD5 (const String& text)
  3869. {
  3870. ProcessContext context;
  3871. const int len = text.length();
  3872. const juce_wchar* const t = text;
  3873. for (int i = 0; i < len; ++i)
  3874. {
  3875. // force the string into integer-sized unicode characters, to try to make it
  3876. // get the same results on all platforms + compilers.
  3877. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3878. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3879. }
  3880. context.finish (result);
  3881. }
  3882. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3883. {
  3884. ProcessContext context;
  3885. if (numBytesToRead < 0)
  3886. numBytesToRead = std::numeric_limits<int64>::max();
  3887. while (numBytesToRead > 0)
  3888. {
  3889. uint8 tempBuffer [512];
  3890. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3891. if (bytesRead <= 0)
  3892. break;
  3893. numBytesToRead -= bytesRead;
  3894. context.processBlock (tempBuffer, bytesRead);
  3895. }
  3896. context.finish (result);
  3897. }
  3898. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3899. {
  3900. processStream (input, numBytesToRead);
  3901. }
  3902. MD5::MD5 (const File& file)
  3903. {
  3904. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3905. if (fin != 0)
  3906. processStream (*fin, -1);
  3907. else
  3908. zerostruct (result);
  3909. }
  3910. MD5::~MD5()
  3911. {
  3912. }
  3913. namespace MD5Functions
  3914. {
  3915. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3916. {
  3917. for (int i = 0; i < (numBytes >> 2); ++i)
  3918. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3919. }
  3920. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3921. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3922. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3923. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3924. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3925. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3926. {
  3927. a += F (b, c, d) + x + ac;
  3928. a = rotateLeft (a, s) + b;
  3929. }
  3930. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3931. {
  3932. a += G (b, c, d) + x + ac;
  3933. a = rotateLeft (a, s) + b;
  3934. }
  3935. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3936. {
  3937. a += H (b, c, d) + x + ac;
  3938. a = rotateLeft (a, s) + b;
  3939. }
  3940. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3941. {
  3942. a += I (b, c, d) + x + ac;
  3943. a = rotateLeft (a, s) + b;
  3944. }
  3945. }
  3946. MD5::ProcessContext::ProcessContext()
  3947. {
  3948. state[0] = 0x67452301;
  3949. state[1] = 0xefcdab89;
  3950. state[2] = 0x98badcfe;
  3951. state[3] = 0x10325476;
  3952. count[0] = 0;
  3953. count[1] = 0;
  3954. }
  3955. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3956. {
  3957. int bufferPos = ((count[0] >> 3) & 0x3F);
  3958. count[0] += (uint32) (dataSize << 3);
  3959. if (count[0] < ((uint32) dataSize << 3))
  3960. count[1]++;
  3961. count[1] += (uint32) (dataSize >> 29);
  3962. const size_t spaceLeft = 64 - bufferPos;
  3963. size_t i = 0;
  3964. if (dataSize >= spaceLeft)
  3965. {
  3966. memcpy (buffer + bufferPos, data, spaceLeft);
  3967. transform (buffer);
  3968. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3969. transform (static_cast <const char*> (data) + i);
  3970. bufferPos = 0;
  3971. }
  3972. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3973. }
  3974. void MD5::ProcessContext::finish (void* const result)
  3975. {
  3976. unsigned char encodedLength[8];
  3977. MD5Functions::encode (encodedLength, count, 8);
  3978. // Pad out to 56 mod 64.
  3979. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3980. const int paddingLength = (index < 56) ? (56 - index)
  3981. : (120 - index);
  3982. uint8 paddingBuffer [64];
  3983. zeromem (paddingBuffer, paddingLength);
  3984. paddingBuffer [0] = 0x80;
  3985. processBlock (paddingBuffer, paddingLength);
  3986. processBlock (encodedLength, 8);
  3987. MD5Functions::encode (result, state, 16);
  3988. zerostruct (buffer);
  3989. }
  3990. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3991. {
  3992. using namespace MD5Functions;
  3993. uint32 a = state[0];
  3994. uint32 b = state[1];
  3995. uint32 c = state[2];
  3996. uint32 d = state[3];
  3997. uint32 x[16];
  3998. encode (x, bufferToTransform, 64);
  3999. enum Constants
  4000. {
  4001. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4002. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4003. };
  4004. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4005. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4006. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4007. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4008. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4009. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4010. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4011. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4012. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4013. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4014. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4015. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4016. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4017. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4018. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4019. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4020. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4021. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4022. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4023. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4024. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4025. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4026. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4027. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4028. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4029. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4030. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4031. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4032. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4033. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4034. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4035. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4036. state[0] += a;
  4037. state[1] += b;
  4038. state[2] += c;
  4039. state[3] += d;
  4040. zerostruct (x);
  4041. }
  4042. const MemoryBlock MD5::getRawChecksumData() const
  4043. {
  4044. return MemoryBlock (result, sizeof (result));
  4045. }
  4046. const String MD5::toHexString() const
  4047. {
  4048. return String::toHexString (result, sizeof (result), 0);
  4049. }
  4050. bool MD5::operator== (const MD5& other) const
  4051. {
  4052. return memcmp (result, other.result, sizeof (result)) == 0;
  4053. }
  4054. bool MD5::operator!= (const MD5& other) const
  4055. {
  4056. return ! operator== (other);
  4057. }
  4058. END_JUCE_NAMESPACE
  4059. /*** End of inlined file: juce_MD5.cpp ***/
  4060. /*** Start of inlined file: juce_Primes.cpp ***/
  4061. BEGIN_JUCE_NAMESPACE
  4062. namespace PrimesHelpers
  4063. {
  4064. static void createSmallSieve (const int numBits, BigInteger& result)
  4065. {
  4066. result.setBit (numBits);
  4067. result.clearBit (numBits); // to enlarge the array
  4068. result.setBit (0);
  4069. int n = 2;
  4070. do
  4071. {
  4072. for (int i = n + n; i < numBits; i += n)
  4073. result.setBit (i);
  4074. n = result.findNextClearBit (n + 1);
  4075. }
  4076. while (n <= (numBits >> 1));
  4077. }
  4078. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4079. const BigInteger& smallSieve, const int smallSieveSize)
  4080. {
  4081. jassert (! base[0]); // must be even!
  4082. result.setBit (numBits);
  4083. result.clearBit (numBits); // to enlarge the array
  4084. int index = smallSieve.findNextClearBit (0);
  4085. do
  4086. {
  4087. const int prime = (index << 1) + 1;
  4088. BigInteger r (base), remainder;
  4089. r.divideBy (prime, remainder);
  4090. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4091. if (r.isZero())
  4092. i += prime;
  4093. if ((i & 1) == 0)
  4094. i += prime;
  4095. i = (i - 1) >> 1;
  4096. while (i < numBits)
  4097. {
  4098. result.setBit (i);
  4099. i += prime;
  4100. }
  4101. index = smallSieve.findNextClearBit (index + 1);
  4102. }
  4103. while (index < smallSieveSize);
  4104. }
  4105. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4106. const int numBits, BigInteger& result, const int certainty)
  4107. {
  4108. for (int i = 0; i < numBits; ++i)
  4109. {
  4110. if (! sieve[i])
  4111. {
  4112. result = base + (unsigned int) ((i << 1) + 1);
  4113. if (Primes::isProbablyPrime (result, certainty))
  4114. return true;
  4115. }
  4116. }
  4117. return false;
  4118. }
  4119. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4120. {
  4121. const BigInteger one (1), two (2);
  4122. const BigInteger nMinusOne (n - one);
  4123. BigInteger d (nMinusOne);
  4124. const int s = d.findNextSetBit (0);
  4125. d >>= s;
  4126. BigInteger smallPrimes;
  4127. int numBitsInSmallPrimes = 0;
  4128. for (;;)
  4129. {
  4130. numBitsInSmallPrimes += 256;
  4131. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4132. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4133. if (numPrimesFound > iterations + 1)
  4134. break;
  4135. }
  4136. int smallPrime = 2;
  4137. while (--iterations >= 0)
  4138. {
  4139. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4140. BigInteger r (smallPrime);
  4141. r.exponentModulo (d, n);
  4142. if (r != one && r != nMinusOne)
  4143. {
  4144. for (int j = 0; j < s; ++j)
  4145. {
  4146. r.exponentModulo (two, n);
  4147. if (r == nMinusOne)
  4148. break;
  4149. }
  4150. if (r != nMinusOne)
  4151. return false;
  4152. }
  4153. }
  4154. return true;
  4155. }
  4156. }
  4157. const BigInteger Primes::createProbablePrime (const int bitLength,
  4158. const int certainty,
  4159. const int* randomSeeds,
  4160. int numRandomSeeds)
  4161. {
  4162. using namespace PrimesHelpers;
  4163. int defaultSeeds [16];
  4164. if (numRandomSeeds <= 0)
  4165. {
  4166. randomSeeds = defaultSeeds;
  4167. numRandomSeeds = numElementsInArray (defaultSeeds);
  4168. Random r (0);
  4169. for (int j = 10; --j >= 0;)
  4170. {
  4171. r.setSeedRandomly();
  4172. for (int i = numRandomSeeds; --i >= 0;)
  4173. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4174. }
  4175. }
  4176. BigInteger smallSieve;
  4177. const int smallSieveSize = 15000;
  4178. createSmallSieve (smallSieveSize, smallSieve);
  4179. BigInteger p;
  4180. for (int i = numRandomSeeds; --i >= 0;)
  4181. {
  4182. BigInteger p2;
  4183. Random r (randomSeeds[i]);
  4184. r.fillBitsRandomly (p2, 0, bitLength);
  4185. p ^= p2;
  4186. }
  4187. p.setBit (bitLength - 1);
  4188. p.clearBit (0);
  4189. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4190. while (p.getHighestBit() < bitLength)
  4191. {
  4192. p += 2 * searchLen;
  4193. BigInteger sieve;
  4194. bigSieve (p, searchLen, sieve,
  4195. smallSieve, smallSieveSize);
  4196. BigInteger candidate;
  4197. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4198. return candidate;
  4199. }
  4200. jassertfalse;
  4201. return BigInteger();
  4202. }
  4203. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4204. {
  4205. using namespace PrimesHelpers;
  4206. if (! number[0])
  4207. return false;
  4208. if (number.getHighestBit() <= 10)
  4209. {
  4210. const int num = number.getBitRangeAsInt (0, 10);
  4211. for (int i = num / 2; --i > 1;)
  4212. if (num % i == 0)
  4213. return false;
  4214. return true;
  4215. }
  4216. else
  4217. {
  4218. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4219. return false;
  4220. return passesMillerRabin (number, certainty);
  4221. }
  4222. }
  4223. END_JUCE_NAMESPACE
  4224. /*** End of inlined file: juce_Primes.cpp ***/
  4225. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4226. BEGIN_JUCE_NAMESPACE
  4227. RSAKey::RSAKey()
  4228. {
  4229. }
  4230. RSAKey::RSAKey (const String& s)
  4231. {
  4232. if (s.containsChar (','))
  4233. {
  4234. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4235. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4236. }
  4237. else
  4238. {
  4239. // the string needs to be two hex numbers, comma-separated..
  4240. jassertfalse;
  4241. }
  4242. }
  4243. RSAKey::~RSAKey()
  4244. {
  4245. }
  4246. bool RSAKey::operator== (const RSAKey& other) const throw()
  4247. {
  4248. return part1 == other.part1 && part2 == other.part2;
  4249. }
  4250. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4251. {
  4252. return ! operator== (other);
  4253. }
  4254. const String RSAKey::toString() const
  4255. {
  4256. return part1.toString (16) + "," + part2.toString (16);
  4257. }
  4258. bool RSAKey::applyToValue (BigInteger& value) const
  4259. {
  4260. if (part1.isZero() || part2.isZero() || value <= 0)
  4261. {
  4262. jassertfalse; // using an uninitialised key
  4263. value.clear();
  4264. return false;
  4265. }
  4266. BigInteger result;
  4267. while (! value.isZero())
  4268. {
  4269. result *= part2;
  4270. BigInteger remainder;
  4271. value.divideBy (part2, remainder);
  4272. remainder.exponentModulo (part1, part2);
  4273. result += remainder;
  4274. }
  4275. value.swapWith (result);
  4276. return true;
  4277. }
  4278. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4279. {
  4280. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4281. // are fast to divide + multiply
  4282. for (int i = 2; i <= 65536; i *= 2)
  4283. {
  4284. const BigInteger e (1 + i);
  4285. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4286. return e;
  4287. }
  4288. BigInteger e (4);
  4289. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4290. ++e;
  4291. return e;
  4292. }
  4293. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4294. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4295. {
  4296. jassert (numBits > 16); // not much point using less than this..
  4297. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4298. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4299. const BigInteger n (p * q);
  4300. const BigInteger m (--p * --q);
  4301. const BigInteger e (findBestCommonDivisor (p, q));
  4302. BigInteger d (e);
  4303. d.inverseModulo (m);
  4304. publicKey.part1 = e;
  4305. publicKey.part2 = n;
  4306. privateKey.part1 = d;
  4307. privateKey.part2 = n;
  4308. }
  4309. END_JUCE_NAMESPACE
  4310. /*** End of inlined file: juce_RSAKey.cpp ***/
  4311. /*** Start of inlined file: juce_InputStream.cpp ***/
  4312. BEGIN_JUCE_NAMESPACE
  4313. char InputStream::readByte()
  4314. {
  4315. char temp = 0;
  4316. read (&temp, 1);
  4317. return temp;
  4318. }
  4319. bool InputStream::readBool()
  4320. {
  4321. return readByte() != 0;
  4322. }
  4323. short InputStream::readShort()
  4324. {
  4325. char temp[2];
  4326. if (read (temp, 2) == 2)
  4327. return (short) ByteOrder::littleEndianShort (temp);
  4328. return 0;
  4329. }
  4330. short InputStream::readShortBigEndian()
  4331. {
  4332. char temp[2];
  4333. if (read (temp, 2) == 2)
  4334. return (short) ByteOrder::bigEndianShort (temp);
  4335. return 0;
  4336. }
  4337. int InputStream::readInt()
  4338. {
  4339. char temp[4];
  4340. if (read (temp, 4) == 4)
  4341. return (int) ByteOrder::littleEndianInt (temp);
  4342. return 0;
  4343. }
  4344. int InputStream::readIntBigEndian()
  4345. {
  4346. char temp[4];
  4347. if (read (temp, 4) == 4)
  4348. return (int) ByteOrder::bigEndianInt (temp);
  4349. return 0;
  4350. }
  4351. int InputStream::readCompressedInt()
  4352. {
  4353. const unsigned char sizeByte = readByte();
  4354. if (sizeByte == 0)
  4355. return 0;
  4356. const int numBytes = (sizeByte & 0x7f);
  4357. if (numBytes > 4)
  4358. {
  4359. jassertfalse; // trying to read corrupt data - this method must only be used
  4360. // to read data that was written by OutputStream::writeCompressedInt()
  4361. return 0;
  4362. }
  4363. char bytes[4] = { 0, 0, 0, 0 };
  4364. if (read (bytes, numBytes) != numBytes)
  4365. return 0;
  4366. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4367. return (sizeByte >> 7) ? -num : num;
  4368. }
  4369. int64 InputStream::readInt64()
  4370. {
  4371. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4372. if (read (n.asBytes, 8) == 8)
  4373. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4374. return 0;
  4375. }
  4376. int64 InputStream::readInt64BigEndian()
  4377. {
  4378. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4379. if (read (n.asBytes, 8) == 8)
  4380. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4381. return 0;
  4382. }
  4383. float InputStream::readFloat()
  4384. {
  4385. // the union below relies on these types being the same size...
  4386. static_jassert (sizeof (int32) == sizeof (float));
  4387. union { int32 asInt; float asFloat; } n;
  4388. n.asInt = (int32) readInt();
  4389. return n.asFloat;
  4390. }
  4391. float InputStream::readFloatBigEndian()
  4392. {
  4393. union { int32 asInt; float asFloat; } n;
  4394. n.asInt = (int32) readIntBigEndian();
  4395. return n.asFloat;
  4396. }
  4397. double InputStream::readDouble()
  4398. {
  4399. union { int64 asInt; double asDouble; } n;
  4400. n.asInt = readInt64();
  4401. return n.asDouble;
  4402. }
  4403. double InputStream::readDoubleBigEndian()
  4404. {
  4405. union { int64 asInt; double asDouble; } n;
  4406. n.asInt = readInt64BigEndian();
  4407. return n.asDouble;
  4408. }
  4409. const String InputStream::readString()
  4410. {
  4411. MemoryBlock buffer (256);
  4412. char* data = static_cast<char*> (buffer.getData());
  4413. size_t i = 0;
  4414. while ((data[i] = readByte()) != 0)
  4415. {
  4416. if (++i >= buffer.getSize())
  4417. {
  4418. buffer.setSize (buffer.getSize() + 512);
  4419. data = static_cast<char*> (buffer.getData());
  4420. }
  4421. }
  4422. return String::fromUTF8 (data, (int) i);
  4423. }
  4424. const String InputStream::readNextLine()
  4425. {
  4426. MemoryBlock buffer (256);
  4427. char* data = static_cast<char*> (buffer.getData());
  4428. size_t i = 0;
  4429. while ((data[i] = readByte()) != 0)
  4430. {
  4431. if (data[i] == '\n')
  4432. break;
  4433. if (data[i] == '\r')
  4434. {
  4435. const int64 lastPos = getPosition();
  4436. if (readByte() != '\n')
  4437. setPosition (lastPos);
  4438. break;
  4439. }
  4440. if (++i >= buffer.getSize())
  4441. {
  4442. buffer.setSize (buffer.getSize() + 512);
  4443. data = static_cast<char*> (buffer.getData());
  4444. }
  4445. }
  4446. return String::fromUTF8 (data, (int) i);
  4447. }
  4448. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4449. {
  4450. const int64 totalLength = getTotalLength();
  4451. if (totalLength >= 0)
  4452. {
  4453. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4454. totalLength - getPosition());
  4455. if (numBytes < 0)
  4456. numBytes = totalBytesRemaining;
  4457. else if (numBytes > 0)
  4458. numBytes = jmin (numBytes, totalBytesRemaining);
  4459. else
  4460. return 0;
  4461. }
  4462. const size_t originalBlockSize = block.getSize();
  4463. int totalBytesRead = 0;
  4464. if (numBytes > 0)
  4465. {
  4466. // know how many bytes we want, so we can resize the block first..
  4467. block.setSize (originalBlockSize + numBytes, false);
  4468. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4469. }
  4470. else
  4471. {
  4472. // read until end of stram..
  4473. const int chunkSize = 32768;
  4474. for (;;)
  4475. {
  4476. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4477. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4478. + originalBlockSize
  4479. + totalBytesRead,
  4480. chunkSize);
  4481. if (bytesJustIn == 0)
  4482. break;
  4483. totalBytesRead += bytesJustIn;
  4484. }
  4485. }
  4486. // trim off any excess left at the end
  4487. block.setSize (originalBlockSize + totalBytesRead, false);
  4488. return totalBytesRead;
  4489. }
  4490. const String InputStream::readEntireStreamAsString()
  4491. {
  4492. MemoryBlock mb;
  4493. const int size = readIntoMemoryBlock (mb);
  4494. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4495. }
  4496. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4497. {
  4498. if (numBytesToSkip > 0)
  4499. {
  4500. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4501. HeapBlock<char> temp (skipBufferSize);
  4502. while (numBytesToSkip > 0 && ! isExhausted())
  4503. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4504. }
  4505. }
  4506. END_JUCE_NAMESPACE
  4507. /*** End of inlined file: juce_InputStream.cpp ***/
  4508. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4509. BEGIN_JUCE_NAMESPACE
  4510. #if JUCE_DEBUG
  4511. static CriticalSection activeStreamLock;
  4512. static Array<void*> activeStreams;
  4513. void juce_CheckForDanglingStreams()
  4514. {
  4515. /*
  4516. It's always a bad idea to leak any object, but if you're leaking output
  4517. streams, then there's a good chance that you're failing to flush a file
  4518. to disk properly, which could result in corrupted data and other similar
  4519. nastiness..
  4520. */
  4521. jassert (activeStreams.size() == 0);
  4522. };
  4523. #endif
  4524. OutputStream::OutputStream()
  4525. {
  4526. #if JUCE_DEBUG
  4527. const ScopedLock sl (activeStreamLock);
  4528. activeStreams.add (this);
  4529. #endif
  4530. }
  4531. OutputStream::~OutputStream()
  4532. {
  4533. #if JUCE_DEBUG
  4534. const ScopedLock sl (activeStreamLock);
  4535. activeStreams.removeValue (this);
  4536. #endif
  4537. }
  4538. void OutputStream::writeBool (const bool b)
  4539. {
  4540. writeByte (b ? (char) 1
  4541. : (char) 0);
  4542. }
  4543. void OutputStream::writeByte (char byte)
  4544. {
  4545. write (&byte, 1);
  4546. }
  4547. void OutputStream::writeShort (short value)
  4548. {
  4549. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4550. write (&v, 2);
  4551. }
  4552. void OutputStream::writeShortBigEndian (short value)
  4553. {
  4554. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4555. write (&v, 2);
  4556. }
  4557. void OutputStream::writeInt (int value)
  4558. {
  4559. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4560. write (&v, 4);
  4561. }
  4562. void OutputStream::writeIntBigEndian (int value)
  4563. {
  4564. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4565. write (&v, 4);
  4566. }
  4567. void OutputStream::writeCompressedInt (int value)
  4568. {
  4569. unsigned int un = (value < 0) ? (unsigned int) -value
  4570. : (unsigned int) value;
  4571. uint8 data[5];
  4572. int num = 0;
  4573. while (un > 0)
  4574. {
  4575. data[++num] = (uint8) un;
  4576. un >>= 8;
  4577. }
  4578. data[0] = (uint8) num;
  4579. if (value < 0)
  4580. data[0] |= 0x80;
  4581. write (data, num + 1);
  4582. }
  4583. void OutputStream::writeInt64 (int64 value)
  4584. {
  4585. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4586. write (&v, 8);
  4587. }
  4588. void OutputStream::writeInt64BigEndian (int64 value)
  4589. {
  4590. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4591. write (&v, 8);
  4592. }
  4593. void OutputStream::writeFloat (float value)
  4594. {
  4595. union { int asInt; float asFloat; } n;
  4596. n.asFloat = value;
  4597. writeInt (n.asInt);
  4598. }
  4599. void OutputStream::writeFloatBigEndian (float value)
  4600. {
  4601. union { int asInt; float asFloat; } n;
  4602. n.asFloat = value;
  4603. writeIntBigEndian (n.asInt);
  4604. }
  4605. void OutputStream::writeDouble (double value)
  4606. {
  4607. union { int64 asInt; double asDouble; } n;
  4608. n.asDouble = value;
  4609. writeInt64 (n.asInt);
  4610. }
  4611. void OutputStream::writeDoubleBigEndian (double value)
  4612. {
  4613. union { int64 asInt; double asDouble; } n;
  4614. n.asDouble = value;
  4615. writeInt64BigEndian (n.asInt);
  4616. }
  4617. void OutputStream::writeString (const String& text)
  4618. {
  4619. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4620. // if lots of large, persistent strings were to be written to streams).
  4621. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4622. HeapBlock<char> temp (numBytes);
  4623. text.copyToUTF8 (temp, numBytes);
  4624. write (temp, numBytes);
  4625. }
  4626. void OutputStream::writeText (const String& text, const bool asUnicode,
  4627. const bool writeUnicodeHeaderBytes)
  4628. {
  4629. if (asUnicode)
  4630. {
  4631. if (writeUnicodeHeaderBytes)
  4632. write ("\x0ff\x0fe", 2);
  4633. const juce_wchar* src = text;
  4634. bool lastCharWasReturn = false;
  4635. while (*src != 0)
  4636. {
  4637. if (*src == L'\n' && ! lastCharWasReturn)
  4638. writeShort ((short) L'\r');
  4639. lastCharWasReturn = (*src == L'\r');
  4640. writeShort ((short) *src++);
  4641. }
  4642. }
  4643. else
  4644. {
  4645. const char* src = text.toUTF8();
  4646. const char* t = src;
  4647. for (;;)
  4648. {
  4649. if (*t == '\n')
  4650. {
  4651. if (t > src)
  4652. write (src, (int) (t - src));
  4653. write ("\r\n", 2);
  4654. src = t + 1;
  4655. }
  4656. else if (*t == '\r')
  4657. {
  4658. if (t[1] == '\n')
  4659. ++t;
  4660. }
  4661. else if (*t == 0)
  4662. {
  4663. if (t > src)
  4664. write (src, (int) (t - src));
  4665. break;
  4666. }
  4667. ++t;
  4668. }
  4669. }
  4670. }
  4671. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4672. {
  4673. if (numBytesToWrite < 0)
  4674. numBytesToWrite = std::numeric_limits<int64>::max();
  4675. int numWritten = 0;
  4676. while (numBytesToWrite > 0 && ! source.isExhausted())
  4677. {
  4678. char buffer [8192];
  4679. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4680. if (num <= 0)
  4681. break;
  4682. write (buffer, num);
  4683. numBytesToWrite -= num;
  4684. numWritten += num;
  4685. }
  4686. return numWritten;
  4687. }
  4688. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4689. {
  4690. return stream << String (number);
  4691. }
  4692. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4693. {
  4694. return stream << String (number);
  4695. }
  4696. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4697. {
  4698. stream.writeByte (character);
  4699. return stream;
  4700. }
  4701. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4702. {
  4703. stream.write (text, (int) strlen (text));
  4704. return stream;
  4705. }
  4706. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4707. {
  4708. stream.write (data.getData(), (int) data.getSize());
  4709. return stream;
  4710. }
  4711. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4712. {
  4713. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4714. if (in != 0)
  4715. stream.writeFromInputStream (*in, -1);
  4716. return stream;
  4717. }
  4718. END_JUCE_NAMESPACE
  4719. /*** End of inlined file: juce_OutputStream.cpp ***/
  4720. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4721. BEGIN_JUCE_NAMESPACE
  4722. DirectoryIterator::DirectoryIterator (const File& directory,
  4723. bool isRecursive_,
  4724. const String& wildCard_,
  4725. const int whatToLookFor_)
  4726. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4727. wildCard (wildCard_),
  4728. path (File::addTrailingSeparator (directory.getFullPathName())),
  4729. index (-1),
  4730. totalNumFiles (-1),
  4731. whatToLookFor (whatToLookFor_),
  4732. isRecursive (isRecursive_)
  4733. {
  4734. // you have to specify the type of files you're looking for!
  4735. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4736. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4737. }
  4738. DirectoryIterator::~DirectoryIterator()
  4739. {
  4740. }
  4741. bool DirectoryIterator::next()
  4742. {
  4743. return next (0, 0, 0, 0, 0, 0);
  4744. }
  4745. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4746. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4747. {
  4748. if (subIterator != 0)
  4749. {
  4750. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4751. return true;
  4752. subIterator = 0;
  4753. }
  4754. String filename;
  4755. bool isDirectory, isHidden;
  4756. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4757. {
  4758. ++index;
  4759. if (! filename.containsOnly ("."))
  4760. {
  4761. const File fileFound (path + filename, 0);
  4762. bool matches = false;
  4763. if (isDirectory)
  4764. {
  4765. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4766. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4767. matches = (whatToLookFor & File::findDirectories) != 0;
  4768. }
  4769. else
  4770. {
  4771. matches = (whatToLookFor & File::findFiles) != 0;
  4772. }
  4773. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4774. if (matches && isRecursive)
  4775. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4776. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4777. matches = ! isHidden;
  4778. if (matches)
  4779. {
  4780. currentFile = fileFound;
  4781. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4782. if (isDirResult != 0) *isDirResult = isDirectory;
  4783. return true;
  4784. }
  4785. else if (subIterator != 0)
  4786. {
  4787. return next();
  4788. }
  4789. }
  4790. }
  4791. return false;
  4792. }
  4793. const File DirectoryIterator::getFile() const
  4794. {
  4795. if (subIterator != 0)
  4796. return subIterator->getFile();
  4797. return currentFile;
  4798. }
  4799. float DirectoryIterator::getEstimatedProgress() const
  4800. {
  4801. if (totalNumFiles < 0)
  4802. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4803. if (totalNumFiles <= 0)
  4804. return 0.0f;
  4805. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4806. : (float) index;
  4807. return detailedIndex / totalNumFiles;
  4808. }
  4809. END_JUCE_NAMESPACE
  4810. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4811. /*** Start of inlined file: juce_File.cpp ***/
  4812. #if ! JUCE_WINDOWS
  4813. #include <pwd.h>
  4814. #endif
  4815. BEGIN_JUCE_NAMESPACE
  4816. File::File (const String& fullPathName)
  4817. : fullPath (parseAbsolutePath (fullPathName))
  4818. {
  4819. }
  4820. File::File (const String& path, int)
  4821. : fullPath (path)
  4822. {
  4823. }
  4824. const File File::createFileWithoutCheckingPath (const String& path)
  4825. {
  4826. return File (path, 0);
  4827. }
  4828. File::File (const File& other)
  4829. : fullPath (other.fullPath)
  4830. {
  4831. }
  4832. File& File::operator= (const String& newPath)
  4833. {
  4834. fullPath = parseAbsolutePath (newPath);
  4835. return *this;
  4836. }
  4837. File& File::operator= (const File& other)
  4838. {
  4839. fullPath = other.fullPath;
  4840. return *this;
  4841. }
  4842. const File File::nonexistent;
  4843. const String File::parseAbsolutePath (const String& p)
  4844. {
  4845. if (p.isEmpty())
  4846. return String::empty;
  4847. #if JUCE_WINDOWS
  4848. // Windows..
  4849. String path (p.replaceCharacter ('/', '\\'));
  4850. if (path.startsWithChar (File::separator))
  4851. {
  4852. if (path[1] != File::separator)
  4853. {
  4854. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4855. If you're trying to parse a string that may be either a relative path or an absolute path,
  4856. you MUST provide a context against which the partial path can be evaluated - you can do
  4857. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4858. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4859. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4860. */
  4861. jassertfalse;
  4862. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4863. }
  4864. }
  4865. else if (! path.containsChar (':'))
  4866. {
  4867. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4868. If you're trying to parse a string that may be either a relative path or an absolute path,
  4869. you MUST provide a context against which the partial path can be evaluated - you can do
  4870. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4871. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4872. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4873. */
  4874. jassertfalse;
  4875. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4876. }
  4877. #else
  4878. // Mac or Linux..
  4879. String path (p.replaceCharacter ('\\', '/'));
  4880. if (path.startsWithChar ('~'))
  4881. {
  4882. if (path[1] == File::separator || path[1] == 0)
  4883. {
  4884. // expand a name of the form "~/abc"
  4885. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4886. + path.substring (1);
  4887. }
  4888. else
  4889. {
  4890. // expand a name of type "~dave/abc"
  4891. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4892. struct passwd* const pw = getpwnam (userName.toUTF8());
  4893. if (pw != 0)
  4894. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4895. }
  4896. }
  4897. else if (! path.startsWithChar (File::separator))
  4898. {
  4899. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4900. If you're trying to parse a string that may be either a relative path or an absolute path,
  4901. you MUST provide a context against which the partial path can be evaluated - you can do
  4902. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4903. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4904. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4905. */
  4906. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4907. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4908. }
  4909. #endif
  4910. return path.trimCharactersAtEnd (separatorString);
  4911. }
  4912. const String File::addTrailingSeparator (const String& path)
  4913. {
  4914. return path.endsWithChar (File::separator) ? path
  4915. : path + File::separator;
  4916. }
  4917. #if JUCE_LINUX
  4918. #define NAMES_ARE_CASE_SENSITIVE 1
  4919. #endif
  4920. bool File::areFileNamesCaseSensitive()
  4921. {
  4922. #if NAMES_ARE_CASE_SENSITIVE
  4923. return true;
  4924. #else
  4925. return false;
  4926. #endif
  4927. }
  4928. bool File::operator== (const File& other) const
  4929. {
  4930. #if NAMES_ARE_CASE_SENSITIVE
  4931. return fullPath == other.fullPath;
  4932. #else
  4933. return fullPath.equalsIgnoreCase (other.fullPath);
  4934. #endif
  4935. }
  4936. bool File::operator!= (const File& other) const
  4937. {
  4938. return ! operator== (other);
  4939. }
  4940. bool File::operator< (const File& other) const
  4941. {
  4942. #if NAMES_ARE_CASE_SENSITIVE
  4943. return fullPath < other.fullPath;
  4944. #else
  4945. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4946. #endif
  4947. }
  4948. bool File::operator> (const File& other) const
  4949. {
  4950. #if NAMES_ARE_CASE_SENSITIVE
  4951. return fullPath > other.fullPath;
  4952. #else
  4953. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4954. #endif
  4955. }
  4956. bool File::setReadOnly (const bool shouldBeReadOnly,
  4957. const bool applyRecursively) const
  4958. {
  4959. bool worked = true;
  4960. if (applyRecursively && isDirectory())
  4961. {
  4962. Array <File> subFiles;
  4963. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4964. for (int i = subFiles.size(); --i >= 0;)
  4965. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4966. }
  4967. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4968. }
  4969. bool File::deleteRecursively() const
  4970. {
  4971. bool worked = true;
  4972. if (isDirectory())
  4973. {
  4974. Array<File> subFiles;
  4975. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4976. for (int i = subFiles.size(); --i >= 0;)
  4977. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4978. }
  4979. return deleteFile() && worked;
  4980. }
  4981. bool File::moveFileTo (const File& newFile) const
  4982. {
  4983. if (newFile.fullPath == fullPath)
  4984. return true;
  4985. #if ! NAMES_ARE_CASE_SENSITIVE
  4986. if (*this != newFile)
  4987. #endif
  4988. if (! newFile.deleteFile())
  4989. return false;
  4990. return moveInternal (newFile);
  4991. }
  4992. bool File::copyFileTo (const File& newFile) const
  4993. {
  4994. return (*this == newFile)
  4995. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4996. }
  4997. bool File::copyDirectoryTo (const File& newDirectory) const
  4998. {
  4999. if (isDirectory() && newDirectory.createDirectory())
  5000. {
  5001. Array<File> subFiles;
  5002. findChildFiles (subFiles, File::findFiles, false);
  5003. int i;
  5004. for (i = 0; i < subFiles.size(); ++i)
  5005. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5006. return false;
  5007. subFiles.clear();
  5008. findChildFiles (subFiles, File::findDirectories, false);
  5009. for (i = 0; i < subFiles.size(); ++i)
  5010. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5011. return false;
  5012. return true;
  5013. }
  5014. return false;
  5015. }
  5016. const String File::getPathUpToLastSlash() const
  5017. {
  5018. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5019. if (lastSlash > 0)
  5020. return fullPath.substring (0, lastSlash);
  5021. else if (lastSlash == 0)
  5022. return separatorString;
  5023. else
  5024. return fullPath;
  5025. }
  5026. const File File::getParentDirectory() const
  5027. {
  5028. return File (getPathUpToLastSlash(), (int) 0);
  5029. }
  5030. const String File::getFileName() const
  5031. {
  5032. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5033. }
  5034. int File::hashCode() const
  5035. {
  5036. return fullPath.hashCode();
  5037. }
  5038. int64 File::hashCode64() const
  5039. {
  5040. return fullPath.hashCode64();
  5041. }
  5042. const String File::getFileNameWithoutExtension() const
  5043. {
  5044. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5045. const int lastDot = fullPath.lastIndexOfChar ('.');
  5046. if (lastDot > lastSlash)
  5047. return fullPath.substring (lastSlash, lastDot);
  5048. else
  5049. return fullPath.substring (lastSlash);
  5050. }
  5051. bool File::isAChildOf (const File& potentialParent) const
  5052. {
  5053. if (potentialParent == File::nonexistent)
  5054. return false;
  5055. const String ourPath (getPathUpToLastSlash());
  5056. #if NAMES_ARE_CASE_SENSITIVE
  5057. if (potentialParent.fullPath == ourPath)
  5058. #else
  5059. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5060. #endif
  5061. {
  5062. return true;
  5063. }
  5064. else if (potentialParent.fullPath.length() >= ourPath.length())
  5065. {
  5066. return false;
  5067. }
  5068. else
  5069. {
  5070. return getParentDirectory().isAChildOf (potentialParent);
  5071. }
  5072. }
  5073. bool File::isAbsolutePath (const String& path)
  5074. {
  5075. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5076. #if JUCE_WINDOWS
  5077. || (path.isNotEmpty() && path[1] == ':');
  5078. #else
  5079. || path.startsWithChar ('~');
  5080. #endif
  5081. }
  5082. const File File::getChildFile (String relativePath) const
  5083. {
  5084. if (isAbsolutePath (relativePath))
  5085. {
  5086. // the path is really absolute..
  5087. return File (relativePath);
  5088. }
  5089. else
  5090. {
  5091. // it's relative, so remove any ../ or ./ bits at the start.
  5092. String path (fullPath);
  5093. if (relativePath[0] == '.')
  5094. {
  5095. #if JUCE_WINDOWS
  5096. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5097. #else
  5098. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5099. #endif
  5100. while (relativePath[0] == '.')
  5101. {
  5102. if (relativePath[1] == '.')
  5103. {
  5104. if (relativePath [2] == 0 || relativePath[2] == separator)
  5105. {
  5106. const int lastSlash = path.lastIndexOfChar (separator);
  5107. if (lastSlash >= 0)
  5108. path = path.substring (0, lastSlash);
  5109. relativePath = relativePath.substring (3);
  5110. }
  5111. else
  5112. {
  5113. break;
  5114. }
  5115. }
  5116. else if (relativePath[1] == separator)
  5117. {
  5118. relativePath = relativePath.substring (2);
  5119. }
  5120. else
  5121. {
  5122. break;
  5123. }
  5124. }
  5125. }
  5126. return File (addTrailingSeparator (path) + relativePath);
  5127. }
  5128. }
  5129. const File File::getSiblingFile (const String& fileName) const
  5130. {
  5131. return getParentDirectory().getChildFile (fileName);
  5132. }
  5133. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5134. {
  5135. if (bytes == 1)
  5136. {
  5137. return "1 byte";
  5138. }
  5139. else if (bytes < 1024)
  5140. {
  5141. return String ((int) bytes) + " bytes";
  5142. }
  5143. else if (bytes < 1024 * 1024)
  5144. {
  5145. return String (bytes / 1024.0, 1) + " KB";
  5146. }
  5147. else if (bytes < 1024 * 1024 * 1024)
  5148. {
  5149. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5150. }
  5151. else
  5152. {
  5153. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5154. }
  5155. }
  5156. bool File::create() const
  5157. {
  5158. if (exists())
  5159. return true;
  5160. {
  5161. const File parentDir (getParentDirectory());
  5162. if (parentDir == *this || ! parentDir.createDirectory())
  5163. return false;
  5164. FileOutputStream fo (*this, 8);
  5165. }
  5166. return exists();
  5167. }
  5168. bool File::createDirectory() const
  5169. {
  5170. if (! isDirectory())
  5171. {
  5172. const File parentDir (getParentDirectory());
  5173. if (parentDir == *this || ! parentDir.createDirectory())
  5174. return false;
  5175. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5176. return isDirectory();
  5177. }
  5178. return true;
  5179. }
  5180. const Time File::getCreationTime() const
  5181. {
  5182. int64 m, a, c;
  5183. getFileTimesInternal (m, a, c);
  5184. return Time (c);
  5185. }
  5186. const Time File::getLastModificationTime() const
  5187. {
  5188. int64 m, a, c;
  5189. getFileTimesInternal (m, a, c);
  5190. return Time (m);
  5191. }
  5192. const Time File::getLastAccessTime() const
  5193. {
  5194. int64 m, a, c;
  5195. getFileTimesInternal (m, a, c);
  5196. return Time (a);
  5197. }
  5198. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5199. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5200. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5201. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5202. {
  5203. if (! existsAsFile())
  5204. return false;
  5205. FileInputStream in (*this);
  5206. return getSize() == in.readIntoMemoryBlock (destBlock);
  5207. }
  5208. const String File::loadFileAsString() const
  5209. {
  5210. if (! existsAsFile())
  5211. return String::empty;
  5212. FileInputStream in (*this);
  5213. return in.readEntireStreamAsString();
  5214. }
  5215. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5216. {
  5217. return (whatToLookFor & (isDir ? findDirectories
  5218. : findFiles)) != 0
  5219. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5220. }
  5221. int File::findChildFiles (Array<File>& results,
  5222. const int whatToLookFor,
  5223. const bool searchRecursively,
  5224. const String& wildCardPattern) const
  5225. {
  5226. // you have to specify the type of files you're looking for!
  5227. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5228. int total = 0;
  5229. if (isDirectory())
  5230. {
  5231. // find child files or directories in this directory first..
  5232. String path (addTrailingSeparator (fullPath)), filename;
  5233. bool itemIsDirectory, itemIsHidden;
  5234. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5235. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5236. {
  5237. if (! filename.containsOnly ("."))
  5238. {
  5239. const File fileFound (path + filename, 0);
  5240. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5241. {
  5242. results.add (fileFound);
  5243. ++total;
  5244. }
  5245. if (searchRecursively && itemIsDirectory
  5246. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5247. {
  5248. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5249. }
  5250. }
  5251. }
  5252. }
  5253. return total;
  5254. }
  5255. int File::getNumberOfChildFiles (const int whatToLookFor,
  5256. const String& wildCardPattern) const
  5257. {
  5258. // you have to specify the type of files you're looking for!
  5259. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5260. int count = 0;
  5261. if (isDirectory())
  5262. {
  5263. String filename;
  5264. bool itemIsDirectory, itemIsHidden;
  5265. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5266. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5267. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5268. && ! filename.containsOnly ("."))
  5269. ++count;
  5270. }
  5271. else
  5272. {
  5273. // trying to search for files inside a non-directory?
  5274. jassertfalse;
  5275. }
  5276. return count;
  5277. }
  5278. bool File::containsSubDirectories() const
  5279. {
  5280. if (isDirectory())
  5281. {
  5282. String filename;
  5283. bool itemIsDirectory;
  5284. DirectoryIterator::NativeIterator i (*this, "*");
  5285. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5286. if (itemIsDirectory)
  5287. return true;
  5288. }
  5289. return false;
  5290. }
  5291. const File File::getNonexistentChildFile (const String& prefix_,
  5292. const String& suffix,
  5293. bool putNumbersInBrackets) const
  5294. {
  5295. File f (getChildFile (prefix_ + suffix));
  5296. if (f.exists())
  5297. {
  5298. int num = 2;
  5299. String prefix (prefix_);
  5300. // remove any bracketed numbers that may already be on the end..
  5301. if (prefix.trim().endsWithChar (')'))
  5302. {
  5303. putNumbersInBrackets = true;
  5304. const int openBracks = prefix.lastIndexOfChar ('(');
  5305. const int closeBracks = prefix.lastIndexOfChar (')');
  5306. if (openBracks > 0
  5307. && closeBracks > openBracks
  5308. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5309. {
  5310. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5311. prefix = prefix.substring (0, openBracks);
  5312. }
  5313. }
  5314. // also use brackets if it ends in a digit.
  5315. putNumbersInBrackets = putNumbersInBrackets
  5316. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5317. do
  5318. {
  5319. if (putNumbersInBrackets)
  5320. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5321. else
  5322. f = getChildFile (prefix + String (num++) + suffix);
  5323. } while (f.exists());
  5324. }
  5325. return f;
  5326. }
  5327. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5328. {
  5329. if (exists())
  5330. {
  5331. return getParentDirectory()
  5332. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5333. getFileExtension(),
  5334. putNumbersInBrackets);
  5335. }
  5336. else
  5337. {
  5338. return *this;
  5339. }
  5340. }
  5341. const String File::getFileExtension() const
  5342. {
  5343. String ext;
  5344. if (! isDirectory())
  5345. {
  5346. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5347. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5348. ext = fullPath.substring (indexOfDot);
  5349. }
  5350. return ext;
  5351. }
  5352. bool File::hasFileExtension (const String& possibleSuffix) const
  5353. {
  5354. if (possibleSuffix.isEmpty())
  5355. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5356. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5357. if (semicolon >= 0)
  5358. {
  5359. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5360. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5361. }
  5362. else
  5363. {
  5364. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5365. {
  5366. if (possibleSuffix.startsWithChar ('.'))
  5367. return true;
  5368. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5369. if (dotPos >= 0)
  5370. return fullPath [dotPos] == '.';
  5371. }
  5372. }
  5373. return false;
  5374. }
  5375. const File File::withFileExtension (const String& newExtension) const
  5376. {
  5377. if (fullPath.isEmpty())
  5378. return File::nonexistent;
  5379. String filePart (getFileName());
  5380. int i = filePart.lastIndexOfChar ('.');
  5381. if (i >= 0)
  5382. filePart = filePart.substring (0, i);
  5383. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5384. filePart << '.';
  5385. return getSiblingFile (filePart + newExtension);
  5386. }
  5387. bool File::startAsProcess (const String& parameters) const
  5388. {
  5389. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5390. }
  5391. FileInputStream* File::createInputStream() const
  5392. {
  5393. if (existsAsFile())
  5394. return new FileInputStream (*this);
  5395. return 0;
  5396. }
  5397. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5398. {
  5399. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5400. if (out->failedToOpen())
  5401. return 0;
  5402. return out.release();
  5403. }
  5404. bool File::appendData (const void* const dataToAppend,
  5405. const int numberOfBytes) const
  5406. {
  5407. if (numberOfBytes > 0)
  5408. {
  5409. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5410. if (out == 0)
  5411. return false;
  5412. out->write (dataToAppend, numberOfBytes);
  5413. }
  5414. return true;
  5415. }
  5416. bool File::replaceWithData (const void* const dataToWrite,
  5417. const int numberOfBytes) const
  5418. {
  5419. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5420. if (numberOfBytes <= 0)
  5421. return deleteFile();
  5422. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5423. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5424. return tempFile.overwriteTargetFileWithTemporary();
  5425. }
  5426. bool File::appendText (const String& text,
  5427. const bool asUnicode,
  5428. const bool writeUnicodeHeaderBytes) const
  5429. {
  5430. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5431. if (out != 0)
  5432. {
  5433. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5434. return true;
  5435. }
  5436. return false;
  5437. }
  5438. bool File::replaceWithText (const String& textToWrite,
  5439. const bool asUnicode,
  5440. const bool writeUnicodeHeaderBytes) const
  5441. {
  5442. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5443. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5444. return tempFile.overwriteTargetFileWithTemporary();
  5445. }
  5446. bool File::hasIdenticalContentTo (const File& other) const
  5447. {
  5448. if (other == *this)
  5449. return true;
  5450. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5451. {
  5452. FileInputStream in1 (*this), in2 (other);
  5453. const int bufferSize = 4096;
  5454. HeapBlock <char> buffer1, buffer2;
  5455. buffer1.malloc (bufferSize);
  5456. buffer2.malloc (bufferSize);
  5457. for (;;)
  5458. {
  5459. const int num1 = in1.read (buffer1, bufferSize);
  5460. const int num2 = in2.read (buffer2, bufferSize);
  5461. if (num1 != num2)
  5462. break;
  5463. if (num1 <= 0)
  5464. return true;
  5465. if (memcmp (buffer1, buffer2, num1) != 0)
  5466. break;
  5467. }
  5468. }
  5469. return false;
  5470. }
  5471. const String File::createLegalPathName (const String& original)
  5472. {
  5473. String s (original);
  5474. String start;
  5475. if (s[1] == ':')
  5476. {
  5477. start = s.substring (0, 2);
  5478. s = s.substring (2);
  5479. }
  5480. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5481. .substring (0, 1024);
  5482. }
  5483. const String File::createLegalFileName (const String& original)
  5484. {
  5485. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5486. const int maxLength = 128; // only the length of the filename, not the whole path
  5487. const int len = s.length();
  5488. if (len > maxLength)
  5489. {
  5490. const int lastDot = s.lastIndexOfChar ('.');
  5491. if (lastDot > jmax (0, len - 12))
  5492. {
  5493. s = s.substring (0, maxLength - (len - lastDot))
  5494. + s.substring (lastDot);
  5495. }
  5496. else
  5497. {
  5498. s = s.substring (0, maxLength);
  5499. }
  5500. }
  5501. return s;
  5502. }
  5503. const String File::getRelativePathFrom (const File& dir) const
  5504. {
  5505. String thisPath (fullPath);
  5506. {
  5507. int len = thisPath.length();
  5508. while (--len >= 0 && thisPath [len] == File::separator)
  5509. thisPath [len] = 0;
  5510. }
  5511. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5512. : dir.fullPath));
  5513. const int len = jmin (thisPath.length(), dirPath.length());
  5514. int commonBitLength = 0;
  5515. for (int i = 0; i < len; ++i)
  5516. {
  5517. #if NAMES_ARE_CASE_SENSITIVE
  5518. if (thisPath[i] != dirPath[i])
  5519. #else
  5520. if (CharacterFunctions::toLowerCase (thisPath[i])
  5521. != CharacterFunctions::toLowerCase (dirPath[i]))
  5522. #endif
  5523. {
  5524. break;
  5525. }
  5526. ++commonBitLength;
  5527. }
  5528. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5529. --commonBitLength;
  5530. // if the only common bit is the root, then just return the full path..
  5531. if (commonBitLength <= 0
  5532. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5533. return fullPath;
  5534. thisPath = thisPath.substring (commonBitLength);
  5535. dirPath = dirPath.substring (commonBitLength);
  5536. while (dirPath.isNotEmpty())
  5537. {
  5538. #if JUCE_WINDOWS
  5539. thisPath = "..\\" + thisPath;
  5540. #else
  5541. thisPath = "../" + thisPath;
  5542. #endif
  5543. const int sep = dirPath.indexOfChar (separator);
  5544. if (sep >= 0)
  5545. dirPath = dirPath.substring (sep + 1);
  5546. else
  5547. dirPath = String::empty;
  5548. }
  5549. return thisPath;
  5550. }
  5551. const File File::createTempFile (const String& fileNameEnding)
  5552. {
  5553. const File tempFile (getSpecialLocation (tempDirectory)
  5554. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5555. .withFileExtension (fileNameEnding));
  5556. if (tempFile.exists())
  5557. return createTempFile (fileNameEnding);
  5558. else
  5559. return tempFile;
  5560. }
  5561. END_JUCE_NAMESPACE
  5562. /*** End of inlined file: juce_File.cpp ***/
  5563. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5564. BEGIN_JUCE_NAMESPACE
  5565. void* juce_fileOpen (const File& file, bool forWriting);
  5566. void juce_fileClose (void* handle);
  5567. int juce_fileRead (void* handle, void* buffer, int size);
  5568. int64 juce_fileSetPosition (void* handle, int64 pos);
  5569. FileInputStream::FileInputStream (const File& f)
  5570. : file (f),
  5571. currentPosition (0),
  5572. needToSeek (true)
  5573. {
  5574. totalSize = f.getSize();
  5575. fileHandle = juce_fileOpen (f, false);
  5576. }
  5577. FileInputStream::~FileInputStream()
  5578. {
  5579. juce_fileClose (fileHandle);
  5580. }
  5581. int64 FileInputStream::getTotalLength()
  5582. {
  5583. return totalSize;
  5584. }
  5585. int FileInputStream::read (void* buffer, int bytesToRead)
  5586. {
  5587. int num = 0;
  5588. if (needToSeek)
  5589. {
  5590. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5591. return 0;
  5592. needToSeek = false;
  5593. }
  5594. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5595. currentPosition += num;
  5596. return num;
  5597. }
  5598. bool FileInputStream::isExhausted()
  5599. {
  5600. return currentPosition >= totalSize;
  5601. }
  5602. int64 FileInputStream::getPosition()
  5603. {
  5604. return currentPosition;
  5605. }
  5606. bool FileInputStream::setPosition (int64 pos)
  5607. {
  5608. pos = jlimit ((int64) 0, totalSize, pos);
  5609. needToSeek |= (currentPosition != pos);
  5610. currentPosition = pos;
  5611. return true;
  5612. }
  5613. END_JUCE_NAMESPACE
  5614. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5615. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5616. BEGIN_JUCE_NAMESPACE
  5617. void* juce_fileOpen (const File& file, bool forWriting);
  5618. void juce_fileClose (void* handle);
  5619. int juce_fileWrite (void* handle, const void* buffer, int size);
  5620. int64 juce_fileSetPosition (void* handle, int64 pos);
  5621. FileOutputStream::FileOutputStream (const File& f,
  5622. const int bufferSize_)
  5623. : file (f),
  5624. bufferSize (bufferSize_),
  5625. bytesInBuffer (0)
  5626. {
  5627. fileHandle = juce_fileOpen (f, true);
  5628. if (fileHandle != 0)
  5629. {
  5630. currentPosition = getPositionInternal();
  5631. if (currentPosition < 0)
  5632. {
  5633. jassertfalse;
  5634. juce_fileClose (fileHandle);
  5635. fileHandle = 0;
  5636. }
  5637. }
  5638. buffer.malloc (jmax (bufferSize_, 16));
  5639. }
  5640. FileOutputStream::~FileOutputStream()
  5641. {
  5642. flush();
  5643. juce_fileClose (fileHandle);
  5644. }
  5645. int64 FileOutputStream::getPosition()
  5646. {
  5647. return currentPosition;
  5648. }
  5649. bool FileOutputStream::setPosition (int64 newPosition)
  5650. {
  5651. if (newPosition != currentPosition)
  5652. {
  5653. flush();
  5654. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5655. }
  5656. return newPosition == currentPosition;
  5657. }
  5658. void FileOutputStream::flush()
  5659. {
  5660. if (bytesInBuffer > 0)
  5661. {
  5662. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5663. bytesInBuffer = 0;
  5664. }
  5665. flushInternal();
  5666. }
  5667. bool FileOutputStream::write (const void* const src, const int numBytes)
  5668. {
  5669. if (bytesInBuffer + numBytes < bufferSize)
  5670. {
  5671. memcpy (buffer + bytesInBuffer, src, numBytes);
  5672. bytesInBuffer += numBytes;
  5673. currentPosition += numBytes;
  5674. }
  5675. else
  5676. {
  5677. if (bytesInBuffer > 0)
  5678. {
  5679. // flush the reservoir
  5680. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5681. bytesInBuffer = 0;
  5682. if (! wroteOk)
  5683. return false;
  5684. }
  5685. if (numBytes < bufferSize)
  5686. {
  5687. memcpy (buffer + bytesInBuffer, src, numBytes);
  5688. bytesInBuffer += numBytes;
  5689. currentPosition += numBytes;
  5690. }
  5691. else
  5692. {
  5693. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5694. currentPosition += bytesWritten;
  5695. return bytesWritten == numBytes;
  5696. }
  5697. }
  5698. return true;
  5699. }
  5700. END_JUCE_NAMESPACE
  5701. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5702. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5703. BEGIN_JUCE_NAMESPACE
  5704. FileSearchPath::FileSearchPath()
  5705. {
  5706. }
  5707. FileSearchPath::FileSearchPath (const String& path)
  5708. {
  5709. init (path);
  5710. }
  5711. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5712. : directories (other.directories)
  5713. {
  5714. }
  5715. FileSearchPath::~FileSearchPath()
  5716. {
  5717. }
  5718. FileSearchPath& FileSearchPath::operator= (const String& path)
  5719. {
  5720. init (path);
  5721. return *this;
  5722. }
  5723. void FileSearchPath::init (const String& path)
  5724. {
  5725. directories.clear();
  5726. directories.addTokens (path, ";", "\"");
  5727. directories.trim();
  5728. directories.removeEmptyStrings();
  5729. for (int i = directories.size(); --i >= 0;)
  5730. directories.set (i, directories[i].unquoted());
  5731. }
  5732. int FileSearchPath::getNumPaths() const
  5733. {
  5734. return directories.size();
  5735. }
  5736. const File FileSearchPath::operator[] (const int index) const
  5737. {
  5738. return File (directories [index]);
  5739. }
  5740. const String FileSearchPath::toString() const
  5741. {
  5742. StringArray directories2 (directories);
  5743. for (int i = directories2.size(); --i >= 0;)
  5744. if (directories2[i].containsChar (';'))
  5745. directories2.set (i, directories2[i].quoted());
  5746. return directories2.joinIntoString (";");
  5747. }
  5748. void FileSearchPath::add (const File& dir, const int insertIndex)
  5749. {
  5750. directories.insert (insertIndex, dir.getFullPathName());
  5751. }
  5752. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5753. {
  5754. for (int i = 0; i < directories.size(); ++i)
  5755. if (File (directories[i]) == dir)
  5756. return;
  5757. add (dir);
  5758. }
  5759. void FileSearchPath::remove (const int index)
  5760. {
  5761. directories.remove (index);
  5762. }
  5763. void FileSearchPath::addPath (const FileSearchPath& other)
  5764. {
  5765. for (int i = 0; i < other.getNumPaths(); ++i)
  5766. addIfNotAlreadyThere (other[i]);
  5767. }
  5768. void FileSearchPath::removeRedundantPaths()
  5769. {
  5770. for (int i = directories.size(); --i >= 0;)
  5771. {
  5772. const File d1 (directories[i]);
  5773. for (int j = directories.size(); --j >= 0;)
  5774. {
  5775. const File d2 (directories[j]);
  5776. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5777. {
  5778. directories.remove (i);
  5779. break;
  5780. }
  5781. }
  5782. }
  5783. }
  5784. void FileSearchPath::removeNonExistentPaths()
  5785. {
  5786. for (int i = directories.size(); --i >= 0;)
  5787. if (! File (directories[i]).isDirectory())
  5788. directories.remove (i);
  5789. }
  5790. int FileSearchPath::findChildFiles (Array<File>& results,
  5791. const int whatToLookFor,
  5792. const bool searchRecursively,
  5793. const String& wildCardPattern) const
  5794. {
  5795. int total = 0;
  5796. for (int i = 0; i < directories.size(); ++i)
  5797. total += operator[] (i).findChildFiles (results,
  5798. whatToLookFor,
  5799. searchRecursively,
  5800. wildCardPattern);
  5801. return total;
  5802. }
  5803. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5804. const bool checkRecursively) const
  5805. {
  5806. for (int i = directories.size(); --i >= 0;)
  5807. {
  5808. const File d (directories[i]);
  5809. if (checkRecursively)
  5810. {
  5811. if (fileToCheck.isAChildOf (d))
  5812. return true;
  5813. }
  5814. else
  5815. {
  5816. if (fileToCheck.getParentDirectory() == d)
  5817. return true;
  5818. }
  5819. }
  5820. return false;
  5821. }
  5822. END_JUCE_NAMESPACE
  5823. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5824. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5825. BEGIN_JUCE_NAMESPACE
  5826. NamedPipe::NamedPipe()
  5827. : internal (0)
  5828. {
  5829. }
  5830. NamedPipe::~NamedPipe()
  5831. {
  5832. close();
  5833. }
  5834. bool NamedPipe::openExisting (const String& pipeName)
  5835. {
  5836. currentPipeName = pipeName;
  5837. return openInternal (pipeName, false);
  5838. }
  5839. bool NamedPipe::createNewPipe (const String& pipeName)
  5840. {
  5841. currentPipeName = pipeName;
  5842. return openInternal (pipeName, true);
  5843. }
  5844. bool NamedPipe::isOpen() const
  5845. {
  5846. return internal != 0;
  5847. }
  5848. const String NamedPipe::getName() const
  5849. {
  5850. return currentPipeName;
  5851. }
  5852. // other methods for this class are implemented in the platform-specific files
  5853. END_JUCE_NAMESPACE
  5854. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5855. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5856. BEGIN_JUCE_NAMESPACE
  5857. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5858. {
  5859. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5860. "temp_" + String (Random::getSystemRandom().nextInt()),
  5861. suffix,
  5862. optionFlags);
  5863. }
  5864. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5865. : targetFile (targetFile_)
  5866. {
  5867. // If you use this constructor, you need to give it a valid target file!
  5868. jassert (targetFile != File::nonexistent);
  5869. createTempFile (targetFile.getParentDirectory(),
  5870. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5871. targetFile.getFileExtension(),
  5872. optionFlags);
  5873. }
  5874. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5875. const String& suffix, const int optionFlags)
  5876. {
  5877. if ((optionFlags & useHiddenFile) != 0)
  5878. name = "." + name;
  5879. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5880. }
  5881. TemporaryFile::~TemporaryFile()
  5882. {
  5883. // Have a few attempts at deleting the file before giving up..
  5884. for (int i = 5; --i >= 0;)
  5885. {
  5886. if (temporaryFile.deleteFile())
  5887. return;
  5888. Thread::sleep (50);
  5889. }
  5890. // Failed to delete our temporary file! Check that you've deleted all the
  5891. // file output streams that were using it!
  5892. jassertfalse;
  5893. }
  5894. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5895. {
  5896. // This method only works if you created this object with the constructor
  5897. // that takes a target file!
  5898. jassert (targetFile != File::nonexistent);
  5899. if (temporaryFile.exists())
  5900. {
  5901. // Have a few attempts at overwriting the file before giving up..
  5902. for (int i = 5; --i >= 0;)
  5903. {
  5904. if (temporaryFile.moveFileTo (targetFile))
  5905. return true;
  5906. Thread::sleep (100);
  5907. }
  5908. }
  5909. else
  5910. {
  5911. // There's no temporary file to use. If your write failed, you should
  5912. // probably check, and not bother calling this method.
  5913. jassertfalse;
  5914. }
  5915. return false;
  5916. }
  5917. END_JUCE_NAMESPACE
  5918. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5919. /*** Start of inlined file: juce_Socket.cpp ***/
  5920. #if JUCE_WINDOWS
  5921. #include <winsock2.h>
  5922. #if JUCE_MSVC
  5923. #pragma warning (push)
  5924. #pragma warning (disable : 4127 4389 4018)
  5925. #endif
  5926. #else
  5927. #if JUCE_LINUX
  5928. #include <sys/types.h>
  5929. #include <sys/socket.h>
  5930. #include <sys/errno.h>
  5931. #include <unistd.h>
  5932. #include <netinet/in.h>
  5933. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5934. #include <CoreServices/CoreServices.h>
  5935. #endif
  5936. #include <fcntl.h>
  5937. #include <netdb.h>
  5938. #include <arpa/inet.h>
  5939. #include <netinet/tcp.h>
  5940. #endif
  5941. BEGIN_JUCE_NAMESPACE
  5942. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5943. typedef socklen_t juce_socklen_t;
  5944. #else
  5945. typedef int juce_socklen_t;
  5946. #endif
  5947. #if JUCE_WINDOWS
  5948. namespace SocketHelpers
  5949. {
  5950. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5951. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5952. }
  5953. static void initWin32Sockets()
  5954. {
  5955. static CriticalSection lock;
  5956. const ScopedLock sl (lock);
  5957. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  5958. {
  5959. WSADATA wsaData;
  5960. const WORD wVersionRequested = MAKEWORD (1, 1);
  5961. WSAStartup (wVersionRequested, &wsaData);
  5962. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  5963. }
  5964. }
  5965. void juce_shutdownWin32Sockets()
  5966. {
  5967. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  5968. (*SocketHelpers::juce_CloseWin32SocketLib)();
  5969. }
  5970. #endif
  5971. namespace SocketHelpers
  5972. {
  5973. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5974. {
  5975. const int sndBufSize = 65536;
  5976. const int rcvBufSize = 65536;
  5977. const int one = 1;
  5978. return handle > 0
  5979. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5980. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5981. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5982. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5983. }
  5984. static bool bindSocketToPort (const int handle, const int port) throw()
  5985. {
  5986. if (handle <= 0 || port <= 0)
  5987. return false;
  5988. struct sockaddr_in servTmpAddr;
  5989. zerostruct (servTmpAddr);
  5990. servTmpAddr.sin_family = PF_INET;
  5991. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5992. servTmpAddr.sin_port = htons ((uint16) port);
  5993. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5994. }
  5995. static int readSocket (const int handle,
  5996. void* const destBuffer, const int maxBytesToRead,
  5997. bool volatile& connected,
  5998. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5999. {
  6000. int bytesRead = 0;
  6001. while (bytesRead < maxBytesToRead)
  6002. {
  6003. int bytesThisTime;
  6004. #if JUCE_WINDOWS
  6005. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6006. #else
  6007. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6008. && errno == EINTR
  6009. && connected)
  6010. {
  6011. }
  6012. #endif
  6013. if (bytesThisTime <= 0 || ! connected)
  6014. {
  6015. if (bytesRead == 0)
  6016. bytesRead = -1;
  6017. break;
  6018. }
  6019. bytesRead += bytesThisTime;
  6020. if (! blockUntilSpecifiedAmountHasArrived)
  6021. break;
  6022. }
  6023. return bytesRead;
  6024. }
  6025. static int waitForReadiness (const int handle, const bool forReading,
  6026. const int timeoutMsecs) throw()
  6027. {
  6028. struct timeval timeout;
  6029. struct timeval* timeoutp;
  6030. if (timeoutMsecs >= 0)
  6031. {
  6032. timeout.tv_sec = timeoutMsecs / 1000;
  6033. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6034. timeoutp = &timeout;
  6035. }
  6036. else
  6037. {
  6038. timeoutp = 0;
  6039. }
  6040. fd_set rset, wset;
  6041. FD_ZERO (&rset);
  6042. FD_SET (handle, &rset);
  6043. FD_ZERO (&wset);
  6044. FD_SET (handle, &wset);
  6045. fd_set* const prset = forReading ? &rset : 0;
  6046. fd_set* const pwset = forReading ? 0 : &wset;
  6047. #if JUCE_WINDOWS
  6048. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6049. return -1;
  6050. #else
  6051. {
  6052. int result;
  6053. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6054. && errno == EINTR)
  6055. {
  6056. }
  6057. if (result < 0)
  6058. return -1;
  6059. }
  6060. #endif
  6061. {
  6062. int opt;
  6063. juce_socklen_t len = sizeof (opt);
  6064. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6065. || opt != 0)
  6066. return -1;
  6067. }
  6068. if ((forReading && FD_ISSET (handle, &rset))
  6069. || ((! forReading) && FD_ISSET (handle, &wset)))
  6070. return 1;
  6071. return 0;
  6072. }
  6073. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6074. {
  6075. #if JUCE_WINDOWS
  6076. u_long nonBlocking = shouldBlock ? 0 : 1;
  6077. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6078. return false;
  6079. #else
  6080. int socketFlags = fcntl (handle, F_GETFL, 0);
  6081. if (socketFlags == -1)
  6082. return false;
  6083. if (shouldBlock)
  6084. socketFlags &= ~O_NONBLOCK;
  6085. else
  6086. socketFlags |= O_NONBLOCK;
  6087. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6088. return false;
  6089. #endif
  6090. return true;
  6091. }
  6092. static bool connectSocket (int volatile& handle,
  6093. const bool isDatagram,
  6094. void** serverAddress,
  6095. const String& hostName,
  6096. const int portNumber,
  6097. const int timeOutMillisecs) throw()
  6098. {
  6099. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6100. if (hostEnt == 0)
  6101. return false;
  6102. struct in_addr targetAddress;
  6103. memcpy (&targetAddress.s_addr,
  6104. *(hostEnt->h_addr_list),
  6105. sizeof (targetAddress.s_addr));
  6106. struct sockaddr_in servTmpAddr;
  6107. zerostruct (servTmpAddr);
  6108. servTmpAddr.sin_family = PF_INET;
  6109. servTmpAddr.sin_addr = targetAddress;
  6110. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6111. if (handle < 0)
  6112. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6113. if (handle < 0)
  6114. return false;
  6115. if (isDatagram)
  6116. {
  6117. *serverAddress = new struct sockaddr_in();
  6118. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6119. return true;
  6120. }
  6121. setSocketBlockingState (handle, false);
  6122. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6123. if (result < 0)
  6124. {
  6125. #if JUCE_WINDOWS
  6126. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6127. #else
  6128. if (errno == EINPROGRESS)
  6129. #endif
  6130. {
  6131. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6132. {
  6133. setSocketBlockingState (handle, true);
  6134. return false;
  6135. }
  6136. }
  6137. }
  6138. setSocketBlockingState (handle, true);
  6139. resetSocketOptions (handle, false, false);
  6140. return true;
  6141. }
  6142. }
  6143. StreamingSocket::StreamingSocket()
  6144. : portNumber (0),
  6145. handle (-1),
  6146. connected (false),
  6147. isListener (false)
  6148. {
  6149. #if JUCE_WINDOWS
  6150. initWin32Sockets();
  6151. #endif
  6152. }
  6153. StreamingSocket::StreamingSocket (const String& hostName_,
  6154. const int portNumber_,
  6155. const int handle_)
  6156. : hostName (hostName_),
  6157. portNumber (portNumber_),
  6158. handle (handle_),
  6159. connected (true),
  6160. isListener (false)
  6161. {
  6162. #if JUCE_WINDOWS
  6163. initWin32Sockets();
  6164. #endif
  6165. SocketHelpers::resetSocketOptions (handle_, false, false);
  6166. }
  6167. StreamingSocket::~StreamingSocket()
  6168. {
  6169. close();
  6170. }
  6171. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6172. {
  6173. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6174. : -1;
  6175. }
  6176. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6177. {
  6178. if (isListener || ! connected)
  6179. return -1;
  6180. #if JUCE_WINDOWS
  6181. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6182. #else
  6183. int result;
  6184. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6185. && errno == EINTR)
  6186. {
  6187. }
  6188. return result;
  6189. #endif
  6190. }
  6191. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6192. const int timeoutMsecs) const
  6193. {
  6194. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6195. : -1;
  6196. }
  6197. bool StreamingSocket::bindToPort (const int port)
  6198. {
  6199. return SocketHelpers::bindSocketToPort (handle, port);
  6200. }
  6201. bool StreamingSocket::connect (const String& remoteHostName,
  6202. const int remotePortNumber,
  6203. const int timeOutMillisecs)
  6204. {
  6205. if (isListener)
  6206. {
  6207. jassertfalse; // a listener socket can't connect to another one!
  6208. return false;
  6209. }
  6210. if (connected)
  6211. close();
  6212. hostName = remoteHostName;
  6213. portNumber = remotePortNumber;
  6214. isListener = false;
  6215. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  6216. remotePortNumber, timeOutMillisecs);
  6217. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  6218. {
  6219. close();
  6220. return false;
  6221. }
  6222. return true;
  6223. }
  6224. void StreamingSocket::close()
  6225. {
  6226. #if JUCE_WINDOWS
  6227. if (handle != SOCKET_ERROR || connected)
  6228. closesocket (handle);
  6229. connected = false;
  6230. #else
  6231. if (connected)
  6232. {
  6233. connected = false;
  6234. if (isListener)
  6235. {
  6236. // need to do this to interrupt the accept() function..
  6237. StreamingSocket temp;
  6238. temp.connect ("localhost", portNumber, 1000);
  6239. }
  6240. }
  6241. if (handle != -1)
  6242. ::close (handle);
  6243. #endif
  6244. hostName = String::empty;
  6245. portNumber = 0;
  6246. handle = -1;
  6247. isListener = false;
  6248. }
  6249. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6250. {
  6251. if (connected)
  6252. close();
  6253. hostName = "listener";
  6254. portNumber = newPortNumber;
  6255. isListener = true;
  6256. struct sockaddr_in servTmpAddr;
  6257. zerostruct (servTmpAddr);
  6258. servTmpAddr.sin_family = PF_INET;
  6259. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6260. if (localHostName.isNotEmpty())
  6261. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6262. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6263. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6264. if (handle < 0)
  6265. return false;
  6266. const int reuse = 1;
  6267. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6268. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6269. || listen (handle, SOMAXCONN) < 0)
  6270. {
  6271. close();
  6272. return false;
  6273. }
  6274. connected = true;
  6275. return true;
  6276. }
  6277. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6278. {
  6279. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6280. // prepare this socket as a listener.
  6281. if (connected && isListener)
  6282. {
  6283. struct sockaddr address;
  6284. juce_socklen_t len = sizeof (sockaddr);
  6285. const int newSocket = (int) accept (handle, &address, &len);
  6286. if (newSocket >= 0 && connected)
  6287. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6288. portNumber, newSocket);
  6289. }
  6290. return 0;
  6291. }
  6292. bool StreamingSocket::isLocal() const throw()
  6293. {
  6294. return hostName == "127.0.0.1";
  6295. }
  6296. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6297. : portNumber (0),
  6298. handle (-1),
  6299. connected (true),
  6300. allowBroadcast (allowBroadcast_),
  6301. serverAddress (0)
  6302. {
  6303. #if JUCE_WINDOWS
  6304. initWin32Sockets();
  6305. #endif
  6306. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6307. bindToPort (localPortNumber);
  6308. }
  6309. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6310. const int handle_, const int localPortNumber)
  6311. : hostName (hostName_),
  6312. portNumber (portNumber_),
  6313. handle (handle_),
  6314. connected (true),
  6315. allowBroadcast (false),
  6316. serverAddress (0)
  6317. {
  6318. #if JUCE_WINDOWS
  6319. initWin32Sockets();
  6320. #endif
  6321. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  6322. bindToPort (localPortNumber);
  6323. }
  6324. DatagramSocket::~DatagramSocket()
  6325. {
  6326. close();
  6327. delete ((struct sockaddr_in*) serverAddress);
  6328. serverAddress = 0;
  6329. }
  6330. void DatagramSocket::close()
  6331. {
  6332. #if JUCE_WINDOWS
  6333. closesocket (handle);
  6334. connected = false;
  6335. #else
  6336. connected = false;
  6337. ::close (handle);
  6338. #endif
  6339. hostName = String::empty;
  6340. portNumber = 0;
  6341. handle = -1;
  6342. }
  6343. bool DatagramSocket::bindToPort (const int port)
  6344. {
  6345. return SocketHelpers::bindSocketToPort (handle, port);
  6346. }
  6347. bool DatagramSocket::connect (const String& remoteHostName,
  6348. const int remotePortNumber,
  6349. const int timeOutMillisecs)
  6350. {
  6351. if (connected)
  6352. close();
  6353. hostName = remoteHostName;
  6354. portNumber = remotePortNumber;
  6355. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  6356. remoteHostName, remotePortNumber,
  6357. timeOutMillisecs);
  6358. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  6359. {
  6360. close();
  6361. return false;
  6362. }
  6363. return true;
  6364. }
  6365. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6366. {
  6367. struct sockaddr address;
  6368. juce_socklen_t len = sizeof (sockaddr);
  6369. while (waitUntilReady (true, -1) == 1)
  6370. {
  6371. char buf[1];
  6372. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6373. {
  6374. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6375. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6376. -1, -1);
  6377. }
  6378. }
  6379. return 0;
  6380. }
  6381. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6382. const int timeoutMsecs) const
  6383. {
  6384. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6385. : -1;
  6386. }
  6387. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6388. {
  6389. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6390. : -1;
  6391. }
  6392. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6393. {
  6394. // You need to call connect() first to set the server address..
  6395. jassert (serverAddress != 0 && connected);
  6396. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6397. numBytesToWrite, 0,
  6398. (const struct sockaddr*) serverAddress,
  6399. sizeof (struct sockaddr_in))
  6400. : -1;
  6401. }
  6402. bool DatagramSocket::isLocal() const throw()
  6403. {
  6404. return hostName == "127.0.0.1";
  6405. }
  6406. #if JUCE_MSVC
  6407. #pragma warning (pop)
  6408. #endif
  6409. END_JUCE_NAMESPACE
  6410. /*** End of inlined file: juce_Socket.cpp ***/
  6411. /*** Start of inlined file: juce_URL.cpp ***/
  6412. BEGIN_JUCE_NAMESPACE
  6413. URL::URL()
  6414. {
  6415. }
  6416. URL::URL (const String& url_)
  6417. : url (url_)
  6418. {
  6419. int i = url.indexOfChar ('?');
  6420. if (i >= 0)
  6421. {
  6422. do
  6423. {
  6424. const int nextAmp = url.indexOfChar (i + 1, '&');
  6425. const int equalsPos = url.indexOfChar (i + 1, '=');
  6426. if (equalsPos > i + 1)
  6427. {
  6428. if (nextAmp < 0)
  6429. {
  6430. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6431. removeEscapeChars (url.substring (equalsPos + 1)));
  6432. }
  6433. else if (nextAmp > 0 && equalsPos < nextAmp)
  6434. {
  6435. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6436. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6437. }
  6438. }
  6439. i = nextAmp;
  6440. }
  6441. while (i >= 0);
  6442. url = url.upToFirstOccurrenceOf ("?", false, false);
  6443. }
  6444. }
  6445. URL::URL (const URL& other)
  6446. : url (other.url),
  6447. postData (other.postData),
  6448. parameters (other.parameters),
  6449. filesToUpload (other.filesToUpload),
  6450. mimeTypes (other.mimeTypes)
  6451. {
  6452. }
  6453. URL& URL::operator= (const URL& other)
  6454. {
  6455. url = other.url;
  6456. postData = other.postData;
  6457. parameters = other.parameters;
  6458. filesToUpload = other.filesToUpload;
  6459. mimeTypes = other.mimeTypes;
  6460. return *this;
  6461. }
  6462. URL::~URL()
  6463. {
  6464. }
  6465. static const String getMangledParameters (const StringPairArray& parameters)
  6466. {
  6467. String p;
  6468. for (int i = 0; i < parameters.size(); ++i)
  6469. {
  6470. if (i > 0)
  6471. p += '&';
  6472. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6473. << '='
  6474. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6475. }
  6476. return p;
  6477. }
  6478. const String URL::toString (const bool includeGetParameters) const
  6479. {
  6480. if (includeGetParameters && parameters.size() > 0)
  6481. return url + "?" + getMangledParameters (parameters);
  6482. else
  6483. return url;
  6484. }
  6485. bool URL::isWellFormed() const
  6486. {
  6487. //xxx TODO
  6488. return url.isNotEmpty();
  6489. }
  6490. static int findStartOfDomain (const String& url)
  6491. {
  6492. int i = 0;
  6493. while (CharacterFunctions::isLetterOrDigit (url[i])
  6494. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6495. ++i;
  6496. return url[i] == ':' ? i + 1 : 0;
  6497. }
  6498. const String URL::getDomain() const
  6499. {
  6500. int start = findStartOfDomain (url);
  6501. while (url[start] == '/')
  6502. ++start;
  6503. const int end1 = url.indexOfChar (start, '/');
  6504. const int end2 = url.indexOfChar (start, ':');
  6505. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6506. : jmin (end1, end2);
  6507. return url.substring (start, end);
  6508. }
  6509. const String URL::getSubPath() const
  6510. {
  6511. int start = findStartOfDomain (url);
  6512. while (url[start] == '/')
  6513. ++start;
  6514. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6515. return startOfPath <= 0 ? String::empty
  6516. : url.substring (startOfPath);
  6517. }
  6518. const String URL::getScheme() const
  6519. {
  6520. return url.substring (0, findStartOfDomain (url) - 1);
  6521. }
  6522. const URL URL::withNewSubPath (const String& newPath) const
  6523. {
  6524. int start = findStartOfDomain (url);
  6525. while (url[start] == '/')
  6526. ++start;
  6527. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6528. URL u (*this);
  6529. if (startOfPath > 0)
  6530. u.url = url.substring (0, startOfPath);
  6531. if (! u.url.endsWithChar ('/'))
  6532. u.url << '/';
  6533. if (newPath.startsWithChar ('/'))
  6534. u.url << newPath.substring (1);
  6535. else
  6536. u.url << newPath;
  6537. return u;
  6538. }
  6539. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6540. {
  6541. if (possibleURL.startsWithIgnoreCase ("http:")
  6542. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6543. return true;
  6544. if (possibleURL.startsWithIgnoreCase ("file:")
  6545. || possibleURL.containsChar ('@')
  6546. || possibleURL.endsWithChar ('.')
  6547. || (! possibleURL.containsChar ('.')))
  6548. return false;
  6549. if (possibleURL.startsWithIgnoreCase ("www.")
  6550. && possibleURL.substring (5).containsChar ('.'))
  6551. return true;
  6552. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6553. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6554. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6555. return true;
  6556. return false;
  6557. }
  6558. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6559. {
  6560. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6561. return atSign > 0
  6562. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6563. && (! possibleEmailAddress.endsWithChar ('.'));
  6564. }
  6565. void* juce_openInternetFile (const String& url,
  6566. const String& headers,
  6567. const MemoryBlock& optionalPostData,
  6568. const bool isPost,
  6569. URL::OpenStreamProgressCallback* callback,
  6570. void* callbackContext,
  6571. int timeOutMs);
  6572. void juce_closeInternetFile (void* handle);
  6573. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6574. int juce_seekInInternetFile (void* handle, int newPosition);
  6575. int64 juce_getInternetFileContentLength (void* handle);
  6576. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6577. class WebInputStream : public InputStream
  6578. {
  6579. public:
  6580. WebInputStream (const URL& url,
  6581. const bool isPost_,
  6582. URL::OpenStreamProgressCallback* const progressCallback_,
  6583. void* const progressCallbackContext_,
  6584. const String& extraHeaders,
  6585. const int timeOutMs_,
  6586. StringPairArray* const responseHeaders)
  6587. : position (0),
  6588. finished (false),
  6589. isPost (isPost_),
  6590. progressCallback (progressCallback_),
  6591. progressCallbackContext (progressCallbackContext_),
  6592. timeOutMs (timeOutMs_)
  6593. {
  6594. server = url.toString (! isPost);
  6595. if (isPost_)
  6596. createHeadersAndPostData (url);
  6597. headers += extraHeaders;
  6598. if (! headers.endsWithChar ('\n'))
  6599. headers << "\r\n";
  6600. handle = juce_openInternetFile (server, headers, postData, isPost,
  6601. progressCallback_, progressCallbackContext_,
  6602. timeOutMs);
  6603. if (responseHeaders != 0)
  6604. juce_getInternetFileHeaders (handle, *responseHeaders);
  6605. }
  6606. ~WebInputStream()
  6607. {
  6608. juce_closeInternetFile (handle);
  6609. }
  6610. bool isError() const { return handle == 0; }
  6611. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6612. bool isExhausted() { return finished; }
  6613. int64 getPosition() { return position; }
  6614. int read (void* dest, int bytes)
  6615. {
  6616. if (finished || isError())
  6617. {
  6618. return 0;
  6619. }
  6620. else
  6621. {
  6622. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6623. position += bytesRead;
  6624. if (bytesRead == 0)
  6625. finished = true;
  6626. return bytesRead;
  6627. }
  6628. }
  6629. bool setPosition (int64 wantedPos)
  6630. {
  6631. if (wantedPos != position)
  6632. {
  6633. finished = false;
  6634. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6635. if (actualPos == wantedPos)
  6636. {
  6637. position = wantedPos;
  6638. }
  6639. else
  6640. {
  6641. if (wantedPos < position)
  6642. {
  6643. juce_closeInternetFile (handle);
  6644. position = 0;
  6645. finished = false;
  6646. handle = juce_openInternetFile (server, headers, postData, isPost,
  6647. progressCallback, progressCallbackContext,
  6648. timeOutMs);
  6649. }
  6650. skipNextBytes (wantedPos - position);
  6651. }
  6652. }
  6653. return true;
  6654. }
  6655. juce_UseDebuggingNewOperator
  6656. private:
  6657. String server, headers;
  6658. MemoryBlock postData;
  6659. int64 position;
  6660. bool finished;
  6661. const bool isPost;
  6662. void* handle;
  6663. URL::OpenStreamProgressCallback* const progressCallback;
  6664. void* const progressCallbackContext;
  6665. const int timeOutMs;
  6666. void createHeadersAndPostData (const URL& url)
  6667. {
  6668. MemoryOutputStream data (256, 256, &postData);
  6669. if (url.getFilesToUpload().size() > 0)
  6670. {
  6671. // need to upload some files, so do it as multi-part...
  6672. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6673. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6674. data << "--" << boundary;
  6675. int i;
  6676. for (i = 0; i < url.getParameters().size(); ++i)
  6677. {
  6678. data << "\r\nContent-Disposition: form-data; name=\""
  6679. << url.getParameters().getAllKeys() [i]
  6680. << "\"\r\n\r\n"
  6681. << url.getParameters().getAllValues() [i]
  6682. << "\r\n--"
  6683. << boundary;
  6684. }
  6685. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6686. {
  6687. const File file (url.getFilesToUpload().getAllValues() [i]);
  6688. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6689. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6690. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6691. const String mimeType (url.getMimeTypesOfUploadFiles()
  6692. .getValue (paramName, String::empty));
  6693. if (mimeType.isNotEmpty())
  6694. data << "Content-Type: " << mimeType << "\r\n";
  6695. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6696. << file << "\r\n--" << boundary;
  6697. }
  6698. data << "--\r\n";
  6699. data.flush();
  6700. }
  6701. else
  6702. {
  6703. data << getMangledParameters (url.getParameters())
  6704. << url.getPostData();
  6705. data.flush();
  6706. // just a short text attachment, so use simple url encoding..
  6707. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6708. + String ((unsigned int) postData.getSize())
  6709. + "\r\n";
  6710. }
  6711. }
  6712. WebInputStream (const WebInputStream&);
  6713. WebInputStream& operator= (const WebInputStream&);
  6714. };
  6715. InputStream* URL::createInputStream (const bool usePostCommand,
  6716. OpenStreamProgressCallback* const progressCallback,
  6717. void* const progressCallbackContext,
  6718. const String& extraHeaders,
  6719. const int timeOutMs,
  6720. StringPairArray* const responseHeaders) const
  6721. {
  6722. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6723. progressCallback, progressCallbackContext,
  6724. extraHeaders, timeOutMs, responseHeaders));
  6725. return wi->isError() ? 0 : wi.release();
  6726. }
  6727. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6728. const bool usePostCommand) const
  6729. {
  6730. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6731. if (in != 0)
  6732. {
  6733. in->readIntoMemoryBlock (destData, -1);
  6734. return true;
  6735. }
  6736. return false;
  6737. }
  6738. const String URL::readEntireTextStream (const bool usePostCommand) const
  6739. {
  6740. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6741. if (in != 0)
  6742. return in->readEntireStreamAsString();
  6743. return String::empty;
  6744. }
  6745. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6746. {
  6747. XmlDocument doc (readEntireTextStream (usePostCommand));
  6748. return doc.getDocumentElement();
  6749. }
  6750. const URL URL::withParameter (const String& parameterName,
  6751. const String& parameterValue) const
  6752. {
  6753. URL u (*this);
  6754. u.parameters.set (parameterName, parameterValue);
  6755. return u;
  6756. }
  6757. const URL URL::withFileToUpload (const String& parameterName,
  6758. const File& fileToUpload,
  6759. const String& mimeType) const
  6760. {
  6761. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6762. URL u (*this);
  6763. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6764. u.mimeTypes.set (parameterName, mimeType);
  6765. return u;
  6766. }
  6767. const URL URL::withPOSTData (const String& postData_) const
  6768. {
  6769. URL u (*this);
  6770. u.postData = postData_;
  6771. return u;
  6772. }
  6773. const StringPairArray& URL::getParameters() const
  6774. {
  6775. return parameters;
  6776. }
  6777. const StringPairArray& URL::getFilesToUpload() const
  6778. {
  6779. return filesToUpload;
  6780. }
  6781. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6782. {
  6783. return mimeTypes;
  6784. }
  6785. const String URL::removeEscapeChars (const String& s)
  6786. {
  6787. String result (s.replaceCharacter ('+', ' '));
  6788. int nextPercent = 0;
  6789. for (;;)
  6790. {
  6791. nextPercent = result.indexOfChar (nextPercent, '%');
  6792. if (nextPercent < 0)
  6793. break;
  6794. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6795. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6796. ++nextPercent;
  6797. }
  6798. return result;
  6799. }
  6800. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6801. {
  6802. String result;
  6803. result.preallocateStorage (s.length() + 8);
  6804. const char* utf8 = s.toUTF8();
  6805. const char* legalChars = isParameter ? "_-.*!'()"
  6806. : "_-$.*!'(),";
  6807. while (*utf8 != 0)
  6808. {
  6809. const char c = *utf8++;
  6810. if (CharacterFunctions::isLetterOrDigit (c)
  6811. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6812. {
  6813. result << c;
  6814. }
  6815. else
  6816. {
  6817. const int v = (int) (uint8) c;
  6818. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6819. }
  6820. }
  6821. return result;
  6822. }
  6823. bool URL::launchInDefaultBrowser() const
  6824. {
  6825. String u (toString (true));
  6826. if (u.containsChar ('@') && ! u.containsChar (':'))
  6827. u = "mailto:" + u;
  6828. return PlatformUtilities::openDocument (u, String::empty);
  6829. }
  6830. END_JUCE_NAMESPACE
  6831. /*** End of inlined file: juce_URL.cpp ***/
  6832. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6833. BEGIN_JUCE_NAMESPACE
  6834. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6835. const int bufferSize_,
  6836. const bool deleteSourceWhenDestroyed)
  6837. : source (source_),
  6838. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6839. bufferSize (jmax (256, bufferSize_)),
  6840. position (source_->getPosition()),
  6841. lastReadPos (0),
  6842. bufferOverlap (128)
  6843. {
  6844. const int sourceSize = (int) source_->getTotalLength();
  6845. if (sourceSize >= 0)
  6846. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6847. bufferStart = position;
  6848. buffer.malloc (bufferSize);
  6849. }
  6850. BufferedInputStream::~BufferedInputStream()
  6851. {
  6852. }
  6853. int64 BufferedInputStream::getTotalLength()
  6854. {
  6855. return source->getTotalLength();
  6856. }
  6857. int64 BufferedInputStream::getPosition()
  6858. {
  6859. return position;
  6860. }
  6861. bool BufferedInputStream::setPosition (int64 newPosition)
  6862. {
  6863. position = jmax ((int64) 0, newPosition);
  6864. return true;
  6865. }
  6866. bool BufferedInputStream::isExhausted()
  6867. {
  6868. return (position >= lastReadPos)
  6869. && source->isExhausted();
  6870. }
  6871. void BufferedInputStream::ensureBuffered()
  6872. {
  6873. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6874. if (position < bufferStart || position >= bufferEndOverlap)
  6875. {
  6876. int bytesRead;
  6877. if (position < lastReadPos
  6878. && position >= bufferEndOverlap
  6879. && position >= bufferStart)
  6880. {
  6881. const int bytesToKeep = (int) (lastReadPos - position);
  6882. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6883. bufferStart = position;
  6884. bytesRead = source->read (buffer + bytesToKeep,
  6885. bufferSize - bytesToKeep);
  6886. lastReadPos += bytesRead;
  6887. bytesRead += bytesToKeep;
  6888. }
  6889. else
  6890. {
  6891. bufferStart = position;
  6892. source->setPosition (bufferStart);
  6893. bytesRead = source->read (buffer, bufferSize);
  6894. lastReadPos = bufferStart + bytesRead;
  6895. }
  6896. while (bytesRead < bufferSize)
  6897. buffer [bytesRead++] = 0;
  6898. }
  6899. }
  6900. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6901. {
  6902. if (position >= bufferStart
  6903. && position + maxBytesToRead <= lastReadPos)
  6904. {
  6905. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6906. position += maxBytesToRead;
  6907. return maxBytesToRead;
  6908. }
  6909. else
  6910. {
  6911. if (position < bufferStart || position >= lastReadPos)
  6912. ensureBuffered();
  6913. int bytesRead = 0;
  6914. while (maxBytesToRead > 0)
  6915. {
  6916. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6917. if (bytesAvailable > 0)
  6918. {
  6919. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6920. maxBytesToRead -= bytesAvailable;
  6921. bytesRead += bytesAvailable;
  6922. position += bytesAvailable;
  6923. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6924. }
  6925. const int64 oldLastReadPos = lastReadPos;
  6926. ensureBuffered();
  6927. if (oldLastReadPos == lastReadPos)
  6928. break; // if ensureBuffered() failed to read any more data, bail out
  6929. if (isExhausted())
  6930. break;
  6931. }
  6932. return bytesRead;
  6933. }
  6934. }
  6935. const String BufferedInputStream::readString()
  6936. {
  6937. if (position >= bufferStart
  6938. && position < lastReadPos)
  6939. {
  6940. const int maxChars = (int) (lastReadPos - position);
  6941. const char* const src = buffer + (int) (position - bufferStart);
  6942. for (int i = 0; i < maxChars; ++i)
  6943. {
  6944. if (src[i] == 0)
  6945. {
  6946. position += i + 1;
  6947. return String::fromUTF8 (src, i);
  6948. }
  6949. }
  6950. }
  6951. return InputStream::readString();
  6952. }
  6953. END_JUCE_NAMESPACE
  6954. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6955. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6956. BEGIN_JUCE_NAMESPACE
  6957. FileInputSource::FileInputSource (const File& file_)
  6958. : file (file_)
  6959. {
  6960. }
  6961. FileInputSource::~FileInputSource()
  6962. {
  6963. }
  6964. InputStream* FileInputSource::createInputStream()
  6965. {
  6966. return file.createInputStream();
  6967. }
  6968. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6969. {
  6970. return file.getSiblingFile (relatedItemPath).createInputStream();
  6971. }
  6972. int64 FileInputSource::hashCode() const
  6973. {
  6974. return file.hashCode();
  6975. }
  6976. END_JUCE_NAMESPACE
  6977. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6978. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6979. BEGIN_JUCE_NAMESPACE
  6980. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6981. const size_t sourceDataSize,
  6982. const bool keepInternalCopy)
  6983. : data (static_cast <const char*> (sourceData)),
  6984. dataSize (sourceDataSize),
  6985. position (0)
  6986. {
  6987. if (keepInternalCopy)
  6988. {
  6989. internalCopy.append (data, sourceDataSize);
  6990. data = static_cast <const char*> (internalCopy.getData());
  6991. }
  6992. }
  6993. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6994. const bool keepInternalCopy)
  6995. : data (static_cast <const char*> (sourceData.getData())),
  6996. dataSize (sourceData.getSize()),
  6997. position (0)
  6998. {
  6999. if (keepInternalCopy)
  7000. {
  7001. internalCopy = sourceData;
  7002. data = static_cast <const char*> (internalCopy.getData());
  7003. }
  7004. }
  7005. MemoryInputStream::~MemoryInputStream()
  7006. {
  7007. }
  7008. int64 MemoryInputStream::getTotalLength()
  7009. {
  7010. return dataSize;
  7011. }
  7012. int MemoryInputStream::read (void* const buffer, const int howMany)
  7013. {
  7014. jassert (howMany >= 0);
  7015. const int num = jmin (howMany, (int) (dataSize - position));
  7016. memcpy (buffer, data + position, num);
  7017. position += num;
  7018. return (int) num;
  7019. }
  7020. bool MemoryInputStream::isExhausted()
  7021. {
  7022. return (position >= dataSize);
  7023. }
  7024. bool MemoryInputStream::setPosition (const int64 pos)
  7025. {
  7026. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7027. return true;
  7028. }
  7029. int64 MemoryInputStream::getPosition()
  7030. {
  7031. return position;
  7032. }
  7033. END_JUCE_NAMESPACE
  7034. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7035. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7036. BEGIN_JUCE_NAMESPACE
  7037. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  7038. const size_t blockSizeToIncreaseBy,
  7039. MemoryBlock* const memoryBlockToWriteTo)
  7040. : data (memoryBlockToWriteTo),
  7041. position (0),
  7042. size (0),
  7043. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  7044. {
  7045. if (data == 0)
  7046. dataToDelete = data = new MemoryBlock (initialSize);
  7047. else
  7048. data->setSize (initialSize, false);
  7049. }
  7050. MemoryOutputStream::~MemoryOutputStream()
  7051. {
  7052. flush();
  7053. }
  7054. void MemoryOutputStream::flush()
  7055. {
  7056. if (dataToDelete == 0)
  7057. data->setSize (size, false);
  7058. }
  7059. void MemoryOutputStream::reset() throw()
  7060. {
  7061. position = 0;
  7062. size = 0;
  7063. }
  7064. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7065. {
  7066. if (howMany > 0)
  7067. {
  7068. size_t storageNeeded = position + howMany;
  7069. if (storageNeeded >= data->getSize())
  7070. {
  7071. // if we need more space, increase the block by at least 10%..
  7072. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7073. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7074. data->ensureSize (storageNeeded);
  7075. }
  7076. data->copyFrom (buffer, (int) position, howMany);
  7077. position += howMany;
  7078. size = jmax (size, position);
  7079. }
  7080. return true;
  7081. }
  7082. const char* MemoryOutputStream::getData() const throw()
  7083. {
  7084. char* const d = static_cast <char*> (data->getData());
  7085. if (data->getSize() > size)
  7086. d [size] = 0;
  7087. return d;
  7088. }
  7089. bool MemoryOutputStream::setPosition (int64 newPosition)
  7090. {
  7091. if (newPosition <= (int64) size)
  7092. {
  7093. // ok to seek backwards
  7094. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7095. return true;
  7096. }
  7097. else
  7098. {
  7099. // trying to make it bigger isn't a good thing to do..
  7100. return false;
  7101. }
  7102. }
  7103. const String MemoryOutputStream::toUTF8() const
  7104. {
  7105. return String (getData(), getDataSize());
  7106. }
  7107. END_JUCE_NAMESPACE
  7108. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7109. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7110. BEGIN_JUCE_NAMESPACE
  7111. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7112. const int64 startPositionInSourceStream_,
  7113. const int64 lengthOfSourceStream_,
  7114. const bool deleteSourceWhenDestroyed)
  7115. : source (sourceStream),
  7116. startPositionInSourceStream (startPositionInSourceStream_),
  7117. lengthOfSourceStream (lengthOfSourceStream_)
  7118. {
  7119. if (deleteSourceWhenDestroyed)
  7120. sourceToDelete = source;
  7121. setPosition (0);
  7122. }
  7123. SubregionStream::~SubregionStream()
  7124. {
  7125. }
  7126. int64 SubregionStream::getTotalLength()
  7127. {
  7128. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7129. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7130. : srcLen;
  7131. }
  7132. int64 SubregionStream::getPosition()
  7133. {
  7134. return source->getPosition() - startPositionInSourceStream;
  7135. }
  7136. bool SubregionStream::setPosition (int64 newPosition)
  7137. {
  7138. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7139. }
  7140. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7141. {
  7142. if (lengthOfSourceStream < 0)
  7143. {
  7144. return source->read (destBuffer, maxBytesToRead);
  7145. }
  7146. else
  7147. {
  7148. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7149. if (maxBytesToRead <= 0)
  7150. return 0;
  7151. return source->read (destBuffer, maxBytesToRead);
  7152. }
  7153. }
  7154. bool SubregionStream::isExhausted()
  7155. {
  7156. if (lengthOfSourceStream >= 0)
  7157. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7158. else
  7159. return source->isExhausted();
  7160. }
  7161. END_JUCE_NAMESPACE
  7162. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7163. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7164. BEGIN_JUCE_NAMESPACE
  7165. PerformanceCounter::PerformanceCounter (const String& name_,
  7166. int runsPerPrintout,
  7167. const File& loggingFile)
  7168. : name (name_),
  7169. numRuns (0),
  7170. runsPerPrint (runsPerPrintout),
  7171. totalTime (0),
  7172. outputFile (loggingFile)
  7173. {
  7174. if (outputFile != File::nonexistent)
  7175. {
  7176. String s ("**** Counter for \"");
  7177. s << name_ << "\" started at: "
  7178. << Time::getCurrentTime().toString (true, true)
  7179. << "\r\n";
  7180. outputFile.appendText (s, false, false);
  7181. }
  7182. }
  7183. PerformanceCounter::~PerformanceCounter()
  7184. {
  7185. printStatistics();
  7186. }
  7187. void PerformanceCounter::start()
  7188. {
  7189. started = Time::getHighResolutionTicks();
  7190. }
  7191. void PerformanceCounter::stop()
  7192. {
  7193. const int64 now = Time::getHighResolutionTicks();
  7194. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7195. if (++numRuns == runsPerPrint)
  7196. printStatistics();
  7197. }
  7198. void PerformanceCounter::printStatistics()
  7199. {
  7200. if (numRuns > 0)
  7201. {
  7202. String s ("Performance count for \"");
  7203. s << name << "\" - average over " << numRuns << " run(s) = ";
  7204. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7205. if (micros > 10000)
  7206. s << (micros/1000) << " millisecs";
  7207. else
  7208. s << micros << " microsecs";
  7209. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7210. Logger::outputDebugString (s);
  7211. s << "\r\n";
  7212. if (outputFile != File::nonexistent)
  7213. outputFile.appendText (s, false, false);
  7214. numRuns = 0;
  7215. totalTime = 0;
  7216. }
  7217. }
  7218. END_JUCE_NAMESPACE
  7219. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7220. /*** Start of inlined file: juce_Uuid.cpp ***/
  7221. BEGIN_JUCE_NAMESPACE
  7222. Uuid::Uuid()
  7223. {
  7224. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7225. // to make it very very unlikely that two UUIDs will ever be the same..
  7226. static int64 macAddresses[2];
  7227. static bool hasCheckedMacAddresses = false;
  7228. if (! hasCheckedMacAddresses)
  7229. {
  7230. hasCheckedMacAddresses = true;
  7231. SystemStats::getMACAddresses (macAddresses, 2);
  7232. }
  7233. value.asInt64[0] = macAddresses[0];
  7234. value.asInt64[1] = macAddresses[1];
  7235. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7236. // whose seed will carry over between calls to this method.
  7237. Random r (macAddresses[0] ^ macAddresses[1]
  7238. ^ Random::getSystemRandom().nextInt64());
  7239. for (int i = 4; --i >= 0;)
  7240. {
  7241. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7242. value.asInt[i] ^= r.nextInt();
  7243. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7244. }
  7245. }
  7246. Uuid::~Uuid() throw()
  7247. {
  7248. }
  7249. Uuid::Uuid (const Uuid& other)
  7250. : value (other.value)
  7251. {
  7252. }
  7253. Uuid& Uuid::operator= (const Uuid& other)
  7254. {
  7255. value = other.value;
  7256. return *this;
  7257. }
  7258. bool Uuid::operator== (const Uuid& other) const
  7259. {
  7260. return value.asInt64[0] == other.value.asInt64[0]
  7261. && value.asInt64[1] == other.value.asInt64[1];
  7262. }
  7263. bool Uuid::operator!= (const Uuid& other) const
  7264. {
  7265. return ! operator== (other);
  7266. }
  7267. bool Uuid::isNull() const throw()
  7268. {
  7269. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7270. }
  7271. const String Uuid::toString() const
  7272. {
  7273. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7274. }
  7275. Uuid::Uuid (const String& uuidString)
  7276. {
  7277. operator= (uuidString);
  7278. }
  7279. Uuid& Uuid::operator= (const String& uuidString)
  7280. {
  7281. MemoryBlock mb;
  7282. mb.loadFromHexString (uuidString);
  7283. mb.ensureSize (sizeof (value.asBytes), true);
  7284. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7285. return *this;
  7286. }
  7287. Uuid::Uuid (const uint8* const rawData)
  7288. {
  7289. operator= (rawData);
  7290. }
  7291. Uuid& Uuid::operator= (const uint8* const rawData)
  7292. {
  7293. if (rawData != 0)
  7294. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7295. else
  7296. zeromem (value.asBytes, sizeof (value.asBytes));
  7297. return *this;
  7298. }
  7299. END_JUCE_NAMESPACE
  7300. /*** End of inlined file: juce_Uuid.cpp ***/
  7301. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7302. BEGIN_JUCE_NAMESPACE
  7303. class ZipFile::ZipEntryInfo
  7304. {
  7305. public:
  7306. ZipFile::ZipEntry entry;
  7307. int streamOffset;
  7308. int compressedSize;
  7309. bool compressed;
  7310. };
  7311. class ZipFile::ZipInputStream : public InputStream
  7312. {
  7313. public:
  7314. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7315. : file (file_),
  7316. zipEntryInfo (zei),
  7317. pos (0),
  7318. headerSize (0),
  7319. inputStream (0)
  7320. {
  7321. inputStream = file_.inputStream;
  7322. if (file_.inputSource != 0)
  7323. {
  7324. inputStream = file.inputSource->createInputStream();
  7325. }
  7326. else
  7327. {
  7328. #if JUCE_DEBUG
  7329. file_.numOpenStreams++;
  7330. #endif
  7331. }
  7332. char buffer [30];
  7333. if (inputStream != 0
  7334. && inputStream->setPosition (zei.streamOffset)
  7335. && inputStream->read (buffer, 30) == 30
  7336. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7337. {
  7338. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7339. + ByteOrder::littleEndianShort (buffer + 28);
  7340. }
  7341. }
  7342. ~ZipInputStream() throw()
  7343. {
  7344. #if JUCE_DEBUG
  7345. if (inputStream != 0 && inputStream == file.inputStream)
  7346. file.numOpenStreams--;
  7347. #endif
  7348. if (inputStream != file.inputStream)
  7349. delete inputStream;
  7350. }
  7351. int64 getTotalLength() throw()
  7352. {
  7353. return zipEntryInfo.compressedSize;
  7354. }
  7355. int read (void* buffer, int howMany) throw()
  7356. {
  7357. if (headerSize <= 0)
  7358. return 0;
  7359. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7360. if (inputStream == 0)
  7361. return 0;
  7362. int num;
  7363. if (inputStream == file.inputStream)
  7364. {
  7365. const ScopedLock sl (file.lock);
  7366. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7367. num = inputStream->read (buffer, howMany);
  7368. }
  7369. else
  7370. {
  7371. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7372. num = inputStream->read (buffer, howMany);
  7373. }
  7374. pos += num;
  7375. return num;
  7376. }
  7377. bool isExhausted() throw()
  7378. {
  7379. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7380. }
  7381. int64 getPosition() throw()
  7382. {
  7383. return pos;
  7384. }
  7385. bool setPosition (int64 newPos) throw()
  7386. {
  7387. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7388. return true;
  7389. }
  7390. private:
  7391. ZipFile& file;
  7392. ZipEntryInfo zipEntryInfo;
  7393. int64 pos;
  7394. int headerSize;
  7395. InputStream* inputStream;
  7396. ZipInputStream (const ZipInputStream&);
  7397. ZipInputStream& operator= (const ZipInputStream&);
  7398. };
  7399. ZipFile::ZipFile (InputStream* const source_,
  7400. const bool deleteStreamWhenDestroyed) throw()
  7401. : inputStream (source_)
  7402. #if JUCE_DEBUG
  7403. , numOpenStreams (0)
  7404. #endif
  7405. {
  7406. if (deleteStreamWhenDestroyed)
  7407. streamToDelete = inputStream;
  7408. init();
  7409. }
  7410. ZipFile::ZipFile (const File& file)
  7411. : inputStream (0)
  7412. #if JUCE_DEBUG
  7413. , numOpenStreams (0)
  7414. #endif
  7415. {
  7416. inputSource = new FileInputSource (file);
  7417. init();
  7418. }
  7419. ZipFile::ZipFile (InputSource* const inputSource_)
  7420. : inputStream (0),
  7421. inputSource (inputSource_)
  7422. #if JUCE_DEBUG
  7423. , numOpenStreams (0)
  7424. #endif
  7425. {
  7426. init();
  7427. }
  7428. ZipFile::~ZipFile() throw()
  7429. {
  7430. #if JUCE_DEBUG
  7431. entries.clear();
  7432. // If you hit this assertion, it means you've created a stream to read
  7433. // one of the items in the zipfile, but you've forgotten to delete that
  7434. // stream object before deleting the file.. Streams can't be kept open
  7435. // after the file is deleted because they need to share the input
  7436. // stream that the file uses to read itself.
  7437. jassert (numOpenStreams == 0);
  7438. #endif
  7439. }
  7440. int ZipFile::getNumEntries() const throw()
  7441. {
  7442. return entries.size();
  7443. }
  7444. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7445. {
  7446. ZipEntryInfo* const zei = entries [index];
  7447. return zei != 0 ? &(zei->entry) : 0;
  7448. }
  7449. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7450. {
  7451. for (int i = 0; i < entries.size(); ++i)
  7452. if (entries.getUnchecked (i)->entry.filename == fileName)
  7453. return i;
  7454. return -1;
  7455. }
  7456. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7457. {
  7458. return getEntry (getIndexOfFileName (fileName));
  7459. }
  7460. InputStream* ZipFile::createStreamForEntry (const int index)
  7461. {
  7462. ZipEntryInfo* const zei = entries[index];
  7463. InputStream* stream = 0;
  7464. if (zei != 0)
  7465. {
  7466. stream = new ZipInputStream (*this, *zei);
  7467. if (zei->compressed)
  7468. {
  7469. stream = new GZIPDecompressorInputStream (stream, true, true,
  7470. zei->entry.uncompressedSize);
  7471. // (much faster to unzip in big blocks using a buffer..)
  7472. stream = new BufferedInputStream (stream, 32768, true);
  7473. }
  7474. }
  7475. return stream;
  7476. }
  7477. class ZipFile::ZipFilenameComparator
  7478. {
  7479. public:
  7480. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7481. {
  7482. return first->entry.filename.compare (second->entry.filename);
  7483. }
  7484. };
  7485. void ZipFile::sortEntriesByFilename()
  7486. {
  7487. ZipFilenameComparator sorter;
  7488. entries.sort (sorter);
  7489. }
  7490. void ZipFile::init()
  7491. {
  7492. ScopedPointer <InputStream> toDelete;
  7493. InputStream* in = inputStream;
  7494. if (inputSource != 0)
  7495. {
  7496. in = inputSource->createInputStream();
  7497. toDelete = in;
  7498. }
  7499. if (in != 0)
  7500. {
  7501. int numEntries = 0;
  7502. int pos = findEndOfZipEntryTable (in, numEntries);
  7503. if (pos >= 0 && pos < in->getTotalLength())
  7504. {
  7505. const int size = (int) (in->getTotalLength() - pos);
  7506. in->setPosition (pos);
  7507. MemoryBlock headerData;
  7508. if (in->readIntoMemoryBlock (headerData, size) == size)
  7509. {
  7510. pos = 0;
  7511. for (int i = 0; i < numEntries; ++i)
  7512. {
  7513. if (pos + 46 > size)
  7514. break;
  7515. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7516. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7517. if (pos + 46 + fileNameLen > size)
  7518. break;
  7519. ZipEntryInfo* const zei = new ZipEntryInfo();
  7520. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7521. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7522. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7523. const int year = 1980 + (date >> 9);
  7524. const int month = ((date >> 5) & 15) - 1;
  7525. const int day = date & 31;
  7526. const int hours = time >> 11;
  7527. const int minutes = (time >> 5) & 63;
  7528. const int seconds = (time & 31) << 1;
  7529. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7530. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7531. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7532. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7533. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7534. entries.add (zei);
  7535. pos += 46 + fileNameLen
  7536. + ByteOrder::littleEndianShort (buffer + 30)
  7537. + ByteOrder::littleEndianShort (buffer + 32);
  7538. }
  7539. }
  7540. }
  7541. }
  7542. }
  7543. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7544. {
  7545. BufferedInputStream in (input, 8192, false);
  7546. in.setPosition (in.getTotalLength());
  7547. int64 pos = in.getPosition();
  7548. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7549. char buffer [32];
  7550. zeromem (buffer, sizeof (buffer));
  7551. while (pos > lowestPos)
  7552. {
  7553. in.setPosition (pos - 22);
  7554. pos = in.getPosition();
  7555. memcpy (buffer + 22, buffer, 4);
  7556. if (in.read (buffer, 22) != 22)
  7557. return 0;
  7558. for (int i = 0; i < 22; ++i)
  7559. {
  7560. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7561. {
  7562. in.setPosition (pos + i);
  7563. in.read (buffer, 22);
  7564. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7565. return ByteOrder::littleEndianInt (buffer + 16);
  7566. }
  7567. }
  7568. }
  7569. return 0;
  7570. }
  7571. void ZipFile::uncompressTo (const File& targetDirectory,
  7572. const bool shouldOverwriteFiles)
  7573. {
  7574. for (int i = 0; i < entries.size(); ++i)
  7575. {
  7576. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7577. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7578. if (zei.filename.endsWithChar ('/'))
  7579. {
  7580. targetFile.createDirectory(); // (entry is a directory, not a file)
  7581. }
  7582. else
  7583. {
  7584. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7585. if (in != 0)
  7586. {
  7587. if (shouldOverwriteFiles)
  7588. targetFile.deleteFile();
  7589. if ((! targetFile.exists())
  7590. && targetFile.getParentDirectory().createDirectory())
  7591. {
  7592. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7593. if (out != 0)
  7594. {
  7595. out->writeFromInputStream (*in, -1);
  7596. out = 0;
  7597. targetFile.setCreationTime (zei.fileTime);
  7598. targetFile.setLastModificationTime (zei.fileTime);
  7599. targetFile.setLastAccessTime (zei.fileTime);
  7600. }
  7601. }
  7602. }
  7603. }
  7604. }
  7605. }
  7606. END_JUCE_NAMESPACE
  7607. /*** End of inlined file: juce_ZipFile.cpp ***/
  7608. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7609. #if JUCE_MSVC
  7610. #pragma warning (push)
  7611. #pragma warning (disable: 4514 4996)
  7612. #endif
  7613. #include <cwctype>
  7614. #include <cctype>
  7615. #include <ctime>
  7616. BEGIN_JUCE_NAMESPACE
  7617. int CharacterFunctions::length (const char* const s) throw()
  7618. {
  7619. return (int) strlen (s);
  7620. }
  7621. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7622. {
  7623. return (int) wcslen (s);
  7624. }
  7625. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7626. {
  7627. strncpy (dest, src, maxChars);
  7628. }
  7629. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7630. {
  7631. wcsncpy (dest, src, maxChars);
  7632. }
  7633. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7634. {
  7635. mbstowcs (dest, src, maxChars);
  7636. }
  7637. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7638. {
  7639. wcstombs (dest, src, maxChars);
  7640. }
  7641. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7642. {
  7643. return (int) wcstombs (0, src, 0);
  7644. }
  7645. void CharacterFunctions::append (char* dest, const char* src) throw()
  7646. {
  7647. strcat (dest, src);
  7648. }
  7649. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7650. {
  7651. wcscat (dest, src);
  7652. }
  7653. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7654. {
  7655. return strcmp (s1, s2);
  7656. }
  7657. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7658. {
  7659. jassert (s1 != 0 && s2 != 0);
  7660. return wcscmp (s1, s2);
  7661. }
  7662. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7663. {
  7664. jassert (s1 != 0 && s2 != 0);
  7665. return strncmp (s1, s2, maxChars);
  7666. }
  7667. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7668. {
  7669. jassert (s1 != 0 && s2 != 0);
  7670. return wcsncmp (s1, s2, maxChars);
  7671. }
  7672. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7673. {
  7674. jassert (s1 != 0 && s2 != 0);
  7675. for (;;)
  7676. {
  7677. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7678. if (diff != 0)
  7679. return diff;
  7680. else if (*s1 == 0)
  7681. break;
  7682. ++s1;
  7683. ++s2;
  7684. }
  7685. return 0;
  7686. }
  7687. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7688. {
  7689. return -compare (s2, s1);
  7690. }
  7691. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7692. {
  7693. jassert (s1 != 0 && s2 != 0);
  7694. #if JUCE_WINDOWS
  7695. return stricmp (s1, s2);
  7696. #else
  7697. return strcasecmp (s1, s2);
  7698. #endif
  7699. }
  7700. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7701. {
  7702. jassert (s1 != 0 && s2 != 0);
  7703. #if JUCE_WINDOWS
  7704. return _wcsicmp (s1, s2);
  7705. #else
  7706. for (;;)
  7707. {
  7708. if (*s1 != *s2)
  7709. {
  7710. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7711. if (diff != 0)
  7712. return diff < 0 ? -1 : 1;
  7713. }
  7714. else if (*s1 == 0)
  7715. break;
  7716. ++s1;
  7717. ++s2;
  7718. }
  7719. return 0;
  7720. #endif
  7721. }
  7722. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7723. {
  7724. jassert (s1 != 0 && s2 != 0);
  7725. for (;;)
  7726. {
  7727. if (*s1 != *s2)
  7728. {
  7729. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7730. if (diff != 0)
  7731. return diff < 0 ? -1 : 1;
  7732. }
  7733. else if (*s1 == 0)
  7734. break;
  7735. ++s1;
  7736. ++s2;
  7737. }
  7738. return 0;
  7739. }
  7740. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7741. {
  7742. jassert (s1 != 0 && s2 != 0);
  7743. #if JUCE_WINDOWS
  7744. return strnicmp (s1, s2, maxChars);
  7745. #else
  7746. return strncasecmp (s1, s2, maxChars);
  7747. #endif
  7748. }
  7749. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7750. {
  7751. jassert (s1 != 0 && s2 != 0);
  7752. #if JUCE_WINDOWS
  7753. return _wcsnicmp (s1, s2, maxChars);
  7754. #else
  7755. while (--maxChars >= 0)
  7756. {
  7757. if (*s1 != *s2)
  7758. {
  7759. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7760. if (diff != 0)
  7761. return diff < 0 ? -1 : 1;
  7762. }
  7763. else if (*s1 == 0)
  7764. break;
  7765. ++s1;
  7766. ++s2;
  7767. }
  7768. return 0;
  7769. #endif
  7770. }
  7771. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7772. {
  7773. return strstr (haystack, needle);
  7774. }
  7775. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7776. {
  7777. return wcsstr (haystack, needle);
  7778. }
  7779. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7780. {
  7781. if (haystack != 0)
  7782. {
  7783. int i = 0;
  7784. if (ignoreCase)
  7785. {
  7786. const char n1 = toLowerCase (needle);
  7787. const char n2 = toUpperCase (needle);
  7788. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7789. {
  7790. while (haystack[i] != 0)
  7791. {
  7792. if (haystack[i] == n1 || haystack[i] == n2)
  7793. return i;
  7794. ++i;
  7795. }
  7796. return -1;
  7797. }
  7798. jassert (n1 == needle);
  7799. }
  7800. while (haystack[i] != 0)
  7801. {
  7802. if (haystack[i] == needle)
  7803. return i;
  7804. ++i;
  7805. }
  7806. }
  7807. return -1;
  7808. }
  7809. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7810. {
  7811. if (haystack != 0)
  7812. {
  7813. int i = 0;
  7814. if (ignoreCase)
  7815. {
  7816. const juce_wchar n1 = toLowerCase (needle);
  7817. const juce_wchar n2 = toUpperCase (needle);
  7818. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7819. {
  7820. while (haystack[i] != 0)
  7821. {
  7822. if (haystack[i] == n1 || haystack[i] == n2)
  7823. return i;
  7824. ++i;
  7825. }
  7826. return -1;
  7827. }
  7828. jassert (n1 == needle);
  7829. }
  7830. while (haystack[i] != 0)
  7831. {
  7832. if (haystack[i] == needle)
  7833. return i;
  7834. ++i;
  7835. }
  7836. }
  7837. return -1;
  7838. }
  7839. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7840. {
  7841. jassert (haystack != 0);
  7842. int i = 0;
  7843. while (haystack[i] != 0)
  7844. {
  7845. if (haystack[i] == needle)
  7846. return i;
  7847. ++i;
  7848. }
  7849. return -1;
  7850. }
  7851. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7852. {
  7853. jassert (haystack != 0);
  7854. int i = 0;
  7855. while (haystack[i] != 0)
  7856. {
  7857. if (haystack[i] == needle)
  7858. return i;
  7859. ++i;
  7860. }
  7861. return -1;
  7862. }
  7863. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7864. {
  7865. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7866. }
  7867. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7868. {
  7869. if (allowedChars == 0)
  7870. return 0;
  7871. int i = 0;
  7872. for (;;)
  7873. {
  7874. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7875. break;
  7876. ++i;
  7877. }
  7878. return i;
  7879. }
  7880. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7881. {
  7882. return (int) strftime (dest, maxChars, format, tm);
  7883. }
  7884. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7885. {
  7886. return (int) wcsftime (dest, maxChars, format, tm);
  7887. }
  7888. int CharacterFunctions::getIntValue (const char* const s) throw()
  7889. {
  7890. return atoi (s);
  7891. }
  7892. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7893. {
  7894. #if JUCE_WINDOWS
  7895. return _wtoi (s);
  7896. #else
  7897. int v = 0;
  7898. while (isWhitespace (*s))
  7899. ++s;
  7900. const bool isNeg = *s == '-';
  7901. if (isNeg)
  7902. ++s;
  7903. for (;;)
  7904. {
  7905. const wchar_t c = *s++;
  7906. if (c >= '0' && c <= '9')
  7907. v = v * 10 + (int) (c - '0');
  7908. else
  7909. break;
  7910. }
  7911. return isNeg ? -v : v;
  7912. #endif
  7913. }
  7914. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7915. {
  7916. #if JUCE_LINUX
  7917. return atoll (s);
  7918. #elif JUCE_WINDOWS
  7919. return _atoi64 (s);
  7920. #else
  7921. int64 v = 0;
  7922. while (isWhitespace (*s))
  7923. ++s;
  7924. const bool isNeg = *s == '-';
  7925. if (isNeg)
  7926. ++s;
  7927. for (;;)
  7928. {
  7929. const char c = *s++;
  7930. if (c >= '0' && c <= '9')
  7931. v = v * 10 + (int64) (c - '0');
  7932. else
  7933. break;
  7934. }
  7935. return isNeg ? -v : v;
  7936. #endif
  7937. }
  7938. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7939. {
  7940. #if JUCE_WINDOWS
  7941. return _wtoi64 (s);
  7942. #else
  7943. int64 v = 0;
  7944. while (isWhitespace (*s))
  7945. ++s;
  7946. const bool isNeg = *s == '-';
  7947. if (isNeg)
  7948. ++s;
  7949. for (;;)
  7950. {
  7951. const juce_wchar c = *s++;
  7952. if (c >= '0' && c <= '9')
  7953. v = v * 10 + (int64) (c - '0');
  7954. else
  7955. break;
  7956. }
  7957. return isNeg ? -v : v;
  7958. #endif
  7959. }
  7960. static double juce_mulexp10 (const double value, int exponent) throw()
  7961. {
  7962. if (exponent == 0)
  7963. return value;
  7964. if (value == 0)
  7965. return 0;
  7966. const bool negative = (exponent < 0);
  7967. if (negative)
  7968. exponent = -exponent;
  7969. double result = 1.0, power = 10.0;
  7970. for (int bit = 1; exponent != 0; bit <<= 1)
  7971. {
  7972. if ((exponent & bit) != 0)
  7973. {
  7974. exponent ^= bit;
  7975. result *= power;
  7976. if (exponent == 0)
  7977. break;
  7978. }
  7979. power *= power;
  7980. }
  7981. return negative ? (value / result) : (value * result);
  7982. }
  7983. template <class CharType>
  7984. double juce_atof (const CharType* const original) throw()
  7985. {
  7986. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7987. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7988. int exponent = 0, decPointIndex = 0, digit = 0;
  7989. int lastDigit = 0, numSignificantDigits = 0;
  7990. bool isNegative = false, digitsFound = false;
  7991. const int maxSignificantDigits = 15 + 2;
  7992. const CharType* s = original;
  7993. while (CharacterFunctions::isWhitespace (*s))
  7994. ++s;
  7995. switch (*s)
  7996. {
  7997. case '-': isNegative = true; // fall-through..
  7998. case '+': ++s;
  7999. }
  8000. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8001. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8002. for (;;)
  8003. {
  8004. if (CharacterFunctions::isDigit (*s))
  8005. {
  8006. lastDigit = digit;
  8007. digit = *s++ - '0';
  8008. digitsFound = true;
  8009. if (decPointIndex != 0)
  8010. exponentAdjustment[1]++;
  8011. if (numSignificantDigits == 0 && digit == 0)
  8012. continue;
  8013. if (++numSignificantDigits > maxSignificantDigits)
  8014. {
  8015. if (digit > 5)
  8016. ++accumulator [decPointIndex];
  8017. else if (digit == 5 && (lastDigit & 1) != 0)
  8018. ++accumulator [decPointIndex];
  8019. if (decPointIndex > 0)
  8020. exponentAdjustment[1]--;
  8021. else
  8022. exponentAdjustment[0]++;
  8023. while (CharacterFunctions::isDigit (*s))
  8024. {
  8025. ++s;
  8026. if (decPointIndex == 0)
  8027. exponentAdjustment[0]++;
  8028. }
  8029. }
  8030. else
  8031. {
  8032. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8033. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8034. {
  8035. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8036. + accumulator [decPointIndex];
  8037. accumulator [decPointIndex] = 0;
  8038. exponentAccumulator [decPointIndex] = 0;
  8039. }
  8040. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8041. exponentAccumulator [decPointIndex]++;
  8042. }
  8043. }
  8044. else if (decPointIndex == 0 && *s == '.')
  8045. {
  8046. ++s;
  8047. decPointIndex = 1;
  8048. if (numSignificantDigits > maxSignificantDigits)
  8049. {
  8050. while (CharacterFunctions::isDigit (*s))
  8051. ++s;
  8052. break;
  8053. }
  8054. }
  8055. else
  8056. {
  8057. break;
  8058. }
  8059. }
  8060. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8061. if (decPointIndex != 0)
  8062. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8063. if ((*s == 'e' || *s == 'E') && digitsFound)
  8064. {
  8065. bool negativeExponent = false;
  8066. switch (*++s)
  8067. {
  8068. case '-': negativeExponent = true; // fall-through..
  8069. case '+': ++s;
  8070. }
  8071. while (CharacterFunctions::isDigit (*s))
  8072. exponent = (exponent * 10) + (*s++ - '0');
  8073. if (negativeExponent)
  8074. exponent = -exponent;
  8075. }
  8076. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8077. if (decPointIndex != 0)
  8078. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8079. return isNegative ? -r : r;
  8080. }
  8081. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8082. {
  8083. return juce_atof <char> (s);
  8084. }
  8085. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8086. {
  8087. return juce_atof <juce_wchar> (s);
  8088. }
  8089. char CharacterFunctions::toUpperCase (const char character) throw()
  8090. {
  8091. return (char) toupper (character);
  8092. }
  8093. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8094. {
  8095. return towupper (character);
  8096. }
  8097. void CharacterFunctions::toUpperCase (char* s) throw()
  8098. {
  8099. #if JUCE_WINDOWS
  8100. strupr (s);
  8101. #else
  8102. while (*s != 0)
  8103. {
  8104. *s = toUpperCase (*s);
  8105. ++s;
  8106. }
  8107. #endif
  8108. }
  8109. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8110. {
  8111. #if JUCE_WINDOWS
  8112. _wcsupr (s);
  8113. #else
  8114. while (*s != 0)
  8115. {
  8116. *s = toUpperCase (*s);
  8117. ++s;
  8118. }
  8119. #endif
  8120. }
  8121. bool CharacterFunctions::isUpperCase (const char character) throw()
  8122. {
  8123. return isupper (character) != 0;
  8124. }
  8125. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8126. {
  8127. #if JUCE_WINDOWS
  8128. return iswupper (character) != 0;
  8129. #else
  8130. return toLowerCase (character) != character;
  8131. #endif
  8132. }
  8133. char CharacterFunctions::toLowerCase (const char character) throw()
  8134. {
  8135. return (char) tolower (character);
  8136. }
  8137. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8138. {
  8139. return towlower (character);
  8140. }
  8141. void CharacterFunctions::toLowerCase (char* s) throw()
  8142. {
  8143. #if JUCE_WINDOWS
  8144. strlwr (s);
  8145. #else
  8146. while (*s != 0)
  8147. {
  8148. *s = toLowerCase (*s);
  8149. ++s;
  8150. }
  8151. #endif
  8152. }
  8153. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8154. {
  8155. #if JUCE_WINDOWS
  8156. _wcslwr (s);
  8157. #else
  8158. while (*s != 0)
  8159. {
  8160. *s = toLowerCase (*s);
  8161. ++s;
  8162. }
  8163. #endif
  8164. }
  8165. bool CharacterFunctions::isLowerCase (const char character) throw()
  8166. {
  8167. return islower (character) != 0;
  8168. }
  8169. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8170. {
  8171. #if JUCE_WINDOWS
  8172. return iswlower (character) != 0;
  8173. #else
  8174. return toUpperCase (character) != character;
  8175. #endif
  8176. }
  8177. bool CharacterFunctions::isWhitespace (const char character) throw()
  8178. {
  8179. return character == ' ' || (character <= 13 && character >= 9);
  8180. }
  8181. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8182. {
  8183. return iswspace (character) != 0;
  8184. }
  8185. bool CharacterFunctions::isDigit (const char character) throw()
  8186. {
  8187. return (character >= '0' && character <= '9');
  8188. }
  8189. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8190. {
  8191. return iswdigit (character) != 0;
  8192. }
  8193. bool CharacterFunctions::isLetter (const char character) throw()
  8194. {
  8195. return (character >= 'a' && character <= 'z')
  8196. || (character >= 'A' && character <= 'Z');
  8197. }
  8198. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8199. {
  8200. return iswalpha (character) != 0;
  8201. }
  8202. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8203. {
  8204. return (character >= 'a' && character <= 'z')
  8205. || (character >= 'A' && character <= 'Z')
  8206. || (character >= '0' && character <= '9');
  8207. }
  8208. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8209. {
  8210. return iswalnum (character) != 0;
  8211. }
  8212. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8213. {
  8214. unsigned int d = digit - '0';
  8215. if (d < (unsigned int) 10)
  8216. return (int) d;
  8217. d += (unsigned int) ('0' - 'a');
  8218. if (d < (unsigned int) 6)
  8219. return (int) d + 10;
  8220. d += (unsigned int) ('a' - 'A');
  8221. if (d < (unsigned int) 6)
  8222. return (int) d + 10;
  8223. return -1;
  8224. }
  8225. #if JUCE_MSVC
  8226. #pragma warning (pop)
  8227. #endif
  8228. END_JUCE_NAMESPACE
  8229. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8230. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8231. BEGIN_JUCE_NAMESPACE
  8232. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8233. {
  8234. loadFromText (fileContents);
  8235. }
  8236. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8237. {
  8238. loadFromText (fileToLoad.loadFileAsString());
  8239. }
  8240. LocalisedStrings::~LocalisedStrings()
  8241. {
  8242. }
  8243. const String LocalisedStrings::translate (const String& text) const
  8244. {
  8245. return translations.getValue (text, text);
  8246. }
  8247. static int findCloseQuote (const String& text, int startPos)
  8248. {
  8249. juce_wchar lastChar = 0;
  8250. for (;;)
  8251. {
  8252. const juce_wchar c = text [startPos];
  8253. if (c == 0 || (c == '"' && lastChar != '\\'))
  8254. break;
  8255. lastChar = c;
  8256. ++startPos;
  8257. }
  8258. return startPos;
  8259. }
  8260. static const String unescapeString (const String& s)
  8261. {
  8262. return s.replace ("\\\"", "\"")
  8263. .replace ("\\\'", "\'")
  8264. .replace ("\\t", "\t")
  8265. .replace ("\\r", "\r")
  8266. .replace ("\\n", "\n");
  8267. }
  8268. void LocalisedStrings::loadFromText (const String& fileContents)
  8269. {
  8270. StringArray lines;
  8271. lines.addLines (fileContents);
  8272. for (int i = 0; i < lines.size(); ++i)
  8273. {
  8274. String line (lines[i].trim());
  8275. if (line.startsWithChar ('"'))
  8276. {
  8277. int closeQuote = findCloseQuote (line, 1);
  8278. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8279. if (originalText.isNotEmpty())
  8280. {
  8281. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8282. closeQuote = findCloseQuote (line, openingQuote + 1);
  8283. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8284. if (newText.isNotEmpty())
  8285. translations.set (originalText, newText);
  8286. }
  8287. }
  8288. else if (line.startsWithIgnoreCase ("language:"))
  8289. {
  8290. languageName = line.substring (9).trim();
  8291. }
  8292. else if (line.startsWithIgnoreCase ("countries:"))
  8293. {
  8294. countryCodes.addTokens (line.substring (10).trim(), true);
  8295. countryCodes.trim();
  8296. countryCodes.removeEmptyStrings();
  8297. }
  8298. }
  8299. }
  8300. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8301. {
  8302. translations.setIgnoresCase (shouldIgnoreCase);
  8303. }
  8304. static CriticalSection currentMappingsLock;
  8305. static LocalisedStrings* currentMappings = 0;
  8306. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8307. {
  8308. const ScopedLock sl (currentMappingsLock);
  8309. delete currentMappings;
  8310. currentMappings = newTranslations;
  8311. }
  8312. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8313. {
  8314. return currentMappings;
  8315. }
  8316. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8317. {
  8318. const ScopedLock sl (currentMappingsLock);
  8319. if (currentMappings != 0)
  8320. return currentMappings->translate (text);
  8321. return text;
  8322. }
  8323. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8324. {
  8325. return translateWithCurrentMappings (String (text));
  8326. }
  8327. END_JUCE_NAMESPACE
  8328. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8329. /*** Start of inlined file: juce_String.cpp ***/
  8330. #if JUCE_MSVC
  8331. #pragma warning (push)
  8332. #pragma warning (disable: 4514)
  8333. #endif
  8334. #include <locale>
  8335. BEGIN_JUCE_NAMESPACE
  8336. #if JUCE_MSVC
  8337. #pragma warning (pop)
  8338. #endif
  8339. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8340. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8341. #endif
  8342. class StringHolder
  8343. {
  8344. public:
  8345. StringHolder()
  8346. : refCount (0x3fffffff), allocatedNumChars (0)
  8347. {
  8348. text[0] = 0;
  8349. }
  8350. static juce_wchar* createUninitialised (const size_t numChars)
  8351. {
  8352. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8353. s->refCount.value = 0;
  8354. s->allocatedNumChars = numChars;
  8355. return &(s->text[0]);
  8356. }
  8357. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8358. {
  8359. juce_wchar* const dest = createUninitialised (numChars);
  8360. copyChars (dest, src, numChars);
  8361. return dest;
  8362. }
  8363. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8364. {
  8365. juce_wchar* const dest = createUninitialised (numChars);
  8366. CharacterFunctions::copy (dest, src, (int) numChars);
  8367. dest [numChars] = 0;
  8368. return dest;
  8369. }
  8370. static inline juce_wchar* getEmpty() throw()
  8371. {
  8372. return &(empty.text[0]);
  8373. }
  8374. static void retain (juce_wchar* const text) throw()
  8375. {
  8376. ++(bufferFromText (text)->refCount);
  8377. }
  8378. static inline void release (StringHolder* const b) throw()
  8379. {
  8380. if (--(b->refCount) == -1 && b != &empty)
  8381. delete[] reinterpret_cast <char*> (b);
  8382. }
  8383. static void release (juce_wchar* const text) throw()
  8384. {
  8385. release (bufferFromText (text));
  8386. }
  8387. static juce_wchar* makeUnique (juce_wchar* const text)
  8388. {
  8389. StringHolder* const b = bufferFromText (text);
  8390. if (b->refCount.get() <= 0)
  8391. return text;
  8392. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8393. release (b);
  8394. return newText;
  8395. }
  8396. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8397. {
  8398. StringHolder* const b = bufferFromText (text);
  8399. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8400. return text;
  8401. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8402. copyChars (newText, text, b->allocatedNumChars);
  8403. release (b);
  8404. return newText;
  8405. }
  8406. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8407. {
  8408. return bufferFromText (text)->allocatedNumChars;
  8409. }
  8410. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8411. {
  8412. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8413. dest [numChars] = 0;
  8414. }
  8415. Atomic<int> refCount;
  8416. size_t allocatedNumChars;
  8417. juce_wchar text[1];
  8418. static StringHolder empty;
  8419. private:
  8420. static inline StringHolder* bufferFromText (void* const text) throw()
  8421. {
  8422. // (Can't use offsetof() here because of warnings about this not being a POD)
  8423. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8424. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8425. }
  8426. };
  8427. StringHolder StringHolder::empty;
  8428. const String String::empty;
  8429. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8430. {
  8431. jassert (t[numChars] == 0); // must have a null terminator
  8432. text = StringHolder::createCopy (t, numChars);
  8433. }
  8434. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8435. {
  8436. if (numExtraChars > 0)
  8437. {
  8438. const int oldLen = length();
  8439. const int newTotalLen = oldLen + numExtraChars;
  8440. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8441. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8442. }
  8443. }
  8444. void String::preallocateStorage (const size_t numChars)
  8445. {
  8446. text = StringHolder::makeUniqueWithSize (text, numChars);
  8447. }
  8448. String::String() throw()
  8449. : text (StringHolder::getEmpty())
  8450. {
  8451. }
  8452. String::~String() throw()
  8453. {
  8454. StringHolder::release (text);
  8455. }
  8456. String::String (const String& other) throw()
  8457. : text (other.text)
  8458. {
  8459. StringHolder::retain (text);
  8460. }
  8461. void String::swapWith (String& other) throw()
  8462. {
  8463. swapVariables (text, other.text);
  8464. }
  8465. String& String::operator= (const String& other) throw()
  8466. {
  8467. juce_wchar* const newText = other.text;
  8468. StringHolder::retain (newText);
  8469. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8470. return *this;
  8471. }
  8472. String::String (const size_t numChars, const int /*dummyVariable*/)
  8473. : text (StringHolder::createUninitialised (numChars))
  8474. {
  8475. }
  8476. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8477. {
  8478. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8479. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8480. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8481. }
  8482. String::String (const char* const t)
  8483. {
  8484. if (t != 0 && *t != 0)
  8485. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8486. else
  8487. text = StringHolder::getEmpty();
  8488. }
  8489. String::String (const juce_wchar* const t)
  8490. {
  8491. if (t != 0 && *t != 0)
  8492. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8493. else
  8494. text = StringHolder::getEmpty();
  8495. }
  8496. String::String (const char* const t, const size_t maxChars)
  8497. {
  8498. int i;
  8499. for (i = 0; (size_t) i < maxChars; ++i)
  8500. if (t[i] == 0)
  8501. break;
  8502. if (i > 0)
  8503. text = StringHolder::createCopy (t, i);
  8504. else
  8505. text = StringHolder::getEmpty();
  8506. }
  8507. String::String (const juce_wchar* const t, const size_t maxChars)
  8508. {
  8509. int i;
  8510. for (i = 0; (size_t) i < maxChars; ++i)
  8511. if (t[i] == 0)
  8512. break;
  8513. if (i > 0)
  8514. text = StringHolder::createCopy (t, i);
  8515. else
  8516. text = StringHolder::getEmpty();
  8517. }
  8518. const String String::charToString (const juce_wchar character)
  8519. {
  8520. String result ((size_t) 1, (int) 0);
  8521. result.text[0] = character;
  8522. result.text[1] = 0;
  8523. return result;
  8524. }
  8525. namespace NumberToStringConverters
  8526. {
  8527. // pass in a pointer to the END of a buffer..
  8528. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8529. {
  8530. *--t = 0;
  8531. int64 v = (n >= 0) ? n : -n;
  8532. do
  8533. {
  8534. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8535. v /= 10;
  8536. } while (v > 0);
  8537. if (n < 0)
  8538. *--t = '-';
  8539. return t;
  8540. }
  8541. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8542. {
  8543. *--t = 0;
  8544. do
  8545. {
  8546. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8547. v /= 10;
  8548. } while (v > 0);
  8549. return t;
  8550. }
  8551. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8552. {
  8553. if (n == (int) 0x80000000) // (would cause an overflow)
  8554. return int64ToString (t, n);
  8555. *--t = 0;
  8556. int v = abs (n);
  8557. do
  8558. {
  8559. *--t = (juce_wchar) ('0' + (v % 10));
  8560. v /= 10;
  8561. } while (v > 0);
  8562. if (n < 0)
  8563. *--t = '-';
  8564. return t;
  8565. }
  8566. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8567. {
  8568. *--t = 0;
  8569. do
  8570. {
  8571. *--t = (juce_wchar) ('0' + (v % 10));
  8572. v /= 10;
  8573. } while (v > 0);
  8574. return t;
  8575. }
  8576. static juce_wchar getDecimalPoint()
  8577. {
  8578. #if JUCE_WINDOWS && _MSC_VER < 1400
  8579. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8580. #else
  8581. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8582. #endif
  8583. return dp;
  8584. }
  8585. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8586. {
  8587. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8588. {
  8589. juce_wchar* const end = buffer + numChars;
  8590. juce_wchar* t = end;
  8591. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8592. *--t = (juce_wchar) 0;
  8593. while (numDecPlaces >= 0 || v > 0)
  8594. {
  8595. if (numDecPlaces == 0)
  8596. *--t = getDecimalPoint();
  8597. *--t = (juce_wchar) ('0' + (v % 10));
  8598. v /= 10;
  8599. --numDecPlaces;
  8600. }
  8601. if (n < 0)
  8602. *--t = '-';
  8603. len = end - t - 1;
  8604. return t;
  8605. }
  8606. else
  8607. {
  8608. #if JUCE_WINDOWS
  8609. #if _MSC_VER <= 1400
  8610. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8611. #else
  8612. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8613. #endif
  8614. #else
  8615. len = swprintf (buffer, numChars, L"%.9g", n);
  8616. #endif
  8617. return buffer;
  8618. }
  8619. }
  8620. }
  8621. String::String (const int number)
  8622. {
  8623. juce_wchar buffer [16];
  8624. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8625. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8626. createInternal (start, end - start - 1);
  8627. }
  8628. String::String (const unsigned int number)
  8629. {
  8630. juce_wchar buffer [16];
  8631. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8632. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8633. createInternal (start, end - start - 1);
  8634. }
  8635. String::String (const short number)
  8636. {
  8637. juce_wchar buffer [16];
  8638. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8639. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8640. createInternal (start, end - start - 1);
  8641. }
  8642. String::String (const unsigned short number)
  8643. {
  8644. juce_wchar buffer [16];
  8645. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8646. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8647. createInternal (start, end - start - 1);
  8648. }
  8649. String::String (const int64 number)
  8650. {
  8651. juce_wchar buffer [32];
  8652. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8653. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8654. createInternal (start, end - start - 1);
  8655. }
  8656. String::String (const uint64 number)
  8657. {
  8658. juce_wchar buffer [32];
  8659. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8660. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8661. createInternal (start, end - start - 1);
  8662. }
  8663. String::String (const float number, const int numberOfDecimalPlaces)
  8664. {
  8665. juce_wchar buffer [48];
  8666. size_t len;
  8667. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8668. createInternal (start, len);
  8669. }
  8670. String::String (const double number, const int numberOfDecimalPlaces)
  8671. {
  8672. juce_wchar buffer [48];
  8673. size_t len;
  8674. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8675. createInternal (start, len);
  8676. }
  8677. int String::length() const throw()
  8678. {
  8679. return CharacterFunctions::length (text);
  8680. }
  8681. int String::hashCode() const throw()
  8682. {
  8683. const juce_wchar* t = text;
  8684. int result = 0;
  8685. while (*t != (juce_wchar) 0)
  8686. result = 31 * result + *t++;
  8687. return result;
  8688. }
  8689. int64 String::hashCode64() const throw()
  8690. {
  8691. const juce_wchar* t = text;
  8692. int64 result = 0;
  8693. while (*t != (juce_wchar) 0)
  8694. result = 101 * result + *t++;
  8695. return result;
  8696. }
  8697. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8698. {
  8699. return string1.compare (string2) == 0;
  8700. }
  8701. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8702. {
  8703. return string1.compare (string2) == 0;
  8704. }
  8705. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8706. {
  8707. return string1.compare (string2) == 0;
  8708. }
  8709. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8710. {
  8711. return string1.compare (string2) != 0;
  8712. }
  8713. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8714. {
  8715. return string1.compare (string2) != 0;
  8716. }
  8717. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8718. {
  8719. return string1.compare (string2) != 0;
  8720. }
  8721. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8722. {
  8723. return string1.compare (string2) > 0;
  8724. }
  8725. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8726. {
  8727. return string1.compare (string2) < 0;
  8728. }
  8729. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8730. {
  8731. return string1.compare (string2) >= 0;
  8732. }
  8733. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8734. {
  8735. return string1.compare (string2) <= 0;
  8736. }
  8737. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8738. {
  8739. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8740. : isEmpty();
  8741. }
  8742. bool String::equalsIgnoreCase (const char* t) const throw()
  8743. {
  8744. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8745. : isEmpty();
  8746. }
  8747. bool String::equalsIgnoreCase (const String& other) const throw()
  8748. {
  8749. return text == other.text
  8750. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8751. }
  8752. int String::compare (const String& other) const throw()
  8753. {
  8754. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8755. }
  8756. int String::compare (const char* other) const throw()
  8757. {
  8758. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8759. }
  8760. int String::compare (const juce_wchar* other) const throw()
  8761. {
  8762. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8763. }
  8764. int String::compareIgnoreCase (const String& other) const throw()
  8765. {
  8766. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8767. }
  8768. int String::compareLexicographically (const String& other) const throw()
  8769. {
  8770. const juce_wchar* s1 = text;
  8771. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8772. ++s1;
  8773. const juce_wchar* s2 = other.text;
  8774. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8775. ++s2;
  8776. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8777. }
  8778. String& String::operator+= (const juce_wchar* const t)
  8779. {
  8780. if (t != 0)
  8781. appendInternal (t, CharacterFunctions::length (t));
  8782. return *this;
  8783. }
  8784. String& String::operator+= (const String& other)
  8785. {
  8786. if (isEmpty())
  8787. operator= (other);
  8788. else
  8789. appendInternal (other.text, other.length());
  8790. return *this;
  8791. }
  8792. String& String::operator+= (const char ch)
  8793. {
  8794. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8795. return operator+= (static_cast <const juce_wchar*> (asString));
  8796. }
  8797. String& String::operator+= (const juce_wchar ch)
  8798. {
  8799. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8800. return operator+= (static_cast <const juce_wchar*> (asString));
  8801. }
  8802. String& String::operator+= (const int number)
  8803. {
  8804. juce_wchar buffer [16];
  8805. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8806. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8807. appendInternal (start, (int) (end - start));
  8808. return *this;
  8809. }
  8810. String& String::operator+= (const unsigned int number)
  8811. {
  8812. juce_wchar buffer [16];
  8813. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8814. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8815. appendInternal (start, (int) (end - start));
  8816. return *this;
  8817. }
  8818. void String::append (const juce_wchar* const other, const int howMany)
  8819. {
  8820. if (howMany > 0)
  8821. {
  8822. int i;
  8823. for (i = 0; i < howMany; ++i)
  8824. if (other[i] == 0)
  8825. break;
  8826. appendInternal (other, i);
  8827. }
  8828. }
  8829. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8830. {
  8831. String s (string1);
  8832. return s += string2;
  8833. }
  8834. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8835. {
  8836. String s (string1);
  8837. return s += string2;
  8838. }
  8839. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8840. {
  8841. return String::charToString (string1) + string2;
  8842. }
  8843. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8844. {
  8845. return String::charToString (string1) + string2;
  8846. }
  8847. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8848. {
  8849. return string1 += string2;
  8850. }
  8851. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8852. {
  8853. return string1 += string2;
  8854. }
  8855. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8856. {
  8857. return string1 += string2;
  8858. }
  8859. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8860. {
  8861. return string1 += string2;
  8862. }
  8863. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8864. {
  8865. return string1 += string2;
  8866. }
  8867. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8868. {
  8869. return string1 += characterToAppend;
  8870. }
  8871. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8872. {
  8873. return string1 += characterToAppend;
  8874. }
  8875. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8876. {
  8877. return string1 += string2;
  8878. }
  8879. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8880. {
  8881. return string1 += string2;
  8882. }
  8883. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8884. {
  8885. return string1 += string2;
  8886. }
  8887. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8888. {
  8889. return string1 += (int) number;
  8890. }
  8891. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8892. {
  8893. return string1 += number;
  8894. }
  8895. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8896. {
  8897. return string1 += number;
  8898. }
  8899. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8900. {
  8901. return string1 += (int) number;
  8902. }
  8903. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8904. {
  8905. return string1 += (unsigned int) number;
  8906. }
  8907. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8908. {
  8909. return string1 += String (number);
  8910. }
  8911. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8912. {
  8913. return string1 += String (number);
  8914. }
  8915. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8916. {
  8917. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8918. // if lots of large, persistent strings were to be written to streams).
  8919. const int numBytes = text.getNumBytesAsUTF8();
  8920. HeapBlock<char> temp (numBytes + 1);
  8921. text.copyToUTF8 (temp, numBytes + 1);
  8922. stream.write (temp, numBytes);
  8923. return stream;
  8924. }
  8925. int String::indexOfChar (const juce_wchar character) const throw()
  8926. {
  8927. const juce_wchar* t = text;
  8928. for (;;)
  8929. {
  8930. if (*t == character)
  8931. return (int) (t - text);
  8932. if (*t++ == 0)
  8933. return -1;
  8934. }
  8935. }
  8936. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8937. {
  8938. for (int i = length(); --i >= 0;)
  8939. if (text[i] == character)
  8940. return i;
  8941. return -1;
  8942. }
  8943. int String::indexOf (const String& t) const throw()
  8944. {
  8945. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8946. return r == 0 ? -1 : (int) (r - text);
  8947. }
  8948. int String::indexOfChar (const int startIndex,
  8949. const juce_wchar character) const throw()
  8950. {
  8951. if (startIndex > 0 && startIndex >= length())
  8952. return -1;
  8953. const juce_wchar* t = text + jmax (0, startIndex);
  8954. for (;;)
  8955. {
  8956. if (*t == character)
  8957. return (int) (t - text);
  8958. if (*t == 0)
  8959. return -1;
  8960. ++t;
  8961. }
  8962. }
  8963. int String::indexOfAnyOf (const String& charactersToLookFor,
  8964. const int startIndex,
  8965. const bool ignoreCase) const throw()
  8966. {
  8967. if (startIndex > 0 && startIndex >= length())
  8968. return -1;
  8969. const juce_wchar* t = text + jmax (0, startIndex);
  8970. while (*t != 0)
  8971. {
  8972. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8973. return (int) (t - text);
  8974. ++t;
  8975. }
  8976. return -1;
  8977. }
  8978. int String::indexOf (const int startIndex, const String& other) const throw()
  8979. {
  8980. if (startIndex > 0 && startIndex >= length())
  8981. return -1;
  8982. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8983. return found == 0 ? -1 : (int) (found - text);
  8984. }
  8985. int String::indexOfIgnoreCase (const String& other) const throw()
  8986. {
  8987. if (other.isNotEmpty())
  8988. {
  8989. const int len = other.length();
  8990. const int end = length() - len;
  8991. for (int i = 0; i <= end; ++i)
  8992. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8993. return i;
  8994. }
  8995. return -1;
  8996. }
  8997. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8998. {
  8999. if (other.isNotEmpty())
  9000. {
  9001. const int len = other.length();
  9002. const int end = length() - len;
  9003. for (int i = jmax (0, startIndex); i <= end; ++i)
  9004. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9005. return i;
  9006. }
  9007. return -1;
  9008. }
  9009. int String::lastIndexOf (const String& other) const throw()
  9010. {
  9011. if (other.isNotEmpty())
  9012. {
  9013. const int len = other.length();
  9014. int i = length() - len;
  9015. if (i >= 0)
  9016. {
  9017. const juce_wchar* n = text + i;
  9018. while (i >= 0)
  9019. {
  9020. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9021. return i;
  9022. --i;
  9023. }
  9024. }
  9025. }
  9026. return -1;
  9027. }
  9028. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9029. {
  9030. if (other.isNotEmpty())
  9031. {
  9032. const int len = other.length();
  9033. int i = length() - len;
  9034. if (i >= 0)
  9035. {
  9036. const juce_wchar* n = text + i;
  9037. while (i >= 0)
  9038. {
  9039. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9040. return i;
  9041. --i;
  9042. }
  9043. }
  9044. }
  9045. return -1;
  9046. }
  9047. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9048. {
  9049. for (int i = length(); --i >= 0;)
  9050. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9051. return i;
  9052. return -1;
  9053. }
  9054. bool String::contains (const String& other) const throw()
  9055. {
  9056. return indexOf (other) >= 0;
  9057. }
  9058. bool String::containsChar (const juce_wchar character) const throw()
  9059. {
  9060. const juce_wchar* t = text;
  9061. for (;;)
  9062. {
  9063. if (*t == 0)
  9064. return false;
  9065. if (*t == character)
  9066. return true;
  9067. ++t;
  9068. }
  9069. }
  9070. bool String::containsIgnoreCase (const String& t) const throw()
  9071. {
  9072. return indexOfIgnoreCase (t) >= 0;
  9073. }
  9074. int String::indexOfWholeWord (const String& word) const throw()
  9075. {
  9076. if (word.isNotEmpty())
  9077. {
  9078. const int wordLen = word.length();
  9079. const int end = length() - wordLen;
  9080. const juce_wchar* t = text;
  9081. for (int i = 0; i <= end; ++i)
  9082. {
  9083. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9084. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9085. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9086. {
  9087. return i;
  9088. }
  9089. ++t;
  9090. }
  9091. }
  9092. return -1;
  9093. }
  9094. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9095. {
  9096. if (word.isNotEmpty())
  9097. {
  9098. const int wordLen = word.length();
  9099. const int end = length() - wordLen;
  9100. const juce_wchar* t = text;
  9101. for (int i = 0; i <= end; ++i)
  9102. {
  9103. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9104. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9105. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9106. {
  9107. return i;
  9108. }
  9109. ++t;
  9110. }
  9111. }
  9112. return -1;
  9113. }
  9114. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9115. {
  9116. return indexOfWholeWord (wordToLookFor) >= 0;
  9117. }
  9118. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9119. {
  9120. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9121. }
  9122. static int indexOfMatch (const juce_wchar* const wildcard,
  9123. const juce_wchar* const test,
  9124. const bool ignoreCase) throw()
  9125. {
  9126. int start = 0;
  9127. while (test [start] != 0)
  9128. {
  9129. int i = 0;
  9130. for (;;)
  9131. {
  9132. const juce_wchar wc = wildcard [i];
  9133. const juce_wchar c = test [i + start];
  9134. if (wc == c
  9135. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9136. || (wc == '?' && c != 0))
  9137. {
  9138. if (wc == 0)
  9139. return start;
  9140. ++i;
  9141. }
  9142. else
  9143. {
  9144. if (wc == '*' && (wildcard [i + 1] == 0
  9145. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9146. {
  9147. return start;
  9148. }
  9149. break;
  9150. }
  9151. }
  9152. ++start;
  9153. }
  9154. return -1;
  9155. }
  9156. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9157. {
  9158. int i = 0;
  9159. for (;;)
  9160. {
  9161. const juce_wchar wc = wildcard.text [i];
  9162. const juce_wchar c = text [i];
  9163. if (wc == c
  9164. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9165. || (wc == '?' && c != 0))
  9166. {
  9167. if (wc == 0)
  9168. return true;
  9169. ++i;
  9170. }
  9171. else
  9172. {
  9173. return wc == '*' && (wildcard [i + 1] == 0
  9174. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9175. }
  9176. }
  9177. }
  9178. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9179. {
  9180. const int len = stringToRepeat.length();
  9181. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9182. juce_wchar* n = result.text;
  9183. *n = 0;
  9184. while (--numberOfTimesToRepeat >= 0)
  9185. {
  9186. StringHolder::copyChars (n, stringToRepeat.text, len);
  9187. n += len;
  9188. }
  9189. return result;
  9190. }
  9191. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9192. {
  9193. jassert (padCharacter != 0);
  9194. const int len = length();
  9195. if (len >= minimumLength || padCharacter == 0)
  9196. return *this;
  9197. String result ((size_t) minimumLength + 1, (int) 0);
  9198. juce_wchar* n = result.text;
  9199. minimumLength -= len;
  9200. while (--minimumLength >= 0)
  9201. *n++ = padCharacter;
  9202. StringHolder::copyChars (n, text, len);
  9203. return result;
  9204. }
  9205. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9206. {
  9207. jassert (padCharacter != 0);
  9208. const int len = length();
  9209. if (len >= minimumLength || padCharacter == 0)
  9210. return *this;
  9211. String result (*this, (size_t) minimumLength);
  9212. juce_wchar* n = result.text + len;
  9213. minimumLength -= len;
  9214. while (--minimumLength >= 0)
  9215. *n++ = padCharacter;
  9216. *n = 0;
  9217. return result;
  9218. }
  9219. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9220. {
  9221. if (index < 0)
  9222. {
  9223. // a negative index to replace from?
  9224. jassertfalse;
  9225. index = 0;
  9226. }
  9227. if (numCharsToReplace < 0)
  9228. {
  9229. // replacing a negative number of characters?
  9230. numCharsToReplace = 0;
  9231. jassertfalse;
  9232. }
  9233. const int len = length();
  9234. if (index + numCharsToReplace > len)
  9235. {
  9236. if (index > len)
  9237. {
  9238. // replacing beyond the end of the string?
  9239. index = len;
  9240. jassertfalse;
  9241. }
  9242. numCharsToReplace = len - index;
  9243. }
  9244. const int newStringLen = stringToInsert.length();
  9245. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9246. if (newTotalLen <= 0)
  9247. return String::empty;
  9248. String result ((size_t) newTotalLen, (int) 0);
  9249. StringHolder::copyChars (result.text, text, index);
  9250. if (newStringLen > 0)
  9251. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9252. const int endStringLen = newTotalLen - (index + newStringLen);
  9253. if (endStringLen > 0)
  9254. StringHolder::copyChars (result.text + (index + newStringLen),
  9255. text + (index + numCharsToReplace),
  9256. endStringLen);
  9257. return result;
  9258. }
  9259. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9260. {
  9261. const int stringToReplaceLen = stringToReplace.length();
  9262. const int stringToInsertLen = stringToInsert.length();
  9263. int i = 0;
  9264. String result (*this);
  9265. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9266. : result.indexOf (i, stringToReplace))) >= 0)
  9267. {
  9268. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9269. i += stringToInsertLen;
  9270. }
  9271. return result;
  9272. }
  9273. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9274. {
  9275. const int index = indexOfChar (charToReplace);
  9276. if (index < 0)
  9277. return *this;
  9278. String result (*this, size_t());
  9279. juce_wchar* t = result.text + index;
  9280. while (*t != 0)
  9281. {
  9282. if (*t == charToReplace)
  9283. *t = charToInsert;
  9284. ++t;
  9285. }
  9286. return result;
  9287. }
  9288. const String String::replaceCharacters (const String& charactersToReplace,
  9289. const String& charactersToInsertInstead) const
  9290. {
  9291. String result (*this, size_t());
  9292. juce_wchar* t = result.text;
  9293. const int len2 = charactersToInsertInstead.length();
  9294. // the two strings passed in are supposed to be the same length!
  9295. jassert (len2 == charactersToReplace.length());
  9296. while (*t != 0)
  9297. {
  9298. const int index = charactersToReplace.indexOfChar (*t);
  9299. if (((unsigned int) index) < (unsigned int) len2)
  9300. *t = charactersToInsertInstead [index];
  9301. ++t;
  9302. }
  9303. return result;
  9304. }
  9305. bool String::startsWith (const String& other) const throw()
  9306. {
  9307. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9308. }
  9309. bool String::startsWithIgnoreCase (const String& other) const throw()
  9310. {
  9311. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9312. }
  9313. bool String::startsWithChar (const juce_wchar character) const throw()
  9314. {
  9315. jassert (character != 0); // strings can't contain a null character!
  9316. return text[0] == character;
  9317. }
  9318. bool String::endsWithChar (const juce_wchar character) const throw()
  9319. {
  9320. jassert (character != 0); // strings can't contain a null character!
  9321. return text[0] != 0
  9322. && text [length() - 1] == character;
  9323. }
  9324. bool String::endsWith (const String& other) const throw()
  9325. {
  9326. const int thisLen = length();
  9327. const int otherLen = other.length();
  9328. return thisLen >= otherLen
  9329. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9330. }
  9331. bool String::endsWithIgnoreCase (const String& other) const throw()
  9332. {
  9333. const int thisLen = length();
  9334. const int otherLen = other.length();
  9335. return thisLen >= otherLen
  9336. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9337. }
  9338. const String String::toUpperCase() const
  9339. {
  9340. String result (*this, size_t());
  9341. CharacterFunctions::toUpperCase (result.text);
  9342. return result;
  9343. }
  9344. const String String::toLowerCase() const
  9345. {
  9346. String result (*this, size_t());
  9347. CharacterFunctions::toLowerCase (result.text);
  9348. return result;
  9349. }
  9350. juce_wchar& String::operator[] (const int index)
  9351. {
  9352. jassert (((unsigned int) index) <= (unsigned int) length());
  9353. text = StringHolder::makeUnique (text);
  9354. return text [index];
  9355. }
  9356. juce_wchar String::getLastCharacter() const throw()
  9357. {
  9358. return isEmpty() ? juce_wchar() : text [length() - 1];
  9359. }
  9360. const String String::substring (int start, int end) const
  9361. {
  9362. if (start < 0)
  9363. start = 0;
  9364. else if (end <= start)
  9365. return empty;
  9366. int len = 0;
  9367. while (len <= end && text [len] != 0)
  9368. ++len;
  9369. if (end >= len)
  9370. {
  9371. if (start == 0)
  9372. return *this;
  9373. end = len;
  9374. }
  9375. return String (text + start, end - start);
  9376. }
  9377. const String String::substring (const int start) const
  9378. {
  9379. if (start <= 0)
  9380. return *this;
  9381. const int len = length();
  9382. if (start >= len)
  9383. return empty;
  9384. return String (text + start, len - start);
  9385. }
  9386. const String String::dropLastCharacters (const int numberToDrop) const
  9387. {
  9388. return String (text, jmax (0, length() - numberToDrop));
  9389. }
  9390. const String String::getLastCharacters (const int numCharacters) const
  9391. {
  9392. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9393. }
  9394. const String String::fromFirstOccurrenceOf (const String& sub,
  9395. const bool includeSubString,
  9396. const bool ignoreCase) const
  9397. {
  9398. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9399. : indexOf (sub);
  9400. if (i < 0)
  9401. return empty;
  9402. return substring (includeSubString ? i : i + sub.length());
  9403. }
  9404. const String String::fromLastOccurrenceOf (const String& sub,
  9405. const bool includeSubString,
  9406. const bool ignoreCase) const
  9407. {
  9408. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9409. : lastIndexOf (sub);
  9410. if (i < 0)
  9411. return *this;
  9412. return substring (includeSubString ? i : i + sub.length());
  9413. }
  9414. const String String::upToFirstOccurrenceOf (const String& sub,
  9415. const bool includeSubString,
  9416. const bool ignoreCase) const
  9417. {
  9418. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9419. : indexOf (sub);
  9420. if (i < 0)
  9421. return *this;
  9422. return substring (0, includeSubString ? i + sub.length() : i);
  9423. }
  9424. const String String::upToLastOccurrenceOf (const String& sub,
  9425. const bool includeSubString,
  9426. const bool ignoreCase) const
  9427. {
  9428. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9429. : lastIndexOf (sub);
  9430. if (i < 0)
  9431. return *this;
  9432. return substring (0, includeSubString ? i + sub.length() : i);
  9433. }
  9434. bool String::isQuotedString() const
  9435. {
  9436. const String trimmed (trimStart());
  9437. return trimmed[0] == '"'
  9438. || trimmed[0] == '\'';
  9439. }
  9440. const String String::unquoted() const
  9441. {
  9442. String s (*this);
  9443. if (s.text[0] == '"' || s.text[0] == '\'')
  9444. s = s.substring (1);
  9445. const int lastCharIndex = s.length() - 1;
  9446. if (lastCharIndex >= 0
  9447. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9448. s [lastCharIndex] = 0;
  9449. return s;
  9450. }
  9451. const String String::quoted (const juce_wchar quoteCharacter) const
  9452. {
  9453. if (isEmpty())
  9454. return charToString (quoteCharacter) + quoteCharacter;
  9455. String t (*this);
  9456. if (! t.startsWithChar (quoteCharacter))
  9457. t = charToString (quoteCharacter) + t;
  9458. if (! t.endsWithChar (quoteCharacter))
  9459. t += quoteCharacter;
  9460. return t;
  9461. }
  9462. const String String::trim() const
  9463. {
  9464. if (isEmpty())
  9465. return empty;
  9466. int start = 0;
  9467. while (CharacterFunctions::isWhitespace (text [start]))
  9468. ++start;
  9469. const int len = length();
  9470. int end = len - 1;
  9471. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9472. --end;
  9473. ++end;
  9474. if (end <= start)
  9475. return empty;
  9476. else if (start > 0 || end < len)
  9477. return String (text + start, end - start);
  9478. return *this;
  9479. }
  9480. const String String::trimStart() const
  9481. {
  9482. if (isEmpty())
  9483. return empty;
  9484. const juce_wchar* t = text;
  9485. while (CharacterFunctions::isWhitespace (*t))
  9486. ++t;
  9487. if (t == text)
  9488. return *this;
  9489. return String (t);
  9490. }
  9491. const String String::trimEnd() const
  9492. {
  9493. if (isEmpty())
  9494. return empty;
  9495. const juce_wchar* endT = text + (length() - 1);
  9496. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9497. --endT;
  9498. return String (text, (int) (++endT - text));
  9499. }
  9500. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9501. {
  9502. const juce_wchar* t = text;
  9503. while (charactersToTrim.containsChar (*t))
  9504. ++t;
  9505. return t == text ? *this : String (t);
  9506. }
  9507. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9508. {
  9509. if (isEmpty())
  9510. return empty;
  9511. const int len = length();
  9512. const juce_wchar* endT = text + (len - 1);
  9513. int numToRemove = 0;
  9514. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9515. {
  9516. ++numToRemove;
  9517. --endT;
  9518. }
  9519. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9520. }
  9521. const String String::retainCharacters (const String& charactersToRetain) const
  9522. {
  9523. if (isEmpty())
  9524. return empty;
  9525. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9526. juce_wchar* dst = result.text;
  9527. const juce_wchar* src = text;
  9528. while (*src != 0)
  9529. {
  9530. if (charactersToRetain.containsChar (*src))
  9531. *dst++ = *src;
  9532. ++src;
  9533. }
  9534. *dst = 0;
  9535. return result;
  9536. }
  9537. const String String::removeCharacters (const String& charactersToRemove) const
  9538. {
  9539. if (isEmpty())
  9540. return empty;
  9541. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9542. juce_wchar* dst = result.text;
  9543. const juce_wchar* src = text;
  9544. while (*src != 0)
  9545. {
  9546. if (! charactersToRemove.containsChar (*src))
  9547. *dst++ = *src;
  9548. ++src;
  9549. }
  9550. *dst = 0;
  9551. return result;
  9552. }
  9553. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9554. {
  9555. int i = 0;
  9556. for (;;)
  9557. {
  9558. if (! permittedCharacters.containsChar (text[i]))
  9559. break;
  9560. ++i;
  9561. }
  9562. return substring (0, i);
  9563. }
  9564. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9565. {
  9566. const juce_wchar* const t = text;
  9567. int i = 0;
  9568. while (t[i] != 0)
  9569. {
  9570. if (charactersToStopAt.containsChar (t[i]))
  9571. return String (text, i);
  9572. ++i;
  9573. }
  9574. return empty;
  9575. }
  9576. bool String::containsOnly (const String& chars) const throw()
  9577. {
  9578. const juce_wchar* t = text;
  9579. while (*t != 0)
  9580. if (! chars.containsChar (*t++))
  9581. return false;
  9582. return true;
  9583. }
  9584. bool String::containsAnyOf (const String& chars) const throw()
  9585. {
  9586. const juce_wchar* t = text;
  9587. while (*t != 0)
  9588. if (chars.containsChar (*t++))
  9589. return true;
  9590. return false;
  9591. }
  9592. bool String::containsNonWhitespaceChars() const throw()
  9593. {
  9594. const juce_wchar* t = text;
  9595. while (*t != 0)
  9596. if (! CharacterFunctions::isWhitespace (*t++))
  9597. return true;
  9598. return false;
  9599. }
  9600. const String String::formatted (const juce_wchar* const pf, ... )
  9601. {
  9602. jassert (pf != 0);
  9603. va_list args;
  9604. va_start (args, pf);
  9605. size_t bufferSize = 256;
  9606. String result (bufferSize, (int) 0);
  9607. result.text[0] = 0;
  9608. for (;;)
  9609. {
  9610. #if JUCE_LINUX && JUCE_64BIT
  9611. va_list tempArgs;
  9612. va_copy (tempArgs, args);
  9613. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9614. va_end (tempArgs);
  9615. #elif JUCE_WINDOWS
  9616. #if JUCE_MSVC
  9617. #pragma warning (push)
  9618. #pragma warning (disable: 4996)
  9619. #endif
  9620. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9621. #if JUCE_MSVC
  9622. #pragma warning (pop)
  9623. #endif
  9624. #else
  9625. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9626. #endif
  9627. if (num > 0)
  9628. return result;
  9629. bufferSize += 256;
  9630. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9631. break; // returns -1 because of an error rather than because it needs more space.
  9632. result.preallocateStorage (bufferSize);
  9633. }
  9634. return empty;
  9635. }
  9636. int String::getIntValue() const throw()
  9637. {
  9638. return CharacterFunctions::getIntValue (text);
  9639. }
  9640. int String::getTrailingIntValue() const throw()
  9641. {
  9642. int n = 0;
  9643. int mult = 1;
  9644. const juce_wchar* t = text + length();
  9645. while (--t >= text)
  9646. {
  9647. const juce_wchar c = *t;
  9648. if (! CharacterFunctions::isDigit (c))
  9649. {
  9650. if (c == '-')
  9651. n = -n;
  9652. break;
  9653. }
  9654. n += mult * (c - '0');
  9655. mult *= 10;
  9656. }
  9657. return n;
  9658. }
  9659. int64 String::getLargeIntValue() const throw()
  9660. {
  9661. return CharacterFunctions::getInt64Value (text);
  9662. }
  9663. float String::getFloatValue() const throw()
  9664. {
  9665. return (float) CharacterFunctions::getDoubleValue (text);
  9666. }
  9667. double String::getDoubleValue() const throw()
  9668. {
  9669. return CharacterFunctions::getDoubleValue (text);
  9670. }
  9671. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9672. const String String::toHexString (const int number)
  9673. {
  9674. juce_wchar buffer[32];
  9675. juce_wchar* const end = buffer + 32;
  9676. juce_wchar* t = end;
  9677. *--t = 0;
  9678. unsigned int v = (unsigned int) number;
  9679. do
  9680. {
  9681. *--t = hexDigits [v & 15];
  9682. v >>= 4;
  9683. } while (v != 0);
  9684. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9685. }
  9686. const String String::toHexString (const int64 number)
  9687. {
  9688. juce_wchar buffer[32];
  9689. juce_wchar* const end = buffer + 32;
  9690. juce_wchar* t = end;
  9691. *--t = 0;
  9692. uint64 v = (uint64) number;
  9693. do
  9694. {
  9695. *--t = hexDigits [(int) (v & 15)];
  9696. v >>= 4;
  9697. } while (v != 0);
  9698. return String (t, (int) (((char*) end) - (char*) t));
  9699. }
  9700. const String String::toHexString (const short number)
  9701. {
  9702. return toHexString ((int) (unsigned short) number);
  9703. }
  9704. const String String::toHexString (const unsigned char* data,
  9705. const int size,
  9706. const int groupSize)
  9707. {
  9708. if (size <= 0)
  9709. return empty;
  9710. int numChars = (size * 2) + 2;
  9711. if (groupSize > 0)
  9712. numChars += size / groupSize;
  9713. String s ((size_t) numChars, (int) 0);
  9714. juce_wchar* d = s.text;
  9715. for (int i = 0; i < size; ++i)
  9716. {
  9717. *d++ = hexDigits [(*data) >> 4];
  9718. *d++ = hexDigits [(*data) & 0xf];
  9719. ++data;
  9720. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9721. *d++ = ' ';
  9722. }
  9723. *d = 0;
  9724. return s;
  9725. }
  9726. int String::getHexValue32() const throw()
  9727. {
  9728. int result = 0;
  9729. const juce_wchar* c = text;
  9730. for (;;)
  9731. {
  9732. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9733. if (hexValue >= 0)
  9734. result = (result << 4) | hexValue;
  9735. else if (*c == 0)
  9736. break;
  9737. ++c;
  9738. }
  9739. return result;
  9740. }
  9741. int64 String::getHexValue64() const throw()
  9742. {
  9743. int64 result = 0;
  9744. const juce_wchar* c = text;
  9745. for (;;)
  9746. {
  9747. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9748. if (hexValue >= 0)
  9749. result = (result << 4) | hexValue;
  9750. else if (*c == 0)
  9751. break;
  9752. ++c;
  9753. }
  9754. return result;
  9755. }
  9756. const String String::createStringFromData (const void* const data_, const int size)
  9757. {
  9758. const char* const data = static_cast <const char*> (data_);
  9759. if (size <= 0 || data == 0)
  9760. {
  9761. return empty;
  9762. }
  9763. else if (size < 2)
  9764. {
  9765. return charToString (data[0]);
  9766. }
  9767. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9768. || (data[0] == (char)-1 && data[1] == (char)-2))
  9769. {
  9770. // assume it's 16-bit unicode
  9771. const bool bigEndian = (data[0] == (char)-2);
  9772. const int numChars = size / 2 - 1;
  9773. String result;
  9774. result.preallocateStorage (numChars + 2);
  9775. const uint16* const src = (const uint16*) (data + 2);
  9776. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9777. if (bigEndian)
  9778. {
  9779. for (int i = 0; i < numChars; ++i)
  9780. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9781. }
  9782. else
  9783. {
  9784. for (int i = 0; i < numChars; ++i)
  9785. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9786. }
  9787. dst [numChars] = 0;
  9788. return result;
  9789. }
  9790. else
  9791. {
  9792. return String::fromUTF8 (data, size);
  9793. }
  9794. }
  9795. const char* String::toUTF8() const
  9796. {
  9797. if (isEmpty())
  9798. {
  9799. return reinterpret_cast <const char*> (text);
  9800. }
  9801. else
  9802. {
  9803. const int currentLen = length() + 1;
  9804. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9805. String* const mutableThis = const_cast <String*> (this);
  9806. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9807. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9808. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9809. return otherCopy;
  9810. }
  9811. }
  9812. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9813. {
  9814. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9815. int num = 0, index = 0;
  9816. for (;;)
  9817. {
  9818. const uint32 c = (uint32) text [index++];
  9819. if (c >= 0x80)
  9820. {
  9821. int numExtraBytes = 1;
  9822. if (c >= 0x800)
  9823. {
  9824. ++numExtraBytes;
  9825. if (c >= 0x10000)
  9826. {
  9827. ++numExtraBytes;
  9828. if (c >= 0x200000)
  9829. {
  9830. ++numExtraBytes;
  9831. if (c >= 0x4000000)
  9832. ++numExtraBytes;
  9833. }
  9834. }
  9835. }
  9836. if (buffer != 0)
  9837. {
  9838. if (num + numExtraBytes >= maxBufferSizeBytes)
  9839. {
  9840. buffer [num++] = 0;
  9841. break;
  9842. }
  9843. else
  9844. {
  9845. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9846. while (--numExtraBytes >= 0)
  9847. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9848. }
  9849. }
  9850. else
  9851. {
  9852. num += numExtraBytes + 1;
  9853. }
  9854. }
  9855. else
  9856. {
  9857. if (buffer != 0)
  9858. {
  9859. if (num + 1 >= maxBufferSizeBytes)
  9860. {
  9861. buffer [num++] = 0;
  9862. break;
  9863. }
  9864. buffer [num] = (uint8) c;
  9865. }
  9866. ++num;
  9867. }
  9868. if (c == 0)
  9869. break;
  9870. }
  9871. return num;
  9872. }
  9873. int String::getNumBytesAsUTF8() const throw()
  9874. {
  9875. int num = 0;
  9876. const juce_wchar* t = text;
  9877. for (;;)
  9878. {
  9879. const uint32 c = (uint32) *t;
  9880. if (c >= 0x80)
  9881. {
  9882. ++num;
  9883. if (c >= 0x800)
  9884. {
  9885. ++num;
  9886. if (c >= 0x10000)
  9887. {
  9888. ++num;
  9889. if (c >= 0x200000)
  9890. {
  9891. ++num;
  9892. if (c >= 0x4000000)
  9893. ++num;
  9894. }
  9895. }
  9896. }
  9897. }
  9898. else if (c == 0)
  9899. break;
  9900. ++num;
  9901. ++t;
  9902. }
  9903. return num;
  9904. }
  9905. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9906. {
  9907. if (buffer == 0)
  9908. return empty;
  9909. if (bufferSizeBytes < 0)
  9910. bufferSizeBytes = std::numeric_limits<int>::max();
  9911. size_t numBytes;
  9912. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9913. if (buffer [numBytes] == 0)
  9914. break;
  9915. String result ((size_t) numBytes + 1, (int) 0);
  9916. juce_wchar* dest = result.text;
  9917. size_t i = 0;
  9918. while (i < numBytes)
  9919. {
  9920. const char c = buffer [i++];
  9921. if (c < 0)
  9922. {
  9923. unsigned int mask = 0x7f;
  9924. int bit = 0x40;
  9925. int numExtraValues = 0;
  9926. while (bit != 0 && (c & bit) != 0)
  9927. {
  9928. bit >>= 1;
  9929. mask >>= 1;
  9930. ++numExtraValues;
  9931. }
  9932. int n = (mask & (unsigned char) c);
  9933. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9934. {
  9935. const char nextByte = buffer[i];
  9936. if ((nextByte & 0xc0) != 0x80)
  9937. break;
  9938. n <<= 6;
  9939. n |= (nextByte & 0x3f);
  9940. ++i;
  9941. }
  9942. *dest++ = (juce_wchar) n;
  9943. }
  9944. else
  9945. {
  9946. *dest++ = (juce_wchar) c;
  9947. }
  9948. }
  9949. *dest = 0;
  9950. return result;
  9951. }
  9952. const char* String::toCString() const
  9953. {
  9954. if (isEmpty())
  9955. {
  9956. return reinterpret_cast <const char*> (text);
  9957. }
  9958. else
  9959. {
  9960. const int len = length();
  9961. String* const mutableThis = const_cast <String*> (this);
  9962. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9963. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9964. CharacterFunctions::copy (otherCopy, text, len);
  9965. otherCopy [len] = 0;
  9966. return otherCopy;
  9967. }
  9968. }
  9969. #if JUCE_MSVC
  9970. #pragma warning (push)
  9971. #pragma warning (disable: 4514 4996)
  9972. #endif
  9973. int String::getNumBytesAsCString() const throw()
  9974. {
  9975. return (int) wcstombs (0, text, 0);
  9976. }
  9977. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9978. {
  9979. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9980. if (destBuffer != 0 && numBytes >= 0)
  9981. destBuffer [numBytes] = 0;
  9982. return numBytes;
  9983. }
  9984. #if JUCE_MSVC
  9985. #pragma warning (pop)
  9986. #endif
  9987. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9988. {
  9989. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9990. }
  9991. String::Concatenator::Concatenator (String& stringToAppendTo)
  9992. : result (stringToAppendTo),
  9993. nextIndex (stringToAppendTo.length())
  9994. {
  9995. }
  9996. String::Concatenator::~Concatenator()
  9997. {
  9998. }
  9999. void String::Concatenator::append (const String& s)
  10000. {
  10001. const int len = s.length();
  10002. if (len > 0)
  10003. {
  10004. result.preallocateStorage (nextIndex + len);
  10005. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10006. nextIndex += len;
  10007. }
  10008. }
  10009. END_JUCE_NAMESPACE
  10010. /*** End of inlined file: juce_String.cpp ***/
  10011. /*** Start of inlined file: juce_StringArray.cpp ***/
  10012. BEGIN_JUCE_NAMESPACE
  10013. StringArray::StringArray() throw()
  10014. {
  10015. }
  10016. StringArray::StringArray (const StringArray& other)
  10017. : strings (other.strings)
  10018. {
  10019. }
  10020. StringArray::StringArray (const String& firstValue)
  10021. {
  10022. strings.add (firstValue);
  10023. }
  10024. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10025. const int numberOfStrings)
  10026. {
  10027. for (int i = 0; i < numberOfStrings; ++i)
  10028. strings.add (initialStrings [i]);
  10029. }
  10030. StringArray::StringArray (const char* const* const initialStrings,
  10031. const int numberOfStrings)
  10032. {
  10033. for (int i = 0; i < numberOfStrings; ++i)
  10034. strings.add (initialStrings [i]);
  10035. }
  10036. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10037. {
  10038. int i = 0;
  10039. while (initialStrings[i] != 0)
  10040. strings.add (initialStrings [i++]);
  10041. }
  10042. StringArray::StringArray (const char* const* const initialStrings)
  10043. {
  10044. int i = 0;
  10045. while (initialStrings[i] != 0)
  10046. strings.add (initialStrings [i++]);
  10047. }
  10048. StringArray& StringArray::operator= (const StringArray& other)
  10049. {
  10050. strings = other.strings;
  10051. return *this;
  10052. }
  10053. StringArray::~StringArray()
  10054. {
  10055. }
  10056. bool StringArray::operator== (const StringArray& other) const throw()
  10057. {
  10058. if (other.size() != size())
  10059. return false;
  10060. for (int i = size(); --i >= 0;)
  10061. if (other.strings.getReference(i) != strings.getReference(i))
  10062. return false;
  10063. return true;
  10064. }
  10065. bool StringArray::operator!= (const StringArray& other) const throw()
  10066. {
  10067. return ! operator== (other);
  10068. }
  10069. void StringArray::clear()
  10070. {
  10071. strings.clear();
  10072. }
  10073. const String& StringArray::operator[] (const int index) const throw()
  10074. {
  10075. if (((unsigned int) index) < (unsigned int) strings.size())
  10076. return strings.getReference (index);
  10077. return String::empty;
  10078. }
  10079. String& StringArray::getReference (const int index) throw()
  10080. {
  10081. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10082. return strings.getReference (index);
  10083. }
  10084. void StringArray::add (const String& newString)
  10085. {
  10086. strings.add (newString);
  10087. }
  10088. void StringArray::insert (const int index, const String& newString)
  10089. {
  10090. strings.insert (index, newString);
  10091. }
  10092. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10093. {
  10094. if (! contains (newString, ignoreCase))
  10095. add (newString);
  10096. }
  10097. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10098. {
  10099. if (startIndex < 0)
  10100. {
  10101. jassertfalse;
  10102. startIndex = 0;
  10103. }
  10104. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10105. numElementsToAdd = otherArray.size() - startIndex;
  10106. while (--numElementsToAdd >= 0)
  10107. strings.add (otherArray.strings.getReference (startIndex++));
  10108. }
  10109. void StringArray::set (const int index, const String& newString)
  10110. {
  10111. strings.set (index, newString);
  10112. }
  10113. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10114. {
  10115. if (ignoreCase)
  10116. {
  10117. for (int i = size(); --i >= 0;)
  10118. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10119. return true;
  10120. }
  10121. else
  10122. {
  10123. for (int i = size(); --i >= 0;)
  10124. if (stringToLookFor == strings.getReference(i))
  10125. return true;
  10126. }
  10127. return false;
  10128. }
  10129. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10130. {
  10131. if (i < 0)
  10132. i = 0;
  10133. const int numElements = size();
  10134. if (ignoreCase)
  10135. {
  10136. while (i < numElements)
  10137. {
  10138. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10139. return i;
  10140. ++i;
  10141. }
  10142. }
  10143. else
  10144. {
  10145. while (i < numElements)
  10146. {
  10147. if (stringToLookFor == strings.getReference (i))
  10148. return i;
  10149. ++i;
  10150. }
  10151. }
  10152. return -1;
  10153. }
  10154. void StringArray::remove (const int index)
  10155. {
  10156. strings.remove (index);
  10157. }
  10158. void StringArray::removeString (const String& stringToRemove,
  10159. const bool ignoreCase)
  10160. {
  10161. if (ignoreCase)
  10162. {
  10163. for (int i = size(); --i >= 0;)
  10164. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10165. strings.remove (i);
  10166. }
  10167. else
  10168. {
  10169. for (int i = size(); --i >= 0;)
  10170. if (stringToRemove == strings.getReference (i))
  10171. strings.remove (i);
  10172. }
  10173. }
  10174. void StringArray::removeRange (int startIndex, int numberToRemove)
  10175. {
  10176. strings.removeRange (startIndex, numberToRemove);
  10177. }
  10178. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10179. {
  10180. if (removeWhitespaceStrings)
  10181. {
  10182. for (int i = size(); --i >= 0;)
  10183. if (! strings.getReference(i).containsNonWhitespaceChars())
  10184. strings.remove (i);
  10185. }
  10186. else
  10187. {
  10188. for (int i = size(); --i >= 0;)
  10189. if (strings.getReference(i).isEmpty())
  10190. strings.remove (i);
  10191. }
  10192. }
  10193. void StringArray::trim()
  10194. {
  10195. for (int i = size(); --i >= 0;)
  10196. {
  10197. String& s = strings.getReference(i);
  10198. s = s.trim();
  10199. }
  10200. }
  10201. class InternalStringArrayComparator_CaseSensitive
  10202. {
  10203. public:
  10204. static int compareElements (String& first, String& second) { return first.compare (second); }
  10205. };
  10206. class InternalStringArrayComparator_CaseInsensitive
  10207. {
  10208. public:
  10209. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10210. };
  10211. void StringArray::sort (const bool ignoreCase)
  10212. {
  10213. if (ignoreCase)
  10214. {
  10215. InternalStringArrayComparator_CaseInsensitive comp;
  10216. strings.sort (comp);
  10217. }
  10218. else
  10219. {
  10220. InternalStringArrayComparator_CaseSensitive comp;
  10221. strings.sort (comp);
  10222. }
  10223. }
  10224. void StringArray::move (const int currentIndex, int newIndex) throw()
  10225. {
  10226. strings.move (currentIndex, newIndex);
  10227. }
  10228. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10229. {
  10230. const int last = (numberToJoin < 0) ? size()
  10231. : jmin (size(), start + numberToJoin);
  10232. if (start < 0)
  10233. start = 0;
  10234. if (start >= last)
  10235. return String::empty;
  10236. if (start == last - 1)
  10237. return strings.getReference (start);
  10238. const int separatorLen = separator.length();
  10239. int charsNeeded = separatorLen * (last - start - 1);
  10240. for (int i = start; i < last; ++i)
  10241. charsNeeded += strings.getReference(i).length();
  10242. String result;
  10243. result.preallocateStorage (charsNeeded);
  10244. juce_wchar* dest = result;
  10245. while (start < last)
  10246. {
  10247. const String& s = strings.getReference (start);
  10248. const int len = s.length();
  10249. if (len > 0)
  10250. {
  10251. s.copyToUnicode (dest, len);
  10252. dest += len;
  10253. }
  10254. if (++start < last && separatorLen > 0)
  10255. {
  10256. separator.copyToUnicode (dest, separatorLen);
  10257. dest += separatorLen;
  10258. }
  10259. }
  10260. *dest = 0;
  10261. return result;
  10262. }
  10263. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10264. {
  10265. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10266. }
  10267. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10268. {
  10269. int num = 0;
  10270. if (text.isNotEmpty())
  10271. {
  10272. bool insideQuotes = false;
  10273. juce_wchar currentQuoteChar = 0;
  10274. int i = 0;
  10275. int tokenStart = 0;
  10276. for (;;)
  10277. {
  10278. const juce_wchar c = text[i];
  10279. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10280. if (! isBreak)
  10281. {
  10282. if (quoteCharacters.containsChar (c))
  10283. {
  10284. if (insideQuotes)
  10285. {
  10286. // only break out of quotes-mode if we find a matching quote to the
  10287. // one that we opened with..
  10288. if (currentQuoteChar == c)
  10289. insideQuotes = false;
  10290. }
  10291. else
  10292. {
  10293. insideQuotes = true;
  10294. currentQuoteChar = c;
  10295. }
  10296. }
  10297. }
  10298. else
  10299. {
  10300. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10301. ++num;
  10302. tokenStart = i + 1;
  10303. }
  10304. if (c == 0)
  10305. break;
  10306. ++i;
  10307. }
  10308. }
  10309. return num;
  10310. }
  10311. int StringArray::addLines (const String& sourceText)
  10312. {
  10313. int numLines = 0;
  10314. const juce_wchar* text = sourceText;
  10315. while (*text != 0)
  10316. {
  10317. const juce_wchar* const startOfLine = text;
  10318. while (*text != 0)
  10319. {
  10320. if (*text == '\r')
  10321. {
  10322. ++text;
  10323. if (*text == '\n')
  10324. ++text;
  10325. break;
  10326. }
  10327. if (*text == '\n')
  10328. {
  10329. ++text;
  10330. break;
  10331. }
  10332. ++text;
  10333. }
  10334. const juce_wchar* endOfLine = text;
  10335. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10336. --endOfLine;
  10337. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10338. --endOfLine;
  10339. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10340. ++numLines;
  10341. }
  10342. return numLines;
  10343. }
  10344. void StringArray::removeDuplicates (const bool ignoreCase)
  10345. {
  10346. for (int i = 0; i < size() - 1; ++i)
  10347. {
  10348. const String s (strings.getReference(i));
  10349. int nextIndex = i + 1;
  10350. for (;;)
  10351. {
  10352. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10353. if (nextIndex < 0)
  10354. break;
  10355. strings.remove (nextIndex);
  10356. }
  10357. }
  10358. }
  10359. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10360. const bool appendNumberToFirstInstance,
  10361. const juce_wchar* preNumberString,
  10362. const juce_wchar* postNumberString)
  10363. {
  10364. if (preNumberString == 0)
  10365. preNumberString = L" (";
  10366. if (postNumberString == 0)
  10367. postNumberString = L")";
  10368. for (int i = 0; i < size() - 1; ++i)
  10369. {
  10370. String& s = strings.getReference(i);
  10371. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10372. if (nextIndex >= 0)
  10373. {
  10374. const String original (s);
  10375. int number = 0;
  10376. if (appendNumberToFirstInstance)
  10377. s = original + preNumberString + String (++number) + postNumberString;
  10378. else
  10379. ++number;
  10380. while (nextIndex >= 0)
  10381. {
  10382. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10383. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10384. }
  10385. }
  10386. }
  10387. }
  10388. void StringArray::minimiseStorageOverheads()
  10389. {
  10390. strings.minimiseStorageOverheads();
  10391. }
  10392. END_JUCE_NAMESPACE
  10393. /*** End of inlined file: juce_StringArray.cpp ***/
  10394. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10395. BEGIN_JUCE_NAMESPACE
  10396. StringPairArray::StringPairArray (const bool ignoreCase_)
  10397. : ignoreCase (ignoreCase_)
  10398. {
  10399. }
  10400. StringPairArray::StringPairArray (const StringPairArray& other)
  10401. : keys (other.keys),
  10402. values (other.values),
  10403. ignoreCase (other.ignoreCase)
  10404. {
  10405. }
  10406. StringPairArray::~StringPairArray()
  10407. {
  10408. }
  10409. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10410. {
  10411. keys = other.keys;
  10412. values = other.values;
  10413. return *this;
  10414. }
  10415. bool StringPairArray::operator== (const StringPairArray& other) const
  10416. {
  10417. for (int i = keys.size(); --i >= 0;)
  10418. if (other [keys[i]] != values[i])
  10419. return false;
  10420. return true;
  10421. }
  10422. bool StringPairArray::operator!= (const StringPairArray& other) const
  10423. {
  10424. return ! operator== (other);
  10425. }
  10426. const String& StringPairArray::operator[] (const String& key) const
  10427. {
  10428. return values [keys.indexOf (key, ignoreCase)];
  10429. }
  10430. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10431. {
  10432. const int i = keys.indexOf (key, ignoreCase);
  10433. if (i >= 0)
  10434. return values[i];
  10435. return defaultReturnValue;
  10436. }
  10437. void StringPairArray::set (const String& key, const String& value)
  10438. {
  10439. const int i = keys.indexOf (key, ignoreCase);
  10440. if (i >= 0)
  10441. {
  10442. values.set (i, value);
  10443. }
  10444. else
  10445. {
  10446. keys.add (key);
  10447. values.add (value);
  10448. }
  10449. }
  10450. void StringPairArray::addArray (const StringPairArray& other)
  10451. {
  10452. for (int i = 0; i < other.size(); ++i)
  10453. set (other.keys[i], other.values[i]);
  10454. }
  10455. void StringPairArray::clear()
  10456. {
  10457. keys.clear();
  10458. values.clear();
  10459. }
  10460. void StringPairArray::remove (const String& key)
  10461. {
  10462. remove (keys.indexOf (key, ignoreCase));
  10463. }
  10464. void StringPairArray::remove (const int index)
  10465. {
  10466. keys.remove (index);
  10467. values.remove (index);
  10468. }
  10469. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10470. {
  10471. ignoreCase = shouldIgnoreCase;
  10472. }
  10473. const String StringPairArray::getDescription() const
  10474. {
  10475. String s;
  10476. for (int i = 0; i < keys.size(); ++i)
  10477. {
  10478. s << keys[i] << " = " << values[i];
  10479. if (i < keys.size())
  10480. s << ", ";
  10481. }
  10482. return s;
  10483. }
  10484. void StringPairArray::minimiseStorageOverheads()
  10485. {
  10486. keys.minimiseStorageOverheads();
  10487. values.minimiseStorageOverheads();
  10488. }
  10489. END_JUCE_NAMESPACE
  10490. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10491. /*** Start of inlined file: juce_StringPool.cpp ***/
  10492. BEGIN_JUCE_NAMESPACE
  10493. StringPool::StringPool() throw() {}
  10494. StringPool::~StringPool() {}
  10495. template <class StringType>
  10496. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10497. {
  10498. int start = 0;
  10499. int end = strings.size();
  10500. for (;;)
  10501. {
  10502. if (start >= end)
  10503. {
  10504. jassert (start <= end);
  10505. strings.insert (start, newString);
  10506. return strings.getReference (start);
  10507. }
  10508. else
  10509. {
  10510. const String& startString = strings.getReference (start);
  10511. if (startString == newString)
  10512. return startString;
  10513. const int halfway = (start + end) >> 1;
  10514. if (halfway == start)
  10515. {
  10516. if (startString.compare (newString) < 0)
  10517. ++start;
  10518. strings.insert (start, newString);
  10519. return strings.getReference (start);
  10520. }
  10521. const int comp = strings.getReference (halfway).compare (newString);
  10522. if (comp == 0)
  10523. return strings.getReference (halfway);
  10524. else if (comp < 0)
  10525. start = halfway;
  10526. else
  10527. end = halfway;
  10528. }
  10529. }
  10530. }
  10531. const juce_wchar* StringPool::getPooledString (const String& s)
  10532. {
  10533. if (s.isEmpty())
  10534. return String::empty;
  10535. return getPooledStringFromArray (strings, s);
  10536. }
  10537. const juce_wchar* StringPool::getPooledString (const char* const s)
  10538. {
  10539. if (s == 0 || *s == 0)
  10540. return String::empty;
  10541. return getPooledStringFromArray (strings, s);
  10542. }
  10543. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10544. {
  10545. if (s == 0 || *s == 0)
  10546. return String::empty;
  10547. return getPooledStringFromArray (strings, s);
  10548. }
  10549. int StringPool::size() const throw()
  10550. {
  10551. return strings.size();
  10552. }
  10553. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10554. {
  10555. return strings [index];
  10556. }
  10557. END_JUCE_NAMESPACE
  10558. /*** End of inlined file: juce_StringPool.cpp ***/
  10559. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10560. BEGIN_JUCE_NAMESPACE
  10561. XmlDocument::XmlDocument (const String& documentText)
  10562. : originalText (documentText),
  10563. ignoreEmptyTextElements (true)
  10564. {
  10565. }
  10566. XmlDocument::XmlDocument (const File& file)
  10567. : ignoreEmptyTextElements (true)
  10568. {
  10569. inputSource = new FileInputSource (file);
  10570. }
  10571. XmlDocument::~XmlDocument()
  10572. {
  10573. }
  10574. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10575. {
  10576. inputSource = newSource;
  10577. }
  10578. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10579. {
  10580. ignoreEmptyTextElements = shouldBeIgnored;
  10581. }
  10582. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10583. {
  10584. return CharacterFunctions::isLetterOrDigit (c)
  10585. || c == '_' || c == '-' || c == ':' || c == '.';
  10586. }
  10587. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10588. {
  10589. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10590. : isXmlIdentifierCharSlow (c);
  10591. }
  10592. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10593. {
  10594. String textToParse (originalText);
  10595. if (textToParse.isEmpty() && inputSource != 0)
  10596. {
  10597. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10598. if (in != 0)
  10599. {
  10600. MemoryBlock data;
  10601. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10602. if (data.getSize() >= 2
  10603. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10604. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10605. {
  10606. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10607. }
  10608. else
  10609. {
  10610. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10611. }
  10612. if (! onlyReadOuterDocumentElement)
  10613. originalText = textToParse;
  10614. }
  10615. }
  10616. input = textToParse;
  10617. lastError = String::empty;
  10618. errorOccurred = false;
  10619. outOfData = false;
  10620. needToLoadDTD = true;
  10621. for (int i = 0; i < 128; ++i)
  10622. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10623. if (textToParse.isEmpty())
  10624. {
  10625. lastError = "not enough input";
  10626. }
  10627. else
  10628. {
  10629. skipHeader();
  10630. if (input != 0)
  10631. {
  10632. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10633. if (! errorOccurred)
  10634. return result.release();
  10635. }
  10636. else
  10637. {
  10638. lastError = "incorrect xml header";
  10639. }
  10640. }
  10641. return 0;
  10642. }
  10643. const String& XmlDocument::getLastParseError() const throw()
  10644. {
  10645. return lastError;
  10646. }
  10647. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10648. {
  10649. lastError = desc;
  10650. errorOccurred = ! carryOn;
  10651. }
  10652. const String XmlDocument::getFileContents (const String& filename) const
  10653. {
  10654. if (inputSource != 0)
  10655. {
  10656. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10657. if (in != 0)
  10658. return in->readEntireStreamAsString();
  10659. }
  10660. return String::empty;
  10661. }
  10662. juce_wchar XmlDocument::readNextChar() throw()
  10663. {
  10664. if (*input != 0)
  10665. {
  10666. return *input++;
  10667. }
  10668. else
  10669. {
  10670. outOfData = true;
  10671. return 0;
  10672. }
  10673. }
  10674. int XmlDocument::findNextTokenLength() throw()
  10675. {
  10676. int len = 0;
  10677. juce_wchar c = *input;
  10678. while (isXmlIdentifierChar (c))
  10679. c = input [++len];
  10680. return len;
  10681. }
  10682. void XmlDocument::skipHeader()
  10683. {
  10684. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10685. if (found != 0)
  10686. {
  10687. input = found;
  10688. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10689. if (input == 0)
  10690. return;
  10691. input += 2;
  10692. }
  10693. skipNextWhiteSpace();
  10694. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10695. if (docType == 0)
  10696. return;
  10697. input = docType + 9;
  10698. int n = 1;
  10699. while (n > 0)
  10700. {
  10701. const juce_wchar c = readNextChar();
  10702. if (outOfData)
  10703. return;
  10704. if (c == '<')
  10705. ++n;
  10706. else if (c == '>')
  10707. --n;
  10708. }
  10709. docType += 9;
  10710. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10711. }
  10712. void XmlDocument::skipNextWhiteSpace()
  10713. {
  10714. for (;;)
  10715. {
  10716. juce_wchar c = *input;
  10717. while (CharacterFunctions::isWhitespace (c))
  10718. c = *++input;
  10719. if (c == 0)
  10720. {
  10721. outOfData = true;
  10722. break;
  10723. }
  10724. else if (c == '<')
  10725. {
  10726. if (input[1] == '!'
  10727. && input[2] == '-'
  10728. && input[3] == '-')
  10729. {
  10730. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10731. if (closeComment == 0)
  10732. {
  10733. outOfData = true;
  10734. break;
  10735. }
  10736. input = closeComment + 3;
  10737. continue;
  10738. }
  10739. else if (input[1] == '?')
  10740. {
  10741. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10742. if (closeBracket == 0)
  10743. {
  10744. outOfData = true;
  10745. break;
  10746. }
  10747. input = closeBracket + 2;
  10748. continue;
  10749. }
  10750. }
  10751. break;
  10752. }
  10753. }
  10754. void XmlDocument::readQuotedString (String& result)
  10755. {
  10756. const juce_wchar quote = readNextChar();
  10757. while (! outOfData)
  10758. {
  10759. const juce_wchar c = readNextChar();
  10760. if (c == quote)
  10761. break;
  10762. if (c == '&')
  10763. {
  10764. --input;
  10765. readEntity (result);
  10766. }
  10767. else
  10768. {
  10769. --input;
  10770. const juce_wchar* const start = input;
  10771. for (;;)
  10772. {
  10773. const juce_wchar character = *input;
  10774. if (character == quote)
  10775. {
  10776. result.append (start, (int) (input - start));
  10777. ++input;
  10778. return;
  10779. }
  10780. else if (character == '&')
  10781. {
  10782. result.append (start, (int) (input - start));
  10783. break;
  10784. }
  10785. else if (character == 0)
  10786. {
  10787. outOfData = true;
  10788. setLastError ("unmatched quotes", false);
  10789. break;
  10790. }
  10791. ++input;
  10792. }
  10793. }
  10794. }
  10795. }
  10796. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10797. {
  10798. XmlElement* node = 0;
  10799. skipNextWhiteSpace();
  10800. if (outOfData)
  10801. return 0;
  10802. input = CharacterFunctions::find (input, JUCE_T("<"));
  10803. if (input != 0)
  10804. {
  10805. ++input;
  10806. int tagLen = findNextTokenLength();
  10807. if (tagLen == 0)
  10808. {
  10809. // no tag name - but allow for a gap after the '<' before giving an error
  10810. skipNextWhiteSpace();
  10811. tagLen = findNextTokenLength();
  10812. if (tagLen == 0)
  10813. {
  10814. setLastError ("tag name missing", false);
  10815. return node;
  10816. }
  10817. }
  10818. node = new XmlElement (String (input, tagLen));
  10819. input += tagLen;
  10820. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10821. // look for attributes
  10822. for (;;)
  10823. {
  10824. skipNextWhiteSpace();
  10825. const juce_wchar c = *input;
  10826. // empty tag..
  10827. if (c == '/' && input[1] == '>')
  10828. {
  10829. input += 2;
  10830. break;
  10831. }
  10832. // parse the guts of the element..
  10833. if (c == '>')
  10834. {
  10835. ++input;
  10836. skipNextWhiteSpace();
  10837. if (alsoParseSubElements)
  10838. readChildElements (node);
  10839. break;
  10840. }
  10841. // get an attribute..
  10842. if (isXmlIdentifierChar (c))
  10843. {
  10844. const int attNameLen = findNextTokenLength();
  10845. if (attNameLen > 0)
  10846. {
  10847. const juce_wchar* attNameStart = input;
  10848. input += attNameLen;
  10849. skipNextWhiteSpace();
  10850. if (readNextChar() == '=')
  10851. {
  10852. skipNextWhiteSpace();
  10853. const juce_wchar nextChar = *input;
  10854. if (nextChar == '"' || nextChar == '\'')
  10855. {
  10856. XmlElement::XmlAttributeNode* const newAtt
  10857. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10858. String::empty);
  10859. readQuotedString (newAtt->value);
  10860. if (lastAttribute == 0)
  10861. node->attributes = newAtt;
  10862. else
  10863. lastAttribute->next = newAtt;
  10864. lastAttribute = newAtt;
  10865. continue;
  10866. }
  10867. }
  10868. }
  10869. }
  10870. else
  10871. {
  10872. if (! outOfData)
  10873. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10874. }
  10875. break;
  10876. }
  10877. }
  10878. return node;
  10879. }
  10880. void XmlDocument::readChildElements (XmlElement* parent)
  10881. {
  10882. XmlElement* lastChildNode = 0;
  10883. for (;;)
  10884. {
  10885. skipNextWhiteSpace();
  10886. if (outOfData)
  10887. {
  10888. setLastError ("unmatched tags", false);
  10889. break;
  10890. }
  10891. if (*input == '<')
  10892. {
  10893. if (input[1] == '/')
  10894. {
  10895. // our close tag..
  10896. input = CharacterFunctions::find (input, JUCE_T(">"));
  10897. ++input;
  10898. break;
  10899. }
  10900. else if (input[1] == '!'
  10901. && input[2] == '['
  10902. && input[3] == 'C'
  10903. && input[4] == 'D'
  10904. && input[5] == 'A'
  10905. && input[6] == 'T'
  10906. && input[7] == 'A'
  10907. && input[8] == '[')
  10908. {
  10909. input += 9;
  10910. const juce_wchar* const inputStart = input;
  10911. int len = 0;
  10912. for (;;)
  10913. {
  10914. if (*input == 0)
  10915. {
  10916. setLastError ("unterminated CDATA section", false);
  10917. outOfData = true;
  10918. break;
  10919. }
  10920. else if (input[0] == ']'
  10921. && input[1] == ']'
  10922. && input[2] == '>')
  10923. {
  10924. input += 3;
  10925. break;
  10926. }
  10927. ++input;
  10928. ++len;
  10929. }
  10930. XmlElement* const e = new XmlElement ((int) 0);
  10931. e->setText (String (inputStart, len));
  10932. if (lastChildNode != 0)
  10933. lastChildNode->nextElement = e;
  10934. else
  10935. parent->addChildElement (e);
  10936. lastChildNode = e;
  10937. }
  10938. else
  10939. {
  10940. // this is some other element, so parse and add it..
  10941. XmlElement* const n = readNextElement (true);
  10942. if (n != 0)
  10943. {
  10944. if (lastChildNode == 0)
  10945. parent->addChildElement (n);
  10946. else
  10947. lastChildNode->nextElement = n;
  10948. lastChildNode = n;
  10949. }
  10950. else
  10951. {
  10952. return;
  10953. }
  10954. }
  10955. }
  10956. else
  10957. {
  10958. // read character block..
  10959. XmlElement* const e = new XmlElement ((int)0);
  10960. if (lastChildNode != 0)
  10961. lastChildNode->nextElement = e;
  10962. else
  10963. parent->addChildElement (e);
  10964. lastChildNode = e;
  10965. String textElementContent;
  10966. for (;;)
  10967. {
  10968. const juce_wchar c = *input;
  10969. if (c == '<')
  10970. break;
  10971. if (c == 0)
  10972. {
  10973. setLastError ("unmatched tags", false);
  10974. outOfData = true;
  10975. return;
  10976. }
  10977. if (c == '&')
  10978. {
  10979. String entity;
  10980. readEntity (entity);
  10981. if (entity.startsWithChar ('<') && entity [1] != 0)
  10982. {
  10983. const juce_wchar* const oldInput = input;
  10984. const bool oldOutOfData = outOfData;
  10985. input = entity;
  10986. outOfData = false;
  10987. for (;;)
  10988. {
  10989. XmlElement* const n = readNextElement (true);
  10990. if (n == 0)
  10991. break;
  10992. if (lastChildNode == 0)
  10993. parent->addChildElement (n);
  10994. else
  10995. lastChildNode->nextElement = n;
  10996. lastChildNode = n;
  10997. }
  10998. input = oldInput;
  10999. outOfData = oldOutOfData;
  11000. }
  11001. else
  11002. {
  11003. textElementContent += entity;
  11004. }
  11005. }
  11006. else
  11007. {
  11008. const juce_wchar* start = input;
  11009. int len = 0;
  11010. for (;;)
  11011. {
  11012. const juce_wchar nextChar = *input;
  11013. if (nextChar == '<' || nextChar == '&')
  11014. {
  11015. break;
  11016. }
  11017. else if (nextChar == 0)
  11018. {
  11019. setLastError ("unmatched tags", false);
  11020. outOfData = true;
  11021. return;
  11022. }
  11023. ++input;
  11024. ++len;
  11025. }
  11026. textElementContent.append (start, len);
  11027. }
  11028. }
  11029. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11030. : textElementContent.isNotEmpty())
  11031. e->setText (textElementContent);
  11032. }
  11033. }
  11034. }
  11035. void XmlDocument::readEntity (String& result)
  11036. {
  11037. // skip over the ampersand
  11038. ++input;
  11039. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11040. {
  11041. input += 4;
  11042. result += '&';
  11043. }
  11044. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11045. {
  11046. input += 5;
  11047. result += '"';
  11048. }
  11049. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11050. {
  11051. input += 5;
  11052. result += '\'';
  11053. }
  11054. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11055. {
  11056. input += 3;
  11057. result += '<';
  11058. }
  11059. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11060. {
  11061. input += 3;
  11062. result += '>';
  11063. }
  11064. else if (*input == '#')
  11065. {
  11066. int charCode = 0;
  11067. ++input;
  11068. if (*input == 'x' || *input == 'X')
  11069. {
  11070. ++input;
  11071. int numChars = 0;
  11072. while (input[0] != ';')
  11073. {
  11074. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11075. if (hexValue < 0 || ++numChars > 8)
  11076. {
  11077. setLastError ("illegal escape sequence", true);
  11078. break;
  11079. }
  11080. charCode = (charCode << 4) | hexValue;
  11081. ++input;
  11082. }
  11083. ++input;
  11084. }
  11085. else if (input[0] >= '0' && input[0] <= '9')
  11086. {
  11087. int numChars = 0;
  11088. while (input[0] != ';')
  11089. {
  11090. if (++numChars > 12)
  11091. {
  11092. setLastError ("illegal escape sequence", true);
  11093. break;
  11094. }
  11095. charCode = charCode * 10 + (input[0] - '0');
  11096. ++input;
  11097. }
  11098. ++input;
  11099. }
  11100. else
  11101. {
  11102. setLastError ("illegal escape sequence", true);
  11103. result += '&';
  11104. return;
  11105. }
  11106. result << (juce_wchar) charCode;
  11107. }
  11108. else
  11109. {
  11110. const juce_wchar* const entityNameStart = input;
  11111. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11112. if (closingSemiColon == 0)
  11113. {
  11114. outOfData = true;
  11115. result += '&';
  11116. }
  11117. else
  11118. {
  11119. input = closingSemiColon + 1;
  11120. result += expandExternalEntity (String (entityNameStart,
  11121. (int) (closingSemiColon - entityNameStart)));
  11122. }
  11123. }
  11124. }
  11125. const String XmlDocument::expandEntity (const String& ent)
  11126. {
  11127. if (ent.equalsIgnoreCase ("amp"))
  11128. return String::charToString ('&');
  11129. if (ent.equalsIgnoreCase ("quot"))
  11130. return String::charToString ('"');
  11131. if (ent.equalsIgnoreCase ("apos"))
  11132. return String::charToString ('\'');
  11133. if (ent.equalsIgnoreCase ("lt"))
  11134. return String::charToString ('<');
  11135. if (ent.equalsIgnoreCase ("gt"))
  11136. return String::charToString ('>');
  11137. if (ent[0] == '#')
  11138. {
  11139. if (ent[1] == 'x' || ent[1] == 'X')
  11140. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11141. if (ent[1] >= '0' && ent[1] <= '9')
  11142. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11143. setLastError ("illegal escape sequence", false);
  11144. return String::charToString ('&');
  11145. }
  11146. return expandExternalEntity (ent);
  11147. }
  11148. const String XmlDocument::expandExternalEntity (const String& entity)
  11149. {
  11150. if (needToLoadDTD)
  11151. {
  11152. if (dtdText.isNotEmpty())
  11153. {
  11154. dtdText = dtdText.trimCharactersAtEnd (">");
  11155. tokenisedDTD.addTokens (dtdText, true);
  11156. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11157. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11158. {
  11159. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11160. tokenisedDTD.clear();
  11161. tokenisedDTD.addTokens (getFileContents (fn), true);
  11162. }
  11163. else
  11164. {
  11165. tokenisedDTD.clear();
  11166. const int openBracket = dtdText.indexOfChar ('[');
  11167. if (openBracket > 0)
  11168. {
  11169. const int closeBracket = dtdText.lastIndexOfChar (']');
  11170. if (closeBracket > openBracket)
  11171. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11172. closeBracket), true);
  11173. }
  11174. }
  11175. for (int i = tokenisedDTD.size(); --i >= 0;)
  11176. {
  11177. if (tokenisedDTD[i].startsWithChar ('%')
  11178. && tokenisedDTD[i].endsWithChar (';'))
  11179. {
  11180. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11181. StringArray newToks;
  11182. newToks.addTokens (parsed, true);
  11183. tokenisedDTD.remove (i);
  11184. for (int j = newToks.size(); --j >= 0;)
  11185. tokenisedDTD.insert (i, newToks[j]);
  11186. }
  11187. }
  11188. }
  11189. needToLoadDTD = false;
  11190. }
  11191. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11192. {
  11193. if (tokenisedDTD[i] == entity)
  11194. {
  11195. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11196. {
  11197. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11198. // check for sub-entities..
  11199. int ampersand = ent.indexOfChar ('&');
  11200. while (ampersand >= 0)
  11201. {
  11202. const int semiColon = ent.indexOf (i + 1, ";");
  11203. if (semiColon < 0)
  11204. {
  11205. setLastError ("entity without terminating semi-colon", false);
  11206. break;
  11207. }
  11208. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11209. ent = ent.substring (0, ampersand)
  11210. + resolved
  11211. + ent.substring (semiColon + 1);
  11212. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11213. }
  11214. return ent;
  11215. }
  11216. }
  11217. }
  11218. setLastError ("unknown entity", true);
  11219. return entity;
  11220. }
  11221. const String XmlDocument::getParameterEntity (const String& entity)
  11222. {
  11223. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11224. {
  11225. if (tokenisedDTD[i] == entity)
  11226. {
  11227. if (tokenisedDTD [i - 1] == "%"
  11228. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11229. {
  11230. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11231. if (ent.equalsIgnoreCase ("system"))
  11232. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11233. else
  11234. return ent.trim().unquoted();
  11235. }
  11236. }
  11237. }
  11238. return entity;
  11239. }
  11240. END_JUCE_NAMESPACE
  11241. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11242. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11243. BEGIN_JUCE_NAMESPACE
  11244. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11245. : name (other.name),
  11246. value (other.value),
  11247. next (0)
  11248. {
  11249. }
  11250. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11251. : name (name_),
  11252. value (value_),
  11253. next (0)
  11254. {
  11255. }
  11256. XmlElement::XmlElement (const String& tagName_) throw()
  11257. : tagName (tagName_),
  11258. firstChildElement (0),
  11259. nextElement (0),
  11260. attributes (0)
  11261. {
  11262. // the tag name mustn't be empty, or it'll look like a text element!
  11263. jassert (tagName_.containsNonWhitespaceChars())
  11264. // The tag can't contain spaces or other characters that would create invalid XML!
  11265. jassert (! tagName_.containsAnyOf (" <>/&"));
  11266. }
  11267. XmlElement::XmlElement (int /*dummy*/) throw()
  11268. : firstChildElement (0),
  11269. nextElement (0),
  11270. attributes (0)
  11271. {
  11272. }
  11273. XmlElement::XmlElement (const XmlElement& other)
  11274. : tagName (other.tagName),
  11275. firstChildElement (0),
  11276. nextElement (0),
  11277. attributes (0)
  11278. {
  11279. copyChildrenAndAttributesFrom (other);
  11280. }
  11281. XmlElement& XmlElement::operator= (const XmlElement& other)
  11282. {
  11283. if (this != &other)
  11284. {
  11285. removeAllAttributes();
  11286. deleteAllChildElements();
  11287. tagName = other.tagName;
  11288. copyChildrenAndAttributesFrom (other);
  11289. }
  11290. return *this;
  11291. }
  11292. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11293. {
  11294. XmlElement* child = other.firstChildElement;
  11295. XmlElement* lastChild = 0;
  11296. while (child != 0)
  11297. {
  11298. XmlElement* const copiedChild = new XmlElement (*child);
  11299. if (lastChild != 0)
  11300. lastChild->nextElement = copiedChild;
  11301. else
  11302. firstChildElement = copiedChild;
  11303. lastChild = copiedChild;
  11304. child = child->nextElement;
  11305. }
  11306. const XmlAttributeNode* att = other.attributes;
  11307. XmlAttributeNode* lastAtt = 0;
  11308. while (att != 0)
  11309. {
  11310. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11311. if (lastAtt != 0)
  11312. lastAtt->next = newAtt;
  11313. else
  11314. attributes = newAtt;
  11315. lastAtt = newAtt;
  11316. att = att->next;
  11317. }
  11318. }
  11319. XmlElement::~XmlElement() throw()
  11320. {
  11321. XmlElement* child = firstChildElement;
  11322. while (child != 0)
  11323. {
  11324. XmlElement* const nextChild = child->nextElement;
  11325. delete child;
  11326. child = nextChild;
  11327. }
  11328. XmlAttributeNode* att = attributes;
  11329. while (att != 0)
  11330. {
  11331. XmlAttributeNode* const nextAtt = att->next;
  11332. delete att;
  11333. att = nextAtt;
  11334. }
  11335. }
  11336. namespace XmlOutputFunctions
  11337. {
  11338. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11339. {
  11340. if ((character >= 'a' && character <= 'z')
  11341. || (character >= 'A' && character <= 'Z')
  11342. || (character >= '0' && character <= '9'))
  11343. return true;
  11344. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  11345. do
  11346. {
  11347. if (((juce_wchar) (uint8) *t) == character)
  11348. return true;
  11349. }
  11350. while (*++t != 0);
  11351. return false;
  11352. }
  11353. static void generateLegalCharConstants()
  11354. {
  11355. uint8 n[32];
  11356. zerostruct (n);
  11357. for (int i = 0; i < 256; ++i)
  11358. if (isLegalXmlCharSlow (i))
  11359. n[i >> 3] |= (1 << (i & 7));
  11360. String s;
  11361. for (int i = 0; i < 32; ++i)
  11362. s << (int) n[i] << ", ";
  11363. DBG (s);
  11364. }*/
  11365. static bool isLegalXmlChar (const uint32 c) throw()
  11366. {
  11367. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  11368. return c < sizeof (legalChars) * 8
  11369. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11370. }
  11371. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11372. {
  11373. const juce_wchar* t = text;
  11374. for (;;)
  11375. {
  11376. const juce_wchar character = *t++;
  11377. if (character == 0)
  11378. {
  11379. break;
  11380. }
  11381. else if (isLegalXmlChar ((uint32) character))
  11382. {
  11383. outputStream << (char) character;
  11384. }
  11385. else
  11386. {
  11387. switch (character)
  11388. {
  11389. case '&': outputStream << "&amp;"; break;
  11390. case '"': outputStream << "&quot;"; break;
  11391. case '>': outputStream << "&gt;"; break;
  11392. case '<': outputStream << "&lt;"; break;
  11393. case '\n':
  11394. if (changeNewLines)
  11395. outputStream << "&#10;";
  11396. else
  11397. outputStream << (char) character;
  11398. break;
  11399. case '\r':
  11400. if (changeNewLines)
  11401. outputStream << "&#13;";
  11402. else
  11403. outputStream << (char) character;
  11404. break;
  11405. default:
  11406. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11407. break;
  11408. }
  11409. }
  11410. }
  11411. }
  11412. static void writeSpaces (OutputStream& out, int numSpaces)
  11413. {
  11414. if (numSpaces > 0)
  11415. {
  11416. const char* const blanks = " ";
  11417. const int blankSize = (int) sizeof (blanks) - 1;
  11418. while (numSpaces > blankSize)
  11419. {
  11420. out.write (blanks, blankSize);
  11421. numSpaces -= blankSize;
  11422. }
  11423. out.write (blanks, numSpaces);
  11424. }
  11425. }
  11426. }
  11427. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11428. const int indentationLevel,
  11429. const int lineWrapLength) const
  11430. {
  11431. using namespace XmlOutputFunctions;
  11432. writeSpaces (outputStream, indentationLevel);
  11433. if (! isTextElement())
  11434. {
  11435. outputStream.writeByte ('<');
  11436. outputStream << tagName;
  11437. const int attIndent = indentationLevel + tagName.length() + 1;
  11438. int lineLen = 0;
  11439. const XmlAttributeNode* att = attributes;
  11440. while (att != 0)
  11441. {
  11442. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11443. {
  11444. outputStream.write ("\r\n", 2);
  11445. writeSpaces (outputStream, attIndent);
  11446. lineLen = 0;
  11447. }
  11448. const int64 startPos = outputStream.getPosition();
  11449. outputStream.writeByte (' ');
  11450. outputStream << att->name;
  11451. outputStream.write ("=\"", 2);
  11452. escapeIllegalXmlChars (outputStream, att->value, true);
  11453. outputStream.writeByte ('"');
  11454. lineLen += (int) (outputStream.getPosition() - startPos);
  11455. att = att->next;
  11456. }
  11457. if (firstChildElement != 0)
  11458. {
  11459. XmlElement* child = firstChildElement;
  11460. if (child->nextElement == 0 && child->isTextElement())
  11461. {
  11462. outputStream.writeByte ('>');
  11463. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11464. }
  11465. else
  11466. {
  11467. if (indentationLevel >= 0)
  11468. outputStream.write (">\r\n", 3);
  11469. else
  11470. outputStream.writeByte ('>');
  11471. bool lastWasTextNode = false;
  11472. while (child != 0)
  11473. {
  11474. if (child->isTextElement())
  11475. {
  11476. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11477. writeSpaces (outputStream, indentationLevel + 2);
  11478. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11479. lastWasTextNode = true;
  11480. }
  11481. else
  11482. {
  11483. if (indentationLevel >= 0)
  11484. {
  11485. if (lastWasTextNode)
  11486. outputStream.write ("\r\n", 2);
  11487. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11488. }
  11489. else
  11490. {
  11491. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11492. }
  11493. lastWasTextNode = false;
  11494. }
  11495. child = child->nextElement;
  11496. }
  11497. if (indentationLevel >= 0)
  11498. {
  11499. if (lastWasTextNode)
  11500. outputStream.write ("\r\n", 2);
  11501. writeSpaces (outputStream, indentationLevel);
  11502. }
  11503. }
  11504. outputStream.write ("</", 2);
  11505. outputStream << tagName;
  11506. if (indentationLevel >= 0)
  11507. outputStream.write (">\r\n", 3);
  11508. else
  11509. outputStream.writeByte ('>');
  11510. }
  11511. else
  11512. {
  11513. if (indentationLevel >= 0)
  11514. outputStream.write ("/>\r\n", 4);
  11515. else
  11516. outputStream.write ("/>", 2);
  11517. }
  11518. }
  11519. else
  11520. {
  11521. if (indentationLevel >= 0)
  11522. writeSpaces (outputStream, indentationLevel + 2);
  11523. escapeIllegalXmlChars (outputStream, getText(), false);
  11524. }
  11525. }
  11526. const String XmlElement::createDocument (const String& dtdToUse,
  11527. const bool allOnOneLine,
  11528. const bool includeXmlHeader,
  11529. const String& encodingType,
  11530. const int lineWrapLength) const
  11531. {
  11532. MemoryOutputStream mem (2048, 4096);
  11533. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11534. return mem.toUTF8();
  11535. }
  11536. void XmlElement::writeToStream (OutputStream& output,
  11537. const String& dtdToUse,
  11538. const bool allOnOneLine,
  11539. const bool includeXmlHeader,
  11540. const String& encodingType,
  11541. const int lineWrapLength) const
  11542. {
  11543. if (includeXmlHeader)
  11544. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11545. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11546. if (dtdToUse.isNotEmpty())
  11547. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11548. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11549. }
  11550. bool XmlElement::writeToFile (const File& file,
  11551. const String& dtdToUse,
  11552. const String& encodingType,
  11553. const int lineWrapLength) const
  11554. {
  11555. if (file.hasWriteAccess())
  11556. {
  11557. TemporaryFile tempFile (file);
  11558. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11559. if (out != 0)
  11560. {
  11561. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11562. out = 0;
  11563. return tempFile.overwriteTargetFileWithTemporary();
  11564. }
  11565. }
  11566. return false;
  11567. }
  11568. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11569. {
  11570. #if JUCE_DEBUG
  11571. // if debugging, check that the case is actually the same, because
  11572. // valid xml is case-sensitive, and although this lets it pass, it's
  11573. // better not to..
  11574. if (tagName.equalsIgnoreCase (tagNameWanted))
  11575. {
  11576. jassert (tagName == tagNameWanted);
  11577. return true;
  11578. }
  11579. else
  11580. {
  11581. return false;
  11582. }
  11583. #else
  11584. return tagName.equalsIgnoreCase (tagNameWanted);
  11585. #endif
  11586. }
  11587. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11588. {
  11589. XmlElement* e = nextElement;
  11590. while (e != 0 && ! e->hasTagName (requiredTagName))
  11591. e = e->nextElement;
  11592. return e;
  11593. }
  11594. int XmlElement::getNumAttributes() const throw()
  11595. {
  11596. const XmlAttributeNode* att = attributes;
  11597. int count = 0;
  11598. while (att != 0)
  11599. {
  11600. att = att->next;
  11601. ++count;
  11602. }
  11603. return count;
  11604. }
  11605. const String& XmlElement::getAttributeName (const int index) const throw()
  11606. {
  11607. const XmlAttributeNode* att = attributes;
  11608. int count = 0;
  11609. while (att != 0)
  11610. {
  11611. if (count == index)
  11612. return att->name;
  11613. att = att->next;
  11614. ++count;
  11615. }
  11616. return String::empty;
  11617. }
  11618. const String& XmlElement::getAttributeValue (const int index) const throw()
  11619. {
  11620. const XmlAttributeNode* att = attributes;
  11621. int count = 0;
  11622. while (att != 0)
  11623. {
  11624. if (count == index)
  11625. return att->value;
  11626. att = att->next;
  11627. ++count;
  11628. }
  11629. return String::empty;
  11630. }
  11631. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11632. {
  11633. const XmlAttributeNode* att = attributes;
  11634. while (att != 0)
  11635. {
  11636. if (att->name.equalsIgnoreCase (attributeName))
  11637. return true;
  11638. att = att->next;
  11639. }
  11640. return false;
  11641. }
  11642. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11643. {
  11644. const XmlAttributeNode* att = attributes;
  11645. while (att != 0)
  11646. {
  11647. if (att->name.equalsIgnoreCase (attributeName))
  11648. return att->value;
  11649. att = att->next;
  11650. }
  11651. return String::empty;
  11652. }
  11653. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11654. {
  11655. const XmlAttributeNode* att = attributes;
  11656. while (att != 0)
  11657. {
  11658. if (att->name.equalsIgnoreCase (attributeName))
  11659. return att->value;
  11660. att = att->next;
  11661. }
  11662. return defaultReturnValue;
  11663. }
  11664. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11665. {
  11666. const XmlAttributeNode* att = attributes;
  11667. while (att != 0)
  11668. {
  11669. if (att->name.equalsIgnoreCase (attributeName))
  11670. return att->value.getIntValue();
  11671. att = att->next;
  11672. }
  11673. return defaultReturnValue;
  11674. }
  11675. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11676. {
  11677. const XmlAttributeNode* att = attributes;
  11678. while (att != 0)
  11679. {
  11680. if (att->name.equalsIgnoreCase (attributeName))
  11681. return att->value.getDoubleValue();
  11682. att = att->next;
  11683. }
  11684. return defaultReturnValue;
  11685. }
  11686. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11687. {
  11688. const XmlAttributeNode* att = attributes;
  11689. while (att != 0)
  11690. {
  11691. if (att->name.equalsIgnoreCase (attributeName))
  11692. {
  11693. juce_wchar firstChar = att->value[0];
  11694. if (CharacterFunctions::isWhitespace (firstChar))
  11695. firstChar = att->value.trimStart() [0];
  11696. return firstChar == '1'
  11697. || firstChar == 't'
  11698. || firstChar == 'y'
  11699. || firstChar == 'T'
  11700. || firstChar == 'Y';
  11701. }
  11702. att = att->next;
  11703. }
  11704. return defaultReturnValue;
  11705. }
  11706. bool XmlElement::compareAttribute (const String& attributeName,
  11707. const String& stringToCompareAgainst,
  11708. const bool ignoreCase) const throw()
  11709. {
  11710. const XmlAttributeNode* att = attributes;
  11711. while (att != 0)
  11712. {
  11713. if (att->name.equalsIgnoreCase (attributeName))
  11714. {
  11715. if (ignoreCase)
  11716. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11717. else
  11718. return att->value == stringToCompareAgainst;
  11719. }
  11720. att = att->next;
  11721. }
  11722. return false;
  11723. }
  11724. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11725. {
  11726. #if JUCE_DEBUG
  11727. // check the identifier being passed in is legal..
  11728. const juce_wchar* t = attributeName;
  11729. while (*t != 0)
  11730. {
  11731. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11732. || *t == '_'
  11733. || *t == '-'
  11734. || *t == ':');
  11735. ++t;
  11736. }
  11737. #endif
  11738. if (attributes == 0)
  11739. {
  11740. attributes = new XmlAttributeNode (attributeName, value);
  11741. }
  11742. else
  11743. {
  11744. XmlAttributeNode* att = attributes;
  11745. for (;;)
  11746. {
  11747. if (att->name.equalsIgnoreCase (attributeName))
  11748. {
  11749. att->value = value;
  11750. break;
  11751. }
  11752. else if (att->next == 0)
  11753. {
  11754. att->next = new XmlAttributeNode (attributeName, value);
  11755. break;
  11756. }
  11757. att = att->next;
  11758. }
  11759. }
  11760. }
  11761. void XmlElement::setAttribute (const String& attributeName, const int number)
  11762. {
  11763. setAttribute (attributeName, String (number));
  11764. }
  11765. void XmlElement::setAttribute (const String& attributeName, const double number)
  11766. {
  11767. setAttribute (attributeName, String (number));
  11768. }
  11769. void XmlElement::removeAttribute (const String& attributeName) throw()
  11770. {
  11771. XmlAttributeNode* att = attributes;
  11772. XmlAttributeNode* lastAtt = 0;
  11773. while (att != 0)
  11774. {
  11775. if (att->name.equalsIgnoreCase (attributeName))
  11776. {
  11777. if (lastAtt == 0)
  11778. attributes = att->next;
  11779. else
  11780. lastAtt->next = att->next;
  11781. delete att;
  11782. break;
  11783. }
  11784. lastAtt = att;
  11785. att = att->next;
  11786. }
  11787. }
  11788. void XmlElement::removeAllAttributes() throw()
  11789. {
  11790. while (attributes != 0)
  11791. {
  11792. XmlAttributeNode* const nextAtt = attributes->next;
  11793. delete attributes;
  11794. attributes = nextAtt;
  11795. }
  11796. }
  11797. int XmlElement::getNumChildElements() const throw()
  11798. {
  11799. int count = 0;
  11800. const XmlElement* child = firstChildElement;
  11801. while (child != 0)
  11802. {
  11803. ++count;
  11804. child = child->nextElement;
  11805. }
  11806. return count;
  11807. }
  11808. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11809. {
  11810. int count = 0;
  11811. XmlElement* child = firstChildElement;
  11812. while (child != 0 && count < index)
  11813. {
  11814. child = child->nextElement;
  11815. ++count;
  11816. }
  11817. return child;
  11818. }
  11819. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11820. {
  11821. XmlElement* child = firstChildElement;
  11822. while (child != 0)
  11823. {
  11824. if (child->hasTagName (childName))
  11825. break;
  11826. child = child->nextElement;
  11827. }
  11828. return child;
  11829. }
  11830. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11831. {
  11832. if (newNode != 0)
  11833. {
  11834. if (firstChildElement == 0)
  11835. {
  11836. firstChildElement = newNode;
  11837. }
  11838. else
  11839. {
  11840. XmlElement* child = firstChildElement;
  11841. while (child->nextElement != 0)
  11842. child = child->nextElement;
  11843. child->nextElement = newNode;
  11844. // if this is non-zero, then something's probably
  11845. // gone wrong..
  11846. jassert (newNode->nextElement == 0);
  11847. }
  11848. }
  11849. }
  11850. void XmlElement::insertChildElement (XmlElement* const newNode,
  11851. int indexToInsertAt) throw()
  11852. {
  11853. if (newNode != 0)
  11854. {
  11855. removeChildElement (newNode, false);
  11856. if (indexToInsertAt == 0)
  11857. {
  11858. newNode->nextElement = firstChildElement;
  11859. firstChildElement = newNode;
  11860. }
  11861. else
  11862. {
  11863. if (firstChildElement == 0)
  11864. {
  11865. firstChildElement = newNode;
  11866. }
  11867. else
  11868. {
  11869. if (indexToInsertAt < 0)
  11870. indexToInsertAt = std::numeric_limits<int>::max();
  11871. XmlElement* child = firstChildElement;
  11872. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11873. child = child->nextElement;
  11874. newNode->nextElement = child->nextElement;
  11875. child->nextElement = newNode;
  11876. }
  11877. }
  11878. }
  11879. }
  11880. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11881. {
  11882. XmlElement* const newElement = new XmlElement (childTagName);
  11883. addChildElement (newElement);
  11884. return newElement;
  11885. }
  11886. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11887. XmlElement* const newNode) throw()
  11888. {
  11889. if (newNode != 0)
  11890. {
  11891. XmlElement* child = firstChildElement;
  11892. XmlElement* previousNode = 0;
  11893. while (child != 0)
  11894. {
  11895. if (child == currentChildElement)
  11896. {
  11897. if (child != newNode)
  11898. {
  11899. if (previousNode == 0)
  11900. firstChildElement = newNode;
  11901. else
  11902. previousNode->nextElement = newNode;
  11903. newNode->nextElement = child->nextElement;
  11904. delete child;
  11905. }
  11906. return true;
  11907. }
  11908. previousNode = child;
  11909. child = child->nextElement;
  11910. }
  11911. }
  11912. return false;
  11913. }
  11914. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11915. const bool shouldDeleteTheChild) throw()
  11916. {
  11917. if (childToRemove != 0)
  11918. {
  11919. if (firstChildElement == childToRemove)
  11920. {
  11921. firstChildElement = childToRemove->nextElement;
  11922. childToRemove->nextElement = 0;
  11923. }
  11924. else
  11925. {
  11926. XmlElement* child = firstChildElement;
  11927. XmlElement* last = 0;
  11928. while (child != 0)
  11929. {
  11930. if (child == childToRemove)
  11931. {
  11932. if (last == 0)
  11933. firstChildElement = child->nextElement;
  11934. else
  11935. last->nextElement = child->nextElement;
  11936. childToRemove->nextElement = 0;
  11937. break;
  11938. }
  11939. last = child;
  11940. child = child->nextElement;
  11941. }
  11942. }
  11943. if (shouldDeleteTheChild)
  11944. delete childToRemove;
  11945. }
  11946. }
  11947. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11948. const bool ignoreOrderOfAttributes) const throw()
  11949. {
  11950. if (this != other)
  11951. {
  11952. if (other == 0 || tagName != other->tagName)
  11953. {
  11954. return false;
  11955. }
  11956. if (ignoreOrderOfAttributes)
  11957. {
  11958. int totalAtts = 0;
  11959. const XmlAttributeNode* att = attributes;
  11960. while (att != 0)
  11961. {
  11962. if (! other->compareAttribute (att->name, att->value))
  11963. return false;
  11964. att = att->next;
  11965. ++totalAtts;
  11966. }
  11967. if (totalAtts != other->getNumAttributes())
  11968. return false;
  11969. }
  11970. else
  11971. {
  11972. const XmlAttributeNode* thisAtt = attributes;
  11973. const XmlAttributeNode* otherAtt = other->attributes;
  11974. for (;;)
  11975. {
  11976. if (thisAtt == 0 || otherAtt == 0)
  11977. {
  11978. if (thisAtt == otherAtt) // both 0, so it's a match
  11979. break;
  11980. return false;
  11981. }
  11982. if (thisAtt->name != otherAtt->name
  11983. || thisAtt->value != otherAtt->value)
  11984. {
  11985. return false;
  11986. }
  11987. thisAtt = thisAtt->next;
  11988. otherAtt = otherAtt->next;
  11989. }
  11990. }
  11991. const XmlElement* thisChild = firstChildElement;
  11992. const XmlElement* otherChild = other->firstChildElement;
  11993. for (;;)
  11994. {
  11995. if (thisChild == 0 || otherChild == 0)
  11996. {
  11997. if (thisChild == otherChild) // both 0, so it's a match
  11998. break;
  11999. return false;
  12000. }
  12001. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12002. return false;
  12003. thisChild = thisChild->nextElement;
  12004. otherChild = otherChild->nextElement;
  12005. }
  12006. }
  12007. return true;
  12008. }
  12009. void XmlElement::deleteAllChildElements() throw()
  12010. {
  12011. while (firstChildElement != 0)
  12012. {
  12013. XmlElement* const nextChild = firstChildElement->nextElement;
  12014. delete firstChildElement;
  12015. firstChildElement = nextChild;
  12016. }
  12017. }
  12018. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12019. {
  12020. XmlElement* child = firstChildElement;
  12021. while (child != 0)
  12022. {
  12023. if (child->hasTagName (name))
  12024. {
  12025. XmlElement* const nextChild = child->nextElement;
  12026. removeChildElement (child, true);
  12027. child = nextChild;
  12028. }
  12029. else
  12030. {
  12031. child = child->nextElement;
  12032. }
  12033. }
  12034. }
  12035. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12036. {
  12037. const XmlElement* child = firstChildElement;
  12038. while (child != 0)
  12039. {
  12040. if (child == possibleChild)
  12041. return true;
  12042. child = child->nextElement;
  12043. }
  12044. return false;
  12045. }
  12046. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12047. {
  12048. if (this == elementToLookFor || elementToLookFor == 0)
  12049. return 0;
  12050. XmlElement* child = firstChildElement;
  12051. while (child != 0)
  12052. {
  12053. if (elementToLookFor == child)
  12054. return this;
  12055. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12056. if (found != 0)
  12057. return found;
  12058. child = child->nextElement;
  12059. }
  12060. return 0;
  12061. }
  12062. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12063. {
  12064. XmlElement* e = firstChildElement;
  12065. while (e != 0)
  12066. {
  12067. *elems++ = e;
  12068. e = e->nextElement;
  12069. }
  12070. }
  12071. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12072. {
  12073. XmlElement* e = firstChildElement = elems[0];
  12074. for (int i = 1; i < num; ++i)
  12075. {
  12076. e->nextElement = elems[i];
  12077. e = e->nextElement;
  12078. }
  12079. e->nextElement = 0;
  12080. }
  12081. bool XmlElement::isTextElement() const throw()
  12082. {
  12083. return tagName.isEmpty();
  12084. }
  12085. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12086. const String& XmlElement::getText() const throw()
  12087. {
  12088. jassert (isTextElement()); // you're trying to get the text from an element that
  12089. // isn't actually a text element.. If this contains text sub-nodes, you
  12090. // probably want to use getAllSubText instead.
  12091. return getStringAttribute (juce_xmltextContentAttributeName);
  12092. }
  12093. void XmlElement::setText (const String& newText)
  12094. {
  12095. if (isTextElement())
  12096. setAttribute (juce_xmltextContentAttributeName, newText);
  12097. else
  12098. jassertfalse; // you can only change the text in a text element, not a normal one.
  12099. }
  12100. const String XmlElement::getAllSubText() const
  12101. {
  12102. String result;
  12103. String::Concatenator concatenator (result);
  12104. const XmlElement* child = firstChildElement;
  12105. while (child != 0)
  12106. {
  12107. if (child->isTextElement())
  12108. concatenator.append (child->getText());
  12109. child = child->nextElement;
  12110. }
  12111. return result;
  12112. }
  12113. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12114. const String& defaultReturnValue) const
  12115. {
  12116. const XmlElement* const child = getChildByName (childTagName);
  12117. if (child != 0)
  12118. return child->getAllSubText();
  12119. return defaultReturnValue;
  12120. }
  12121. XmlElement* XmlElement::createTextElement (const String& text)
  12122. {
  12123. XmlElement* const e = new XmlElement ((int) 0);
  12124. e->setAttribute (juce_xmltextContentAttributeName, text);
  12125. return e;
  12126. }
  12127. void XmlElement::addTextElement (const String& text)
  12128. {
  12129. addChildElement (createTextElement (text));
  12130. }
  12131. void XmlElement::deleteAllTextElements() throw()
  12132. {
  12133. XmlElement* child = firstChildElement;
  12134. while (child != 0)
  12135. {
  12136. XmlElement* const next = child->nextElement;
  12137. if (child->isTextElement())
  12138. removeChildElement (child, true);
  12139. child = next;
  12140. }
  12141. }
  12142. END_JUCE_NAMESPACE
  12143. /*** End of inlined file: juce_XmlElement.cpp ***/
  12144. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12145. BEGIN_JUCE_NAMESPACE
  12146. ReadWriteLock::ReadWriteLock() throw()
  12147. : numWaitingWriters (0),
  12148. numWriters (0),
  12149. writerThreadId (0)
  12150. {
  12151. }
  12152. ReadWriteLock::~ReadWriteLock() throw()
  12153. {
  12154. jassert (readerThreads.size() == 0);
  12155. jassert (numWriters == 0);
  12156. }
  12157. void ReadWriteLock::enterRead() const throw()
  12158. {
  12159. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12160. const ScopedLock sl (accessLock);
  12161. for (;;)
  12162. {
  12163. jassert (readerThreads.size() % 2 == 0);
  12164. int i;
  12165. for (i = 0; i < readerThreads.size(); i += 2)
  12166. if (readerThreads.getUnchecked(i) == threadId)
  12167. break;
  12168. if (i < readerThreads.size()
  12169. || numWriters + numWaitingWriters == 0
  12170. || (threadId == writerThreadId && numWriters > 0))
  12171. {
  12172. if (i < readerThreads.size())
  12173. {
  12174. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12175. }
  12176. else
  12177. {
  12178. readerThreads.add (threadId);
  12179. readerThreads.add ((Thread::ThreadID) 1);
  12180. }
  12181. return;
  12182. }
  12183. const ScopedUnlock ul (accessLock);
  12184. waitEvent.wait (100);
  12185. }
  12186. }
  12187. void ReadWriteLock::exitRead() const throw()
  12188. {
  12189. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12190. const ScopedLock sl (accessLock);
  12191. for (int i = 0; i < readerThreads.size(); i += 2)
  12192. {
  12193. if (readerThreads.getUnchecked(i) == threadId)
  12194. {
  12195. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12196. if (newCount == 0)
  12197. {
  12198. readerThreads.removeRange (i, 2);
  12199. waitEvent.signal();
  12200. }
  12201. else
  12202. {
  12203. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12204. }
  12205. return;
  12206. }
  12207. }
  12208. jassertfalse; // unlocking a lock that wasn't locked..
  12209. }
  12210. void ReadWriteLock::enterWrite() const throw()
  12211. {
  12212. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12213. const ScopedLock sl (accessLock);
  12214. for (;;)
  12215. {
  12216. if (readerThreads.size() + numWriters == 0
  12217. || threadId == writerThreadId
  12218. || (readerThreads.size() == 2
  12219. && readerThreads.getUnchecked(0) == threadId))
  12220. {
  12221. writerThreadId = threadId;
  12222. ++numWriters;
  12223. break;
  12224. }
  12225. ++numWaitingWriters;
  12226. accessLock.exit();
  12227. waitEvent.wait (100);
  12228. accessLock.enter();
  12229. --numWaitingWriters;
  12230. }
  12231. }
  12232. bool ReadWriteLock::tryEnterWrite() const throw()
  12233. {
  12234. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12235. const ScopedLock sl (accessLock);
  12236. if (readerThreads.size() + numWriters == 0
  12237. || threadId == writerThreadId
  12238. || (readerThreads.size() == 2
  12239. && readerThreads.getUnchecked(0) == threadId))
  12240. {
  12241. writerThreadId = threadId;
  12242. ++numWriters;
  12243. return true;
  12244. }
  12245. return false;
  12246. }
  12247. void ReadWriteLock::exitWrite() const throw()
  12248. {
  12249. const ScopedLock sl (accessLock);
  12250. // check this thread actually had the lock..
  12251. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12252. if (--numWriters == 0)
  12253. {
  12254. writerThreadId = 0;
  12255. waitEvent.signal();
  12256. }
  12257. }
  12258. END_JUCE_NAMESPACE
  12259. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12260. /*** Start of inlined file: juce_Thread.cpp ***/
  12261. BEGIN_JUCE_NAMESPACE
  12262. // these functions are implemented in the platform-specific code.
  12263. void* juce_createThread (void* userData);
  12264. void juce_killThread (void* handle);
  12265. bool juce_setThreadPriority (void* handle, int priority);
  12266. void juce_setCurrentThreadName (const String& name);
  12267. #if JUCE_WINDOWS
  12268. void juce_CloseThreadHandle (void* handle);
  12269. #endif
  12270. void Thread::threadEntryPoint (Thread* const thread)
  12271. {
  12272. {
  12273. const ScopedLock sl (runningThreadsLock);
  12274. runningThreads.add (thread);
  12275. }
  12276. JUCE_TRY
  12277. {
  12278. thread->threadId_ = Thread::getCurrentThreadId();
  12279. if (thread->threadName_.isNotEmpty())
  12280. juce_setCurrentThreadName (thread->threadName_);
  12281. if (thread->startSuspensionEvent_.wait (10000))
  12282. {
  12283. if (thread->affinityMask_ != 0)
  12284. setCurrentThreadAffinityMask (thread->affinityMask_);
  12285. thread->run();
  12286. }
  12287. }
  12288. JUCE_CATCH_ALL_ASSERT
  12289. {
  12290. const ScopedLock sl (runningThreadsLock);
  12291. jassert (runningThreads.contains (thread));
  12292. runningThreads.removeValue (thread);
  12293. }
  12294. #if JUCE_WINDOWS
  12295. juce_CloseThreadHandle (thread->threadHandle_);
  12296. #endif
  12297. thread->threadHandle_ = 0;
  12298. thread->threadId_ = 0;
  12299. }
  12300. // used to wrap the incoming call from the platform-specific code
  12301. void JUCE_API juce_threadEntryPoint (void* userData)
  12302. {
  12303. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12304. }
  12305. Thread::Thread (const String& threadName)
  12306. : threadName_ (threadName),
  12307. threadHandle_ (0),
  12308. threadPriority_ (5),
  12309. threadId_ (0),
  12310. affinityMask_ (0),
  12311. threadShouldExit_ (false)
  12312. {
  12313. }
  12314. Thread::~Thread()
  12315. {
  12316. stopThread (100);
  12317. }
  12318. void Thread::startThread()
  12319. {
  12320. const ScopedLock sl (startStopLock);
  12321. threadShouldExit_ = false;
  12322. if (threadHandle_ == 0)
  12323. {
  12324. threadHandle_ = juce_createThread (this);
  12325. juce_setThreadPriority (threadHandle_, threadPriority_);
  12326. startSuspensionEvent_.signal();
  12327. }
  12328. }
  12329. void Thread::startThread (const int priority)
  12330. {
  12331. const ScopedLock sl (startStopLock);
  12332. if (threadHandle_ == 0)
  12333. {
  12334. threadPriority_ = priority;
  12335. startThread();
  12336. }
  12337. else
  12338. {
  12339. setPriority (priority);
  12340. }
  12341. }
  12342. bool Thread::isThreadRunning() const
  12343. {
  12344. return threadHandle_ != 0;
  12345. }
  12346. void Thread::signalThreadShouldExit()
  12347. {
  12348. threadShouldExit_ = true;
  12349. }
  12350. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12351. {
  12352. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12353. jassert (getThreadId() != getCurrentThreadId());
  12354. const int sleepMsPerIteration = 5;
  12355. int count = timeOutMilliseconds / sleepMsPerIteration;
  12356. while (isThreadRunning())
  12357. {
  12358. if (timeOutMilliseconds > 0 && --count < 0)
  12359. return false;
  12360. sleep (sleepMsPerIteration);
  12361. }
  12362. return true;
  12363. }
  12364. void Thread::stopThread (const int timeOutMilliseconds)
  12365. {
  12366. // agh! You can't stop the thread that's calling this method! How on earth
  12367. // would that work??
  12368. jassert (getCurrentThreadId() != getThreadId());
  12369. const ScopedLock sl (startStopLock);
  12370. if (isThreadRunning())
  12371. {
  12372. signalThreadShouldExit();
  12373. notify();
  12374. if (timeOutMilliseconds != 0)
  12375. waitForThreadToExit (timeOutMilliseconds);
  12376. if (isThreadRunning())
  12377. {
  12378. // very bad karma if this point is reached, as
  12379. // there are bound to be locks and events left in
  12380. // silly states when a thread is killed by force..
  12381. jassertfalse;
  12382. Logger::writeToLog ("!! killing thread by force !!");
  12383. juce_killThread (threadHandle_);
  12384. threadHandle_ = 0;
  12385. threadId_ = 0;
  12386. const ScopedLock sl2 (runningThreadsLock);
  12387. runningThreads.removeValue (this);
  12388. }
  12389. }
  12390. }
  12391. bool Thread::setPriority (const int priority)
  12392. {
  12393. const ScopedLock sl (startStopLock);
  12394. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12395. if (worked)
  12396. threadPriority_ = priority;
  12397. return worked;
  12398. }
  12399. bool Thread::setCurrentThreadPriority (const int priority)
  12400. {
  12401. return juce_setThreadPriority (0, priority);
  12402. }
  12403. void Thread::setAffinityMask (const uint32 affinityMask)
  12404. {
  12405. affinityMask_ = affinityMask;
  12406. }
  12407. bool Thread::wait (const int timeOutMilliseconds) const
  12408. {
  12409. return defaultEvent_.wait (timeOutMilliseconds);
  12410. }
  12411. void Thread::notify() const
  12412. {
  12413. defaultEvent_.signal();
  12414. }
  12415. int Thread::getNumRunningThreads()
  12416. {
  12417. return runningThreads.size();
  12418. }
  12419. Thread* Thread::getCurrentThread()
  12420. {
  12421. const ThreadID thisId = getCurrentThreadId();
  12422. const ScopedLock sl (runningThreadsLock);
  12423. for (int i = runningThreads.size(); --i >= 0;)
  12424. {
  12425. Thread* const t = runningThreads.getUnchecked(i);
  12426. if (t->threadId_ == thisId)
  12427. return t;
  12428. }
  12429. return 0;
  12430. }
  12431. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12432. {
  12433. {
  12434. const ScopedLock sl (runningThreadsLock);
  12435. for (int i = runningThreads.size(); --i >= 0;)
  12436. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12437. }
  12438. for (;;)
  12439. {
  12440. Thread* firstThread;
  12441. {
  12442. const ScopedLock sl (runningThreadsLock);
  12443. firstThread = runningThreads.getFirst();
  12444. }
  12445. if (firstThread == 0)
  12446. break;
  12447. firstThread->stopThread (timeOutMilliseconds);
  12448. }
  12449. }
  12450. Array<Thread*> Thread::runningThreads;
  12451. CriticalSection Thread::runningThreadsLock;
  12452. END_JUCE_NAMESPACE
  12453. /*** End of inlined file: juce_Thread.cpp ***/
  12454. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12455. BEGIN_JUCE_NAMESPACE
  12456. ThreadPoolJob::ThreadPoolJob (const String& name)
  12457. : jobName (name),
  12458. pool (0),
  12459. shouldStop (false),
  12460. isActive (false),
  12461. shouldBeDeleted (false)
  12462. {
  12463. }
  12464. ThreadPoolJob::~ThreadPoolJob()
  12465. {
  12466. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12467. // to remove it first!
  12468. jassert (pool == 0 || ! pool->contains (this));
  12469. }
  12470. const String ThreadPoolJob::getJobName() const
  12471. {
  12472. return jobName;
  12473. }
  12474. void ThreadPoolJob::setJobName (const String& newName)
  12475. {
  12476. jobName = newName;
  12477. }
  12478. void ThreadPoolJob::signalJobShouldExit()
  12479. {
  12480. shouldStop = true;
  12481. }
  12482. class ThreadPool::ThreadPoolThread : public Thread
  12483. {
  12484. public:
  12485. ThreadPoolThread (ThreadPool& pool_)
  12486. : Thread ("Pool"),
  12487. pool (pool_),
  12488. busy (false)
  12489. {
  12490. }
  12491. ~ThreadPoolThread()
  12492. {
  12493. }
  12494. void run()
  12495. {
  12496. while (! threadShouldExit())
  12497. {
  12498. if (! pool.runNextJob())
  12499. wait (500);
  12500. }
  12501. }
  12502. private:
  12503. ThreadPool& pool;
  12504. bool volatile busy;
  12505. ThreadPoolThread (const ThreadPoolThread&);
  12506. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12507. };
  12508. ThreadPool::ThreadPool (const int numThreads,
  12509. const bool startThreadsOnlyWhenNeeded,
  12510. const int stopThreadsWhenNotUsedTimeoutMs)
  12511. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12512. priority (5)
  12513. {
  12514. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12515. for (int i = jmax (1, numThreads); --i >= 0;)
  12516. threads.add (new ThreadPoolThread (*this));
  12517. if (! startThreadsOnlyWhenNeeded)
  12518. for (int i = threads.size(); --i >= 0;)
  12519. threads.getUnchecked(i)->startThread (priority);
  12520. }
  12521. ThreadPool::~ThreadPool()
  12522. {
  12523. removeAllJobs (true, 4000);
  12524. int i;
  12525. for (i = threads.size(); --i >= 0;)
  12526. threads.getUnchecked(i)->signalThreadShouldExit();
  12527. for (i = threads.size(); --i >= 0;)
  12528. threads.getUnchecked(i)->stopThread (500);
  12529. }
  12530. void ThreadPool::addJob (ThreadPoolJob* const job)
  12531. {
  12532. jassert (job != 0);
  12533. jassert (job->pool == 0);
  12534. if (job->pool == 0)
  12535. {
  12536. job->pool = this;
  12537. job->shouldStop = false;
  12538. job->isActive = false;
  12539. {
  12540. const ScopedLock sl (lock);
  12541. jobs.add (job);
  12542. int numRunning = 0;
  12543. for (int i = threads.size(); --i >= 0;)
  12544. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12545. ++numRunning;
  12546. if (numRunning < threads.size())
  12547. {
  12548. bool startedOne = false;
  12549. int n = 1000;
  12550. while (--n >= 0 && ! startedOne)
  12551. {
  12552. for (int i = threads.size(); --i >= 0;)
  12553. {
  12554. if (! threads.getUnchecked(i)->isThreadRunning())
  12555. {
  12556. threads.getUnchecked(i)->startThread (priority);
  12557. startedOne = true;
  12558. break;
  12559. }
  12560. }
  12561. if (! startedOne)
  12562. Thread::sleep (2);
  12563. }
  12564. }
  12565. }
  12566. for (int i = threads.size(); --i >= 0;)
  12567. threads.getUnchecked(i)->notify();
  12568. }
  12569. }
  12570. int ThreadPool::getNumJobs() const
  12571. {
  12572. return jobs.size();
  12573. }
  12574. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12575. {
  12576. const ScopedLock sl (lock);
  12577. return jobs [index];
  12578. }
  12579. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12580. {
  12581. const ScopedLock sl (lock);
  12582. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12583. }
  12584. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12585. {
  12586. const ScopedLock sl (lock);
  12587. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12588. }
  12589. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12590. const int timeOutMs) const
  12591. {
  12592. if (job != 0)
  12593. {
  12594. const uint32 start = Time::getMillisecondCounter();
  12595. while (contains (job))
  12596. {
  12597. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12598. return false;
  12599. jobFinishedSignal.wait (2);
  12600. }
  12601. }
  12602. return true;
  12603. }
  12604. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12605. const bool interruptIfRunning,
  12606. const int timeOutMs)
  12607. {
  12608. bool dontWait = true;
  12609. if (job != 0)
  12610. {
  12611. const ScopedLock sl (lock);
  12612. if (jobs.contains (job))
  12613. {
  12614. if (job->isActive)
  12615. {
  12616. if (interruptIfRunning)
  12617. job->signalJobShouldExit();
  12618. dontWait = false;
  12619. }
  12620. else
  12621. {
  12622. jobs.removeValue (job);
  12623. }
  12624. }
  12625. }
  12626. return dontWait || waitForJobToFinish (job, timeOutMs);
  12627. }
  12628. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12629. const int timeOutMs,
  12630. const bool deleteInactiveJobs,
  12631. ThreadPool::JobSelector* selectedJobsToRemove)
  12632. {
  12633. Array <ThreadPoolJob*> jobsToWaitFor;
  12634. {
  12635. const ScopedLock sl (lock);
  12636. for (int i = jobs.size(); --i >= 0;)
  12637. {
  12638. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12639. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12640. {
  12641. if (job->isActive)
  12642. {
  12643. jobsToWaitFor.add (job);
  12644. if (interruptRunningJobs)
  12645. job->signalJobShouldExit();
  12646. }
  12647. else
  12648. {
  12649. jobs.remove (i);
  12650. if (deleteInactiveJobs)
  12651. delete job;
  12652. }
  12653. }
  12654. }
  12655. }
  12656. const uint32 start = Time::getMillisecondCounter();
  12657. for (;;)
  12658. {
  12659. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12660. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12661. jobsToWaitFor.remove (i);
  12662. if (jobsToWaitFor.size() == 0)
  12663. break;
  12664. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12665. return false;
  12666. jobFinishedSignal.wait (20);
  12667. }
  12668. return true;
  12669. }
  12670. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12671. {
  12672. StringArray s;
  12673. const ScopedLock sl (lock);
  12674. for (int i = 0; i < jobs.size(); ++i)
  12675. {
  12676. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12677. if (job->isActive || ! onlyReturnActiveJobs)
  12678. s.add (job->getJobName());
  12679. }
  12680. return s;
  12681. }
  12682. bool ThreadPool::setThreadPriorities (const int newPriority)
  12683. {
  12684. bool ok = true;
  12685. if (priority != newPriority)
  12686. {
  12687. priority = newPriority;
  12688. for (int i = threads.size(); --i >= 0;)
  12689. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12690. ok = false;
  12691. }
  12692. return ok;
  12693. }
  12694. bool ThreadPool::runNextJob()
  12695. {
  12696. ThreadPoolJob* job = 0;
  12697. {
  12698. const ScopedLock sl (lock);
  12699. for (int i = 0; i < jobs.size(); ++i)
  12700. {
  12701. job = jobs[i];
  12702. if (job != 0 && ! (job->isActive || job->shouldStop))
  12703. break;
  12704. job = 0;
  12705. }
  12706. if (job != 0)
  12707. job->isActive = true;
  12708. }
  12709. if (job != 0)
  12710. {
  12711. JUCE_TRY
  12712. {
  12713. ThreadPoolJob::JobStatus result = job->runJob();
  12714. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12715. const ScopedLock sl (lock);
  12716. if (jobs.contains (job))
  12717. {
  12718. job->isActive = false;
  12719. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12720. {
  12721. job->pool = 0;
  12722. job->shouldStop = true;
  12723. jobs.removeValue (job);
  12724. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12725. delete job;
  12726. jobFinishedSignal.signal();
  12727. }
  12728. else
  12729. {
  12730. // move the job to the end of the queue if it wants another go
  12731. jobs.move (jobs.indexOf (job), -1);
  12732. }
  12733. }
  12734. }
  12735. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12736. catch (...)
  12737. {
  12738. const ScopedLock sl (lock);
  12739. jobs.removeValue (job);
  12740. }
  12741. #endif
  12742. }
  12743. else
  12744. {
  12745. if (threadStopTimeout > 0
  12746. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12747. {
  12748. const ScopedLock sl (lock);
  12749. if (jobs.size() == 0)
  12750. for (int i = threads.size(); --i >= 0;)
  12751. threads.getUnchecked(i)->signalThreadShouldExit();
  12752. }
  12753. else
  12754. {
  12755. return false;
  12756. }
  12757. }
  12758. return true;
  12759. }
  12760. END_JUCE_NAMESPACE
  12761. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12762. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12763. BEGIN_JUCE_NAMESPACE
  12764. TimeSliceThread::TimeSliceThread (const String& threadName)
  12765. : Thread (threadName),
  12766. index (0),
  12767. clientBeingCalled (0),
  12768. clientsChanged (false)
  12769. {
  12770. }
  12771. TimeSliceThread::~TimeSliceThread()
  12772. {
  12773. stopThread (2000);
  12774. }
  12775. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12776. {
  12777. const ScopedLock sl (listLock);
  12778. clients.addIfNotAlreadyThere (client);
  12779. clientsChanged = true;
  12780. notify();
  12781. }
  12782. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12783. {
  12784. const ScopedLock sl1 (listLock);
  12785. clientsChanged = true;
  12786. // if there's a chance we're in the middle of calling this client, we need to
  12787. // also lock the outer lock..
  12788. if (clientBeingCalled == client)
  12789. {
  12790. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12791. const ScopedLock sl2 (callbackLock);
  12792. const ScopedLock sl3 (listLock);
  12793. clients.removeValue (client);
  12794. }
  12795. else
  12796. {
  12797. clients.removeValue (client);
  12798. }
  12799. }
  12800. int TimeSliceThread::getNumClients() const
  12801. {
  12802. return clients.size();
  12803. }
  12804. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12805. {
  12806. const ScopedLock sl (listLock);
  12807. return clients [i];
  12808. }
  12809. void TimeSliceThread::run()
  12810. {
  12811. int numCallsSinceBusy = 0;
  12812. while (! threadShouldExit())
  12813. {
  12814. int timeToWait = 500;
  12815. {
  12816. const ScopedLock sl (callbackLock);
  12817. {
  12818. const ScopedLock sl2 (listLock);
  12819. if (clients.size() > 0)
  12820. {
  12821. index = (index + 1) % clients.size();
  12822. clientBeingCalled = clients [index];
  12823. }
  12824. else
  12825. {
  12826. index = 0;
  12827. clientBeingCalled = 0;
  12828. }
  12829. if (clientsChanged)
  12830. {
  12831. clientsChanged = false;
  12832. numCallsSinceBusy = 0;
  12833. }
  12834. }
  12835. if (clientBeingCalled != 0)
  12836. {
  12837. if (clientBeingCalled->useTimeSlice())
  12838. numCallsSinceBusy = 0;
  12839. else
  12840. ++numCallsSinceBusy;
  12841. if (numCallsSinceBusy >= clients.size())
  12842. timeToWait = 500;
  12843. else if (index == 0)
  12844. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12845. else
  12846. timeToWait = 0;
  12847. }
  12848. }
  12849. if (timeToWait > 0)
  12850. wait (timeToWait);
  12851. }
  12852. }
  12853. END_JUCE_NAMESPACE
  12854. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12855. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12856. BEGIN_JUCE_NAMESPACE
  12857. DeletedAtShutdown::DeletedAtShutdown()
  12858. {
  12859. const ScopedLock sl (getLock());
  12860. getObjects().add (this);
  12861. }
  12862. DeletedAtShutdown::~DeletedAtShutdown()
  12863. {
  12864. const ScopedLock sl (getLock());
  12865. getObjects().removeValue (this);
  12866. }
  12867. void DeletedAtShutdown::deleteAll()
  12868. {
  12869. // make a local copy of the array, so it can't get into a loop if something
  12870. // creates another DeletedAtShutdown object during its destructor.
  12871. Array <DeletedAtShutdown*> localCopy;
  12872. {
  12873. const ScopedLock sl (getLock());
  12874. localCopy = getObjects();
  12875. }
  12876. for (int i = localCopy.size(); --i >= 0;)
  12877. {
  12878. JUCE_TRY
  12879. {
  12880. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12881. // double-check that it's not already been deleted during another object's destructor.
  12882. {
  12883. const ScopedLock sl (getLock());
  12884. if (! getObjects().contains (deletee))
  12885. deletee = 0;
  12886. }
  12887. delete deletee;
  12888. }
  12889. JUCE_CATCH_EXCEPTION
  12890. }
  12891. // if no objects got re-created during shutdown, this should have been emptied by their
  12892. // destructors
  12893. jassert (getObjects().size() == 0);
  12894. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12895. }
  12896. CriticalSection& DeletedAtShutdown::getLock()
  12897. {
  12898. static CriticalSection lock;
  12899. return lock;
  12900. }
  12901. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12902. {
  12903. static Array <DeletedAtShutdown*> objects;
  12904. return objects;
  12905. }
  12906. END_JUCE_NAMESPACE
  12907. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12908. #endif
  12909. #if JUCE_BUILD_MISC
  12910. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12911. BEGIN_JUCE_NAMESPACE
  12912. class ValueTree::SetPropertyAction : public UndoableAction
  12913. {
  12914. public:
  12915. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  12916. const var& newValue_, const var& oldValue_,
  12917. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12918. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  12919. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  12920. {
  12921. }
  12922. ~SetPropertyAction() {}
  12923. bool perform()
  12924. {
  12925. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12926. if (isDeletingProperty)
  12927. target->removeProperty (name, 0);
  12928. else
  12929. target->setProperty (name, newValue, 0);
  12930. return true;
  12931. }
  12932. bool undo()
  12933. {
  12934. if (isAddingNewProperty)
  12935. target->removeProperty (name, 0);
  12936. else
  12937. target->setProperty (name, oldValue, 0);
  12938. return true;
  12939. }
  12940. int getSizeInUnits()
  12941. {
  12942. return (int) sizeof (*this); //xxx should be more accurate
  12943. }
  12944. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  12945. {
  12946. if (! (isAddingNewProperty || isDeletingProperty))
  12947. {
  12948. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  12949. if (next != 0 && next->target == target && next->name == name
  12950. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  12951. {
  12952. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  12953. }
  12954. }
  12955. return 0;
  12956. }
  12957. private:
  12958. const SharedObjectPtr target;
  12959. const Identifier name;
  12960. const var newValue;
  12961. var oldValue;
  12962. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  12963. SetPropertyAction (const SetPropertyAction&);
  12964. SetPropertyAction& operator= (const SetPropertyAction&);
  12965. };
  12966. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12967. {
  12968. public:
  12969. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12970. const SharedObjectPtr& newChild_)
  12971. : target (target_),
  12972. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12973. childIndex (childIndex_),
  12974. isDeleting (newChild_ == 0)
  12975. {
  12976. jassert (child != 0);
  12977. }
  12978. ~AddOrRemoveChildAction() {}
  12979. bool perform()
  12980. {
  12981. if (isDeleting)
  12982. target->removeChild (childIndex, 0);
  12983. else
  12984. target->addChild (child, childIndex, 0);
  12985. return true;
  12986. }
  12987. bool undo()
  12988. {
  12989. if (isDeleting)
  12990. {
  12991. target->addChild (child, childIndex, 0);
  12992. }
  12993. else
  12994. {
  12995. // If you hit this, it seems that your object's state is getting confused - probably
  12996. // because you've interleaved some undoable and non-undoable operations?
  12997. jassert (childIndex < target->children.size());
  12998. target->removeChild (childIndex, 0);
  12999. }
  13000. return true;
  13001. }
  13002. int getSizeInUnits()
  13003. {
  13004. return (int) sizeof (*this); //xxx should be more accurate
  13005. }
  13006. private:
  13007. const SharedObjectPtr target, child;
  13008. const int childIndex;
  13009. const bool isDeleting;
  13010. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13011. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13012. };
  13013. class ValueTree::MoveChildAction : public UndoableAction
  13014. {
  13015. public:
  13016. MoveChildAction (const SharedObjectPtr& parent_,
  13017. const int startIndex_, const int endIndex_)
  13018. : parent (parent_),
  13019. startIndex (startIndex_),
  13020. endIndex (endIndex_)
  13021. {
  13022. }
  13023. ~MoveChildAction() {}
  13024. bool perform()
  13025. {
  13026. parent->moveChild (startIndex, endIndex, 0);
  13027. return true;
  13028. }
  13029. bool undo()
  13030. {
  13031. parent->moveChild (endIndex, startIndex, 0);
  13032. return true;
  13033. }
  13034. int getSizeInUnits()
  13035. {
  13036. return (int) sizeof (*this); //xxx should be more accurate
  13037. }
  13038. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13039. {
  13040. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13041. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13042. return new MoveChildAction (parent, startIndex, next->endIndex);
  13043. return 0;
  13044. }
  13045. private:
  13046. const SharedObjectPtr parent;
  13047. const int startIndex, endIndex;
  13048. MoveChildAction (const MoveChildAction&);
  13049. MoveChildAction& operator= (const MoveChildAction&);
  13050. };
  13051. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13052. : type (type_), parent (0)
  13053. {
  13054. }
  13055. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13056. : type (other.type), properties (other.properties), parent (0)
  13057. {
  13058. for (int i = 0; i < other.children.size(); ++i)
  13059. {
  13060. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13061. child->parent = this;
  13062. children.add (child);
  13063. }
  13064. }
  13065. ValueTree::SharedObject::~SharedObject()
  13066. {
  13067. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13068. for (int i = children.size(); --i >= 0;)
  13069. {
  13070. const SharedObjectPtr c (children.getUnchecked(i));
  13071. c->parent = 0;
  13072. children.remove (i);
  13073. c->sendParentChangeMessage();
  13074. }
  13075. }
  13076. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13077. {
  13078. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13079. {
  13080. ValueTree* const v = valueTreesWithListeners[i];
  13081. if (v != 0)
  13082. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13083. }
  13084. }
  13085. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13086. {
  13087. ValueTree tree (this);
  13088. ValueTree::SharedObject* t = this;
  13089. while (t != 0)
  13090. {
  13091. t->sendPropertyChangeMessage (tree, property);
  13092. t = t->parent;
  13093. }
  13094. }
  13095. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13096. {
  13097. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13098. {
  13099. ValueTree* const v = valueTreesWithListeners[i];
  13100. if (v != 0)
  13101. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13102. }
  13103. }
  13104. void ValueTree::SharedObject::sendChildChangeMessage()
  13105. {
  13106. ValueTree tree (this);
  13107. ValueTree::SharedObject* t = this;
  13108. while (t != 0)
  13109. {
  13110. t->sendChildChangeMessage (tree);
  13111. t = t->parent;
  13112. }
  13113. }
  13114. void ValueTree::SharedObject::sendParentChangeMessage()
  13115. {
  13116. ValueTree tree (this);
  13117. int i;
  13118. for (i = children.size(); --i >= 0;)
  13119. {
  13120. SharedObject* const t = children[i];
  13121. if (t != 0)
  13122. t->sendParentChangeMessage();
  13123. }
  13124. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13125. {
  13126. ValueTree* const v = valueTreesWithListeners[i];
  13127. if (v != 0)
  13128. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13129. }
  13130. }
  13131. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13132. {
  13133. return properties [name];
  13134. }
  13135. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13136. {
  13137. return properties.getWithDefault (name, defaultReturnValue);
  13138. }
  13139. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13140. {
  13141. if (undoManager == 0)
  13142. {
  13143. if (properties.set (name, newValue))
  13144. sendPropertyChangeMessage (name);
  13145. }
  13146. else
  13147. {
  13148. var* const existingValue = properties.getItem (name);
  13149. if (existingValue != 0)
  13150. {
  13151. if (*existingValue != newValue)
  13152. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13153. }
  13154. else
  13155. {
  13156. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13157. }
  13158. }
  13159. }
  13160. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13161. {
  13162. return properties.contains (name);
  13163. }
  13164. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13165. {
  13166. if (undoManager == 0)
  13167. {
  13168. if (properties.remove (name))
  13169. sendPropertyChangeMessage (name);
  13170. }
  13171. else
  13172. {
  13173. if (properties.contains (name))
  13174. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13175. }
  13176. }
  13177. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13178. {
  13179. if (undoManager == 0)
  13180. {
  13181. while (properties.size() > 0)
  13182. {
  13183. const Identifier name (properties.getName (properties.size() - 1));
  13184. properties.remove (name);
  13185. sendPropertyChangeMessage (name);
  13186. }
  13187. }
  13188. else
  13189. {
  13190. for (int i = properties.size(); --i >= 0;)
  13191. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13192. }
  13193. }
  13194. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13195. {
  13196. for (int i = 0; i < children.size(); ++i)
  13197. if (children.getUnchecked(i)->type == typeToMatch)
  13198. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13199. return ValueTree::invalid;
  13200. }
  13201. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13202. {
  13203. for (int i = 0; i < children.size(); ++i)
  13204. if (children.getUnchecked(i)->type == typeToMatch)
  13205. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13206. SharedObject* const newObject = new SharedObject (typeToMatch);
  13207. addChild (newObject, -1, undoManager);
  13208. return ValueTree (newObject);
  13209. }
  13210. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13211. {
  13212. for (int i = 0; i < children.size(); ++i)
  13213. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13214. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13215. return ValueTree::invalid;
  13216. }
  13217. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13218. {
  13219. const SharedObject* p = parent;
  13220. while (p != 0)
  13221. {
  13222. if (p == possibleParent)
  13223. return true;
  13224. p = p->parent;
  13225. }
  13226. return false;
  13227. }
  13228. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13229. {
  13230. return children.indexOf (child.object);
  13231. }
  13232. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13233. {
  13234. if (child != 0 && child->parent != this)
  13235. {
  13236. if (child != this && ! isAChildOf (child))
  13237. {
  13238. // You should always make sure that a child is removed from its previous parent before
  13239. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13240. // undomanager should be used when removing it from its current parent..
  13241. jassert (child->parent == 0);
  13242. if (child->parent != 0)
  13243. {
  13244. jassert (child->parent->children.indexOf (child) >= 0);
  13245. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13246. }
  13247. if (undoManager == 0)
  13248. {
  13249. children.insert (index, child);
  13250. child->parent = this;
  13251. sendChildChangeMessage();
  13252. child->sendParentChangeMessage();
  13253. }
  13254. else
  13255. {
  13256. if (index < 0)
  13257. index = children.size();
  13258. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13259. }
  13260. }
  13261. else
  13262. {
  13263. // You're attempting to create a recursive loop! A node
  13264. // can't be a child of one of its own children!
  13265. jassertfalse;
  13266. }
  13267. }
  13268. }
  13269. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13270. {
  13271. const SharedObjectPtr child (children [childIndex]);
  13272. if (child != 0)
  13273. {
  13274. if (undoManager == 0)
  13275. {
  13276. children.remove (childIndex);
  13277. child->parent = 0;
  13278. sendChildChangeMessage();
  13279. child->sendParentChangeMessage();
  13280. }
  13281. else
  13282. {
  13283. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13284. }
  13285. }
  13286. }
  13287. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13288. {
  13289. while (children.size() > 0)
  13290. removeChild (children.size() - 1, undoManager);
  13291. }
  13292. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13293. {
  13294. // The source index must be a valid index!
  13295. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13296. if (currentIndex != newIndex
  13297. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13298. {
  13299. if (undoManager == 0)
  13300. {
  13301. children.move (currentIndex, newIndex);
  13302. sendChildChangeMessage();
  13303. }
  13304. else
  13305. {
  13306. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13307. newIndex = children.size() - 1;
  13308. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13309. }
  13310. }
  13311. }
  13312. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13313. {
  13314. if (type != other.type
  13315. || properties.size() != other.properties.size()
  13316. || children.size() != other.children.size()
  13317. || properties != other.properties)
  13318. return false;
  13319. for (int i = 0; i < children.size(); ++i)
  13320. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13321. return false;
  13322. return true;
  13323. }
  13324. ValueTree::ValueTree() throw()
  13325. : object (0)
  13326. {
  13327. }
  13328. const ValueTree ValueTree::invalid;
  13329. ValueTree::ValueTree (const Identifier& type_)
  13330. : object (new ValueTree::SharedObject (type_))
  13331. {
  13332. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13333. }
  13334. ValueTree::ValueTree (SharedObject* const object_)
  13335. : object (object_)
  13336. {
  13337. }
  13338. ValueTree::ValueTree (const ValueTree& other)
  13339. : object (other.object)
  13340. {
  13341. }
  13342. ValueTree& ValueTree::operator= (const ValueTree& other)
  13343. {
  13344. if (listeners.size() > 0)
  13345. {
  13346. if (object != 0)
  13347. object->valueTreesWithListeners.removeValue (this);
  13348. if (other.object != 0)
  13349. other.object->valueTreesWithListeners.add (this);
  13350. }
  13351. object = other.object;
  13352. return *this;
  13353. }
  13354. ValueTree::~ValueTree()
  13355. {
  13356. if (listeners.size() > 0 && object != 0)
  13357. object->valueTreesWithListeners.removeValue (this);
  13358. }
  13359. bool ValueTree::operator== (const ValueTree& other) const throw()
  13360. {
  13361. return object == other.object;
  13362. }
  13363. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13364. {
  13365. return object != other.object;
  13366. }
  13367. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13368. {
  13369. return object == other.object
  13370. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13371. }
  13372. ValueTree ValueTree::createCopy() const
  13373. {
  13374. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13375. }
  13376. bool ValueTree::hasType (const Identifier& typeName) const
  13377. {
  13378. return object != 0 && object->type == typeName;
  13379. }
  13380. const Identifier ValueTree::getType() const
  13381. {
  13382. return object != 0 ? object->type : Identifier();
  13383. }
  13384. ValueTree ValueTree::getParent() const
  13385. {
  13386. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13387. }
  13388. ValueTree ValueTree::getSibling (const int delta) const
  13389. {
  13390. if (object == 0 || object->parent == 0)
  13391. return invalid;
  13392. const int index = object->parent->indexOf (*this) + delta;
  13393. return ValueTree (static_cast <SharedObject*> (object->children [index]));
  13394. }
  13395. const var& ValueTree::operator[] (const Identifier& name) const
  13396. {
  13397. return object == 0 ? var::null : object->getProperty (name);
  13398. }
  13399. const var& ValueTree::getProperty (const Identifier& name) const
  13400. {
  13401. return object == 0 ? var::null : object->getProperty (name);
  13402. }
  13403. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13404. {
  13405. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13406. }
  13407. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13408. {
  13409. jassert (name.toString().isNotEmpty());
  13410. if (object != 0 && name.toString().isNotEmpty())
  13411. object->setProperty (name, newValue, undoManager);
  13412. }
  13413. bool ValueTree::hasProperty (const Identifier& name) const
  13414. {
  13415. return object != 0 && object->hasProperty (name);
  13416. }
  13417. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13418. {
  13419. if (object != 0)
  13420. object->removeProperty (name, undoManager);
  13421. }
  13422. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13423. {
  13424. if (object != 0)
  13425. object->removeAllProperties (undoManager);
  13426. }
  13427. int ValueTree::getNumProperties() const
  13428. {
  13429. return object == 0 ? 0 : object->properties.size();
  13430. }
  13431. const Identifier ValueTree::getPropertyName (const int index) const
  13432. {
  13433. return object == 0 ? Identifier()
  13434. : object->properties.getName (index);
  13435. }
  13436. class ValueTreePropertyValueSource : public Value::ValueSource,
  13437. public ValueTree::Listener
  13438. {
  13439. public:
  13440. ValueTreePropertyValueSource (const ValueTree& tree_,
  13441. const Identifier& property_,
  13442. UndoManager* const undoManager_)
  13443. : tree (tree_),
  13444. property (property_),
  13445. undoManager (undoManager_)
  13446. {
  13447. tree.addListener (this);
  13448. }
  13449. ~ValueTreePropertyValueSource()
  13450. {
  13451. tree.removeListener (this);
  13452. }
  13453. const var getValue() const
  13454. {
  13455. return tree [property];
  13456. }
  13457. void setValue (const var& newValue)
  13458. {
  13459. tree.setProperty (property, newValue, undoManager);
  13460. }
  13461. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13462. {
  13463. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13464. sendChangeMessage (false);
  13465. }
  13466. void valueTreeChildrenChanged (ValueTree&) {}
  13467. void valueTreeParentChanged (ValueTree&) {}
  13468. private:
  13469. ValueTree tree;
  13470. const Identifier property;
  13471. UndoManager* const undoManager;
  13472. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13473. };
  13474. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13475. {
  13476. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13477. }
  13478. int ValueTree::getNumChildren() const
  13479. {
  13480. return object == 0 ? 0 : object->children.size();
  13481. }
  13482. ValueTree ValueTree::getChild (int index) const
  13483. {
  13484. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13485. }
  13486. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13487. {
  13488. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13489. }
  13490. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13491. {
  13492. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13493. }
  13494. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13495. {
  13496. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13497. }
  13498. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13499. {
  13500. return object != 0 && object->isAChildOf (possibleParent.object);
  13501. }
  13502. int ValueTree::indexOf (const ValueTree& child) const
  13503. {
  13504. return object != 0 ? object->indexOf (child) : -1;
  13505. }
  13506. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13507. {
  13508. if (object != 0)
  13509. object->addChild (child.object, index, undoManager);
  13510. }
  13511. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13512. {
  13513. if (object != 0)
  13514. object->removeChild (childIndex, undoManager);
  13515. }
  13516. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13517. {
  13518. if (object != 0)
  13519. object->removeChild (object->children.indexOf (child.object), undoManager);
  13520. }
  13521. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13522. {
  13523. if (object != 0)
  13524. object->removeAllChildren (undoManager);
  13525. }
  13526. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13527. {
  13528. if (object != 0)
  13529. object->moveChild (currentIndex, newIndex, undoManager);
  13530. }
  13531. void ValueTree::addListener (Listener* listener)
  13532. {
  13533. if (listener != 0)
  13534. {
  13535. if (listeners.size() == 0 && object != 0)
  13536. object->valueTreesWithListeners.add (this);
  13537. listeners.add (listener);
  13538. }
  13539. }
  13540. void ValueTree::removeListener (Listener* listener)
  13541. {
  13542. listeners.remove (listener);
  13543. if (listeners.size() == 0 && object != 0)
  13544. object->valueTreesWithListeners.removeValue (this);
  13545. }
  13546. XmlElement* ValueTree::SharedObject::createXml() const
  13547. {
  13548. XmlElement* xml = new XmlElement (type.toString());
  13549. int i;
  13550. for (i = 0; i < properties.size(); ++i)
  13551. {
  13552. Identifier name (properties.getName(i));
  13553. const var& v = properties [name];
  13554. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13555. xml->setAttribute (name.toString(), v.toString());
  13556. }
  13557. for (i = 0; i < children.size(); ++i)
  13558. xml->addChildElement (children.getUnchecked(i)->createXml());
  13559. return xml;
  13560. }
  13561. XmlElement* ValueTree::createXml() const
  13562. {
  13563. return object != 0 ? object->createXml() : 0;
  13564. }
  13565. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13566. {
  13567. ValueTree v (xml.getTagName());
  13568. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13569. for (int i = 0; i < numAtts; ++i)
  13570. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13571. forEachXmlChildElement (xml, e)
  13572. {
  13573. v.addChild (fromXml (*e), -1, 0);
  13574. }
  13575. return v;
  13576. }
  13577. void ValueTree::writeToStream (OutputStream& output)
  13578. {
  13579. output.writeString (getType().toString());
  13580. const int numProps = getNumProperties();
  13581. output.writeCompressedInt (numProps);
  13582. int i;
  13583. for (i = 0; i < numProps; ++i)
  13584. {
  13585. const Identifier name (getPropertyName(i));
  13586. output.writeString (name.toString());
  13587. getProperty(name).writeToStream (output);
  13588. }
  13589. const int numChildren = getNumChildren();
  13590. output.writeCompressedInt (numChildren);
  13591. for (i = 0; i < numChildren; ++i)
  13592. getChild (i).writeToStream (output);
  13593. }
  13594. ValueTree ValueTree::readFromStream (InputStream& input)
  13595. {
  13596. const String type (input.readString());
  13597. if (type.isEmpty())
  13598. return ValueTree::invalid;
  13599. ValueTree v (type);
  13600. const int numProps = input.readCompressedInt();
  13601. if (numProps < 0)
  13602. {
  13603. jassertfalse; // trying to read corrupted data!
  13604. return v;
  13605. }
  13606. int i;
  13607. for (i = 0; i < numProps; ++i)
  13608. {
  13609. const String name (input.readString());
  13610. jassert (name.isNotEmpty());
  13611. const var value (var::readFromStream (input));
  13612. v.setProperty (name, value, 0);
  13613. }
  13614. const int numChildren = input.readCompressedInt();
  13615. for (i = 0; i < numChildren; ++i)
  13616. v.addChild (readFromStream (input), -1, 0);
  13617. return v;
  13618. }
  13619. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13620. {
  13621. MemoryInputStream in (data, numBytes, false);
  13622. return readFromStream (in);
  13623. }
  13624. END_JUCE_NAMESPACE
  13625. /*** End of inlined file: juce_ValueTree.cpp ***/
  13626. /*** Start of inlined file: juce_Value.cpp ***/
  13627. BEGIN_JUCE_NAMESPACE
  13628. Value::ValueSource::ValueSource()
  13629. {
  13630. }
  13631. Value::ValueSource::~ValueSource()
  13632. {
  13633. }
  13634. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13635. {
  13636. if (synchronous)
  13637. {
  13638. for (int i = valuesWithListeners.size(); --i >= 0;)
  13639. {
  13640. Value* const v = valuesWithListeners[i];
  13641. if (v != 0)
  13642. v->callListeners();
  13643. }
  13644. }
  13645. else
  13646. {
  13647. triggerAsyncUpdate();
  13648. }
  13649. }
  13650. void Value::ValueSource::handleAsyncUpdate()
  13651. {
  13652. sendChangeMessage (true);
  13653. }
  13654. class SimpleValueSource : public Value::ValueSource
  13655. {
  13656. public:
  13657. SimpleValueSource()
  13658. {
  13659. }
  13660. SimpleValueSource (const var& initialValue)
  13661. : value (initialValue)
  13662. {
  13663. }
  13664. ~SimpleValueSource()
  13665. {
  13666. }
  13667. const var getValue() const
  13668. {
  13669. return value;
  13670. }
  13671. void setValue (const var& newValue)
  13672. {
  13673. if (newValue != value)
  13674. {
  13675. value = newValue;
  13676. sendChangeMessage (false);
  13677. }
  13678. }
  13679. private:
  13680. var value;
  13681. SimpleValueSource (const SimpleValueSource&);
  13682. SimpleValueSource& operator= (const SimpleValueSource&);
  13683. };
  13684. Value::Value()
  13685. : value (new SimpleValueSource())
  13686. {
  13687. }
  13688. Value::Value (ValueSource* const value_)
  13689. : value (value_)
  13690. {
  13691. jassert (value_ != 0);
  13692. }
  13693. Value::Value (const var& initialValue)
  13694. : value (new SimpleValueSource (initialValue))
  13695. {
  13696. }
  13697. Value::Value (const Value& other)
  13698. : value (other.value)
  13699. {
  13700. }
  13701. Value& Value::operator= (const Value& other)
  13702. {
  13703. value = other.value;
  13704. return *this;
  13705. }
  13706. Value::~Value()
  13707. {
  13708. if (listeners.size() > 0)
  13709. value->valuesWithListeners.removeValue (this);
  13710. }
  13711. const var Value::getValue() const
  13712. {
  13713. return value->getValue();
  13714. }
  13715. Value::operator const var() const
  13716. {
  13717. return getValue();
  13718. }
  13719. void Value::setValue (const var& newValue)
  13720. {
  13721. value->setValue (newValue);
  13722. }
  13723. const String Value::toString() const
  13724. {
  13725. return value->getValue().toString();
  13726. }
  13727. Value& Value::operator= (const var& newValue)
  13728. {
  13729. value->setValue (newValue);
  13730. return *this;
  13731. }
  13732. void Value::referTo (const Value& valueToReferTo)
  13733. {
  13734. if (valueToReferTo.value != value)
  13735. {
  13736. if (listeners.size() > 0)
  13737. {
  13738. value->valuesWithListeners.removeValue (this);
  13739. valueToReferTo.value->valuesWithListeners.add (this);
  13740. }
  13741. value = valueToReferTo.value;
  13742. callListeners();
  13743. }
  13744. }
  13745. bool Value::refersToSameSourceAs (const Value& other) const
  13746. {
  13747. return value == other.value;
  13748. }
  13749. bool Value::operator== (const Value& other) const
  13750. {
  13751. return value == other.value || value->getValue() == other.getValue();
  13752. }
  13753. bool Value::operator!= (const Value& other) const
  13754. {
  13755. return value != other.value && value->getValue() != other.getValue();
  13756. }
  13757. void Value::addListener (Listener* const listener)
  13758. {
  13759. if (listener != 0)
  13760. {
  13761. if (listeners.size() == 0)
  13762. value->valuesWithListeners.add (this);
  13763. listeners.add (listener);
  13764. }
  13765. }
  13766. void Value::removeListener (Listener* const listener)
  13767. {
  13768. listeners.remove (listener);
  13769. if (listeners.size() == 0)
  13770. value->valuesWithListeners.removeValue (this);
  13771. }
  13772. void Value::callListeners()
  13773. {
  13774. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13775. listeners.call (&Listener::valueChanged, v);
  13776. }
  13777. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13778. {
  13779. return stream << value.toString();
  13780. }
  13781. END_JUCE_NAMESPACE
  13782. /*** End of inlined file: juce_Value.cpp ***/
  13783. /*** Start of inlined file: juce_Application.cpp ***/
  13784. #if JUCE_MSVC
  13785. #pragma warning (push)
  13786. #pragma warning (disable: 4245 4514 4100)
  13787. #include <crtdbg.h>
  13788. #pragma warning (pop)
  13789. #endif
  13790. BEGIN_JUCE_NAMESPACE
  13791. void juce_setCurrentThreadName (const String& name);
  13792. static JUCEApplication* appInstance = 0;
  13793. JUCEApplication::JUCEApplication()
  13794. : appReturnValue (0),
  13795. stillInitialising (true)
  13796. {
  13797. }
  13798. JUCEApplication::~JUCEApplication()
  13799. {
  13800. if (appLock != 0)
  13801. {
  13802. appLock->exit();
  13803. appLock = 0;
  13804. }
  13805. }
  13806. JUCEApplication* JUCEApplication::getInstance() throw()
  13807. {
  13808. return appInstance;
  13809. }
  13810. bool JUCEApplication::isInitialising() const throw()
  13811. {
  13812. return stillInitialising;
  13813. }
  13814. const String JUCEApplication::getApplicationVersion()
  13815. {
  13816. return String::empty;
  13817. }
  13818. bool JUCEApplication::moreThanOneInstanceAllowed()
  13819. {
  13820. return true;
  13821. }
  13822. void JUCEApplication::anotherInstanceStarted (const String&)
  13823. {
  13824. }
  13825. void JUCEApplication::systemRequestedQuit()
  13826. {
  13827. quit();
  13828. }
  13829. void JUCEApplication::quit()
  13830. {
  13831. MessageManager::getInstance()->stopDispatchLoop();
  13832. }
  13833. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13834. {
  13835. appReturnValue = newReturnValue;
  13836. }
  13837. void JUCEApplication::unhandledException (const std::exception*,
  13838. const String&,
  13839. const int)
  13840. {
  13841. jassertfalse;
  13842. }
  13843. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13844. const char* const sourceFile,
  13845. const int lineNumber)
  13846. {
  13847. if (appInstance != 0)
  13848. appInstance->unhandledException (e, sourceFile, lineNumber);
  13849. }
  13850. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13851. {
  13852. return 0;
  13853. }
  13854. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13855. {
  13856. commands.add (StandardApplicationCommandIDs::quit);
  13857. }
  13858. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13859. {
  13860. if (commandID == StandardApplicationCommandIDs::quit)
  13861. {
  13862. result.setInfo (TRANS("Quit"),
  13863. TRANS("Quits the application"),
  13864. "Application",
  13865. 0);
  13866. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13867. }
  13868. }
  13869. bool JUCEApplication::perform (const InvocationInfo& info)
  13870. {
  13871. if (info.commandID == StandardApplicationCommandIDs::quit)
  13872. {
  13873. systemRequestedQuit();
  13874. return true;
  13875. }
  13876. return false;
  13877. }
  13878. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13879. {
  13880. if (! app->initialiseApp (commandLine))
  13881. return 0;
  13882. // now loop until a quit message is received..
  13883. JUCE_TRY
  13884. {
  13885. MessageManager::getInstance()->runDispatchLoop();
  13886. }
  13887. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13888. catch (const std::exception& e)
  13889. {
  13890. app->unhandledException (&e, __FILE__, __LINE__);
  13891. }
  13892. catch (...)
  13893. {
  13894. app->unhandledException (0, __FILE__, __LINE__);
  13895. }
  13896. #endif
  13897. return shutdownAppAndClearUp();
  13898. }
  13899. bool JUCEApplication::initialiseApp (String& commandLine)
  13900. {
  13901. jassert (appInstance == 0);
  13902. appInstance = this;
  13903. commandLineParameters = commandLine.trim();
  13904. commandLine = String::empty;
  13905. initialiseJuce_GUI();
  13906. #if ! JUCE_IPHONE
  13907. jassert (appLock == 0); // initialiseApp must only be called once!
  13908. if (! moreThanOneInstanceAllowed())
  13909. {
  13910. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13911. if (! appLock->enter(0))
  13912. {
  13913. appLock = 0;
  13914. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13915. delete appInstance;
  13916. appInstance = 0;
  13917. DBG ("Another instance is running - quitting...");
  13918. return false;
  13919. }
  13920. }
  13921. #endif
  13922. // let the app do its setting-up..
  13923. initialise (commandLineParameters);
  13924. // register for broadcast new app messages
  13925. MessageManager::getInstance()->registerBroadcastListener (this);
  13926. stillInitialising = false;
  13927. return true;
  13928. }
  13929. int JUCEApplication::shutdownAppAndClearUp()
  13930. {
  13931. jassert (appInstance != 0);
  13932. ScopedPointer<JUCEApplication> app (appInstance);
  13933. int returnValue = 0;
  13934. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13935. static bool reentrancyCheck = false;
  13936. if (! reentrancyCheck)
  13937. {
  13938. reentrancyCheck = true;
  13939. JUCE_TRY
  13940. {
  13941. // give the app a chance to clean up..
  13942. app->shutdown();
  13943. }
  13944. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13945. catch (const std::exception& e)
  13946. {
  13947. app->unhandledException (&e, __FILE__, __LINE__);
  13948. }
  13949. catch (...)
  13950. {
  13951. app->unhandledException (0, __FILE__, __LINE__);
  13952. }
  13953. #endif
  13954. JUCE_TRY
  13955. {
  13956. shutdownJuce_GUI();
  13957. returnValue = app->getApplicationReturnValue();
  13958. appInstance = 0;
  13959. app = 0;
  13960. }
  13961. JUCE_CATCH_ALL_ASSERT
  13962. reentrancyCheck = false;
  13963. }
  13964. return returnValue;
  13965. }
  13966. #if JUCE_IPHONE
  13967. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13968. #endif
  13969. #if ! JUCE_WINDOWS
  13970. extern const char* juce_Argv0;
  13971. #endif
  13972. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13973. {
  13974. #if ! JUCE_WINDOWS
  13975. juce_Argv0 = argv[0];
  13976. #endif
  13977. #if JUCE_IPHONE
  13978. const ScopedAutoReleasePool pool;
  13979. return juce_IPhoneMain (argc, argv, newApp);
  13980. #else
  13981. #if JUCE_MAC
  13982. const ScopedAutoReleasePool pool;
  13983. #endif
  13984. String cmd;
  13985. for (int i = 1; i < argc; ++i)
  13986. cmd << argv[i] << ' ';
  13987. return JUCEApplication::main (cmd, newApp);
  13988. #endif
  13989. }
  13990. void JUCEApplication::actionListenerCallback (const String& message)
  13991. {
  13992. if (message.startsWith (getApplicationName() + "/"))
  13993. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13994. }
  13995. static bool juceInitialisedGUI = false;
  13996. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13997. {
  13998. if (! juceInitialisedGUI)
  13999. {
  14000. #if JUCE_MAC || JUCE_IPHONE
  14001. const ScopedAutoReleasePool pool;
  14002. #endif
  14003. juceInitialisedGUI = true;
  14004. initialiseJuce_NonGUI();
  14005. MessageManager::getInstance();
  14006. LookAndFeel::setDefaultLookAndFeel (0);
  14007. juce_setCurrentThreadName ("Juce Message Thread");
  14008. #if JUCE_WINDOWS && JUCE_DEBUG
  14009. // This section is just for catching people who mess up their project settings and
  14010. // turn RTTI off..
  14011. try
  14012. {
  14013. TextButton tb (String::empty);
  14014. Component* c = &tb;
  14015. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  14016. c = dynamic_cast <Button*> (c);
  14017. }
  14018. catch (...)
  14019. {
  14020. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  14021. // got as far as this catch statement, then why haven't you got exception catching
  14022. // turned on in the debugger???
  14023. jassertfalse;
  14024. }
  14025. #endif
  14026. }
  14027. }
  14028. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  14029. {
  14030. if (juceInitialisedGUI)
  14031. {
  14032. #if JUCE_MAC
  14033. const ScopedAutoReleasePool pool;
  14034. #endif
  14035. {
  14036. DeletedAtShutdown::deleteAll();
  14037. LookAndFeel::clearDefaultLookAndFeel();
  14038. }
  14039. delete MessageManager::getInstance();
  14040. shutdownJuce_NonGUI();
  14041. juceInitialisedGUI = false;
  14042. }
  14043. }
  14044. END_JUCE_NAMESPACE
  14045. /*** End of inlined file: juce_Application.cpp ***/
  14046. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14047. BEGIN_JUCE_NAMESPACE
  14048. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14049. : commandID (commandID_),
  14050. flags (0)
  14051. {
  14052. }
  14053. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14054. const String& description_,
  14055. const String& categoryName_,
  14056. const int flags_) throw()
  14057. {
  14058. shortName = shortName_;
  14059. description = description_;
  14060. categoryName = categoryName_;
  14061. flags = flags_;
  14062. }
  14063. void ApplicationCommandInfo::setActive (const bool b) throw()
  14064. {
  14065. if (b)
  14066. flags &= ~isDisabled;
  14067. else
  14068. flags |= isDisabled;
  14069. }
  14070. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14071. {
  14072. if (b)
  14073. flags |= isTicked;
  14074. else
  14075. flags &= ~isTicked;
  14076. }
  14077. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14078. {
  14079. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14080. }
  14081. END_JUCE_NAMESPACE
  14082. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14083. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14084. BEGIN_JUCE_NAMESPACE
  14085. ApplicationCommandManager::ApplicationCommandManager()
  14086. : firstTarget (0)
  14087. {
  14088. keyMappings = new KeyPressMappingSet (this);
  14089. Desktop::getInstance().addFocusChangeListener (this);
  14090. }
  14091. ApplicationCommandManager::~ApplicationCommandManager()
  14092. {
  14093. Desktop::getInstance().removeFocusChangeListener (this);
  14094. keyMappings = 0;
  14095. }
  14096. void ApplicationCommandManager::clearCommands()
  14097. {
  14098. commands.clear();
  14099. keyMappings->clearAllKeyPresses();
  14100. triggerAsyncUpdate();
  14101. }
  14102. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14103. {
  14104. // zero isn't a valid command ID!
  14105. jassert (newCommand.commandID != 0);
  14106. // the name isn't optional!
  14107. jassert (newCommand.shortName.isNotEmpty());
  14108. if (getCommandForID (newCommand.commandID) == 0)
  14109. {
  14110. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14111. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14112. commands.add (newInfo);
  14113. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14114. triggerAsyncUpdate();
  14115. }
  14116. else
  14117. {
  14118. // trying to re-register the same command with different parameters?
  14119. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14120. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14121. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14122. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14123. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14124. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14125. }
  14126. }
  14127. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14128. {
  14129. if (target != 0)
  14130. {
  14131. Array <CommandID> commandIDs;
  14132. target->getAllCommands (commandIDs);
  14133. for (int i = 0; i < commandIDs.size(); ++i)
  14134. {
  14135. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14136. target->getCommandInfo (info.commandID, info);
  14137. registerCommand (info);
  14138. }
  14139. }
  14140. }
  14141. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14142. {
  14143. for (int i = commands.size(); --i >= 0;)
  14144. {
  14145. if (commands.getUnchecked (i)->commandID == commandID)
  14146. {
  14147. commands.remove (i);
  14148. triggerAsyncUpdate();
  14149. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14150. for (int j = keys.size(); --j >= 0;)
  14151. keyMappings->removeKeyPress (keys.getReference (j));
  14152. }
  14153. }
  14154. }
  14155. void ApplicationCommandManager::commandStatusChanged()
  14156. {
  14157. triggerAsyncUpdate();
  14158. }
  14159. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14160. {
  14161. for (int i = commands.size(); --i >= 0;)
  14162. if (commands.getUnchecked(i)->commandID == commandID)
  14163. return commands.getUnchecked(i);
  14164. return 0;
  14165. }
  14166. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14167. {
  14168. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14169. return (ci != 0) ? ci->shortName : String::empty;
  14170. }
  14171. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14172. {
  14173. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14174. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14175. : String::empty;
  14176. }
  14177. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14178. {
  14179. StringArray s;
  14180. for (int i = 0; i < commands.size(); ++i)
  14181. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14182. return s;
  14183. }
  14184. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14185. {
  14186. Array <CommandID> results;
  14187. for (int i = 0; i < commands.size(); ++i)
  14188. if (commands.getUnchecked(i)->categoryName == categoryName)
  14189. results.add (commands.getUnchecked(i)->commandID);
  14190. return results;
  14191. }
  14192. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14193. {
  14194. ApplicationCommandTarget::InvocationInfo info (commandID);
  14195. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14196. return invoke (info, asynchronously);
  14197. }
  14198. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14199. {
  14200. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14201. // manager first..
  14202. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14203. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14204. if (target == 0)
  14205. return false;
  14206. ApplicationCommandInfo commandInfo (0);
  14207. target->getCommandInfo (info_.commandID, commandInfo);
  14208. ApplicationCommandTarget::InvocationInfo info (info_);
  14209. info.commandFlags = commandInfo.flags;
  14210. sendListenerInvokeCallback (info);
  14211. const bool ok = target->invoke (info, asynchronously);
  14212. commandStatusChanged();
  14213. return ok;
  14214. }
  14215. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14216. {
  14217. return firstTarget != 0 ? firstTarget
  14218. : findDefaultComponentTarget();
  14219. }
  14220. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14221. {
  14222. firstTarget = newTarget;
  14223. }
  14224. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14225. ApplicationCommandInfo& upToDateInfo)
  14226. {
  14227. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14228. if (target == 0)
  14229. target = JUCEApplication::getInstance();
  14230. if (target != 0)
  14231. target = target->getTargetForCommand (commandID);
  14232. if (target != 0)
  14233. target->getCommandInfo (commandID, upToDateInfo);
  14234. return target;
  14235. }
  14236. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14237. {
  14238. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14239. if (target == 0 && c != 0)
  14240. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14241. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14242. return target;
  14243. }
  14244. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14245. {
  14246. Component* c = Component::getCurrentlyFocusedComponent();
  14247. if (c == 0)
  14248. {
  14249. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14250. if (activeWindow != 0)
  14251. {
  14252. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14253. if (c == 0)
  14254. c = activeWindow;
  14255. }
  14256. }
  14257. if (c == 0 && Process::isForegroundProcess())
  14258. {
  14259. // getting a bit desperate now - try all desktop comps..
  14260. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14261. {
  14262. ApplicationCommandTarget* const target
  14263. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14264. ->getPeer()->getLastFocusedSubcomponent());
  14265. if (target != 0)
  14266. return target;
  14267. }
  14268. }
  14269. if (c != 0)
  14270. {
  14271. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14272. // if we're focused on a ResizableWindow, chances are that it's the content
  14273. // component that really should get the event. And if not, the event will
  14274. // still be passed up to the top level window anyway, so let's send it to the
  14275. // content comp.
  14276. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14277. c = resizableWindow->getContentComponent();
  14278. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14279. if (target != 0)
  14280. return target;
  14281. }
  14282. return JUCEApplication::getInstance();
  14283. }
  14284. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14285. {
  14286. listeners.add (listener);
  14287. }
  14288. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14289. {
  14290. listeners.remove (listener);
  14291. }
  14292. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14293. {
  14294. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14295. }
  14296. void ApplicationCommandManager::handleAsyncUpdate()
  14297. {
  14298. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14299. }
  14300. void ApplicationCommandManager::globalFocusChanged (Component*)
  14301. {
  14302. commandStatusChanged();
  14303. }
  14304. END_JUCE_NAMESPACE
  14305. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14306. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14307. BEGIN_JUCE_NAMESPACE
  14308. ApplicationCommandTarget::ApplicationCommandTarget()
  14309. {
  14310. }
  14311. ApplicationCommandTarget::~ApplicationCommandTarget()
  14312. {
  14313. messageInvoker = 0;
  14314. }
  14315. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14316. {
  14317. if (isCommandActive (info.commandID))
  14318. {
  14319. if (async)
  14320. {
  14321. if (messageInvoker == 0)
  14322. messageInvoker = new CommandTargetMessageInvoker (this);
  14323. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14324. return true;
  14325. }
  14326. else
  14327. {
  14328. const bool success = perform (info);
  14329. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14330. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14331. // returns the command's info.
  14332. return success;
  14333. }
  14334. }
  14335. return false;
  14336. }
  14337. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14338. {
  14339. Component* c = dynamic_cast <Component*> (this);
  14340. if (c != 0)
  14341. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14342. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14343. return 0;
  14344. }
  14345. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14346. {
  14347. ApplicationCommandTarget* target = this;
  14348. int depth = 0;
  14349. while (target != 0)
  14350. {
  14351. Array <CommandID> commandIDs;
  14352. target->getAllCommands (commandIDs);
  14353. if (commandIDs.contains (commandID))
  14354. return target;
  14355. target = target->getNextCommandTarget();
  14356. ++depth;
  14357. jassert (depth < 100); // could be a recursive command chain??
  14358. jassert (target != this); // definitely a recursive command chain!
  14359. if (depth > 100 || target == this)
  14360. break;
  14361. }
  14362. if (target == 0)
  14363. {
  14364. target = JUCEApplication::getInstance();
  14365. if (target != 0)
  14366. {
  14367. Array <CommandID> commandIDs;
  14368. target->getAllCommands (commandIDs);
  14369. if (commandIDs.contains (commandID))
  14370. return target;
  14371. }
  14372. }
  14373. return 0;
  14374. }
  14375. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14376. {
  14377. ApplicationCommandInfo info (commandID);
  14378. info.flags = ApplicationCommandInfo::isDisabled;
  14379. getCommandInfo (commandID, info);
  14380. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14381. }
  14382. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14383. {
  14384. ApplicationCommandTarget* target = this;
  14385. int depth = 0;
  14386. while (target != 0)
  14387. {
  14388. if (target->tryToInvoke (info, async))
  14389. return true;
  14390. target = target->getNextCommandTarget();
  14391. ++depth;
  14392. jassert (depth < 100); // could be a recursive command chain??
  14393. jassert (target != this); // definitely a recursive command chain!
  14394. if (depth > 100 || target == this)
  14395. break;
  14396. }
  14397. if (target == 0)
  14398. {
  14399. target = JUCEApplication::getInstance();
  14400. if (target != 0)
  14401. return target->tryToInvoke (info, async);
  14402. }
  14403. return false;
  14404. }
  14405. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14406. {
  14407. ApplicationCommandTarget::InvocationInfo info (commandID);
  14408. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14409. return invoke (info, asynchronously);
  14410. }
  14411. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14412. : commandID (commandID_),
  14413. commandFlags (0),
  14414. invocationMethod (direct),
  14415. originatingComponent (0),
  14416. isKeyDown (false),
  14417. millisecsSinceKeyPressed (0)
  14418. {
  14419. }
  14420. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14421. : owner (owner_)
  14422. {
  14423. }
  14424. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14425. {
  14426. }
  14427. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14428. {
  14429. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14430. owner->tryToInvoke (*info, false);
  14431. }
  14432. END_JUCE_NAMESPACE
  14433. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14434. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14435. BEGIN_JUCE_NAMESPACE
  14436. juce_ImplementSingleton (ApplicationProperties)
  14437. ApplicationProperties::ApplicationProperties() throw()
  14438. : msBeforeSaving (3000),
  14439. options (PropertiesFile::storeAsBinary),
  14440. commonSettingsAreReadOnly (0)
  14441. {
  14442. }
  14443. ApplicationProperties::~ApplicationProperties()
  14444. {
  14445. closeFiles();
  14446. clearSingletonInstance();
  14447. }
  14448. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14449. const String& fileNameSuffix,
  14450. const String& folderName_,
  14451. const int millisecondsBeforeSaving,
  14452. const int propertiesFileOptions) throw()
  14453. {
  14454. appName = applicationName;
  14455. fileSuffix = fileNameSuffix;
  14456. folderName = folderName_;
  14457. msBeforeSaving = millisecondsBeforeSaving;
  14458. options = propertiesFileOptions;
  14459. }
  14460. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14461. const bool testCommonSettings,
  14462. const bool showWarningDialogOnFailure)
  14463. {
  14464. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14465. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14466. if (! (userOk && commonOk))
  14467. {
  14468. if (showWarningDialogOnFailure)
  14469. {
  14470. String filenames;
  14471. if (userProps != 0 && ! userOk)
  14472. filenames << '\n' << userProps->getFile().getFullPathName();
  14473. if (commonProps != 0 && ! commonOk)
  14474. filenames << '\n' << commonProps->getFile().getFullPathName();
  14475. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14476. appName + TRANS(" - Unable to save settings"),
  14477. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14478. + appName + TRANS(" needs to be able to write to the following files:\n")
  14479. + filenames
  14480. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14481. }
  14482. return false;
  14483. }
  14484. return true;
  14485. }
  14486. void ApplicationProperties::openFiles() throw()
  14487. {
  14488. // You need to call setStorageParameters() before trying to get hold of the
  14489. // properties!
  14490. jassert (appName.isNotEmpty());
  14491. if (appName.isNotEmpty())
  14492. {
  14493. if (userProps == 0)
  14494. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14495. false, msBeforeSaving, options);
  14496. if (commonProps == 0)
  14497. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14498. true, msBeforeSaving, options);
  14499. userProps->setFallbackPropertySet (commonProps);
  14500. }
  14501. }
  14502. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14503. {
  14504. if (userProps == 0)
  14505. openFiles();
  14506. return userProps;
  14507. }
  14508. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14509. {
  14510. if (commonProps == 0)
  14511. openFiles();
  14512. if (returnUserPropsIfReadOnly)
  14513. {
  14514. if (commonSettingsAreReadOnly == 0)
  14515. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14516. if (commonSettingsAreReadOnly > 0)
  14517. return userProps;
  14518. }
  14519. return commonProps;
  14520. }
  14521. bool ApplicationProperties::saveIfNeeded()
  14522. {
  14523. return (userProps == 0 || userProps->saveIfNeeded())
  14524. && (commonProps == 0 || commonProps->saveIfNeeded());
  14525. }
  14526. void ApplicationProperties::closeFiles()
  14527. {
  14528. userProps = 0;
  14529. commonProps = 0;
  14530. }
  14531. END_JUCE_NAMESPACE
  14532. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14533. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14534. BEGIN_JUCE_NAMESPACE
  14535. namespace PropertyFileConstants
  14536. {
  14537. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14538. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14539. static const char* const fileTag = "PROPERTIES";
  14540. static const char* const valueTag = "VALUE";
  14541. static const char* const nameAttribute = "name";
  14542. static const char* const valueAttribute = "val";
  14543. }
  14544. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14545. const int options_, InterProcessLock* const processLock_)
  14546. : PropertySet (ignoreCaseOfKeyNames),
  14547. file (f),
  14548. timerInterval (millisecondsBeforeSaving),
  14549. options (options_),
  14550. loadedOk (false),
  14551. needsWriting (false),
  14552. processLock (processLock_)
  14553. {
  14554. // You need to correctly specify just one storage format for the file
  14555. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14556. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14557. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14558. ProcessScopedLock pl (createProcessLock());
  14559. if (pl != 0 && ! pl->isLocked())
  14560. return; // locking failure..
  14561. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14562. if (fileStream != 0)
  14563. {
  14564. int magicNumber = fileStream->readInt();
  14565. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14566. {
  14567. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14568. magicNumber = PropertyFileConstants::magicNumber;
  14569. }
  14570. if (magicNumber == PropertyFileConstants::magicNumber)
  14571. {
  14572. loadedOk = true;
  14573. BufferedInputStream in (fileStream.release(), 2048, true);
  14574. int numValues = in.readInt();
  14575. while (--numValues >= 0 && ! in.isExhausted())
  14576. {
  14577. const String key (in.readString());
  14578. const String value (in.readString());
  14579. jassert (key.isNotEmpty());
  14580. if (key.isNotEmpty())
  14581. getAllProperties().set (key, value);
  14582. }
  14583. }
  14584. else
  14585. {
  14586. // Not a binary props file - let's see if it's XML..
  14587. fileStream = 0;
  14588. XmlDocument parser (f);
  14589. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14590. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14591. {
  14592. doc = parser.getDocumentElement();
  14593. if (doc != 0)
  14594. {
  14595. loadedOk = true;
  14596. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14597. {
  14598. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14599. if (name.isNotEmpty())
  14600. {
  14601. getAllProperties().set (name,
  14602. e->getFirstChildElement() != 0
  14603. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14604. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14605. }
  14606. }
  14607. }
  14608. else
  14609. {
  14610. // must be a pretty broken XML file we're trying to parse here,
  14611. // or a sign that this object needs an InterProcessLock,
  14612. // or just a failure reading the file. This last reason is why
  14613. // we don't jassertfalse here.
  14614. }
  14615. }
  14616. }
  14617. }
  14618. else
  14619. {
  14620. loadedOk = ! f.exists();
  14621. }
  14622. }
  14623. PropertiesFile::~PropertiesFile()
  14624. {
  14625. if (! saveIfNeeded())
  14626. jassertfalse;
  14627. }
  14628. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14629. {
  14630. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14631. }
  14632. bool PropertiesFile::saveIfNeeded()
  14633. {
  14634. const ScopedLock sl (getLock());
  14635. return (! needsWriting) || save();
  14636. }
  14637. bool PropertiesFile::needsToBeSaved() const
  14638. {
  14639. const ScopedLock sl (getLock());
  14640. return needsWriting;
  14641. }
  14642. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14643. {
  14644. const ScopedLock sl (getLock());
  14645. needsWriting = needsToBeSaved_;
  14646. }
  14647. bool PropertiesFile::save()
  14648. {
  14649. const ScopedLock sl (getLock());
  14650. stopTimer();
  14651. if (file == File::nonexistent
  14652. || file.isDirectory()
  14653. || ! file.getParentDirectory().createDirectory())
  14654. return false;
  14655. if ((options & storeAsXML) != 0)
  14656. {
  14657. XmlElement doc (PropertyFileConstants::fileTag);
  14658. for (int i = 0; i < getAllProperties().size(); ++i)
  14659. {
  14660. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14661. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14662. // if the value seems to contain xml, store it as such..
  14663. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14664. XmlElement* const childElement = xmlContent.getDocumentElement();
  14665. if (childElement != 0)
  14666. e->addChildElement (childElement);
  14667. else
  14668. e->setAttribute (PropertyFileConstants::valueAttribute,
  14669. getAllProperties().getAllValues() [i]);
  14670. }
  14671. ProcessScopedLock pl (createProcessLock());
  14672. if (pl != 0 && ! pl->isLocked())
  14673. return false; // locking failure..
  14674. if (doc.writeToFile (file, String::empty))
  14675. {
  14676. needsWriting = false;
  14677. return true;
  14678. }
  14679. }
  14680. else
  14681. {
  14682. ProcessScopedLock pl (createProcessLock());
  14683. if (pl != 0 && ! pl->isLocked())
  14684. return false; // locking failure..
  14685. TemporaryFile tempFile (file);
  14686. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14687. if (out != 0)
  14688. {
  14689. if ((options & storeAsCompressedBinary) != 0)
  14690. {
  14691. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14692. out->flush();
  14693. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14694. }
  14695. else
  14696. {
  14697. // have you set up the storage option flags correctly?
  14698. jassert ((options & storeAsBinary) != 0);
  14699. out->writeInt (PropertyFileConstants::magicNumber);
  14700. }
  14701. const int numProperties = getAllProperties().size();
  14702. out->writeInt (numProperties);
  14703. for (int i = 0; i < numProperties; ++i)
  14704. {
  14705. out->writeString (getAllProperties().getAllKeys() [i]);
  14706. out->writeString (getAllProperties().getAllValues() [i]);
  14707. }
  14708. out = 0;
  14709. if (tempFile.overwriteTargetFileWithTemporary())
  14710. {
  14711. needsWriting = false;
  14712. return true;
  14713. }
  14714. }
  14715. }
  14716. return false;
  14717. }
  14718. void PropertiesFile::timerCallback()
  14719. {
  14720. saveIfNeeded();
  14721. }
  14722. void PropertiesFile::propertyChanged()
  14723. {
  14724. sendChangeMessage (this);
  14725. needsWriting = true;
  14726. if (timerInterval > 0)
  14727. startTimer (timerInterval);
  14728. else if (timerInterval == 0)
  14729. saveIfNeeded();
  14730. }
  14731. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14732. const String& fileNameSuffix,
  14733. const String& folderName,
  14734. const bool commonToAllUsers)
  14735. {
  14736. // mustn't have illegal characters in this name..
  14737. jassert (applicationName == File::createLegalFileName (applicationName));
  14738. #if JUCE_MAC || JUCE_IPHONE
  14739. File dir (commonToAllUsers ? "/Library/Preferences"
  14740. : "~/Library/Preferences");
  14741. if (folderName.isNotEmpty())
  14742. dir = dir.getChildFile (folderName);
  14743. #endif
  14744. #ifdef JUCE_LINUX
  14745. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14746. + (folderName.isNotEmpty() ? folderName
  14747. : ("." + applicationName)));
  14748. #endif
  14749. #if JUCE_WINDOWS
  14750. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14751. : File::userApplicationDataDirectory));
  14752. if (dir == File::nonexistent)
  14753. return File::nonexistent;
  14754. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14755. : applicationName);
  14756. #endif
  14757. return dir.getChildFile (applicationName)
  14758. .withFileExtension (fileNameSuffix);
  14759. }
  14760. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14761. const String& fileNameSuffix,
  14762. const String& folderName,
  14763. const bool commonToAllUsers,
  14764. const int millisecondsBeforeSaving,
  14765. const int propertiesFileOptions,
  14766. InterProcessLock* processLock_)
  14767. {
  14768. const File file (getDefaultAppSettingsFile (applicationName,
  14769. fileNameSuffix,
  14770. folderName,
  14771. commonToAllUsers));
  14772. jassert (file != File::nonexistent);
  14773. if (file == File::nonexistent)
  14774. return 0;
  14775. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14776. }
  14777. END_JUCE_NAMESPACE
  14778. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14779. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14780. BEGIN_JUCE_NAMESPACE
  14781. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14782. const String& fileWildcard_,
  14783. const String& openFileDialogTitle_,
  14784. const String& saveFileDialogTitle_)
  14785. : changedSinceSave (false),
  14786. fileExtension (fileExtension_),
  14787. fileWildcard (fileWildcard_),
  14788. openFileDialogTitle (openFileDialogTitle_),
  14789. saveFileDialogTitle (saveFileDialogTitle_)
  14790. {
  14791. }
  14792. FileBasedDocument::~FileBasedDocument()
  14793. {
  14794. }
  14795. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14796. {
  14797. if (changedSinceSave != hasChanged)
  14798. {
  14799. changedSinceSave = hasChanged;
  14800. sendChangeMessage (this);
  14801. }
  14802. }
  14803. void FileBasedDocument::changed()
  14804. {
  14805. changedSinceSave = true;
  14806. sendChangeMessage (this);
  14807. }
  14808. void FileBasedDocument::setFile (const File& newFile)
  14809. {
  14810. if (documentFile != newFile)
  14811. {
  14812. documentFile = newFile;
  14813. changed();
  14814. }
  14815. }
  14816. bool FileBasedDocument::loadFrom (const File& newFile,
  14817. const bool showMessageOnFailure)
  14818. {
  14819. MouseCursor::showWaitCursor();
  14820. const File oldFile (documentFile);
  14821. documentFile = newFile;
  14822. String error;
  14823. if (newFile.existsAsFile())
  14824. {
  14825. error = loadDocument (newFile);
  14826. if (error.isEmpty())
  14827. {
  14828. setChangedFlag (false);
  14829. MouseCursor::hideWaitCursor();
  14830. setLastDocumentOpened (newFile);
  14831. return true;
  14832. }
  14833. }
  14834. else
  14835. {
  14836. error = "The file doesn't exist";
  14837. }
  14838. documentFile = oldFile;
  14839. MouseCursor::hideWaitCursor();
  14840. if (showMessageOnFailure)
  14841. {
  14842. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14843. TRANS("Failed to open file..."),
  14844. TRANS("There was an error while trying to load the file:\n\n")
  14845. + newFile.getFullPathName()
  14846. + "\n\n"
  14847. + error);
  14848. }
  14849. return false;
  14850. }
  14851. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14852. {
  14853. FileChooser fc (openFileDialogTitle,
  14854. getLastDocumentOpened(),
  14855. fileWildcard);
  14856. if (fc.browseForFileToOpen())
  14857. return loadFrom (fc.getResult(), showMessageOnFailure);
  14858. return false;
  14859. }
  14860. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14861. const bool showMessageOnFailure)
  14862. {
  14863. return saveAs (documentFile,
  14864. false,
  14865. askUserForFileIfNotSpecified,
  14866. showMessageOnFailure);
  14867. }
  14868. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14869. const bool warnAboutOverwritingExistingFiles,
  14870. const bool askUserForFileIfNotSpecified,
  14871. const bool showMessageOnFailure)
  14872. {
  14873. if (newFile == File::nonexistent)
  14874. {
  14875. if (askUserForFileIfNotSpecified)
  14876. {
  14877. return saveAsInteractive (true);
  14878. }
  14879. else
  14880. {
  14881. // can't save to an unspecified file
  14882. jassertfalse;
  14883. return failedToWriteToFile;
  14884. }
  14885. }
  14886. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14887. {
  14888. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14889. TRANS("File already exists"),
  14890. TRANS("There's already a file called:\n\n")
  14891. + newFile.getFullPathName()
  14892. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14893. TRANS("overwrite"),
  14894. TRANS("cancel")))
  14895. {
  14896. return userCancelledSave;
  14897. }
  14898. }
  14899. MouseCursor::showWaitCursor();
  14900. const File oldFile (documentFile);
  14901. documentFile = newFile;
  14902. String error (saveDocument (newFile));
  14903. if (error.isEmpty())
  14904. {
  14905. setChangedFlag (false);
  14906. MouseCursor::hideWaitCursor();
  14907. return savedOk;
  14908. }
  14909. documentFile = oldFile;
  14910. MouseCursor::hideWaitCursor();
  14911. if (showMessageOnFailure)
  14912. {
  14913. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14914. TRANS("Error writing to file..."),
  14915. TRANS("An error occurred while trying to save \"")
  14916. + getDocumentTitle()
  14917. + TRANS("\" to the file:\n\n")
  14918. + newFile.getFullPathName()
  14919. + "\n\n"
  14920. + error);
  14921. }
  14922. return failedToWriteToFile;
  14923. }
  14924. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14925. {
  14926. if (! hasChangedSinceSaved())
  14927. return savedOk;
  14928. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14929. TRANS("Closing document..."),
  14930. TRANS("Do you want to save the changes to \"")
  14931. + getDocumentTitle() + "\"?",
  14932. TRANS("save"),
  14933. TRANS("discard changes"),
  14934. TRANS("cancel"));
  14935. if (r == 1)
  14936. {
  14937. // save changes
  14938. return save (true, true);
  14939. }
  14940. else if (r == 2)
  14941. {
  14942. // discard changes
  14943. return savedOk;
  14944. }
  14945. return userCancelledSave;
  14946. }
  14947. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14948. {
  14949. File f;
  14950. if (documentFile.existsAsFile())
  14951. f = documentFile;
  14952. else
  14953. f = getLastDocumentOpened();
  14954. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14955. if (legalFilename.isEmpty())
  14956. legalFilename = "unnamed";
  14957. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14958. f = f.getSiblingFile (legalFilename);
  14959. else
  14960. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14961. f = f.withFileExtension (fileExtension)
  14962. .getNonexistentSibling (true);
  14963. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14964. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14965. {
  14966. setLastDocumentOpened (fc.getResult());
  14967. File chosen (fc.getResult());
  14968. if (chosen.getFileExtension().isEmpty())
  14969. {
  14970. chosen = chosen.withFileExtension (fileExtension);
  14971. if (chosen.exists())
  14972. {
  14973. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14974. TRANS("File already exists"),
  14975. TRANS("There's already a file called:")
  14976. + "\n\n" + chosen.getFullPathName()
  14977. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14978. TRANS("overwrite"),
  14979. TRANS("cancel")))
  14980. {
  14981. return userCancelledSave;
  14982. }
  14983. }
  14984. }
  14985. return saveAs (chosen, false, false, true);
  14986. }
  14987. return userCancelledSave;
  14988. }
  14989. END_JUCE_NAMESPACE
  14990. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14991. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14992. BEGIN_JUCE_NAMESPACE
  14993. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14994. : maxNumberOfItems (10)
  14995. {
  14996. }
  14997. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14998. {
  14999. }
  15000. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15001. {
  15002. maxNumberOfItems = jmax (1, newMaxNumber);
  15003. while (getNumFiles() > maxNumberOfItems)
  15004. files.remove (getNumFiles() - 1);
  15005. }
  15006. int RecentlyOpenedFilesList::getNumFiles() const
  15007. {
  15008. return files.size();
  15009. }
  15010. const File RecentlyOpenedFilesList::getFile (const int index) const
  15011. {
  15012. return File (files [index]);
  15013. }
  15014. void RecentlyOpenedFilesList::clear()
  15015. {
  15016. files.clear();
  15017. }
  15018. void RecentlyOpenedFilesList::addFile (const File& file)
  15019. {
  15020. const String path (file.getFullPathName());
  15021. files.removeString (path, true);
  15022. files.insert (0, path);
  15023. setMaxNumberOfItems (maxNumberOfItems);
  15024. }
  15025. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15026. {
  15027. for (int i = getNumFiles(); --i >= 0;)
  15028. if (! getFile(i).exists())
  15029. files.remove (i);
  15030. }
  15031. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15032. const int baseItemId,
  15033. const bool showFullPaths,
  15034. const bool dontAddNonExistentFiles,
  15035. const File** filesToAvoid)
  15036. {
  15037. int num = 0;
  15038. for (int i = 0; i < getNumFiles(); ++i)
  15039. {
  15040. const File f (getFile(i));
  15041. if ((! dontAddNonExistentFiles) || f.exists())
  15042. {
  15043. bool needsAvoiding = false;
  15044. if (filesToAvoid != 0)
  15045. {
  15046. const File** avoid = filesToAvoid;
  15047. while (*avoid != 0)
  15048. {
  15049. if (f == **avoid)
  15050. {
  15051. needsAvoiding = true;
  15052. break;
  15053. }
  15054. ++avoid;
  15055. }
  15056. }
  15057. if (! needsAvoiding)
  15058. {
  15059. menuToAddTo.addItem (baseItemId + i,
  15060. showFullPaths ? f.getFullPathName()
  15061. : f.getFileName());
  15062. ++num;
  15063. }
  15064. }
  15065. }
  15066. return num;
  15067. }
  15068. const String RecentlyOpenedFilesList::toString() const
  15069. {
  15070. return files.joinIntoString ("\n");
  15071. }
  15072. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15073. {
  15074. clear();
  15075. files.addLines (stringifiedVersion);
  15076. setMaxNumberOfItems (maxNumberOfItems);
  15077. }
  15078. END_JUCE_NAMESPACE
  15079. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15080. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15081. BEGIN_JUCE_NAMESPACE
  15082. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15083. const int minimumTransactions)
  15084. : totalUnitsStored (0),
  15085. nextIndex (0),
  15086. newTransaction (true),
  15087. reentrancyCheck (false)
  15088. {
  15089. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15090. minimumTransactions);
  15091. }
  15092. UndoManager::~UndoManager()
  15093. {
  15094. clearUndoHistory();
  15095. }
  15096. void UndoManager::clearUndoHistory()
  15097. {
  15098. transactions.clear();
  15099. transactionNames.clear();
  15100. totalUnitsStored = 0;
  15101. nextIndex = 0;
  15102. sendChangeMessage (this);
  15103. }
  15104. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15105. {
  15106. return totalUnitsStored;
  15107. }
  15108. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15109. const int minimumTransactions)
  15110. {
  15111. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15112. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15113. }
  15114. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15115. {
  15116. if (command_ != 0)
  15117. {
  15118. ScopedPointer<UndoableAction> command (command_);
  15119. if (actionName.isNotEmpty())
  15120. currentTransactionName = actionName;
  15121. if (reentrancyCheck)
  15122. {
  15123. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15124. // undo() methods, or else these actions won't actually get done.
  15125. return false;
  15126. }
  15127. else if (command->perform())
  15128. {
  15129. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15130. if (commandSet != 0 && ! newTransaction)
  15131. {
  15132. UndoableAction* lastAction = commandSet->getLast();
  15133. if (lastAction != 0)
  15134. {
  15135. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15136. if (coalescedAction != 0)
  15137. {
  15138. command = coalescedAction;
  15139. totalUnitsStored -= lastAction->getSizeInUnits();
  15140. commandSet->removeLast();
  15141. }
  15142. }
  15143. }
  15144. else
  15145. {
  15146. commandSet = new OwnedArray<UndoableAction>();
  15147. transactions.insert (nextIndex, commandSet);
  15148. transactionNames.insert (nextIndex, currentTransactionName);
  15149. ++nextIndex;
  15150. }
  15151. totalUnitsStored += command->getSizeInUnits();
  15152. commandSet->add (command.release());
  15153. newTransaction = false;
  15154. while (nextIndex < transactions.size())
  15155. {
  15156. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15157. for (int i = lastSet->size(); --i >= 0;)
  15158. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15159. transactions.removeLast();
  15160. transactionNames.remove (transactionNames.size() - 1);
  15161. }
  15162. while (nextIndex > 0
  15163. && totalUnitsStored > maxNumUnitsToKeep
  15164. && transactions.size() > minimumTransactionsToKeep)
  15165. {
  15166. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15167. for (int i = firstSet->size(); --i >= 0;)
  15168. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15169. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15170. transactions.remove (0);
  15171. transactionNames.remove (0);
  15172. --nextIndex;
  15173. }
  15174. sendChangeMessage (this);
  15175. return true;
  15176. }
  15177. }
  15178. return false;
  15179. }
  15180. void UndoManager::beginNewTransaction (const String& actionName)
  15181. {
  15182. newTransaction = true;
  15183. currentTransactionName = actionName;
  15184. }
  15185. void UndoManager::setCurrentTransactionName (const String& newName)
  15186. {
  15187. currentTransactionName = newName;
  15188. }
  15189. bool UndoManager::canUndo() const
  15190. {
  15191. return nextIndex > 0;
  15192. }
  15193. bool UndoManager::canRedo() const
  15194. {
  15195. return nextIndex < transactions.size();
  15196. }
  15197. const String UndoManager::getUndoDescription() const
  15198. {
  15199. return transactionNames [nextIndex - 1];
  15200. }
  15201. const String UndoManager::getRedoDescription() const
  15202. {
  15203. return transactionNames [nextIndex];
  15204. }
  15205. bool UndoManager::undo()
  15206. {
  15207. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15208. if (commandSet == 0)
  15209. return false;
  15210. reentrancyCheck = true;
  15211. bool failed = false;
  15212. for (int i = commandSet->size(); --i >= 0;)
  15213. {
  15214. if (! commandSet->getUnchecked(i)->undo())
  15215. {
  15216. jassertfalse;
  15217. failed = true;
  15218. break;
  15219. }
  15220. }
  15221. reentrancyCheck = false;
  15222. if (failed)
  15223. clearUndoHistory();
  15224. else
  15225. --nextIndex;
  15226. beginNewTransaction();
  15227. sendChangeMessage (this);
  15228. return true;
  15229. }
  15230. bool UndoManager::redo()
  15231. {
  15232. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15233. if (commandSet == 0)
  15234. return false;
  15235. reentrancyCheck = true;
  15236. bool failed = false;
  15237. for (int i = 0; i < commandSet->size(); ++i)
  15238. {
  15239. if (! commandSet->getUnchecked(i)->perform())
  15240. {
  15241. jassertfalse;
  15242. failed = true;
  15243. break;
  15244. }
  15245. }
  15246. reentrancyCheck = false;
  15247. if (failed)
  15248. clearUndoHistory();
  15249. else
  15250. ++nextIndex;
  15251. beginNewTransaction();
  15252. sendChangeMessage (this);
  15253. return true;
  15254. }
  15255. bool UndoManager::undoCurrentTransactionOnly()
  15256. {
  15257. return newTransaction ? false : undo();
  15258. }
  15259. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15260. {
  15261. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15262. if (commandSet != 0 && ! newTransaction)
  15263. {
  15264. for (int i = 0; i < commandSet->size(); ++i)
  15265. actionsFound.add (commandSet->getUnchecked(i));
  15266. }
  15267. }
  15268. int UndoManager::getNumActionsInCurrentTransaction() const
  15269. {
  15270. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15271. if (commandSet != 0 && ! newTransaction)
  15272. return commandSet->size();
  15273. return 0;
  15274. }
  15275. END_JUCE_NAMESPACE
  15276. /*** End of inlined file: juce_UndoManager.cpp ***/
  15277. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15278. BEGIN_JUCE_NAMESPACE
  15279. static const char* const aiffFormatName = "AIFF file";
  15280. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15281. class AiffAudioFormatReader : public AudioFormatReader
  15282. {
  15283. public:
  15284. int bytesPerFrame;
  15285. int64 dataChunkStart;
  15286. bool littleEndian;
  15287. AiffAudioFormatReader (InputStream* in)
  15288. : AudioFormatReader (in, TRANS (aiffFormatName))
  15289. {
  15290. if (input->readInt() == chunkName ("FORM"))
  15291. {
  15292. const int len = input->readIntBigEndian();
  15293. const int64 end = input->getPosition() + len;
  15294. const int nextType = input->readInt();
  15295. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15296. {
  15297. bool hasGotVer = false;
  15298. bool hasGotData = false;
  15299. bool hasGotType = false;
  15300. while (input->getPosition() < end)
  15301. {
  15302. const int type = input->readInt();
  15303. const uint32 length = (uint32) input->readIntBigEndian();
  15304. const int64 chunkEnd = input->getPosition() + length;
  15305. if (type == chunkName ("FVER"))
  15306. {
  15307. hasGotVer = true;
  15308. const int ver = input->readIntBigEndian();
  15309. if (ver != 0 && ver != (int)0xa2805140)
  15310. break;
  15311. }
  15312. else if (type == chunkName ("COMM"))
  15313. {
  15314. hasGotType = true;
  15315. numChannels = (unsigned int)input->readShortBigEndian();
  15316. lengthInSamples = input->readIntBigEndian();
  15317. bitsPerSample = input->readShortBigEndian();
  15318. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15319. unsigned char sampleRateBytes[10];
  15320. input->read (sampleRateBytes, 10);
  15321. const int byte0 = sampleRateBytes[0];
  15322. if ((byte0 & 0x80) != 0
  15323. || byte0 <= 0x3F || byte0 > 0x40
  15324. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15325. break;
  15326. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15327. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15328. sampleRate = (int) sampRate;
  15329. if (length <= 18)
  15330. {
  15331. // some types don't have a chunk large enough to include a compression
  15332. // type, so assume it's just big-endian pcm
  15333. littleEndian = false;
  15334. }
  15335. else
  15336. {
  15337. const int compType = input->readInt();
  15338. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15339. {
  15340. littleEndian = false;
  15341. }
  15342. else if (compType == chunkName ("sowt"))
  15343. {
  15344. littleEndian = true;
  15345. }
  15346. else
  15347. {
  15348. sampleRate = 0;
  15349. break;
  15350. }
  15351. }
  15352. }
  15353. else if (type == chunkName ("SSND"))
  15354. {
  15355. hasGotData = true;
  15356. const int offset = input->readIntBigEndian();
  15357. dataChunkStart = input->getPosition() + 4 + offset;
  15358. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15359. }
  15360. else if ((hasGotVer && hasGotData && hasGotType)
  15361. || chunkEnd < input->getPosition()
  15362. || input->isExhausted())
  15363. {
  15364. break;
  15365. }
  15366. input->setPosition (chunkEnd);
  15367. }
  15368. }
  15369. }
  15370. }
  15371. ~AiffAudioFormatReader()
  15372. {
  15373. }
  15374. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15375. int64 startSampleInFile, int numSamples)
  15376. {
  15377. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15378. if (samplesAvailable < numSamples)
  15379. {
  15380. for (int i = numDestChannels; --i >= 0;)
  15381. if (destSamples[i] != 0)
  15382. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15383. numSamples = (int) samplesAvailable;
  15384. }
  15385. if (numSamples <= 0)
  15386. return true;
  15387. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15388. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15389. char tempBuffer [tempBufSize];
  15390. while (numSamples > 0)
  15391. {
  15392. int* left = destSamples[0];
  15393. if (left != 0)
  15394. left += startOffsetInDestBuffer;
  15395. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15396. if (right != 0)
  15397. right += startOffsetInDestBuffer;
  15398. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15399. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15400. if (bytesRead < numThisTime * bytesPerFrame)
  15401. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15402. if (bitsPerSample == 16)
  15403. {
  15404. if (littleEndian)
  15405. {
  15406. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15407. if (numChannels > 1)
  15408. {
  15409. if (left == 0)
  15410. {
  15411. for (int i = numThisTime; --i >= 0;)
  15412. {
  15413. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15414. ++src;
  15415. }
  15416. }
  15417. else if (right == 0)
  15418. {
  15419. for (int i = numThisTime; --i >= 0;)
  15420. {
  15421. ++src;
  15422. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15423. }
  15424. }
  15425. else
  15426. {
  15427. for (int i = numThisTime; --i >= 0;)
  15428. {
  15429. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15430. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15431. }
  15432. }
  15433. }
  15434. else
  15435. {
  15436. for (int i = numThisTime; --i >= 0;)
  15437. {
  15438. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15439. }
  15440. }
  15441. }
  15442. else
  15443. {
  15444. const char* src = tempBuffer;
  15445. if (numChannels > 1)
  15446. {
  15447. if (left == 0)
  15448. {
  15449. for (int i = numThisTime; --i >= 0;)
  15450. {
  15451. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15452. src += 4;
  15453. }
  15454. }
  15455. else if (right == 0)
  15456. {
  15457. for (int i = numThisTime; --i >= 0;)
  15458. {
  15459. src += 2;
  15460. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15461. src += 2;
  15462. }
  15463. }
  15464. else
  15465. {
  15466. for (int i = numThisTime; --i >= 0;)
  15467. {
  15468. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15469. src += 2;
  15470. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15471. src += 2;
  15472. }
  15473. }
  15474. }
  15475. else
  15476. {
  15477. for (int i = numThisTime; --i >= 0;)
  15478. {
  15479. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15480. src += 2;
  15481. }
  15482. }
  15483. }
  15484. }
  15485. else if (bitsPerSample == 24)
  15486. {
  15487. const char* src = (const char*)tempBuffer;
  15488. if (littleEndian)
  15489. {
  15490. if (numChannels > 1)
  15491. {
  15492. if (left == 0)
  15493. {
  15494. for (int i = numThisTime; --i >= 0;)
  15495. {
  15496. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15497. src += 6;
  15498. }
  15499. }
  15500. else if (right == 0)
  15501. {
  15502. for (int i = numThisTime; --i >= 0;)
  15503. {
  15504. src += 3;
  15505. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15506. src += 3;
  15507. }
  15508. }
  15509. else
  15510. {
  15511. for (int i = numThisTime; --i >= 0;)
  15512. {
  15513. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15514. src += 3;
  15515. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15516. src += 3;
  15517. }
  15518. }
  15519. }
  15520. else
  15521. {
  15522. for (int i = numThisTime; --i >= 0;)
  15523. {
  15524. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15525. src += 3;
  15526. }
  15527. }
  15528. }
  15529. else
  15530. {
  15531. if (numChannels > 1)
  15532. {
  15533. if (left == 0)
  15534. {
  15535. for (int i = numThisTime; --i >= 0;)
  15536. {
  15537. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15538. src += 6;
  15539. }
  15540. }
  15541. else if (right == 0)
  15542. {
  15543. for (int i = numThisTime; --i >= 0;)
  15544. {
  15545. src += 3;
  15546. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15547. src += 3;
  15548. }
  15549. }
  15550. else
  15551. {
  15552. for (int i = numThisTime; --i >= 0;)
  15553. {
  15554. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15555. src += 3;
  15556. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15557. src += 3;
  15558. }
  15559. }
  15560. }
  15561. else
  15562. {
  15563. for (int i = numThisTime; --i >= 0;)
  15564. {
  15565. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15566. src += 3;
  15567. }
  15568. }
  15569. }
  15570. }
  15571. else if (bitsPerSample == 32)
  15572. {
  15573. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15574. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15575. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15576. if (littleEndian)
  15577. {
  15578. if (numChannels > 1)
  15579. {
  15580. if (l == 0)
  15581. {
  15582. for (int i = numThisTime; --i >= 0;)
  15583. {
  15584. ++src;
  15585. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15586. }
  15587. }
  15588. else if (r == 0)
  15589. {
  15590. for (int i = numThisTime; --i >= 0;)
  15591. {
  15592. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15593. ++src;
  15594. }
  15595. }
  15596. else
  15597. {
  15598. for (int i = numThisTime; --i >= 0;)
  15599. {
  15600. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15601. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15602. }
  15603. }
  15604. }
  15605. else
  15606. {
  15607. for (int i = numThisTime; --i >= 0;)
  15608. {
  15609. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15610. }
  15611. }
  15612. }
  15613. else
  15614. {
  15615. if (numChannels > 1)
  15616. {
  15617. if (l == 0)
  15618. {
  15619. for (int i = numThisTime; --i >= 0;)
  15620. {
  15621. ++src;
  15622. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15623. }
  15624. }
  15625. else if (r == 0)
  15626. {
  15627. for (int i = numThisTime; --i >= 0;)
  15628. {
  15629. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15630. ++src;
  15631. }
  15632. }
  15633. else
  15634. {
  15635. for (int i = numThisTime; --i >= 0;)
  15636. {
  15637. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15638. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15639. }
  15640. }
  15641. }
  15642. else
  15643. {
  15644. for (int i = numThisTime; --i >= 0;)
  15645. {
  15646. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15647. }
  15648. }
  15649. }
  15650. left = reinterpret_cast <int*> (l);
  15651. right = reinterpret_cast <int*> (r);
  15652. }
  15653. else if (bitsPerSample == 8)
  15654. {
  15655. const char* src = tempBuffer;
  15656. if (numChannels > 1)
  15657. {
  15658. if (left == 0)
  15659. {
  15660. for (int i = numThisTime; --i >= 0;)
  15661. {
  15662. *right++ = ((int) *src++) << 24;
  15663. ++src;
  15664. }
  15665. }
  15666. else if (right == 0)
  15667. {
  15668. for (int i = numThisTime; --i >= 0;)
  15669. {
  15670. ++src;
  15671. *left++ = ((int) *src++) << 24;
  15672. }
  15673. }
  15674. else
  15675. {
  15676. for (int i = numThisTime; --i >= 0;)
  15677. {
  15678. *left++ = ((int) *src++) << 24;
  15679. *right++ = ((int) *src++) << 24;
  15680. }
  15681. }
  15682. }
  15683. else
  15684. {
  15685. for (int i = numThisTime; --i >= 0;)
  15686. {
  15687. *left++ = ((int) *src++) << 24;
  15688. }
  15689. }
  15690. }
  15691. startOffsetInDestBuffer += numThisTime;
  15692. numSamples -= numThisTime;
  15693. }
  15694. if (numSamples > 0)
  15695. {
  15696. for (int i = numDestChannels; --i >= 0;)
  15697. if (destSamples[i] != 0)
  15698. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15699. sizeof (int) * numSamples);
  15700. }
  15701. return true;
  15702. }
  15703. juce_UseDebuggingNewOperator
  15704. private:
  15705. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15706. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15707. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15708. };
  15709. class AiffAudioFormatWriter : public AudioFormatWriter
  15710. {
  15711. MemoryBlock tempBlock;
  15712. uint32 lengthInSamples, bytesWritten;
  15713. int64 headerPosition;
  15714. bool writeFailed;
  15715. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15716. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15717. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15718. void writeHeader()
  15719. {
  15720. const bool couldSeekOk = output->setPosition (headerPosition);
  15721. (void) couldSeekOk;
  15722. // if this fails, you've given it an output stream that can't seek! It needs
  15723. // to be able to seek back to write the header
  15724. jassert (couldSeekOk);
  15725. const int headerLen = 54;
  15726. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15727. audioBytes += (audioBytes & 1);
  15728. output->writeInt (chunkName ("FORM"));
  15729. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15730. output->writeInt (chunkName ("AIFF"));
  15731. output->writeInt (chunkName ("COMM"));
  15732. output->writeIntBigEndian (18);
  15733. output->writeShortBigEndian ((short) numChannels);
  15734. output->writeIntBigEndian (lengthInSamples);
  15735. output->writeShortBigEndian ((short) bitsPerSample);
  15736. uint8 sampleRateBytes[10];
  15737. zeromem (sampleRateBytes, 10);
  15738. if (sampleRate <= 1)
  15739. {
  15740. sampleRateBytes[0] = 0x3f;
  15741. sampleRateBytes[1] = 0xff;
  15742. sampleRateBytes[2] = 0x80;
  15743. }
  15744. else
  15745. {
  15746. int mask = 0x40000000;
  15747. sampleRateBytes[0] = 0x40;
  15748. if (sampleRate >= mask)
  15749. {
  15750. jassertfalse;
  15751. sampleRateBytes[1] = 0x1d;
  15752. }
  15753. else
  15754. {
  15755. int n = (int) sampleRate;
  15756. int i;
  15757. for (i = 0; i <= 32 ; ++i)
  15758. {
  15759. if ((n & mask) != 0)
  15760. break;
  15761. mask >>= 1;
  15762. }
  15763. n = n << (i + 1);
  15764. sampleRateBytes[1] = (uint8) (29 - i);
  15765. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15766. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15767. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15768. sampleRateBytes[5] = (uint8) (n & 0xff);
  15769. }
  15770. }
  15771. output->write (sampleRateBytes, 10);
  15772. output->writeInt (chunkName ("SSND"));
  15773. output->writeIntBigEndian (audioBytes + 8);
  15774. output->writeInt (0);
  15775. output->writeInt (0);
  15776. jassert (output->getPosition() == headerLen);
  15777. }
  15778. public:
  15779. AiffAudioFormatWriter (OutputStream* out,
  15780. const double sampleRate_,
  15781. const unsigned int chans,
  15782. const int bits)
  15783. : AudioFormatWriter (out,
  15784. TRANS (aiffFormatName),
  15785. sampleRate_,
  15786. chans,
  15787. bits),
  15788. lengthInSamples (0),
  15789. bytesWritten (0),
  15790. writeFailed (false)
  15791. {
  15792. headerPosition = out->getPosition();
  15793. writeHeader();
  15794. }
  15795. ~AiffAudioFormatWriter()
  15796. {
  15797. if ((bytesWritten & 1) != 0)
  15798. output->writeByte (0);
  15799. writeHeader();
  15800. }
  15801. bool write (const int** data, int numSamples)
  15802. {
  15803. if (writeFailed)
  15804. return false;
  15805. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15806. tempBlock.ensureSize (bytes, false);
  15807. char* buffer = static_cast <char*> (tempBlock.getData());
  15808. const int* left = data[0];
  15809. const int* right = data[1];
  15810. if (right == 0)
  15811. right = left;
  15812. if (bitsPerSample == 16)
  15813. {
  15814. short* b = reinterpret_cast <short*> (buffer);
  15815. if (numChannels > 1)
  15816. {
  15817. for (int i = numSamples; --i >= 0;)
  15818. {
  15819. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15820. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15821. }
  15822. }
  15823. else
  15824. {
  15825. for (int i = numSamples; --i >= 0;)
  15826. {
  15827. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15828. }
  15829. }
  15830. }
  15831. else if (bitsPerSample == 24)
  15832. {
  15833. char* b = buffer;
  15834. if (numChannels > 1)
  15835. {
  15836. for (int i = numSamples; --i >= 0;)
  15837. {
  15838. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15839. b += 3;
  15840. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15841. b += 3;
  15842. }
  15843. }
  15844. else
  15845. {
  15846. for (int i = numSamples; --i >= 0;)
  15847. {
  15848. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15849. b += 3;
  15850. }
  15851. }
  15852. }
  15853. else if (bitsPerSample == 32)
  15854. {
  15855. uint32* b = reinterpret_cast <uint32*> (buffer);
  15856. if (numChannels > 1)
  15857. {
  15858. for (int i = numSamples; --i >= 0;)
  15859. {
  15860. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15861. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15862. }
  15863. }
  15864. else
  15865. {
  15866. for (int i = numSamples; --i >= 0;)
  15867. {
  15868. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15869. }
  15870. }
  15871. }
  15872. else if (bitsPerSample == 8)
  15873. {
  15874. char* b = buffer;
  15875. if (numChannels > 1)
  15876. {
  15877. for (int i = numSamples; --i >= 0;)
  15878. {
  15879. *b++ = (char) (*left++ >> 24);
  15880. *b++ = (char) (*right++ >> 24);
  15881. }
  15882. }
  15883. else
  15884. {
  15885. for (int i = numSamples; --i >= 0;)
  15886. {
  15887. *b++ = (char) (*left++ >> 24);
  15888. }
  15889. }
  15890. }
  15891. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15892. || ! output->write (buffer, bytes))
  15893. {
  15894. // failed to write to disk, so let's try writing the header.
  15895. // If it's just run out of disk space, then if it does manage
  15896. // to write the header, we'll still have a useable file..
  15897. writeHeader();
  15898. writeFailed = true;
  15899. return false;
  15900. }
  15901. else
  15902. {
  15903. bytesWritten += bytes;
  15904. lengthInSamples += numSamples;
  15905. return true;
  15906. }
  15907. }
  15908. juce_UseDebuggingNewOperator
  15909. };
  15910. AiffAudioFormat::AiffAudioFormat()
  15911. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15912. {
  15913. }
  15914. AiffAudioFormat::~AiffAudioFormat()
  15915. {
  15916. }
  15917. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15918. {
  15919. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15920. return Array <int> (rates);
  15921. }
  15922. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15923. {
  15924. const int depths[] = { 8, 16, 24, 0 };
  15925. return Array <int> (depths);
  15926. }
  15927. bool AiffAudioFormat::canDoStereo()
  15928. {
  15929. return true;
  15930. }
  15931. bool AiffAudioFormat::canDoMono()
  15932. {
  15933. return true;
  15934. }
  15935. #if JUCE_MAC
  15936. bool AiffAudioFormat::canHandleFile (const File& f)
  15937. {
  15938. if (AudioFormat::canHandleFile (f))
  15939. return true;
  15940. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15941. return type == 'AIFF' || type == 'AIFC'
  15942. || type == 'aiff' || type == 'aifc';
  15943. }
  15944. #endif
  15945. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15946. const bool deleteStreamIfOpeningFails)
  15947. {
  15948. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15949. if (w->sampleRate != 0)
  15950. return w.release();
  15951. if (! deleteStreamIfOpeningFails)
  15952. w->input = 0;
  15953. return 0;
  15954. }
  15955. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15956. double sampleRate,
  15957. unsigned int chans,
  15958. int bitsPerSample,
  15959. const StringPairArray& /*metadataValues*/,
  15960. int /*qualityOptionIndex*/)
  15961. {
  15962. if (getPossibleBitDepths().contains (bitsPerSample))
  15963. {
  15964. return new AiffAudioFormatWriter (out,
  15965. sampleRate,
  15966. chans,
  15967. bitsPerSample);
  15968. }
  15969. return 0;
  15970. }
  15971. END_JUCE_NAMESPACE
  15972. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15973. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15974. BEGIN_JUCE_NAMESPACE
  15975. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15976. const String& formatName_)
  15977. : sampleRate (0),
  15978. bitsPerSample (0),
  15979. lengthInSamples (0),
  15980. numChannels (0),
  15981. usesFloatingPointData (false),
  15982. input (in),
  15983. formatName (formatName_)
  15984. {
  15985. }
  15986. AudioFormatReader::~AudioFormatReader()
  15987. {
  15988. delete input;
  15989. }
  15990. bool AudioFormatReader::read (int** destSamples,
  15991. int numDestChannels,
  15992. int64 startSampleInSource,
  15993. int numSamplesToRead,
  15994. const bool fillLeftoverChannelsWithCopies)
  15995. {
  15996. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15997. int startOffsetInDestBuffer = 0;
  15998. if (startSampleInSource < 0)
  15999. {
  16000. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16001. for (int i = numDestChannels; --i >= 0;)
  16002. if (destSamples[i] != 0)
  16003. zeromem (destSamples[i], sizeof (int) * silence);
  16004. startOffsetInDestBuffer += silence;
  16005. numSamplesToRead -= silence;
  16006. startSampleInSource = 0;
  16007. }
  16008. if (numSamplesToRead <= 0)
  16009. return true;
  16010. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16011. startSampleInSource, numSamplesToRead))
  16012. return false;
  16013. if (numDestChannels > (int) numChannels)
  16014. {
  16015. if (fillLeftoverChannelsWithCopies)
  16016. {
  16017. int* lastFullChannel = destSamples[0];
  16018. for (int i = (int) numChannels; --i > 0;)
  16019. {
  16020. if (destSamples[i] != 0)
  16021. {
  16022. lastFullChannel = destSamples[i];
  16023. break;
  16024. }
  16025. }
  16026. if (lastFullChannel != 0)
  16027. for (int i = numChannels; i < numDestChannels; ++i)
  16028. if (destSamples[i] != 0)
  16029. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16030. }
  16031. else
  16032. {
  16033. for (int i = numChannels; i < numDestChannels; ++i)
  16034. if (destSamples[i] != 0)
  16035. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16036. }
  16037. }
  16038. return true;
  16039. }
  16040. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16041. {
  16042. float mn = buffer[0];
  16043. float mx = mn;
  16044. for (int i = 1; i < num; ++i)
  16045. {
  16046. const float s = buffer[i];
  16047. if (s > mx) mx = s;
  16048. if (s < mn) mn = s;
  16049. }
  16050. maxVal = mx;
  16051. minVal = mn;
  16052. }
  16053. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16054. int64 numSamples,
  16055. float& lowestLeft, float& highestLeft,
  16056. float& lowestRight, float& highestRight)
  16057. {
  16058. if (numSamples <= 0)
  16059. {
  16060. lowestLeft = 0;
  16061. lowestRight = 0;
  16062. highestLeft = 0;
  16063. highestRight = 0;
  16064. return;
  16065. }
  16066. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16067. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16068. int* tempBuffer[3];
  16069. tempBuffer[0] = (int*) tempSpace.getData();
  16070. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16071. tempBuffer[2] = 0;
  16072. if (usesFloatingPointData)
  16073. {
  16074. float lmin = 1.0e6f;
  16075. float lmax = -lmin;
  16076. float rmin = lmin;
  16077. float rmax = lmax;
  16078. while (numSamples > 0)
  16079. {
  16080. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16081. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16082. numSamples -= numToDo;
  16083. startSampleInFile += numToDo;
  16084. float bufmin, bufmax;
  16085. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16086. lmin = jmin (lmin, bufmin);
  16087. lmax = jmax (lmax, bufmax);
  16088. if (numChannels > 1)
  16089. {
  16090. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16091. rmin = jmin (rmin, bufmin);
  16092. rmax = jmax (rmax, bufmax);
  16093. }
  16094. }
  16095. if (numChannels <= 1)
  16096. {
  16097. rmax = lmax;
  16098. rmin = lmin;
  16099. }
  16100. lowestLeft = lmin;
  16101. highestLeft = lmax;
  16102. lowestRight = rmin;
  16103. highestRight = rmax;
  16104. }
  16105. else
  16106. {
  16107. int lmax = std::numeric_limits<int>::min();
  16108. int lmin = std::numeric_limits<int>::max();
  16109. int rmax = std::numeric_limits<int>::min();
  16110. int rmin = std::numeric_limits<int>::max();
  16111. while (numSamples > 0)
  16112. {
  16113. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16114. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16115. numSamples -= numToDo;
  16116. startSampleInFile += numToDo;
  16117. for (int j = numChannels; --j >= 0;)
  16118. {
  16119. int bufMax = std::numeric_limits<int>::min();
  16120. int bufMin = std::numeric_limits<int>::max();
  16121. const int* const b = tempBuffer[j];
  16122. for (int i = 0; i < numToDo; ++i)
  16123. {
  16124. const int samp = b[i];
  16125. if (samp < bufMin)
  16126. bufMin = samp;
  16127. if (samp > bufMax)
  16128. bufMax = samp;
  16129. }
  16130. if (j == 0)
  16131. {
  16132. lmax = jmax (lmax, bufMax);
  16133. lmin = jmin (lmin, bufMin);
  16134. }
  16135. else
  16136. {
  16137. rmax = jmax (rmax, bufMax);
  16138. rmin = jmin (rmin, bufMin);
  16139. }
  16140. }
  16141. }
  16142. if (numChannels <= 1)
  16143. {
  16144. rmax = lmax;
  16145. rmin = lmin;
  16146. }
  16147. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16148. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16149. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16150. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16151. }
  16152. }
  16153. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16154. int64 numSamplesToSearch,
  16155. const double magnitudeRangeMinimum,
  16156. const double magnitudeRangeMaximum,
  16157. const int minimumConsecutiveSamples)
  16158. {
  16159. if (numSamplesToSearch == 0)
  16160. return -1;
  16161. const int bufferSize = 4096;
  16162. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16163. int* tempBuffer[3];
  16164. tempBuffer[0] = (int*) tempSpace.getData();
  16165. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16166. tempBuffer[2] = 0;
  16167. int consecutive = 0;
  16168. int64 firstMatchPos = -1;
  16169. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16170. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16171. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16172. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16173. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16174. while (numSamplesToSearch != 0)
  16175. {
  16176. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16177. int64 bufferStart = startSample;
  16178. if (numSamplesToSearch < 0)
  16179. bufferStart -= numThisTime;
  16180. if (bufferStart >= (int) lengthInSamples)
  16181. break;
  16182. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16183. int num = numThisTime;
  16184. while (--num >= 0)
  16185. {
  16186. if (numSamplesToSearch < 0)
  16187. --startSample;
  16188. bool matches = false;
  16189. const int index = (int) (startSample - bufferStart);
  16190. if (usesFloatingPointData)
  16191. {
  16192. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16193. if (sample1 >= magnitudeRangeMinimum
  16194. && sample1 <= magnitudeRangeMaximum)
  16195. {
  16196. matches = true;
  16197. }
  16198. else if (numChannels > 1)
  16199. {
  16200. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16201. matches = (sample2 >= magnitudeRangeMinimum
  16202. && sample2 <= magnitudeRangeMaximum);
  16203. }
  16204. }
  16205. else
  16206. {
  16207. const int sample1 = abs (tempBuffer[0] [index]);
  16208. if (sample1 >= intMagnitudeRangeMinimum
  16209. && sample1 <= intMagnitudeRangeMaximum)
  16210. {
  16211. matches = true;
  16212. }
  16213. else if (numChannels > 1)
  16214. {
  16215. const int sample2 = abs (tempBuffer[1][index]);
  16216. matches = (sample2 >= intMagnitudeRangeMinimum
  16217. && sample2 <= intMagnitudeRangeMaximum);
  16218. }
  16219. }
  16220. if (matches)
  16221. {
  16222. if (firstMatchPos < 0)
  16223. firstMatchPos = startSample;
  16224. if (++consecutive >= minimumConsecutiveSamples)
  16225. {
  16226. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16227. return -1;
  16228. return firstMatchPos;
  16229. }
  16230. }
  16231. else
  16232. {
  16233. consecutive = 0;
  16234. firstMatchPos = -1;
  16235. }
  16236. if (numSamplesToSearch > 0)
  16237. ++startSample;
  16238. }
  16239. if (numSamplesToSearch > 0)
  16240. numSamplesToSearch -= numThisTime;
  16241. else
  16242. numSamplesToSearch += numThisTime;
  16243. }
  16244. return -1;
  16245. }
  16246. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16247. const String& formatName_,
  16248. const double rate,
  16249. const unsigned int numChannels_,
  16250. const unsigned int bitsPerSample_)
  16251. : sampleRate (rate),
  16252. numChannels (numChannels_),
  16253. bitsPerSample (bitsPerSample_),
  16254. usesFloatingPointData (false),
  16255. output (out),
  16256. formatName (formatName_)
  16257. {
  16258. }
  16259. AudioFormatWriter::~AudioFormatWriter()
  16260. {
  16261. delete output;
  16262. }
  16263. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16264. int64 startSample,
  16265. int64 numSamplesToRead)
  16266. {
  16267. const int bufferSize = 16384;
  16268. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16269. int* buffers [128];
  16270. zerostruct (buffers);
  16271. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16272. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16273. if (numSamplesToRead < 0)
  16274. numSamplesToRead = reader.lengthInSamples;
  16275. while (numSamplesToRead > 0)
  16276. {
  16277. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16278. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16279. return false;
  16280. if (reader.usesFloatingPointData != isFloatingPoint())
  16281. {
  16282. int** bufferChan = buffers;
  16283. while (*bufferChan != 0)
  16284. {
  16285. int* b = *bufferChan++;
  16286. if (isFloatingPoint())
  16287. {
  16288. // int -> float
  16289. const double factor = 1.0 / std::numeric_limits<int>::max();
  16290. for (int i = 0; i < numToDo; ++i)
  16291. ((float*) b)[i] = (float) (factor * b[i]);
  16292. }
  16293. else
  16294. {
  16295. // float -> int
  16296. for (int i = 0; i < numToDo; ++i)
  16297. {
  16298. const double samp = *(const float*) b;
  16299. if (samp <= -1.0)
  16300. *b++ = std::numeric_limits<int>::min();
  16301. else if (samp >= 1.0)
  16302. *b++ = std::numeric_limits<int>::max();
  16303. else
  16304. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16305. }
  16306. }
  16307. }
  16308. }
  16309. if (! write ((const int**) buffers, numToDo))
  16310. return false;
  16311. numSamplesToRead -= numToDo;
  16312. startSample += numToDo;
  16313. }
  16314. return true;
  16315. }
  16316. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16317. int numSamplesToRead,
  16318. const int samplesPerBlock)
  16319. {
  16320. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16321. int* buffers [128];
  16322. zerostruct (buffers);
  16323. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16324. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16325. while (numSamplesToRead > 0)
  16326. {
  16327. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16328. AudioSourceChannelInfo info;
  16329. info.buffer = &tempBuffer;
  16330. info.startSample = 0;
  16331. info.numSamples = numToDo;
  16332. info.clearActiveBufferRegion();
  16333. source.getNextAudioBlock (info);
  16334. if (! isFloatingPoint())
  16335. {
  16336. int** bufferChan = buffers;
  16337. while (*bufferChan != 0)
  16338. {
  16339. int* b = *bufferChan++;
  16340. // float -> int
  16341. for (int j = numToDo; --j >= 0;)
  16342. {
  16343. const double samp = *(const float*) b;
  16344. if (samp <= -1.0)
  16345. *b++ = std::numeric_limits<int>::min();
  16346. else if (samp >= 1.0)
  16347. *b++ = std::numeric_limits<int>::max();
  16348. else
  16349. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16350. }
  16351. }
  16352. }
  16353. if (! write ((const int**) buffers, numToDo))
  16354. return false;
  16355. numSamplesToRead -= numToDo;
  16356. }
  16357. return true;
  16358. }
  16359. AudioFormat::AudioFormat (const String& name,
  16360. const StringArray& extensions)
  16361. : formatName (name),
  16362. fileExtensions (extensions)
  16363. {
  16364. }
  16365. AudioFormat::~AudioFormat()
  16366. {
  16367. }
  16368. const String& AudioFormat::getFormatName() const
  16369. {
  16370. return formatName;
  16371. }
  16372. const StringArray& AudioFormat::getFileExtensions() const
  16373. {
  16374. return fileExtensions;
  16375. }
  16376. bool AudioFormat::canHandleFile (const File& f)
  16377. {
  16378. for (int i = 0; i < fileExtensions.size(); ++i)
  16379. if (f.hasFileExtension (fileExtensions[i]))
  16380. return true;
  16381. return false;
  16382. }
  16383. bool AudioFormat::isCompressed()
  16384. {
  16385. return false;
  16386. }
  16387. const StringArray AudioFormat::getQualityOptions()
  16388. {
  16389. return StringArray();
  16390. }
  16391. END_JUCE_NAMESPACE
  16392. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16393. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16394. BEGIN_JUCE_NAMESPACE
  16395. AudioFormatManager::AudioFormatManager()
  16396. : defaultFormatIndex (0)
  16397. {
  16398. }
  16399. AudioFormatManager::~AudioFormatManager()
  16400. {
  16401. clearFormats();
  16402. clearSingletonInstance();
  16403. }
  16404. juce_ImplementSingleton (AudioFormatManager);
  16405. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16406. const bool makeThisTheDefaultFormat)
  16407. {
  16408. jassert (newFormat != 0);
  16409. if (newFormat != 0)
  16410. {
  16411. #if JUCE_DEBUG
  16412. for (int i = getNumKnownFormats(); --i >= 0;)
  16413. {
  16414. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16415. {
  16416. jassertfalse; // trying to add the same format twice!
  16417. }
  16418. }
  16419. #endif
  16420. if (makeThisTheDefaultFormat)
  16421. defaultFormatIndex = getNumKnownFormats();
  16422. knownFormats.add (newFormat);
  16423. }
  16424. }
  16425. void AudioFormatManager::registerBasicFormats()
  16426. {
  16427. #if JUCE_MAC
  16428. registerFormat (new AiffAudioFormat(), true);
  16429. registerFormat (new WavAudioFormat(), false);
  16430. #else
  16431. registerFormat (new WavAudioFormat(), true);
  16432. registerFormat (new AiffAudioFormat(), false);
  16433. #endif
  16434. #if JUCE_USE_FLAC
  16435. registerFormat (new FlacAudioFormat(), false);
  16436. #endif
  16437. #if JUCE_USE_OGGVORBIS
  16438. registerFormat (new OggVorbisAudioFormat(), false);
  16439. #endif
  16440. }
  16441. void AudioFormatManager::clearFormats()
  16442. {
  16443. knownFormats.clear();
  16444. defaultFormatIndex = 0;
  16445. }
  16446. int AudioFormatManager::getNumKnownFormats() const
  16447. {
  16448. return knownFormats.size();
  16449. }
  16450. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16451. {
  16452. return knownFormats [index];
  16453. }
  16454. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16455. {
  16456. return getKnownFormat (defaultFormatIndex);
  16457. }
  16458. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16459. {
  16460. String e (fileExtension);
  16461. if (! e.startsWithChar ('.'))
  16462. e = "." + e;
  16463. for (int i = 0; i < getNumKnownFormats(); ++i)
  16464. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16465. return getKnownFormat(i);
  16466. return 0;
  16467. }
  16468. const String AudioFormatManager::getWildcardForAllFormats() const
  16469. {
  16470. StringArray allExtensions;
  16471. int i;
  16472. for (i = 0; i < getNumKnownFormats(); ++i)
  16473. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16474. allExtensions.trim();
  16475. allExtensions.removeEmptyStrings();
  16476. String s;
  16477. for (i = 0; i < allExtensions.size(); ++i)
  16478. {
  16479. s << '*';
  16480. if (! allExtensions[i].startsWithChar ('.'))
  16481. s << '.';
  16482. s << allExtensions[i];
  16483. if (i < allExtensions.size() - 1)
  16484. s << ';';
  16485. }
  16486. return s;
  16487. }
  16488. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16489. {
  16490. // you need to actually register some formats before the manager can
  16491. // use them to open a file!
  16492. jassert (getNumKnownFormats() > 0);
  16493. for (int i = 0; i < getNumKnownFormats(); ++i)
  16494. {
  16495. AudioFormat* const af = getKnownFormat(i);
  16496. if (af->canHandleFile (file))
  16497. {
  16498. InputStream* const in = file.createInputStream();
  16499. if (in != 0)
  16500. {
  16501. AudioFormatReader* const r = af->createReaderFor (in, true);
  16502. if (r != 0)
  16503. return r;
  16504. }
  16505. }
  16506. }
  16507. return 0;
  16508. }
  16509. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16510. {
  16511. // you need to actually register some formats before the manager can
  16512. // use them to open a file!
  16513. jassert (getNumKnownFormats() > 0);
  16514. ScopedPointer <InputStream> in (audioFileStream);
  16515. if (in != 0)
  16516. {
  16517. const int64 originalStreamPos = in->getPosition();
  16518. for (int i = 0; i < getNumKnownFormats(); ++i)
  16519. {
  16520. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16521. if (r != 0)
  16522. {
  16523. in.release();
  16524. return r;
  16525. }
  16526. in->setPosition (originalStreamPos);
  16527. // the stream that is passed-in must be capable of being repositioned so
  16528. // that all the formats can have a go at opening it.
  16529. jassert (in->getPosition() == originalStreamPos);
  16530. }
  16531. }
  16532. return 0;
  16533. }
  16534. END_JUCE_NAMESPACE
  16535. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16536. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16537. BEGIN_JUCE_NAMESPACE
  16538. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16539. const int64 startSample_,
  16540. const int64 length_,
  16541. const bool deleteSourceWhenDeleted_)
  16542. : AudioFormatReader (0, source_->getFormatName()),
  16543. source (source_),
  16544. startSample (startSample_),
  16545. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16546. {
  16547. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16548. sampleRate = source->sampleRate;
  16549. bitsPerSample = source->bitsPerSample;
  16550. lengthInSamples = length;
  16551. numChannels = source->numChannels;
  16552. usesFloatingPointData = source->usesFloatingPointData;
  16553. }
  16554. AudioSubsectionReader::~AudioSubsectionReader()
  16555. {
  16556. if (deleteSourceWhenDeleted)
  16557. delete source;
  16558. }
  16559. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16560. int64 startSampleInFile, int numSamples)
  16561. {
  16562. if (startSampleInFile + numSamples > length)
  16563. {
  16564. for (int i = numDestChannels; --i >= 0;)
  16565. if (destSamples[i] != 0)
  16566. zeromem (destSamples[i], sizeof (int) * numSamples);
  16567. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16568. if (numSamples <= 0)
  16569. return true;
  16570. }
  16571. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16572. startSampleInFile + startSample, numSamples);
  16573. }
  16574. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16575. int64 numSamples,
  16576. float& lowestLeft,
  16577. float& highestLeft,
  16578. float& lowestRight,
  16579. float& highestRight)
  16580. {
  16581. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16582. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16583. source->readMaxLevels (startSampleInFile + startSample,
  16584. numSamples,
  16585. lowestLeft,
  16586. highestLeft,
  16587. lowestRight,
  16588. highestRight);
  16589. }
  16590. END_JUCE_NAMESPACE
  16591. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16592. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16593. BEGIN_JUCE_NAMESPACE
  16594. const int timeBeforeDeletingReader = 2000;
  16595. struct AudioThumbnailDataFormat
  16596. {
  16597. char thumbnailMagic[4];
  16598. int samplesPerThumbSample;
  16599. int64 totalSamples; // source samples
  16600. int64 numFinishedSamples; // source samples
  16601. int numThumbnailSamples;
  16602. int numChannels;
  16603. int sampleRate;
  16604. char future[16];
  16605. char data[1];
  16606. void swapEndiannessIfNeeded() throw()
  16607. {
  16608. #if JUCE_BIG_ENDIAN
  16609. flip (samplesPerThumbSample);
  16610. flip (totalSamples);
  16611. flip (numFinishedSamples);
  16612. flip (numThumbnailSamples);
  16613. flip (numChannels);
  16614. flip (sampleRate);
  16615. #endif
  16616. }
  16617. private:
  16618. #if JUCE_BIG_ENDIAN
  16619. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16620. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16621. #endif
  16622. };
  16623. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16624. AudioFormatManager& formatManagerToUse_,
  16625. AudioThumbnailCache& cacheToUse)
  16626. : formatManagerToUse (formatManagerToUse_),
  16627. cache (cacheToUse),
  16628. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16629. {
  16630. clear();
  16631. }
  16632. AudioThumbnail::~AudioThumbnail()
  16633. {
  16634. cache.removeThumbnail (this);
  16635. const ScopedLock sl (readerLock);
  16636. reader = 0;
  16637. }
  16638. void AudioThumbnail::setSource (InputSource* const newSource)
  16639. {
  16640. cache.removeThumbnail (this);
  16641. timerCallback(); // stops the timer and deletes the reader
  16642. source = newSource;
  16643. clear();
  16644. if (newSource != 0
  16645. && ! (cache.loadThumb (*this, newSource->hashCode())
  16646. && isFullyLoaded()))
  16647. {
  16648. {
  16649. const ScopedLock sl (readerLock);
  16650. reader = createReader();
  16651. }
  16652. if (reader != 0)
  16653. {
  16654. initialiseFromAudioFile (*reader);
  16655. cache.addThumbnail (this);
  16656. }
  16657. }
  16658. sendChangeMessage (this);
  16659. }
  16660. bool AudioThumbnail::useTimeSlice()
  16661. {
  16662. const ScopedLock sl (readerLock);
  16663. if (isFullyLoaded())
  16664. {
  16665. if (reader != 0)
  16666. startTimer (timeBeforeDeletingReader);
  16667. cache.removeThumbnail (this);
  16668. return false;
  16669. }
  16670. if (reader == 0)
  16671. reader = createReader();
  16672. if (reader != 0)
  16673. {
  16674. readNextBlockFromAudioFile (*reader);
  16675. stopTimer();
  16676. sendChangeMessage (this);
  16677. const bool justFinished = isFullyLoaded();
  16678. if (justFinished)
  16679. cache.storeThumb (*this, source->hashCode());
  16680. return ! justFinished;
  16681. }
  16682. return false;
  16683. }
  16684. AudioFormatReader* AudioThumbnail::createReader() const
  16685. {
  16686. if (source != 0)
  16687. {
  16688. InputStream* const audioFileStream = source->createInputStream();
  16689. if (audioFileStream != 0)
  16690. return formatManagerToUse.createReaderFor (audioFileStream);
  16691. }
  16692. return 0;
  16693. }
  16694. void AudioThumbnail::timerCallback()
  16695. {
  16696. stopTimer();
  16697. const ScopedLock sl (readerLock);
  16698. reader = 0;
  16699. }
  16700. void AudioThumbnail::clear()
  16701. {
  16702. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16703. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16704. d->thumbnailMagic[0] = 'j';
  16705. d->thumbnailMagic[1] = 'a';
  16706. d->thumbnailMagic[2] = 't';
  16707. d->thumbnailMagic[3] = 'm';
  16708. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16709. d->totalSamples = 0;
  16710. d->numFinishedSamples = 0;
  16711. d->numThumbnailSamples = 0;
  16712. d->numChannels = 0;
  16713. d->sampleRate = 0;
  16714. numSamplesCached = 0;
  16715. cacheNeedsRefilling = true;
  16716. }
  16717. void AudioThumbnail::loadFrom (InputStream& input)
  16718. {
  16719. const ScopedLock sl (readerLock);
  16720. data.setSize (0);
  16721. input.readIntoMemoryBlock (data);
  16722. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16723. d->swapEndiannessIfNeeded();
  16724. if (! (d->thumbnailMagic[0] == 'j'
  16725. && d->thumbnailMagic[1] == 'a'
  16726. && d->thumbnailMagic[2] == 't'
  16727. && d->thumbnailMagic[3] == 'm'))
  16728. {
  16729. clear();
  16730. }
  16731. numSamplesCached = 0;
  16732. cacheNeedsRefilling = true;
  16733. }
  16734. void AudioThumbnail::saveTo (OutputStream& output) const
  16735. {
  16736. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16737. d->swapEndiannessIfNeeded();
  16738. output.write (data.getData(), (int) data.getSize());
  16739. d->swapEndiannessIfNeeded();
  16740. }
  16741. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16742. {
  16743. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16744. d->totalSamples = fileReader.lengthInSamples;
  16745. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16746. d->numFinishedSamples = 0;
  16747. d->sampleRate = roundToInt (fileReader.sampleRate);
  16748. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16749. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16750. d = (AudioThumbnailDataFormat*) data.getData();
  16751. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16752. return d->totalSamples > 0;
  16753. }
  16754. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16755. {
  16756. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16757. if (d->numFinishedSamples < d->totalSamples)
  16758. {
  16759. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16760. generateSection (fileReader,
  16761. d->numFinishedSamples,
  16762. numToDo);
  16763. d->numFinishedSamples += numToDo;
  16764. }
  16765. cacheNeedsRefilling = true;
  16766. return (d->numFinishedSamples < d->totalSamples);
  16767. }
  16768. int AudioThumbnail::getNumChannels() const throw()
  16769. {
  16770. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16771. jassert (d != 0);
  16772. return d->numChannels;
  16773. }
  16774. double AudioThumbnail::getTotalLength() const throw()
  16775. {
  16776. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16777. jassert (d != 0);
  16778. if (d->sampleRate > 0)
  16779. return d->totalSamples / (double)d->sampleRate;
  16780. else
  16781. return 0.0;
  16782. }
  16783. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16784. int64 startSample,
  16785. int numSamples)
  16786. {
  16787. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16788. jassert (d != 0);
  16789. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16790. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16791. char* l = getChannelData (0);
  16792. char* r = getChannelData (1);
  16793. for (int i = firstDataPos; i < lastDataPos; ++i)
  16794. {
  16795. const int sourceStart = i * d->samplesPerThumbSample;
  16796. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16797. float lowestLeft, highestLeft, lowestRight, highestRight;
  16798. fileReader.readMaxLevels (sourceStart,
  16799. sourceEnd - sourceStart,
  16800. lowestLeft,
  16801. highestLeft,
  16802. lowestRight,
  16803. highestRight);
  16804. int n = i * 2;
  16805. if (r != 0)
  16806. {
  16807. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16808. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16809. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16810. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16811. }
  16812. else
  16813. {
  16814. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16815. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16816. }
  16817. }
  16818. }
  16819. char* AudioThumbnail::getChannelData (int channel) const
  16820. {
  16821. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16822. jassert (d != 0);
  16823. if (channel >= 0 && channel < d->numChannels)
  16824. return d->data + (channel * 2 * d->numThumbnailSamples);
  16825. return 0;
  16826. }
  16827. bool AudioThumbnail::isFullyLoaded() const throw()
  16828. {
  16829. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16830. jassert (d != 0);
  16831. return d->numFinishedSamples >= d->totalSamples;
  16832. }
  16833. void AudioThumbnail::refillCache (const int numSamples,
  16834. double startTime,
  16835. const double timePerPixel)
  16836. {
  16837. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16838. jassert (d != 0);
  16839. if (numSamples <= 0
  16840. || timePerPixel <= 0.0
  16841. || d->sampleRate <= 0)
  16842. {
  16843. numSamplesCached = 0;
  16844. cacheNeedsRefilling = true;
  16845. return;
  16846. }
  16847. if (numSamples == numSamplesCached
  16848. && numChannelsCached == d->numChannels
  16849. && startTime == cachedStart
  16850. && timePerPixel == cachedTimePerPixel
  16851. && ! cacheNeedsRefilling)
  16852. {
  16853. return;
  16854. }
  16855. numSamplesCached = numSamples;
  16856. numChannelsCached = d->numChannels;
  16857. cachedStart = startTime;
  16858. cachedTimePerPixel = timePerPixel;
  16859. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16860. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16861. const ScopedLock sl (readerLock);
  16862. cacheNeedsRefilling = false;
  16863. if (needExtraDetail && reader == 0)
  16864. reader = createReader();
  16865. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16866. {
  16867. startTimer (timeBeforeDeletingReader);
  16868. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16869. int sample = roundToInt (startTime * d->sampleRate);
  16870. for (int i = numSamples; --i >= 0;)
  16871. {
  16872. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16873. if (sample >= 0)
  16874. {
  16875. if (sample >= reader->lengthInSamples)
  16876. break;
  16877. float lmin, lmax, rmin, rmax;
  16878. reader->readMaxLevels (sample,
  16879. jmax (1, nextSample - sample),
  16880. lmin, lmax, rmin, rmax);
  16881. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16882. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16883. if (numChannelsCached > 1)
  16884. {
  16885. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16886. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16887. }
  16888. cacheData += 2 * numChannelsCached;
  16889. }
  16890. startTime += timePerPixel;
  16891. sample = nextSample;
  16892. }
  16893. }
  16894. else
  16895. {
  16896. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16897. {
  16898. char* const channelData = getChannelData (channelNum);
  16899. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16900. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16901. startTime = cachedStart;
  16902. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16903. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16904. for (int i = numSamples; --i >= 0;)
  16905. {
  16906. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16907. if (sample >= 0 && channelData != 0)
  16908. {
  16909. char mx = -128;
  16910. char mn = 127;
  16911. while (sample <= nextSample)
  16912. {
  16913. if (sample >= numFinished)
  16914. break;
  16915. const int n = sample << 1;
  16916. const char sampMin = channelData [n];
  16917. const char sampMax = channelData [n + 1];
  16918. if (sampMin < mn)
  16919. mn = sampMin;
  16920. if (sampMax > mx)
  16921. mx = sampMax;
  16922. ++sample;
  16923. }
  16924. if (mn <= mx)
  16925. {
  16926. cacheData[0] = mn;
  16927. cacheData[1] = mx;
  16928. }
  16929. else
  16930. {
  16931. cacheData[0] = 1;
  16932. cacheData[1] = 0;
  16933. }
  16934. }
  16935. else
  16936. {
  16937. cacheData[0] = 1;
  16938. cacheData[1] = 0;
  16939. }
  16940. cacheData += numChannelsCached * 2;
  16941. startTime += timePerPixel;
  16942. sample = nextSample;
  16943. }
  16944. }
  16945. }
  16946. }
  16947. void AudioThumbnail::drawChannel (Graphics& g,
  16948. int x, int y, int w, int h,
  16949. double startTime,
  16950. double endTime,
  16951. int channelNum,
  16952. const float verticalZoomFactor)
  16953. {
  16954. refillCache (w, startTime, (endTime - startTime) / w);
  16955. if (numSamplesCached >= w
  16956. && channelNum >= 0
  16957. && channelNum < numChannelsCached)
  16958. {
  16959. const float topY = (float) y;
  16960. const float bottomY = topY + h;
  16961. const float midY = topY + h * 0.5f;
  16962. const float vscale = verticalZoomFactor * h / 256.0f;
  16963. const Rectangle<int> clip (g.getClipBounds());
  16964. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16965. w -= skipLeft;
  16966. x += skipLeft;
  16967. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16968. + (channelNum << 1)
  16969. + skipLeft * (numChannelsCached << 1);
  16970. while (--w >= 0)
  16971. {
  16972. const char mn = cacheData[0];
  16973. const char mx = cacheData[1];
  16974. cacheData += numChannelsCached << 1;
  16975. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16976. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16977. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16978. ++x;
  16979. if (x >= clip.getRight())
  16980. break;
  16981. }
  16982. }
  16983. }
  16984. END_JUCE_NAMESPACE
  16985. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16986. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16987. BEGIN_JUCE_NAMESPACE
  16988. struct ThumbnailCacheEntry
  16989. {
  16990. int64 hash;
  16991. uint32 lastUsed;
  16992. MemoryBlock data;
  16993. juce_UseDebuggingNewOperator
  16994. };
  16995. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16996. : TimeSliceThread ("thumb cache"),
  16997. maxNumThumbsToStore (maxNumThumbsToStore_)
  16998. {
  16999. startThread (2);
  17000. }
  17001. AudioThumbnailCache::~AudioThumbnailCache()
  17002. {
  17003. }
  17004. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17005. {
  17006. for (int i = thumbs.size(); --i >= 0;)
  17007. {
  17008. if (thumbs[i]->hash == hashCode)
  17009. {
  17010. MemoryInputStream in (thumbs[i]->data, false);
  17011. thumb.loadFrom (in);
  17012. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17013. return true;
  17014. }
  17015. }
  17016. return false;
  17017. }
  17018. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17019. const int64 hashCode)
  17020. {
  17021. MemoryOutputStream out;
  17022. thumb.saveTo (out);
  17023. ThumbnailCacheEntry* te = 0;
  17024. for (int i = thumbs.size(); --i >= 0;)
  17025. {
  17026. if (thumbs[i]->hash == hashCode)
  17027. {
  17028. te = thumbs[i];
  17029. break;
  17030. }
  17031. }
  17032. if (te == 0)
  17033. {
  17034. te = new ThumbnailCacheEntry();
  17035. te->hash = hashCode;
  17036. if (thumbs.size() < maxNumThumbsToStore)
  17037. {
  17038. thumbs.add (te);
  17039. }
  17040. else
  17041. {
  17042. int oldest = 0;
  17043. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17044. int i;
  17045. for (i = thumbs.size(); --i >= 0;)
  17046. if (thumbs[i]->lastUsed < oldestTime)
  17047. oldest = i;
  17048. thumbs.set (i, te);
  17049. }
  17050. }
  17051. te->lastUsed = Time::getMillisecondCounter();
  17052. te->data.setSize (0);
  17053. te->data.append (out.getData(), out.getDataSize());
  17054. }
  17055. void AudioThumbnailCache::clear()
  17056. {
  17057. thumbs.clear();
  17058. }
  17059. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17060. {
  17061. addTimeSliceClient (thumb);
  17062. }
  17063. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17064. {
  17065. removeTimeSliceClient (thumb);
  17066. }
  17067. END_JUCE_NAMESPACE
  17068. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17069. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17070. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17071. #if ! JUCE_WINDOWS
  17072. #include <QuickTime/Movies.h>
  17073. #include <QuickTime/QTML.h>
  17074. #include <QuickTime/QuickTimeComponents.h>
  17075. #include <QuickTime/MediaHandlers.h>
  17076. #include <QuickTime/ImageCodec.h>
  17077. #else
  17078. #if JUCE_MSVC
  17079. #pragma warning (push)
  17080. #pragma warning (disable : 4100)
  17081. #endif
  17082. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17083. add its header directory to your include path.
  17084. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17085. flag in juce_Config.h
  17086. */
  17087. #include <Movies.h>
  17088. #include <QTML.h>
  17089. #include <QuickTimeComponents.h>
  17090. #include <MediaHandlers.h>
  17091. #include <ImageCodec.h>
  17092. #if JUCE_MSVC
  17093. #pragma warning (pop)
  17094. #endif
  17095. #endif
  17096. BEGIN_JUCE_NAMESPACE
  17097. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17098. static const char* const quickTimeFormatName = "QuickTime file";
  17099. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17100. class QTAudioReader : public AudioFormatReader
  17101. {
  17102. public:
  17103. QTAudioReader (InputStream* const input_, const int trackNum_)
  17104. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17105. ok (false),
  17106. movie (0),
  17107. trackNum (trackNum_),
  17108. lastSampleRead (0),
  17109. lastThreadId (0),
  17110. extractor (0),
  17111. dataHandle (0)
  17112. {
  17113. bufferList.calloc (256, 1);
  17114. #if JUCE_WINDOWS
  17115. if (InitializeQTML (0) != noErr)
  17116. return;
  17117. #endif
  17118. if (EnterMovies() != noErr)
  17119. return;
  17120. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17121. if (! opened)
  17122. return;
  17123. {
  17124. const int numTracks = GetMovieTrackCount (movie);
  17125. int trackCount = 0;
  17126. for (int i = 1; i <= numTracks; ++i)
  17127. {
  17128. track = GetMovieIndTrack (movie, i);
  17129. media = GetTrackMedia (track);
  17130. OSType mediaType;
  17131. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17132. if (mediaType == SoundMediaType
  17133. && trackCount++ == trackNum_)
  17134. {
  17135. ok = true;
  17136. break;
  17137. }
  17138. }
  17139. }
  17140. if (! ok)
  17141. return;
  17142. ok = false;
  17143. lengthInSamples = GetMediaDecodeDuration (media);
  17144. usesFloatingPointData = false;
  17145. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17146. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17147. / GetMediaTimeScale (media);
  17148. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17149. unsigned long output_layout_size;
  17150. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17151. kQTPropertyClass_MovieAudioExtraction_Audio,
  17152. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17153. 0, &output_layout_size, 0);
  17154. if (err != noErr)
  17155. return;
  17156. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17157. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17158. err = MovieAudioExtractionGetProperty (extractor,
  17159. kQTPropertyClass_MovieAudioExtraction_Audio,
  17160. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17161. output_layout_size, qt_audio_channel_layout, 0);
  17162. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17163. err = MovieAudioExtractionSetProperty (extractor,
  17164. kQTPropertyClass_MovieAudioExtraction_Audio,
  17165. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17166. output_layout_size,
  17167. qt_audio_channel_layout);
  17168. err = MovieAudioExtractionGetProperty (extractor,
  17169. kQTPropertyClass_MovieAudioExtraction_Audio,
  17170. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17171. sizeof (inputStreamDesc),
  17172. &inputStreamDesc, 0);
  17173. if (err != noErr)
  17174. return;
  17175. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17176. | kAudioFormatFlagIsPacked
  17177. | kAudioFormatFlagsNativeEndian;
  17178. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17179. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17180. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17181. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17182. err = MovieAudioExtractionSetProperty (extractor,
  17183. kQTPropertyClass_MovieAudioExtraction_Audio,
  17184. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17185. sizeof (inputStreamDesc),
  17186. &inputStreamDesc);
  17187. if (err != noErr)
  17188. return;
  17189. Boolean allChannelsDiscrete = false;
  17190. err = MovieAudioExtractionSetProperty (extractor,
  17191. kQTPropertyClass_MovieAudioExtraction_Movie,
  17192. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17193. sizeof (allChannelsDiscrete),
  17194. &allChannelsDiscrete);
  17195. if (err != noErr)
  17196. return;
  17197. bufferList->mNumberBuffers = 1;
  17198. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17199. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17200. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17201. bufferList->mBuffers[0].mData = dataBuffer;
  17202. sampleRate = inputStreamDesc.mSampleRate;
  17203. bitsPerSample = 16;
  17204. numChannels = inputStreamDesc.mChannelsPerFrame;
  17205. detachThread();
  17206. ok = true;
  17207. }
  17208. ~QTAudioReader()
  17209. {
  17210. if (dataHandle != 0)
  17211. DisposeHandle (dataHandle);
  17212. if (extractor != 0)
  17213. {
  17214. MovieAudioExtractionEnd (extractor);
  17215. extractor = 0;
  17216. }
  17217. checkThreadIsAttached();
  17218. DisposeMovie (movie);
  17219. #if JUCE_MAC
  17220. ExitMoviesOnThread ();
  17221. #endif
  17222. }
  17223. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17224. int64 startSampleInFile, int numSamples)
  17225. {
  17226. checkThreadIsAttached();
  17227. while (numSamples > 0)
  17228. {
  17229. if (! loadFrame ((int) startSampleInFile))
  17230. return false;
  17231. const int numToDo = jmin (numSamples, samplesPerFrame);
  17232. for (int j = numDestChannels; --j >= 0;)
  17233. {
  17234. if (destSamples[j] != 0)
  17235. {
  17236. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17237. for (int i = 0; i < numToDo; ++i)
  17238. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17239. }
  17240. }
  17241. startOffsetInDestBuffer += numToDo;
  17242. startSampleInFile += numToDo;
  17243. numSamples -= numToDo;
  17244. }
  17245. detachThread();
  17246. return true;
  17247. }
  17248. bool loadFrame (const int sampleNum)
  17249. {
  17250. if (lastSampleRead != sampleNum)
  17251. {
  17252. TimeRecord time;
  17253. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17254. time.base = 0;
  17255. time.value.hi = 0;
  17256. time.value.lo = (UInt32) sampleNum;
  17257. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17258. kQTPropertyClass_MovieAudioExtraction_Movie,
  17259. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17260. sizeof (time), &time);
  17261. if (err != noErr)
  17262. return false;
  17263. }
  17264. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17265. UInt32 outFlags = 0;
  17266. UInt32 actualNumSamples = samplesPerFrame;
  17267. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17268. bufferList, &outFlags);
  17269. lastSampleRead = sampleNum + samplesPerFrame;
  17270. return err == noErr;
  17271. }
  17272. juce_UseDebuggingNewOperator
  17273. bool ok;
  17274. private:
  17275. Movie movie;
  17276. Media media;
  17277. Track track;
  17278. const int trackNum;
  17279. double trackUnitsPerFrame;
  17280. int samplesPerFrame;
  17281. int lastSampleRead;
  17282. Thread::ThreadID lastThreadId;
  17283. MovieAudioExtractionRef extractor;
  17284. AudioStreamBasicDescription inputStreamDesc;
  17285. HeapBlock <AudioBufferList> bufferList;
  17286. HeapBlock <char> dataBuffer;
  17287. Handle dataHandle;
  17288. void checkThreadIsAttached()
  17289. {
  17290. #if JUCE_MAC
  17291. if (Thread::getCurrentThreadId() != lastThreadId)
  17292. EnterMoviesOnThread (0);
  17293. AttachMovieToCurrentThread (movie);
  17294. #endif
  17295. }
  17296. void detachThread()
  17297. {
  17298. #if JUCE_MAC
  17299. DetachMovieFromCurrentThread (movie);
  17300. #endif
  17301. }
  17302. QTAudioReader (const QTAudioReader&);
  17303. QTAudioReader& operator= (const QTAudioReader&);
  17304. };
  17305. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17306. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17307. {
  17308. }
  17309. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17310. {
  17311. }
  17312. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17313. {
  17314. return Array<int>();
  17315. }
  17316. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17317. {
  17318. return Array<int>();
  17319. }
  17320. bool QuickTimeAudioFormat::canDoStereo()
  17321. {
  17322. return true;
  17323. }
  17324. bool QuickTimeAudioFormat::canDoMono()
  17325. {
  17326. return true;
  17327. }
  17328. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17329. const bool deleteStreamIfOpeningFails)
  17330. {
  17331. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17332. if (r->ok)
  17333. return r.release();
  17334. if (! deleteStreamIfOpeningFails)
  17335. r->input = 0;
  17336. return 0;
  17337. }
  17338. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17339. double /*sampleRateToUse*/,
  17340. unsigned int /*numberOfChannels*/,
  17341. int /*bitsPerSample*/,
  17342. const StringPairArray& /*metadataValues*/,
  17343. int /*qualityOptionIndex*/)
  17344. {
  17345. jassertfalse; // not yet implemented!
  17346. return 0;
  17347. }
  17348. END_JUCE_NAMESPACE
  17349. #endif
  17350. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17351. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17352. BEGIN_JUCE_NAMESPACE
  17353. static const char* const wavFormatName = "WAV file";
  17354. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17355. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17356. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17357. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17358. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17359. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17360. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17361. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17362. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17363. const String& originator,
  17364. const String& originatorRef,
  17365. const Time& date,
  17366. const int64 timeReferenceSamples,
  17367. const String& codingHistory)
  17368. {
  17369. StringPairArray m;
  17370. m.set (bwavDescription, description);
  17371. m.set (bwavOriginator, originator);
  17372. m.set (bwavOriginatorRef, originatorRef);
  17373. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17374. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17375. m.set (bwavTimeReference, String (timeReferenceSamples));
  17376. m.set (bwavCodingHistory, codingHistory);
  17377. return m;
  17378. }
  17379. #if JUCE_MSVC
  17380. #pragma pack (push, 1)
  17381. #define PACKED
  17382. #elif JUCE_GCC
  17383. #define PACKED __attribute__((packed))
  17384. #else
  17385. #define PACKED
  17386. #endif
  17387. struct BWAVChunk
  17388. {
  17389. char description [256];
  17390. char originator [32];
  17391. char originatorRef [32];
  17392. char originationDate [10];
  17393. char originationTime [8];
  17394. uint32 timeRefLow;
  17395. uint32 timeRefHigh;
  17396. uint16 version;
  17397. uint8 umid[64];
  17398. uint8 reserved[190];
  17399. char codingHistory[1];
  17400. void copyTo (StringPairArray& values) const
  17401. {
  17402. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17403. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17404. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17405. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17406. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17407. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17408. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17409. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17410. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17411. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17412. }
  17413. static MemoryBlock createFrom (const StringPairArray& values)
  17414. {
  17415. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17416. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17417. data.fillWith (0);
  17418. BWAVChunk* b = (BWAVChunk*) data.getData();
  17419. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17420. // as they get called in the right order..
  17421. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17422. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17423. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17424. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17425. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17426. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17427. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17428. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17429. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17430. if (b->description[0] != 0
  17431. || b->originator[0] != 0
  17432. || b->originationDate[0] != 0
  17433. || b->originationTime[0] != 0
  17434. || b->codingHistory[0] != 0
  17435. || time != 0)
  17436. {
  17437. return data;
  17438. }
  17439. return MemoryBlock();
  17440. }
  17441. } PACKED;
  17442. struct SMPLChunk
  17443. {
  17444. struct SampleLoop
  17445. {
  17446. uint32 identifier;
  17447. uint32 type;
  17448. uint32 start;
  17449. uint32 end;
  17450. uint32 fraction;
  17451. uint32 playCount;
  17452. } PACKED;
  17453. uint32 manufacturer;
  17454. uint32 product;
  17455. uint32 samplePeriod;
  17456. uint32 midiUnityNote;
  17457. uint32 midiPitchFraction;
  17458. uint32 smpteFormat;
  17459. uint32 smpteOffset;
  17460. uint32 numSampleLoops;
  17461. uint32 samplerData;
  17462. SampleLoop loops[1];
  17463. void copyTo (StringPairArray& values, const int totalSize) const
  17464. {
  17465. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17466. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17467. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17468. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17469. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17470. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17471. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17472. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17473. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17474. for (uint32 i = 0; i < numSampleLoops; ++i)
  17475. {
  17476. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17477. break;
  17478. const String prefix ("Loop" + String(i));
  17479. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17480. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17481. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17482. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17483. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17484. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17485. }
  17486. }
  17487. static MemoryBlock createFrom (const StringPairArray& values)
  17488. {
  17489. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17490. if (numLoops <= 0)
  17491. return MemoryBlock();
  17492. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17493. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17494. data.fillWith (0);
  17495. SMPLChunk* s = (SMPLChunk*) data.getData();
  17496. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17497. // as they get called in the right order..
  17498. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17499. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17500. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17501. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17502. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17503. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17504. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17505. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17506. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17507. for (int i = 0; i < numLoops; ++i)
  17508. {
  17509. const String prefix ("Loop" + String(i));
  17510. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17511. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17512. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17513. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17514. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17515. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17516. }
  17517. return data;
  17518. }
  17519. } PACKED;
  17520. struct ExtensibleWavSubFormat
  17521. {
  17522. uint32 data1;
  17523. uint16 data2;
  17524. uint16 data3;
  17525. uint8 data4[8];
  17526. } PACKED;
  17527. #if JUCE_MSVC
  17528. #pragma pack (pop)
  17529. #endif
  17530. #undef PACKED
  17531. class WavAudioFormatReader : public AudioFormatReader
  17532. {
  17533. int bytesPerFrame;
  17534. int64 dataChunkStart, dataLength;
  17535. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17536. WavAudioFormatReader (const WavAudioFormatReader&);
  17537. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17538. public:
  17539. int64 bwavChunkStart, bwavSize;
  17540. WavAudioFormatReader (InputStream* const in)
  17541. : AudioFormatReader (in, TRANS (wavFormatName)),
  17542. dataLength (0),
  17543. bwavChunkStart (0),
  17544. bwavSize (0)
  17545. {
  17546. if (input->readInt() == chunkName ("RIFF"))
  17547. {
  17548. const uint32 len = (uint32) input->readInt();
  17549. const int64 end = input->getPosition() + len;
  17550. bool hasGotType = false;
  17551. bool hasGotData = false;
  17552. if (input->readInt() == chunkName ("WAVE"))
  17553. {
  17554. while (input->getPosition() < end
  17555. && ! input->isExhausted())
  17556. {
  17557. const int chunkType = input->readInt();
  17558. uint32 length = (uint32) input->readInt();
  17559. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17560. if (chunkType == chunkName ("fmt "))
  17561. {
  17562. // read the format chunk
  17563. const unsigned short format = input->readShort();
  17564. const short numChans = input->readShort();
  17565. sampleRate = input->readInt();
  17566. const int bytesPerSec = input->readInt();
  17567. numChannels = numChans;
  17568. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17569. bitsPerSample = 8 * bytesPerFrame / numChans;
  17570. if (format == 3)
  17571. {
  17572. usesFloatingPointData = true;
  17573. }
  17574. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17575. {
  17576. if (length < 40) // too short
  17577. {
  17578. bytesPerFrame = 0;
  17579. }
  17580. else
  17581. {
  17582. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17583. ExtensibleWavSubFormat subFormat;
  17584. subFormat.data1 = input->readInt();
  17585. subFormat.data2 = input->readShort();
  17586. subFormat.data3 = input->readShort();
  17587. input->read (subFormat.data4, sizeof (subFormat.data4));
  17588. const ExtensibleWavSubFormat pcmFormat
  17589. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17590. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17591. {
  17592. const ExtensibleWavSubFormat ambisonicFormat
  17593. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17594. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17595. bytesPerFrame = 0;
  17596. }
  17597. }
  17598. }
  17599. else if (format != 1)
  17600. {
  17601. bytesPerFrame = 0;
  17602. }
  17603. hasGotType = true;
  17604. }
  17605. else if (chunkType == chunkName ("data"))
  17606. {
  17607. // get the data chunk's position
  17608. dataLength = length;
  17609. dataChunkStart = input->getPosition();
  17610. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17611. hasGotData = true;
  17612. }
  17613. else if (chunkType == chunkName ("bext"))
  17614. {
  17615. bwavChunkStart = input->getPosition();
  17616. bwavSize = length;
  17617. // Broadcast-wav extension chunk..
  17618. HeapBlock <BWAVChunk> bwav;
  17619. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17620. input->read (bwav, length);
  17621. bwav->copyTo (metadataValues);
  17622. }
  17623. else if (chunkType == chunkName ("smpl"))
  17624. {
  17625. HeapBlock <SMPLChunk> smpl;
  17626. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17627. input->read (smpl, length);
  17628. smpl->copyTo (metadataValues, length);
  17629. }
  17630. else if (chunkEnd <= input->getPosition())
  17631. {
  17632. break;
  17633. }
  17634. input->setPosition (chunkEnd);
  17635. }
  17636. }
  17637. }
  17638. }
  17639. ~WavAudioFormatReader()
  17640. {
  17641. }
  17642. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17643. int64 startSampleInFile, int numSamples)
  17644. {
  17645. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17646. if (samplesAvailable < numSamples)
  17647. {
  17648. for (int i = numDestChannels; --i >= 0;)
  17649. if (destSamples[i] != 0)
  17650. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17651. numSamples = (int) samplesAvailable;
  17652. }
  17653. if (numSamples <= 0)
  17654. return true;
  17655. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17656. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17657. char tempBuffer [tempBufSize];
  17658. while (numSamples > 0)
  17659. {
  17660. int* left = destSamples[0];
  17661. if (left != 0)
  17662. left += startOffsetInDestBuffer;
  17663. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17664. if (right != 0)
  17665. right += startOffsetInDestBuffer;
  17666. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17667. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17668. if (bytesRead < numThisTime * bytesPerFrame)
  17669. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17670. if (bitsPerSample == 16)
  17671. {
  17672. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17673. if (numChannels > 1)
  17674. {
  17675. if (left == 0)
  17676. {
  17677. for (int i = numThisTime; --i >= 0;)
  17678. {
  17679. ++src;
  17680. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17681. }
  17682. }
  17683. else if (right == 0)
  17684. {
  17685. for (int i = numThisTime; --i >= 0;)
  17686. {
  17687. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17688. ++src;
  17689. }
  17690. }
  17691. else
  17692. {
  17693. for (int i = numThisTime; --i >= 0;)
  17694. {
  17695. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17696. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17697. }
  17698. }
  17699. }
  17700. else
  17701. {
  17702. for (int i = numThisTime; --i >= 0;)
  17703. {
  17704. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17705. }
  17706. }
  17707. }
  17708. else if (bitsPerSample == 24)
  17709. {
  17710. const char* src = tempBuffer;
  17711. if (numChannels > 1)
  17712. {
  17713. if (left == 0)
  17714. {
  17715. for (int i = numThisTime; --i >= 0;)
  17716. {
  17717. src += 3;
  17718. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17719. src += 3;
  17720. }
  17721. }
  17722. else if (right == 0)
  17723. {
  17724. for (int i = numThisTime; --i >= 0;)
  17725. {
  17726. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17727. src += 6;
  17728. }
  17729. }
  17730. else
  17731. {
  17732. for (int i = 0; i < numThisTime; ++i)
  17733. {
  17734. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17735. src += 3;
  17736. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17737. src += 3;
  17738. }
  17739. }
  17740. }
  17741. else
  17742. {
  17743. for (int i = 0; i < numThisTime; ++i)
  17744. {
  17745. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17746. src += 3;
  17747. }
  17748. }
  17749. }
  17750. else if (bitsPerSample == 32)
  17751. {
  17752. const unsigned int* src = (const unsigned int*) tempBuffer;
  17753. unsigned int* l = (unsigned int*) left;
  17754. unsigned int* r = (unsigned int*) right;
  17755. if (numChannels > 1)
  17756. {
  17757. if (l == 0)
  17758. {
  17759. for (int i = numThisTime; --i >= 0;)
  17760. {
  17761. ++src;
  17762. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17763. }
  17764. }
  17765. else if (r == 0)
  17766. {
  17767. for (int i = numThisTime; --i >= 0;)
  17768. {
  17769. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17770. ++src;
  17771. }
  17772. }
  17773. else
  17774. {
  17775. for (int i = numThisTime; --i >= 0;)
  17776. {
  17777. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17778. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17779. }
  17780. }
  17781. }
  17782. else
  17783. {
  17784. for (int i = numThisTime; --i >= 0;)
  17785. {
  17786. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17787. }
  17788. }
  17789. left = (int*)l;
  17790. right = (int*)r;
  17791. }
  17792. else if (bitsPerSample == 8)
  17793. {
  17794. const unsigned char* src = (const unsigned char*) tempBuffer;
  17795. if (numChannels > 1)
  17796. {
  17797. if (left == 0)
  17798. {
  17799. for (int i = numThisTime; --i >= 0;)
  17800. {
  17801. ++src;
  17802. *right++ = ((int) *src++ - 128) << 24;
  17803. }
  17804. }
  17805. else if (right == 0)
  17806. {
  17807. for (int i = numThisTime; --i >= 0;)
  17808. {
  17809. *left++ = ((int) *src++ - 128) << 24;
  17810. ++src;
  17811. }
  17812. }
  17813. else
  17814. {
  17815. for (int i = numThisTime; --i >= 0;)
  17816. {
  17817. *left++ = ((int) *src++ - 128) << 24;
  17818. *right++ = ((int) *src++ - 128) << 24;
  17819. }
  17820. }
  17821. }
  17822. else
  17823. {
  17824. for (int i = numThisTime; --i >= 0;)
  17825. {
  17826. *left++ = ((int)*src++ - 128) << 24;
  17827. }
  17828. }
  17829. }
  17830. startOffsetInDestBuffer += numThisTime;
  17831. numSamples -= numThisTime;
  17832. }
  17833. if (numSamples > 0)
  17834. {
  17835. for (int i = numDestChannels; --i >= 0;)
  17836. if (destSamples[i] != 0)
  17837. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17838. sizeof (int) * numSamples);
  17839. }
  17840. return true;
  17841. }
  17842. juce_UseDebuggingNewOperator
  17843. };
  17844. class WavAudioFormatWriter : public AudioFormatWriter
  17845. {
  17846. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17847. uint32 lengthInSamples, bytesWritten;
  17848. int64 headerPosition;
  17849. bool writeFailed;
  17850. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17851. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17852. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17853. void writeHeader()
  17854. {
  17855. const bool seekedOk = output->setPosition (headerPosition);
  17856. (void) seekedOk;
  17857. // if this fails, you've given it an output stream that can't seek! It needs
  17858. // to be able to seek back to write the header
  17859. jassert (seekedOk);
  17860. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17861. output->writeInt (chunkName ("RIFF"));
  17862. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17863. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17864. output->writeInt (chunkName ("WAVE"));
  17865. output->writeInt (chunkName ("fmt "));
  17866. output->writeInt (16);
  17867. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17868. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17869. output->writeShort ((short) numChannels);
  17870. output->writeInt ((int) sampleRate);
  17871. output->writeInt (bytesPerFrame * (int) sampleRate);
  17872. output->writeShort ((short) bytesPerFrame);
  17873. output->writeShort ((short) bitsPerSample);
  17874. if (bwavChunk.getSize() > 0)
  17875. {
  17876. output->writeInt (chunkName ("bext"));
  17877. output->writeInt ((int) bwavChunk.getSize());
  17878. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17879. }
  17880. if (smplChunk.getSize() > 0)
  17881. {
  17882. output->writeInt (chunkName ("smpl"));
  17883. output->writeInt ((int) smplChunk.getSize());
  17884. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17885. }
  17886. output->writeInt (chunkName ("data"));
  17887. output->writeInt (lengthInSamples * bytesPerFrame);
  17888. usesFloatingPointData = (bitsPerSample == 32);
  17889. }
  17890. public:
  17891. WavAudioFormatWriter (OutputStream* const out,
  17892. const double sampleRate_,
  17893. const unsigned int numChannels_,
  17894. const int bits,
  17895. const StringPairArray& metadataValues)
  17896. : AudioFormatWriter (out,
  17897. TRANS (wavFormatName),
  17898. sampleRate_,
  17899. numChannels_,
  17900. bits),
  17901. lengthInSamples (0),
  17902. bytesWritten (0),
  17903. writeFailed (false)
  17904. {
  17905. if (metadataValues.size() > 0)
  17906. {
  17907. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17908. smplChunk = SMPLChunk::createFrom (metadataValues);
  17909. }
  17910. headerPosition = out->getPosition();
  17911. writeHeader();
  17912. }
  17913. ~WavAudioFormatWriter()
  17914. {
  17915. writeHeader();
  17916. }
  17917. bool write (const int** data, int numSamples)
  17918. {
  17919. if (writeFailed)
  17920. return false;
  17921. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17922. tempBlock.ensureSize (bytes, false);
  17923. char* buffer = static_cast <char*> (tempBlock.getData());
  17924. const int* left = data[0];
  17925. const int* right = data[1];
  17926. if (right == 0)
  17927. right = left;
  17928. if (bitsPerSample == 16)
  17929. {
  17930. short* b = (short*) buffer;
  17931. if (numChannels > 1)
  17932. {
  17933. for (int i = numSamples; --i >= 0;)
  17934. {
  17935. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17936. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17937. }
  17938. }
  17939. else
  17940. {
  17941. for (int i = numSamples; --i >= 0;)
  17942. {
  17943. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17944. }
  17945. }
  17946. }
  17947. else if (bitsPerSample == 24)
  17948. {
  17949. char* b = buffer;
  17950. if (numChannels > 1)
  17951. {
  17952. for (int i = numSamples; --i >= 0;)
  17953. {
  17954. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17955. b += 3;
  17956. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17957. b += 3;
  17958. }
  17959. }
  17960. else
  17961. {
  17962. for (int i = numSamples; --i >= 0;)
  17963. {
  17964. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17965. b += 3;
  17966. }
  17967. }
  17968. }
  17969. else if (bitsPerSample == 32)
  17970. {
  17971. unsigned int* b = (unsigned int*) buffer;
  17972. if (numChannels > 1)
  17973. {
  17974. for (int i = numSamples; --i >= 0;)
  17975. {
  17976. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17977. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17978. }
  17979. }
  17980. else
  17981. {
  17982. for (int i = numSamples; --i >= 0;)
  17983. {
  17984. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17985. }
  17986. }
  17987. }
  17988. else if (bitsPerSample == 8)
  17989. {
  17990. unsigned char* b = (unsigned char*) buffer;
  17991. if (numChannels > 1)
  17992. {
  17993. for (int i = numSamples; --i >= 0;)
  17994. {
  17995. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17996. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17997. }
  17998. }
  17999. else
  18000. {
  18001. for (int i = numSamples; --i >= 0;)
  18002. {
  18003. *b++ = (unsigned char) (128 + (*left++ >> 24));
  18004. }
  18005. }
  18006. }
  18007. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18008. || ! output->write (buffer, bytes))
  18009. {
  18010. // failed to write to disk, so let's try writing the header.
  18011. // If it's just run out of disk space, then if it does manage
  18012. // to write the header, we'll still have a useable file..
  18013. writeHeader();
  18014. writeFailed = true;
  18015. return false;
  18016. }
  18017. else
  18018. {
  18019. bytesWritten += bytes;
  18020. lengthInSamples += numSamples;
  18021. return true;
  18022. }
  18023. }
  18024. juce_UseDebuggingNewOperator
  18025. };
  18026. WavAudioFormat::WavAudioFormat()
  18027. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18028. {
  18029. }
  18030. WavAudioFormat::~WavAudioFormat()
  18031. {
  18032. }
  18033. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18034. {
  18035. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18036. return Array <int> (rates);
  18037. }
  18038. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18039. {
  18040. const int depths[] = { 8, 16, 24, 32, 0 };
  18041. return Array <int> (depths);
  18042. }
  18043. bool WavAudioFormat::canDoStereo()
  18044. {
  18045. return true;
  18046. }
  18047. bool WavAudioFormat::canDoMono()
  18048. {
  18049. return true;
  18050. }
  18051. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18052. const bool deleteStreamIfOpeningFails)
  18053. {
  18054. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18055. if (r->sampleRate != 0)
  18056. return r.release();
  18057. if (! deleteStreamIfOpeningFails)
  18058. r->input = 0;
  18059. return 0;
  18060. }
  18061. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18062. double sampleRate,
  18063. unsigned int numChannels,
  18064. int bitsPerSample,
  18065. const StringPairArray& metadataValues,
  18066. int /*qualityOptionIndex*/)
  18067. {
  18068. if (getPossibleBitDepths().contains (bitsPerSample))
  18069. {
  18070. return new WavAudioFormatWriter (out,
  18071. sampleRate,
  18072. numChannels,
  18073. bitsPerSample,
  18074. metadataValues);
  18075. }
  18076. return 0;
  18077. }
  18078. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18079. {
  18080. TemporaryFile tempFile (file);
  18081. WavAudioFormat wav;
  18082. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18083. if (reader != 0)
  18084. {
  18085. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18086. if (outStream != 0)
  18087. {
  18088. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18089. reader->numChannels, reader->bitsPerSample,
  18090. metadata, 0));
  18091. if (writer != 0)
  18092. {
  18093. outStream.release();
  18094. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18095. writer = 0;
  18096. reader = 0;
  18097. return ok && tempFile.overwriteTargetFileWithTemporary();
  18098. }
  18099. }
  18100. }
  18101. return false;
  18102. }
  18103. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18104. {
  18105. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18106. if (reader != 0)
  18107. {
  18108. const int64 bwavPos = reader->bwavChunkStart;
  18109. const int64 bwavSize = reader->bwavSize;
  18110. reader = 0;
  18111. if (bwavSize > 0)
  18112. {
  18113. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18114. if (chunk.getSize() <= (size_t) bwavSize)
  18115. {
  18116. // the new one will fit in the space available, so write it directly..
  18117. const int64 oldSize = wavFile.getSize();
  18118. {
  18119. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18120. out->setPosition (bwavPos);
  18121. out->write (chunk.getData(), (int) chunk.getSize());
  18122. out->setPosition (oldSize);
  18123. }
  18124. jassert (wavFile.getSize() == oldSize);
  18125. return true;
  18126. }
  18127. }
  18128. }
  18129. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18130. }
  18131. END_JUCE_NAMESPACE
  18132. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18133. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18134. BEGIN_JUCE_NAMESPACE
  18135. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18136. const bool deleteReaderWhenThisIsDeleted)
  18137. : reader (reader_),
  18138. deleteReader (deleteReaderWhenThisIsDeleted),
  18139. nextPlayPos (0),
  18140. looping (false)
  18141. {
  18142. jassert (reader != 0);
  18143. }
  18144. AudioFormatReaderSource::~AudioFormatReaderSource()
  18145. {
  18146. releaseResources();
  18147. if (deleteReader)
  18148. delete reader;
  18149. }
  18150. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18151. {
  18152. nextPlayPos = newPosition;
  18153. }
  18154. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18155. {
  18156. looping = shouldLoop;
  18157. }
  18158. int AudioFormatReaderSource::getNextReadPosition() const
  18159. {
  18160. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18161. : nextPlayPos;
  18162. }
  18163. int AudioFormatReaderSource::getTotalLength() const
  18164. {
  18165. return (int) reader->lengthInSamples;
  18166. }
  18167. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18168. double /*sampleRate*/)
  18169. {
  18170. }
  18171. void AudioFormatReaderSource::releaseResources()
  18172. {
  18173. }
  18174. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18175. {
  18176. if (info.numSamples > 0)
  18177. {
  18178. const int start = nextPlayPos;
  18179. if (looping)
  18180. {
  18181. const int newStart = start % (int) reader->lengthInSamples;
  18182. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18183. if (newEnd > newStart)
  18184. {
  18185. info.buffer->readFromAudioReader (reader,
  18186. info.startSample,
  18187. newEnd - newStart,
  18188. newStart,
  18189. true, true);
  18190. }
  18191. else
  18192. {
  18193. const int endSamps = (int) reader->lengthInSamples - newStart;
  18194. info.buffer->readFromAudioReader (reader,
  18195. info.startSample,
  18196. endSamps,
  18197. newStart,
  18198. true, true);
  18199. info.buffer->readFromAudioReader (reader,
  18200. info.startSample + endSamps,
  18201. newEnd,
  18202. 0,
  18203. true, true);
  18204. }
  18205. nextPlayPos = newEnd;
  18206. }
  18207. else
  18208. {
  18209. info.buffer->readFromAudioReader (reader,
  18210. info.startSample,
  18211. info.numSamples,
  18212. start,
  18213. true, true);
  18214. nextPlayPos += info.numSamples;
  18215. }
  18216. }
  18217. }
  18218. END_JUCE_NAMESPACE
  18219. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18220. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18221. BEGIN_JUCE_NAMESPACE
  18222. AudioSourcePlayer::AudioSourcePlayer()
  18223. : source (0),
  18224. sampleRate (0),
  18225. bufferSize (0),
  18226. tempBuffer (2, 8),
  18227. lastGain (1.0f),
  18228. gain (1.0f)
  18229. {
  18230. }
  18231. AudioSourcePlayer::~AudioSourcePlayer()
  18232. {
  18233. setSource (0);
  18234. }
  18235. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18236. {
  18237. if (source != newSource)
  18238. {
  18239. AudioSource* const oldSource = source;
  18240. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18241. newSource->prepareToPlay (bufferSize, sampleRate);
  18242. {
  18243. const ScopedLock sl (readLock);
  18244. source = newSource;
  18245. }
  18246. if (oldSource != 0)
  18247. oldSource->releaseResources();
  18248. }
  18249. }
  18250. void AudioSourcePlayer::setGain (const float newGain) throw()
  18251. {
  18252. gain = newGain;
  18253. }
  18254. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18255. int totalNumInputChannels,
  18256. float** outputChannelData,
  18257. int totalNumOutputChannels,
  18258. int numSamples)
  18259. {
  18260. // these should have been prepared by audioDeviceAboutToStart()...
  18261. jassert (sampleRate > 0 && bufferSize > 0);
  18262. const ScopedLock sl (readLock);
  18263. if (source != 0)
  18264. {
  18265. AudioSourceChannelInfo info;
  18266. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18267. // messy stuff needed to compact the channels down into an array
  18268. // of non-zero pointers..
  18269. for (i = 0; i < totalNumInputChannels; ++i)
  18270. {
  18271. if (inputChannelData[i] != 0)
  18272. {
  18273. inputChans [numInputs++] = inputChannelData[i];
  18274. if (numInputs >= numElementsInArray (inputChans))
  18275. break;
  18276. }
  18277. }
  18278. for (i = 0; i < totalNumOutputChannels; ++i)
  18279. {
  18280. if (outputChannelData[i] != 0)
  18281. {
  18282. outputChans [numOutputs++] = outputChannelData[i];
  18283. if (numOutputs >= numElementsInArray (outputChans))
  18284. break;
  18285. }
  18286. }
  18287. if (numInputs > numOutputs)
  18288. {
  18289. // if there aren't enough output channels for the number of
  18290. // inputs, we need to create some temporary extra ones (can't
  18291. // use the input data in case it gets written to)
  18292. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18293. false, false, true);
  18294. for (i = 0; i < numOutputs; ++i)
  18295. {
  18296. channels[numActiveChans] = outputChans[i];
  18297. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18298. ++numActiveChans;
  18299. }
  18300. for (i = numOutputs; i < numInputs; ++i)
  18301. {
  18302. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18303. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18304. ++numActiveChans;
  18305. }
  18306. }
  18307. else
  18308. {
  18309. for (i = 0; i < numInputs; ++i)
  18310. {
  18311. channels[numActiveChans] = outputChans[i];
  18312. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18313. ++numActiveChans;
  18314. }
  18315. for (i = numInputs; i < numOutputs; ++i)
  18316. {
  18317. channels[numActiveChans] = outputChans[i];
  18318. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18319. ++numActiveChans;
  18320. }
  18321. }
  18322. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18323. info.buffer = &buffer;
  18324. info.startSample = 0;
  18325. info.numSamples = numSamples;
  18326. source->getNextAudioBlock (info);
  18327. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18328. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18329. lastGain = gain;
  18330. }
  18331. else
  18332. {
  18333. for (int i = 0; i < totalNumOutputChannels; ++i)
  18334. if (outputChannelData[i] != 0)
  18335. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18336. }
  18337. }
  18338. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18339. {
  18340. sampleRate = device->getCurrentSampleRate();
  18341. bufferSize = device->getCurrentBufferSizeSamples();
  18342. zeromem (channels, sizeof (channels));
  18343. if (source != 0)
  18344. source->prepareToPlay (bufferSize, sampleRate);
  18345. }
  18346. void AudioSourcePlayer::audioDeviceStopped()
  18347. {
  18348. if (source != 0)
  18349. source->releaseResources();
  18350. sampleRate = 0.0;
  18351. bufferSize = 0;
  18352. tempBuffer.setSize (2, 8);
  18353. }
  18354. END_JUCE_NAMESPACE
  18355. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18356. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18357. BEGIN_JUCE_NAMESPACE
  18358. AudioTransportSource::AudioTransportSource()
  18359. : source (0),
  18360. resamplerSource (0),
  18361. bufferingSource (0),
  18362. positionableSource (0),
  18363. masterSource (0),
  18364. gain (1.0f),
  18365. lastGain (1.0f),
  18366. playing (false),
  18367. stopped (true),
  18368. sampleRate (44100.0),
  18369. sourceSampleRate (0.0),
  18370. blockSize (128),
  18371. readAheadBufferSize (0),
  18372. isPrepared (false),
  18373. inputStreamEOF (false)
  18374. {
  18375. }
  18376. AudioTransportSource::~AudioTransportSource()
  18377. {
  18378. setSource (0);
  18379. releaseResources();
  18380. }
  18381. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18382. int readAheadBufferSize_,
  18383. double sourceSampleRateToCorrectFor)
  18384. {
  18385. if (source == newSource)
  18386. {
  18387. if (source == 0)
  18388. return;
  18389. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18390. }
  18391. readAheadBufferSize = readAheadBufferSize_;
  18392. sourceSampleRate = sourceSampleRateToCorrectFor;
  18393. ResamplingAudioSource* newResamplerSource = 0;
  18394. BufferingAudioSource* newBufferingSource = 0;
  18395. PositionableAudioSource* newPositionableSource = 0;
  18396. AudioSource* newMasterSource = 0;
  18397. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18398. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18399. AudioSource* oldMasterSource = masterSource;
  18400. if (newSource != 0)
  18401. {
  18402. newPositionableSource = newSource;
  18403. if (readAheadBufferSize_ > 0)
  18404. newPositionableSource = newBufferingSource
  18405. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18406. newPositionableSource->setNextReadPosition (0);
  18407. if (sourceSampleRateToCorrectFor != 0)
  18408. newMasterSource = newResamplerSource
  18409. = new ResamplingAudioSource (newPositionableSource, false);
  18410. else
  18411. newMasterSource = newPositionableSource;
  18412. if (isPrepared)
  18413. {
  18414. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18415. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18416. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18417. }
  18418. }
  18419. {
  18420. const ScopedLock sl (callbackLock);
  18421. source = newSource;
  18422. resamplerSource = newResamplerSource;
  18423. bufferingSource = newBufferingSource;
  18424. masterSource = newMasterSource;
  18425. positionableSource = newPositionableSource;
  18426. playing = false;
  18427. }
  18428. if (oldMasterSource != 0)
  18429. oldMasterSource->releaseResources();
  18430. }
  18431. void AudioTransportSource::start()
  18432. {
  18433. if ((! playing) && masterSource != 0)
  18434. {
  18435. {
  18436. const ScopedLock sl (callbackLock);
  18437. playing = true;
  18438. stopped = false;
  18439. inputStreamEOF = false;
  18440. }
  18441. sendChangeMessage (this);
  18442. }
  18443. }
  18444. void AudioTransportSource::stop()
  18445. {
  18446. if (playing)
  18447. {
  18448. {
  18449. const ScopedLock sl (callbackLock);
  18450. playing = false;
  18451. }
  18452. int n = 500;
  18453. while (--n >= 0 && ! stopped)
  18454. Thread::sleep (2);
  18455. sendChangeMessage (this);
  18456. }
  18457. }
  18458. void AudioTransportSource::setPosition (double newPosition)
  18459. {
  18460. if (sampleRate > 0.0)
  18461. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18462. }
  18463. double AudioTransportSource::getCurrentPosition() const
  18464. {
  18465. if (sampleRate > 0.0)
  18466. return getNextReadPosition() / sampleRate;
  18467. else
  18468. return 0.0;
  18469. }
  18470. void AudioTransportSource::setNextReadPosition (int newPosition)
  18471. {
  18472. if (positionableSource != 0)
  18473. {
  18474. if (sampleRate > 0 && sourceSampleRate > 0)
  18475. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18476. positionableSource->setNextReadPosition (newPosition);
  18477. }
  18478. }
  18479. int AudioTransportSource::getNextReadPosition() const
  18480. {
  18481. if (positionableSource != 0)
  18482. {
  18483. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18484. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18485. }
  18486. return 0;
  18487. }
  18488. int AudioTransportSource::getTotalLength() const
  18489. {
  18490. const ScopedLock sl (callbackLock);
  18491. if (positionableSource != 0)
  18492. {
  18493. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18494. return roundToInt (positionableSource->getTotalLength() * ratio);
  18495. }
  18496. return 0;
  18497. }
  18498. bool AudioTransportSource::isLooping() const
  18499. {
  18500. const ScopedLock sl (callbackLock);
  18501. return positionableSource != 0
  18502. && positionableSource->isLooping();
  18503. }
  18504. void AudioTransportSource::setGain (const float newGain) throw()
  18505. {
  18506. gain = newGain;
  18507. }
  18508. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18509. double sampleRate_)
  18510. {
  18511. const ScopedLock sl (callbackLock);
  18512. sampleRate = sampleRate_;
  18513. blockSize = samplesPerBlockExpected;
  18514. if (masterSource != 0)
  18515. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18516. if (resamplerSource != 0 && sourceSampleRate != 0)
  18517. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18518. isPrepared = true;
  18519. }
  18520. void AudioTransportSource::releaseResources()
  18521. {
  18522. const ScopedLock sl (callbackLock);
  18523. if (masterSource != 0)
  18524. masterSource->releaseResources();
  18525. isPrepared = false;
  18526. }
  18527. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18528. {
  18529. const ScopedLock sl (callbackLock);
  18530. inputStreamEOF = false;
  18531. if (masterSource != 0 && ! stopped)
  18532. {
  18533. masterSource->getNextAudioBlock (info);
  18534. if (! playing)
  18535. {
  18536. // just stopped playing, so fade out the last block..
  18537. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18538. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18539. if (info.numSamples > 256)
  18540. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18541. }
  18542. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18543. && ! positionableSource->isLooping())
  18544. {
  18545. playing = false;
  18546. inputStreamEOF = true;
  18547. sendChangeMessage (this);
  18548. }
  18549. stopped = ! playing;
  18550. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18551. {
  18552. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18553. lastGain, gain);
  18554. }
  18555. }
  18556. else
  18557. {
  18558. info.clearActiveBufferRegion();
  18559. stopped = true;
  18560. }
  18561. lastGain = gain;
  18562. }
  18563. END_JUCE_NAMESPACE
  18564. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18565. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18566. BEGIN_JUCE_NAMESPACE
  18567. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18568. public Thread,
  18569. private Timer
  18570. {
  18571. public:
  18572. SharedBufferingAudioSourceThread()
  18573. : Thread ("Audio Buffer")
  18574. {
  18575. }
  18576. ~SharedBufferingAudioSourceThread()
  18577. {
  18578. stopThread (10000);
  18579. clearSingletonInstance();
  18580. }
  18581. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18582. void addSource (BufferingAudioSource* source)
  18583. {
  18584. const ScopedLock sl (lock);
  18585. if (! sources.contains (source))
  18586. {
  18587. sources.add (source);
  18588. startThread();
  18589. stopTimer();
  18590. }
  18591. notify();
  18592. }
  18593. void removeSource (BufferingAudioSource* source)
  18594. {
  18595. const ScopedLock sl (lock);
  18596. sources.removeValue (source);
  18597. if (sources.size() == 0)
  18598. startTimer (5000);
  18599. }
  18600. private:
  18601. Array <BufferingAudioSource*> sources;
  18602. CriticalSection lock;
  18603. void run()
  18604. {
  18605. while (! threadShouldExit())
  18606. {
  18607. bool busy = false;
  18608. for (int i = sources.size(); --i >= 0;)
  18609. {
  18610. if (threadShouldExit())
  18611. return;
  18612. const ScopedLock sl (lock);
  18613. BufferingAudioSource* const b = sources[i];
  18614. if (b != 0 && b->readNextBufferChunk())
  18615. busy = true;
  18616. }
  18617. if (! busy)
  18618. wait (500);
  18619. }
  18620. }
  18621. void timerCallback()
  18622. {
  18623. stopTimer();
  18624. if (sources.size() == 0)
  18625. deleteInstance();
  18626. }
  18627. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18628. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18629. };
  18630. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18631. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18632. const bool deleteSourceWhenDeleted_,
  18633. int numberOfSamplesToBuffer_)
  18634. : source (source_),
  18635. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18636. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18637. buffer (2, 0),
  18638. bufferValidStart (0),
  18639. bufferValidEnd (0),
  18640. nextPlayPos (0),
  18641. wasSourceLooping (false)
  18642. {
  18643. jassert (source_ != 0);
  18644. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18645. // not using a larger buffer..
  18646. }
  18647. BufferingAudioSource::~BufferingAudioSource()
  18648. {
  18649. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18650. if (thread != 0)
  18651. thread->removeSource (this);
  18652. if (deleteSourceWhenDeleted)
  18653. delete source;
  18654. }
  18655. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18656. {
  18657. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18658. sampleRate = sampleRate_;
  18659. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18660. buffer.clear();
  18661. bufferValidStart = 0;
  18662. bufferValidEnd = 0;
  18663. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18664. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18665. buffer.getNumSamples() / 2))
  18666. {
  18667. SharedBufferingAudioSourceThread::getInstance()->notify();
  18668. Thread::sleep (5);
  18669. }
  18670. }
  18671. void BufferingAudioSource::releaseResources()
  18672. {
  18673. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18674. if (thread != 0)
  18675. thread->removeSource (this);
  18676. buffer.setSize (2, 0);
  18677. source->releaseResources();
  18678. }
  18679. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18680. {
  18681. const ScopedLock sl (bufferStartPosLock);
  18682. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18683. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18684. if (validStart == validEnd)
  18685. {
  18686. // total cache miss
  18687. info.clearActiveBufferRegion();
  18688. }
  18689. else
  18690. {
  18691. if (validStart > 0)
  18692. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18693. if (validEnd < info.numSamples)
  18694. info.buffer->clear (info.startSample + validEnd,
  18695. info.numSamples - validEnd); // partial cache miss at end
  18696. if (validStart < validEnd)
  18697. {
  18698. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18699. {
  18700. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18701. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18702. if (startBufferIndex < endBufferIndex)
  18703. {
  18704. info.buffer->copyFrom (chan, info.startSample + validStart,
  18705. buffer,
  18706. chan, startBufferIndex,
  18707. validEnd - validStart);
  18708. }
  18709. else
  18710. {
  18711. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18712. info.buffer->copyFrom (chan, info.startSample + validStart,
  18713. buffer,
  18714. chan, startBufferIndex,
  18715. initialSize);
  18716. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18717. buffer,
  18718. chan, 0,
  18719. (validEnd - validStart) - initialSize);
  18720. }
  18721. }
  18722. }
  18723. nextPlayPos += info.numSamples;
  18724. if (source->isLooping() && nextPlayPos > 0)
  18725. nextPlayPos %= source->getTotalLength();
  18726. }
  18727. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18728. if (thread != 0)
  18729. thread->notify();
  18730. }
  18731. int BufferingAudioSource::getNextReadPosition() const
  18732. {
  18733. return (source->isLooping() && nextPlayPos > 0)
  18734. ? nextPlayPos % source->getTotalLength()
  18735. : nextPlayPos;
  18736. }
  18737. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18738. {
  18739. const ScopedLock sl (bufferStartPosLock);
  18740. nextPlayPos = newPosition;
  18741. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18742. if (thread != 0)
  18743. thread->notify();
  18744. }
  18745. bool BufferingAudioSource::readNextBufferChunk()
  18746. {
  18747. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18748. {
  18749. const ScopedLock sl (bufferStartPosLock);
  18750. if (wasSourceLooping != isLooping())
  18751. {
  18752. wasSourceLooping = isLooping();
  18753. bufferValidStart = 0;
  18754. bufferValidEnd = 0;
  18755. }
  18756. newBVS = jmax (0, nextPlayPos);
  18757. newBVE = newBVS + buffer.getNumSamples() - 4;
  18758. sectionToReadStart = 0;
  18759. sectionToReadEnd = 0;
  18760. const int maxChunkSize = 2048;
  18761. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18762. {
  18763. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18764. sectionToReadStart = newBVS;
  18765. sectionToReadEnd = newBVE;
  18766. bufferValidStart = 0;
  18767. bufferValidEnd = 0;
  18768. }
  18769. else if (abs (newBVS - bufferValidStart) > 512
  18770. || abs (newBVE - bufferValidEnd) > 512)
  18771. {
  18772. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18773. sectionToReadStart = bufferValidEnd;
  18774. sectionToReadEnd = newBVE;
  18775. bufferValidStart = newBVS;
  18776. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18777. }
  18778. }
  18779. if (sectionToReadStart != sectionToReadEnd)
  18780. {
  18781. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18782. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18783. if (bufferIndexStart < bufferIndexEnd)
  18784. {
  18785. readBufferSection (sectionToReadStart,
  18786. sectionToReadEnd - sectionToReadStart,
  18787. bufferIndexStart);
  18788. }
  18789. else
  18790. {
  18791. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18792. readBufferSection (sectionToReadStart,
  18793. initialSize,
  18794. bufferIndexStart);
  18795. readBufferSection (sectionToReadStart + initialSize,
  18796. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18797. 0);
  18798. }
  18799. const ScopedLock sl2 (bufferStartPosLock);
  18800. bufferValidStart = newBVS;
  18801. bufferValidEnd = newBVE;
  18802. return true;
  18803. }
  18804. else
  18805. {
  18806. return false;
  18807. }
  18808. }
  18809. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18810. {
  18811. if (source->getNextReadPosition() != start)
  18812. source->setNextReadPosition (start);
  18813. AudioSourceChannelInfo info;
  18814. info.buffer = &buffer;
  18815. info.startSample = bufferOffset;
  18816. info.numSamples = length;
  18817. source->getNextAudioBlock (info);
  18818. }
  18819. END_JUCE_NAMESPACE
  18820. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18821. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18822. BEGIN_JUCE_NAMESPACE
  18823. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18824. const bool deleteSourceWhenDeleted_)
  18825. : requiredNumberOfChannels (2),
  18826. source (source_),
  18827. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18828. buffer (2, 16)
  18829. {
  18830. remappedInfo.buffer = &buffer;
  18831. remappedInfo.startSample = 0;
  18832. }
  18833. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18834. {
  18835. if (deleteSourceWhenDeleted)
  18836. delete source;
  18837. }
  18838. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18839. {
  18840. const ScopedLock sl (lock);
  18841. requiredNumberOfChannels = requiredNumberOfChannels_;
  18842. }
  18843. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18844. {
  18845. const ScopedLock sl (lock);
  18846. remappedInputs.clear();
  18847. remappedOutputs.clear();
  18848. }
  18849. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18850. {
  18851. const ScopedLock sl (lock);
  18852. while (remappedInputs.size() < destIndex)
  18853. remappedInputs.add (-1);
  18854. remappedInputs.set (destIndex, sourceIndex);
  18855. }
  18856. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18857. {
  18858. const ScopedLock sl (lock);
  18859. while (remappedOutputs.size() < sourceIndex)
  18860. remappedOutputs.add (-1);
  18861. remappedOutputs.set (sourceIndex, destIndex);
  18862. }
  18863. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18864. {
  18865. const ScopedLock sl (lock);
  18866. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18867. return remappedInputs.getUnchecked (inputChannelIndex);
  18868. return -1;
  18869. }
  18870. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18871. {
  18872. const ScopedLock sl (lock);
  18873. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18874. return remappedOutputs .getUnchecked (outputChannelIndex);
  18875. return -1;
  18876. }
  18877. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18878. {
  18879. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18880. }
  18881. void ChannelRemappingAudioSource::releaseResources()
  18882. {
  18883. source->releaseResources();
  18884. }
  18885. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18886. {
  18887. const ScopedLock sl (lock);
  18888. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18889. const int numChans = bufferToFill.buffer->getNumChannels();
  18890. int i;
  18891. for (i = 0; i < buffer.getNumChannels(); ++i)
  18892. {
  18893. const int remappedChan = getRemappedInputChannel (i);
  18894. if (remappedChan >= 0 && remappedChan < numChans)
  18895. {
  18896. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18897. remappedChan,
  18898. bufferToFill.startSample,
  18899. bufferToFill.numSamples);
  18900. }
  18901. else
  18902. {
  18903. buffer.clear (i, 0, bufferToFill.numSamples);
  18904. }
  18905. }
  18906. remappedInfo.numSamples = bufferToFill.numSamples;
  18907. source->getNextAudioBlock (remappedInfo);
  18908. bufferToFill.clearActiveBufferRegion();
  18909. for (i = 0; i < requiredNumberOfChannels; ++i)
  18910. {
  18911. const int remappedChan = getRemappedOutputChannel (i);
  18912. if (remappedChan >= 0 && remappedChan < numChans)
  18913. {
  18914. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18915. buffer, i, 0, bufferToFill.numSamples);
  18916. }
  18917. }
  18918. }
  18919. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18920. {
  18921. XmlElement* e = new XmlElement ("MAPPINGS");
  18922. String ins, outs;
  18923. int i;
  18924. const ScopedLock sl (lock);
  18925. for (i = 0; i < remappedInputs.size(); ++i)
  18926. ins << remappedInputs.getUnchecked(i) << ' ';
  18927. for (i = 0; i < remappedOutputs.size(); ++i)
  18928. outs << remappedOutputs.getUnchecked(i) << ' ';
  18929. e->setAttribute ("inputs", ins.trimEnd());
  18930. e->setAttribute ("outputs", outs.trimEnd());
  18931. return e;
  18932. }
  18933. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18934. {
  18935. if (e.hasTagName ("MAPPINGS"))
  18936. {
  18937. const ScopedLock sl (lock);
  18938. clearAllMappings();
  18939. StringArray ins, outs;
  18940. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18941. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18942. int i;
  18943. for (i = 0; i < ins.size(); ++i)
  18944. remappedInputs.add (ins[i].getIntValue());
  18945. for (i = 0; i < outs.size(); ++i)
  18946. remappedOutputs.add (outs[i].getIntValue());
  18947. }
  18948. }
  18949. END_JUCE_NAMESPACE
  18950. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18951. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18952. BEGIN_JUCE_NAMESPACE
  18953. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18954. const bool deleteInputWhenDeleted_)
  18955. : input (inputSource),
  18956. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18957. {
  18958. jassert (inputSource != 0);
  18959. for (int i = 2; --i >= 0;)
  18960. iirFilters.add (new IIRFilter());
  18961. }
  18962. IIRFilterAudioSource::~IIRFilterAudioSource()
  18963. {
  18964. if (deleteInputWhenDeleted)
  18965. delete input;
  18966. }
  18967. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18968. {
  18969. for (int i = iirFilters.size(); --i >= 0;)
  18970. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18971. }
  18972. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18973. {
  18974. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18975. for (int i = iirFilters.size(); --i >= 0;)
  18976. iirFilters.getUnchecked(i)->reset();
  18977. }
  18978. void IIRFilterAudioSource::releaseResources()
  18979. {
  18980. input->releaseResources();
  18981. }
  18982. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18983. {
  18984. input->getNextAudioBlock (bufferToFill);
  18985. const int numChannels = bufferToFill.buffer->getNumChannels();
  18986. while (numChannels > iirFilters.size())
  18987. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18988. for (int i = 0; i < numChannels; ++i)
  18989. iirFilters.getUnchecked(i)
  18990. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18991. bufferToFill.numSamples);
  18992. }
  18993. END_JUCE_NAMESPACE
  18994. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18995. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18996. BEGIN_JUCE_NAMESPACE
  18997. MixerAudioSource::MixerAudioSource()
  18998. : tempBuffer (2, 0),
  18999. currentSampleRate (0.0),
  19000. bufferSizeExpected (0)
  19001. {
  19002. }
  19003. MixerAudioSource::~MixerAudioSource()
  19004. {
  19005. removeAllInputs();
  19006. }
  19007. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19008. {
  19009. if (input != 0 && ! inputs.contains (input))
  19010. {
  19011. double localRate;
  19012. int localBufferSize;
  19013. {
  19014. const ScopedLock sl (lock);
  19015. localRate = currentSampleRate;
  19016. localBufferSize = bufferSizeExpected;
  19017. }
  19018. if (localRate != 0.0)
  19019. input->prepareToPlay (localBufferSize, localRate);
  19020. const ScopedLock sl (lock);
  19021. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19022. inputs.add (input);
  19023. }
  19024. }
  19025. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19026. {
  19027. if (input != 0)
  19028. {
  19029. int index;
  19030. {
  19031. const ScopedLock sl (lock);
  19032. index = inputs.indexOf (input);
  19033. if (index >= 0)
  19034. {
  19035. inputsToDelete.shiftBits (index, 1);
  19036. inputs.remove (index);
  19037. }
  19038. }
  19039. if (index >= 0)
  19040. {
  19041. input->releaseResources();
  19042. if (deleteInput)
  19043. delete input;
  19044. }
  19045. }
  19046. }
  19047. void MixerAudioSource::removeAllInputs()
  19048. {
  19049. OwnedArray<AudioSource> toDelete;
  19050. {
  19051. const ScopedLock sl (lock);
  19052. for (int i = inputs.size(); --i >= 0;)
  19053. if (inputsToDelete[i])
  19054. toDelete.add (inputs.getUnchecked(i));
  19055. }
  19056. }
  19057. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19058. {
  19059. tempBuffer.setSize (2, samplesPerBlockExpected);
  19060. const ScopedLock sl (lock);
  19061. currentSampleRate = sampleRate;
  19062. bufferSizeExpected = samplesPerBlockExpected;
  19063. for (int i = inputs.size(); --i >= 0;)
  19064. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19065. }
  19066. void MixerAudioSource::releaseResources()
  19067. {
  19068. const ScopedLock sl (lock);
  19069. for (int i = inputs.size(); --i >= 0;)
  19070. inputs.getUnchecked(i)->releaseResources();
  19071. tempBuffer.setSize (2, 0);
  19072. currentSampleRate = 0;
  19073. bufferSizeExpected = 0;
  19074. }
  19075. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19076. {
  19077. const ScopedLock sl (lock);
  19078. if (inputs.size() > 0)
  19079. {
  19080. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19081. if (inputs.size() > 1)
  19082. {
  19083. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19084. info.buffer->getNumSamples());
  19085. AudioSourceChannelInfo info2;
  19086. info2.buffer = &tempBuffer;
  19087. info2.numSamples = info.numSamples;
  19088. info2.startSample = 0;
  19089. for (int i = 1; i < inputs.size(); ++i)
  19090. {
  19091. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19092. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19093. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19094. }
  19095. }
  19096. }
  19097. else
  19098. {
  19099. info.clearActiveBufferRegion();
  19100. }
  19101. }
  19102. END_JUCE_NAMESPACE
  19103. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19104. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19105. BEGIN_JUCE_NAMESPACE
  19106. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19107. const bool deleteInputWhenDeleted_)
  19108. : input (inputSource),
  19109. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19110. ratio (1.0),
  19111. lastRatio (1.0),
  19112. buffer (2, 0),
  19113. sampsInBuffer (0)
  19114. {
  19115. jassert (input != 0);
  19116. }
  19117. ResamplingAudioSource::~ResamplingAudioSource()
  19118. {
  19119. if (deleteInputWhenDeleted)
  19120. delete input;
  19121. }
  19122. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19123. {
  19124. jassert (samplesInPerOutputSample > 0);
  19125. const ScopedLock sl (ratioLock);
  19126. ratio = jmax (0.0, samplesInPerOutputSample);
  19127. }
  19128. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19129. double sampleRate)
  19130. {
  19131. const ScopedLock sl (ratioLock);
  19132. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19133. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19134. buffer.clear();
  19135. sampsInBuffer = 0;
  19136. bufferPos = 0;
  19137. subSampleOffset = 0.0;
  19138. createLowPass (ratio);
  19139. resetFilters();
  19140. }
  19141. void ResamplingAudioSource::releaseResources()
  19142. {
  19143. input->releaseResources();
  19144. buffer.setSize (2, 0);
  19145. }
  19146. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19147. {
  19148. const ScopedLock sl (ratioLock);
  19149. if (lastRatio != ratio)
  19150. {
  19151. createLowPass (ratio);
  19152. lastRatio = ratio;
  19153. }
  19154. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19155. int bufferSize = buffer.getNumSamples();
  19156. if (bufferSize < sampsNeeded + 8)
  19157. {
  19158. bufferPos %= bufferSize;
  19159. bufferSize = sampsNeeded + 32;
  19160. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19161. }
  19162. bufferPos %= bufferSize;
  19163. int endOfBufferPos = bufferPos + sampsInBuffer;
  19164. while (sampsNeeded > sampsInBuffer)
  19165. {
  19166. endOfBufferPos %= bufferSize;
  19167. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19168. bufferSize - endOfBufferPos);
  19169. AudioSourceChannelInfo readInfo;
  19170. readInfo.buffer = &buffer;
  19171. readInfo.numSamples = numToDo;
  19172. readInfo.startSample = endOfBufferPos;
  19173. input->getNextAudioBlock (readInfo);
  19174. if (ratio > 1.0001)
  19175. {
  19176. // for down-sampling, pre-apply the filter..
  19177. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19178. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19179. }
  19180. sampsInBuffer += numToDo;
  19181. endOfBufferPos += numToDo;
  19182. }
  19183. float* dl = info.buffer->getSampleData (0, info.startSample);
  19184. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19185. const float* const bl = buffer.getSampleData (0, 0);
  19186. const float* const br = buffer.getSampleData (1, 0);
  19187. int nextPos = (bufferPos + 1) % bufferSize;
  19188. for (int m = info.numSamples; --m >= 0;)
  19189. {
  19190. const float alpha = (float) subSampleOffset;
  19191. const float invAlpha = 1.0f - alpha;
  19192. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19193. if (dr != 0)
  19194. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19195. subSampleOffset += ratio;
  19196. jassert (sampsInBuffer > 0);
  19197. while (subSampleOffset >= 1.0)
  19198. {
  19199. if (++bufferPos >= bufferSize)
  19200. bufferPos = 0;
  19201. --sampsInBuffer;
  19202. nextPos = (bufferPos + 1) % bufferSize;
  19203. subSampleOffset -= 1.0;
  19204. }
  19205. }
  19206. if (ratio < 0.9999)
  19207. {
  19208. // for up-sampling, apply the filter after transposing..
  19209. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19210. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19211. }
  19212. else if (ratio <= 1.0001)
  19213. {
  19214. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19215. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19216. {
  19217. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19218. FilterState& fs = filterStates[i];
  19219. if (info.numSamples > 1)
  19220. {
  19221. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19222. }
  19223. else
  19224. {
  19225. fs.y2 = fs.y1;
  19226. fs.x2 = fs.x1;
  19227. }
  19228. fs.y1 = fs.x1 = *endOfBuffer;
  19229. }
  19230. }
  19231. jassert (sampsInBuffer >= 0);
  19232. }
  19233. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19234. {
  19235. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19236. : 0.5 * frequencyRatio;
  19237. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19238. const double nSquared = n * n;
  19239. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19240. setFilterCoefficients (c1,
  19241. c1 * 2.0f,
  19242. c1,
  19243. 1.0,
  19244. c1 * 2.0 * (1.0 - nSquared),
  19245. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19246. }
  19247. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19248. {
  19249. const double a = 1.0 / c4;
  19250. c1 *= a;
  19251. c2 *= a;
  19252. c3 *= a;
  19253. c5 *= a;
  19254. c6 *= a;
  19255. coefficients[0] = c1;
  19256. coefficients[1] = c2;
  19257. coefficients[2] = c3;
  19258. coefficients[3] = c4;
  19259. coefficients[4] = c5;
  19260. coefficients[5] = c6;
  19261. }
  19262. void ResamplingAudioSource::resetFilters()
  19263. {
  19264. zeromem (filterStates, sizeof (filterStates));
  19265. }
  19266. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19267. {
  19268. while (--num >= 0)
  19269. {
  19270. const double in = *samples;
  19271. double out = coefficients[0] * in
  19272. + coefficients[1] * fs.x1
  19273. + coefficients[2] * fs.x2
  19274. - coefficients[4] * fs.y1
  19275. - coefficients[5] * fs.y2;
  19276. #if JUCE_INTEL
  19277. if (! (out < -1.0e-8 || out > 1.0e-8))
  19278. out = 0;
  19279. #endif
  19280. fs.x2 = fs.x1;
  19281. fs.x1 = in;
  19282. fs.y2 = fs.y1;
  19283. fs.y1 = out;
  19284. *samples++ = (float) out;
  19285. }
  19286. }
  19287. END_JUCE_NAMESPACE
  19288. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19289. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19290. BEGIN_JUCE_NAMESPACE
  19291. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19292. : frequency (1000.0),
  19293. sampleRate (44100.0),
  19294. currentPhase (0.0),
  19295. phasePerSample (0.0),
  19296. amplitude (0.5f)
  19297. {
  19298. }
  19299. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19300. {
  19301. }
  19302. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19303. {
  19304. amplitude = newAmplitude;
  19305. }
  19306. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19307. {
  19308. frequency = newFrequencyHz;
  19309. phasePerSample = 0.0;
  19310. }
  19311. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19312. double sampleRate_)
  19313. {
  19314. currentPhase = 0.0;
  19315. phasePerSample = 0.0;
  19316. sampleRate = sampleRate_;
  19317. }
  19318. void ToneGeneratorAudioSource::releaseResources()
  19319. {
  19320. }
  19321. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19322. {
  19323. if (phasePerSample == 0.0)
  19324. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19325. for (int i = 0; i < info.numSamples; ++i)
  19326. {
  19327. const float sample = amplitude * (float) std::sin (currentPhase);
  19328. currentPhase += phasePerSample;
  19329. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19330. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19331. }
  19332. }
  19333. END_JUCE_NAMESPACE
  19334. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19335. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19336. BEGIN_JUCE_NAMESPACE
  19337. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19338. : sampleRate (0),
  19339. bufferSize (0),
  19340. useDefaultInputChannels (true),
  19341. useDefaultOutputChannels (true)
  19342. {
  19343. }
  19344. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19345. {
  19346. return outputDeviceName == other.outputDeviceName
  19347. && inputDeviceName == other.inputDeviceName
  19348. && sampleRate == other.sampleRate
  19349. && bufferSize == other.bufferSize
  19350. && inputChannels == other.inputChannels
  19351. && useDefaultInputChannels == other.useDefaultInputChannels
  19352. && outputChannels == other.outputChannels
  19353. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19354. }
  19355. AudioDeviceManager::AudioDeviceManager()
  19356. : currentAudioDevice (0),
  19357. numInputChansNeeded (0),
  19358. numOutputChansNeeded (2),
  19359. listNeedsScanning (true),
  19360. useInputNames (false),
  19361. inputLevelMeasurementEnabledCount (0),
  19362. inputLevel (0),
  19363. tempBuffer (2, 2),
  19364. defaultMidiOutput (0),
  19365. cpuUsageMs (0),
  19366. timeToCpuScale (0)
  19367. {
  19368. callbackHandler.owner = this;
  19369. }
  19370. AudioDeviceManager::~AudioDeviceManager()
  19371. {
  19372. currentAudioDevice = 0;
  19373. defaultMidiOutput = 0;
  19374. }
  19375. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19376. {
  19377. if (availableDeviceTypes.size() == 0)
  19378. {
  19379. createAudioDeviceTypes (availableDeviceTypes);
  19380. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19381. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19382. if (availableDeviceTypes.size() > 0)
  19383. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19384. }
  19385. }
  19386. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19387. {
  19388. scanDevicesIfNeeded();
  19389. return availableDeviceTypes;
  19390. }
  19391. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19392. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19393. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19394. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19395. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19396. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19397. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19398. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19399. {
  19400. (void) list; // (to avoid 'unused param' warnings)
  19401. #if JUCE_WINDOWS
  19402. #if JUCE_WASAPI
  19403. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19404. list.add (juce_createAudioIODeviceType_WASAPI());
  19405. #endif
  19406. #if JUCE_DIRECTSOUND
  19407. list.add (juce_createAudioIODeviceType_DirectSound());
  19408. #endif
  19409. #if JUCE_ASIO
  19410. list.add (juce_createAudioIODeviceType_ASIO());
  19411. #endif
  19412. #endif
  19413. #if JUCE_MAC
  19414. list.add (juce_createAudioIODeviceType_CoreAudio());
  19415. #endif
  19416. #if JUCE_IPHONE
  19417. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19418. #endif
  19419. #if JUCE_LINUX && JUCE_ALSA
  19420. list.add (juce_createAudioIODeviceType_ALSA());
  19421. #endif
  19422. #if JUCE_LINUX && JUCE_JACK
  19423. list.add (juce_createAudioIODeviceType_JACK());
  19424. #endif
  19425. }
  19426. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19427. const int numOutputChannelsNeeded,
  19428. const XmlElement* const e,
  19429. const bool selectDefaultDeviceOnFailure,
  19430. const String& preferredDefaultDeviceName,
  19431. const AudioDeviceSetup* preferredSetupOptions)
  19432. {
  19433. scanDevicesIfNeeded();
  19434. numInputChansNeeded = numInputChannelsNeeded;
  19435. numOutputChansNeeded = numOutputChannelsNeeded;
  19436. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19437. {
  19438. lastExplicitSettings = new XmlElement (*e);
  19439. String error;
  19440. AudioDeviceSetup setup;
  19441. if (preferredSetupOptions != 0)
  19442. setup = *preferredSetupOptions;
  19443. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19444. {
  19445. setup.inputDeviceName = setup.outputDeviceName
  19446. = e->getStringAttribute ("audioDeviceName");
  19447. }
  19448. else
  19449. {
  19450. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19451. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19452. }
  19453. currentDeviceType = e->getStringAttribute ("deviceType");
  19454. if (currentDeviceType.isEmpty())
  19455. {
  19456. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19457. if (type != 0)
  19458. currentDeviceType = type->getTypeName();
  19459. else if (availableDeviceTypes.size() > 0)
  19460. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19461. }
  19462. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19463. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19464. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19465. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19466. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19467. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19468. error = setAudioDeviceSetup (setup, true);
  19469. midiInsFromXml.clear();
  19470. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19471. midiInsFromXml.add (c->getStringAttribute ("name"));
  19472. const StringArray allMidiIns (MidiInput::getDevices());
  19473. for (int i = allMidiIns.size(); --i >= 0;)
  19474. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19475. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19476. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19477. false, preferredDefaultDeviceName);
  19478. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19479. return error;
  19480. }
  19481. else
  19482. {
  19483. AudioDeviceSetup setup;
  19484. if (preferredSetupOptions != 0)
  19485. {
  19486. setup = *preferredSetupOptions;
  19487. }
  19488. else if (preferredDefaultDeviceName.isNotEmpty())
  19489. {
  19490. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19491. {
  19492. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19493. StringArray outs (type->getDeviceNames (false));
  19494. int i;
  19495. for (i = 0; i < outs.size(); ++i)
  19496. {
  19497. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19498. {
  19499. setup.outputDeviceName = outs[i];
  19500. break;
  19501. }
  19502. }
  19503. StringArray ins (type->getDeviceNames (true));
  19504. for (i = 0; i < ins.size(); ++i)
  19505. {
  19506. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19507. {
  19508. setup.inputDeviceName = ins[i];
  19509. break;
  19510. }
  19511. }
  19512. }
  19513. }
  19514. insertDefaultDeviceNames (setup);
  19515. return setAudioDeviceSetup (setup, false);
  19516. }
  19517. }
  19518. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19519. {
  19520. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19521. if (type != 0)
  19522. {
  19523. if (setup.outputDeviceName.isEmpty())
  19524. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19525. if (setup.inputDeviceName.isEmpty())
  19526. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19527. }
  19528. }
  19529. XmlElement* AudioDeviceManager::createStateXml() const
  19530. {
  19531. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19532. }
  19533. void AudioDeviceManager::scanDevicesIfNeeded()
  19534. {
  19535. if (listNeedsScanning)
  19536. {
  19537. listNeedsScanning = false;
  19538. createDeviceTypesIfNeeded();
  19539. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19540. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19541. }
  19542. }
  19543. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19544. {
  19545. scanDevicesIfNeeded();
  19546. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19547. {
  19548. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19549. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19550. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19551. {
  19552. return type;
  19553. }
  19554. }
  19555. return 0;
  19556. }
  19557. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19558. {
  19559. setup = currentSetup;
  19560. }
  19561. void AudioDeviceManager::deleteCurrentDevice()
  19562. {
  19563. currentAudioDevice = 0;
  19564. currentSetup.inputDeviceName = String::empty;
  19565. currentSetup.outputDeviceName = String::empty;
  19566. }
  19567. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19568. const bool treatAsChosenDevice)
  19569. {
  19570. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19571. {
  19572. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19573. && currentDeviceType != type)
  19574. {
  19575. currentDeviceType = type;
  19576. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19577. insertDefaultDeviceNames (s);
  19578. setAudioDeviceSetup (s, treatAsChosenDevice);
  19579. sendChangeMessage (this);
  19580. break;
  19581. }
  19582. }
  19583. }
  19584. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19585. {
  19586. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19587. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19588. return availableDeviceTypes[i];
  19589. return availableDeviceTypes[0];
  19590. }
  19591. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19592. const bool treatAsChosenDevice)
  19593. {
  19594. jassert (&newSetup != &currentSetup); // this will have no effect
  19595. if (newSetup == currentSetup && currentAudioDevice != 0)
  19596. return String::empty;
  19597. if (! (newSetup == currentSetup))
  19598. sendChangeMessage (this);
  19599. stopDevice();
  19600. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19601. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19602. String error;
  19603. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19604. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19605. {
  19606. deleteCurrentDevice();
  19607. if (treatAsChosenDevice)
  19608. updateXml();
  19609. return String::empty;
  19610. }
  19611. if (currentSetup.inputDeviceName != newInputDeviceName
  19612. || currentSetup.outputDeviceName != newOutputDeviceName
  19613. || currentAudioDevice == 0)
  19614. {
  19615. deleteCurrentDevice();
  19616. scanDevicesIfNeeded();
  19617. if (newOutputDeviceName.isNotEmpty()
  19618. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19619. {
  19620. return "No such device: " + newOutputDeviceName;
  19621. }
  19622. if (newInputDeviceName.isNotEmpty()
  19623. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19624. {
  19625. return "No such device: " + newInputDeviceName;
  19626. }
  19627. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19628. if (currentAudioDevice == 0)
  19629. 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!";
  19630. else
  19631. error = currentAudioDevice->getLastError();
  19632. if (error.isNotEmpty())
  19633. {
  19634. deleteCurrentDevice();
  19635. return error;
  19636. }
  19637. if (newSetup.useDefaultInputChannels)
  19638. {
  19639. inputChannels.clear();
  19640. inputChannels.setRange (0, numInputChansNeeded, true);
  19641. }
  19642. if (newSetup.useDefaultOutputChannels)
  19643. {
  19644. outputChannels.clear();
  19645. outputChannels.setRange (0, numOutputChansNeeded, true);
  19646. }
  19647. if (newInputDeviceName.isEmpty())
  19648. inputChannels.clear();
  19649. if (newOutputDeviceName.isEmpty())
  19650. outputChannels.clear();
  19651. }
  19652. if (! newSetup.useDefaultInputChannels)
  19653. inputChannels = newSetup.inputChannels;
  19654. if (! newSetup.useDefaultOutputChannels)
  19655. outputChannels = newSetup.outputChannels;
  19656. currentSetup = newSetup;
  19657. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19658. error = currentAudioDevice->open (inputChannels,
  19659. outputChannels,
  19660. currentSetup.sampleRate,
  19661. currentSetup.bufferSize);
  19662. if (error.isEmpty())
  19663. {
  19664. currentDeviceType = currentAudioDevice->getTypeName();
  19665. currentAudioDevice->start (&callbackHandler);
  19666. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19667. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19668. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19669. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19670. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19671. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19672. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19673. if (treatAsChosenDevice)
  19674. updateXml();
  19675. }
  19676. else
  19677. {
  19678. deleteCurrentDevice();
  19679. }
  19680. return error;
  19681. }
  19682. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19683. {
  19684. jassert (currentAudioDevice != 0);
  19685. if (rate > 0)
  19686. {
  19687. bool ok = false;
  19688. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19689. {
  19690. const double sr = currentAudioDevice->getSampleRate (i);
  19691. if (sr == rate)
  19692. ok = true;
  19693. }
  19694. if (! ok)
  19695. rate = 0;
  19696. }
  19697. if (rate == 0)
  19698. {
  19699. double lowestAbove44 = 0.0;
  19700. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19701. {
  19702. const double sr = currentAudioDevice->getSampleRate (i);
  19703. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19704. lowestAbove44 = sr;
  19705. }
  19706. if (lowestAbove44 == 0.0)
  19707. rate = currentAudioDevice->getSampleRate (0);
  19708. else
  19709. rate = lowestAbove44;
  19710. }
  19711. return rate;
  19712. }
  19713. void AudioDeviceManager::stopDevice()
  19714. {
  19715. if (currentAudioDevice != 0)
  19716. currentAudioDevice->stop();
  19717. testSound = 0;
  19718. }
  19719. void AudioDeviceManager::closeAudioDevice()
  19720. {
  19721. stopDevice();
  19722. currentAudioDevice = 0;
  19723. }
  19724. void AudioDeviceManager::restartLastAudioDevice()
  19725. {
  19726. if (currentAudioDevice == 0)
  19727. {
  19728. if (currentSetup.inputDeviceName.isEmpty()
  19729. && currentSetup.outputDeviceName.isEmpty())
  19730. {
  19731. // This method will only reload the last device that was running
  19732. // before closeAudioDevice() was called - you need to actually open
  19733. // one first, with setAudioDevice().
  19734. jassertfalse;
  19735. return;
  19736. }
  19737. AudioDeviceSetup s (currentSetup);
  19738. setAudioDeviceSetup (s, false);
  19739. }
  19740. }
  19741. void AudioDeviceManager::updateXml()
  19742. {
  19743. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19744. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19745. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19746. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19747. if (currentAudioDevice != 0)
  19748. {
  19749. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19750. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19751. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19752. if (! currentSetup.useDefaultInputChannels)
  19753. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19754. if (! currentSetup.useDefaultOutputChannels)
  19755. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19756. }
  19757. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19758. {
  19759. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19760. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19761. }
  19762. if (midiInsFromXml.size() > 0)
  19763. {
  19764. // Add any midi devices that have been enabled before, but which aren't currently
  19765. // open because the device has been disconnected.
  19766. const StringArray availableMidiDevices (MidiInput::getDevices());
  19767. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19768. {
  19769. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19770. {
  19771. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19772. m->setAttribute ("name", midiInsFromXml[i]);
  19773. }
  19774. }
  19775. }
  19776. if (defaultMidiOutputName.isNotEmpty())
  19777. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19778. }
  19779. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19780. {
  19781. {
  19782. const ScopedLock sl (audioCallbackLock);
  19783. if (callbacks.contains (newCallback))
  19784. return;
  19785. }
  19786. if (currentAudioDevice != 0 && newCallback != 0)
  19787. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19788. const ScopedLock sl (audioCallbackLock);
  19789. callbacks.add (newCallback);
  19790. }
  19791. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19792. {
  19793. if (callback != 0)
  19794. {
  19795. bool needsDeinitialising = currentAudioDevice != 0;
  19796. {
  19797. const ScopedLock sl (audioCallbackLock);
  19798. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19799. callbacks.removeValue (callback);
  19800. }
  19801. if (needsDeinitialising)
  19802. callback->audioDeviceStopped();
  19803. }
  19804. }
  19805. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19806. int numInputChannels,
  19807. float** outputChannelData,
  19808. int numOutputChannels,
  19809. int numSamples)
  19810. {
  19811. const ScopedLock sl (audioCallbackLock);
  19812. if (inputLevelMeasurementEnabledCount > 0)
  19813. {
  19814. for (int j = 0; j < numSamples; ++j)
  19815. {
  19816. float s = 0;
  19817. for (int i = 0; i < numInputChannels; ++i)
  19818. s += std::abs (inputChannelData[i][j]);
  19819. s /= numInputChannels;
  19820. const double decayFactor = 0.99992;
  19821. if (s > inputLevel)
  19822. inputLevel = s;
  19823. else if (inputLevel > 0.001f)
  19824. inputLevel *= decayFactor;
  19825. else
  19826. inputLevel = 0;
  19827. }
  19828. }
  19829. if (callbacks.size() > 0)
  19830. {
  19831. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19832. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19833. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19834. outputChannelData, numOutputChannels, numSamples);
  19835. float** const tempChans = tempBuffer.getArrayOfChannels();
  19836. for (int i = callbacks.size(); --i > 0;)
  19837. {
  19838. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19839. tempChans, numOutputChannels, numSamples);
  19840. for (int chan = 0; chan < numOutputChannels; ++chan)
  19841. {
  19842. const float* const src = tempChans [chan];
  19843. float* const dst = outputChannelData [chan];
  19844. if (src != 0 && dst != 0)
  19845. for (int j = 0; j < numSamples; ++j)
  19846. dst[j] += src[j];
  19847. }
  19848. }
  19849. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19850. const double filterAmount = 0.2;
  19851. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19852. }
  19853. else
  19854. {
  19855. for (int i = 0; i < numOutputChannels; ++i)
  19856. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19857. }
  19858. if (testSound != 0)
  19859. {
  19860. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19861. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19862. for (int i = 0; i < numOutputChannels; ++i)
  19863. for (int j = 0; j < numSamps; ++j)
  19864. outputChannelData [i][j] += src[j];
  19865. testSoundPosition += numSamps;
  19866. if (testSoundPosition >= testSound->getNumSamples())
  19867. testSound = 0;
  19868. }
  19869. }
  19870. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19871. {
  19872. cpuUsageMs = 0;
  19873. const double sampleRate = device->getCurrentSampleRate();
  19874. const int blockSize = device->getCurrentBufferSizeSamples();
  19875. if (sampleRate > 0.0 && blockSize > 0)
  19876. {
  19877. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19878. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19879. }
  19880. {
  19881. const ScopedLock sl (audioCallbackLock);
  19882. for (int i = callbacks.size(); --i >= 0;)
  19883. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19884. }
  19885. sendChangeMessage (this);
  19886. }
  19887. void AudioDeviceManager::audioDeviceStoppedInt()
  19888. {
  19889. cpuUsageMs = 0;
  19890. timeToCpuScale = 0;
  19891. sendChangeMessage (this);
  19892. const ScopedLock sl (audioCallbackLock);
  19893. for (int i = callbacks.size(); --i >= 0;)
  19894. callbacks.getUnchecked(i)->audioDeviceStopped();
  19895. }
  19896. double AudioDeviceManager::getCpuUsage() const
  19897. {
  19898. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19899. }
  19900. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19901. const bool enabled)
  19902. {
  19903. if (enabled != isMidiInputEnabled (name))
  19904. {
  19905. if (enabled)
  19906. {
  19907. const int index = MidiInput::getDevices().indexOf (name);
  19908. if (index >= 0)
  19909. {
  19910. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19911. if (min != 0)
  19912. {
  19913. enabledMidiInputs.add (min);
  19914. min->start();
  19915. }
  19916. }
  19917. }
  19918. else
  19919. {
  19920. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19921. if (enabledMidiInputs[i]->getName() == name)
  19922. enabledMidiInputs.remove (i);
  19923. }
  19924. updateXml();
  19925. sendChangeMessage (this);
  19926. }
  19927. }
  19928. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19929. {
  19930. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19931. if (enabledMidiInputs[i]->getName() == name)
  19932. return true;
  19933. return false;
  19934. }
  19935. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19936. MidiInputCallback* callback)
  19937. {
  19938. removeMidiInputCallback (name, callback);
  19939. if (name.isEmpty())
  19940. {
  19941. midiCallbacks.add (callback);
  19942. midiCallbackDevices.add (0);
  19943. }
  19944. else
  19945. {
  19946. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19947. {
  19948. if (enabledMidiInputs[i]->getName() == name)
  19949. {
  19950. const ScopedLock sl (midiCallbackLock);
  19951. midiCallbacks.add (callback);
  19952. midiCallbackDevices.add (enabledMidiInputs[i]);
  19953. break;
  19954. }
  19955. }
  19956. }
  19957. }
  19958. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19959. MidiInputCallback* /*callback*/)
  19960. {
  19961. const ScopedLock sl (midiCallbackLock);
  19962. for (int i = midiCallbacks.size(); --i >= 0;)
  19963. {
  19964. String devName;
  19965. if (midiCallbackDevices.getUnchecked(i) != 0)
  19966. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19967. if (devName == name)
  19968. {
  19969. midiCallbacks.remove (i);
  19970. midiCallbackDevices.remove (i);
  19971. }
  19972. }
  19973. }
  19974. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19975. const MidiMessage& message)
  19976. {
  19977. if (! message.isActiveSense())
  19978. {
  19979. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19980. const ScopedLock sl (midiCallbackLock);
  19981. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19982. {
  19983. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19984. if (md == source || (md == 0 && isDefaultSource))
  19985. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19986. }
  19987. }
  19988. }
  19989. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19990. {
  19991. if (defaultMidiOutputName != deviceName)
  19992. {
  19993. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19994. {
  19995. const ScopedLock sl (audioCallbackLock);
  19996. oldCallbacks = callbacks;
  19997. callbacks.clear();
  19998. }
  19999. if (currentAudioDevice != 0)
  20000. for (int i = oldCallbacks.size(); --i >= 0;)
  20001. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20002. defaultMidiOutput = 0;
  20003. defaultMidiOutputName = deviceName;
  20004. if (deviceName.isNotEmpty())
  20005. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20006. if (currentAudioDevice != 0)
  20007. for (int i = oldCallbacks.size(); --i >= 0;)
  20008. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20009. {
  20010. const ScopedLock sl (audioCallbackLock);
  20011. callbacks = oldCallbacks;
  20012. }
  20013. updateXml();
  20014. sendChangeMessage (this);
  20015. }
  20016. }
  20017. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20018. int numInputChannels,
  20019. float** outputChannelData,
  20020. int numOutputChannels,
  20021. int numSamples)
  20022. {
  20023. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20024. }
  20025. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20026. {
  20027. owner->audioDeviceAboutToStartInt (device);
  20028. }
  20029. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20030. {
  20031. owner->audioDeviceStoppedInt();
  20032. }
  20033. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20034. {
  20035. owner->handleIncomingMidiMessageInt (source, message);
  20036. }
  20037. void AudioDeviceManager::playTestSound()
  20038. {
  20039. { // cunningly nested to swap, unlock and delete in that order.
  20040. ScopedPointer <AudioSampleBuffer> oldSound;
  20041. {
  20042. const ScopedLock sl (audioCallbackLock);
  20043. oldSound = testSound;
  20044. }
  20045. }
  20046. testSoundPosition = 0;
  20047. if (currentAudioDevice != 0)
  20048. {
  20049. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20050. const int soundLength = (int) sampleRate;
  20051. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20052. float* samples = newSound->getSampleData (0);
  20053. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20054. const float amplitude = 0.5f;
  20055. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20056. for (int i = 0; i < soundLength; ++i)
  20057. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20058. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20059. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20060. const ScopedLock sl (audioCallbackLock);
  20061. testSound = newSound;
  20062. }
  20063. }
  20064. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20065. {
  20066. const ScopedLock sl (audioCallbackLock);
  20067. if (enableMeasurement)
  20068. ++inputLevelMeasurementEnabledCount;
  20069. else
  20070. --inputLevelMeasurementEnabledCount;
  20071. inputLevel = 0;
  20072. }
  20073. double AudioDeviceManager::getCurrentInputLevel() const
  20074. {
  20075. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20076. return inputLevel;
  20077. }
  20078. END_JUCE_NAMESPACE
  20079. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20080. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20081. BEGIN_JUCE_NAMESPACE
  20082. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20083. : name (deviceName),
  20084. typeName (typeName_)
  20085. {
  20086. }
  20087. AudioIODevice::~AudioIODevice()
  20088. {
  20089. }
  20090. bool AudioIODevice::hasControlPanel() const
  20091. {
  20092. return false;
  20093. }
  20094. bool AudioIODevice::showControlPanel()
  20095. {
  20096. jassertfalse; // this should only be called for devices which return true from
  20097. // their hasControlPanel() method.
  20098. return false;
  20099. }
  20100. END_JUCE_NAMESPACE
  20101. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20102. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20103. BEGIN_JUCE_NAMESPACE
  20104. AudioIODeviceType::AudioIODeviceType (const String& name)
  20105. : typeName (name)
  20106. {
  20107. }
  20108. AudioIODeviceType::~AudioIODeviceType()
  20109. {
  20110. }
  20111. END_JUCE_NAMESPACE
  20112. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20113. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20114. BEGIN_JUCE_NAMESPACE
  20115. MidiOutput::MidiOutput()
  20116. : Thread ("midi out"),
  20117. internal (0),
  20118. firstMessage (0)
  20119. {
  20120. }
  20121. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20122. const double sampleNumber)
  20123. : message (data, len, sampleNumber)
  20124. {
  20125. }
  20126. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20127. const double millisecondCounterToStartAt,
  20128. double samplesPerSecondForBuffer)
  20129. {
  20130. // You've got to call startBackgroundThread() for this to actually work..
  20131. jassert (isThreadRunning());
  20132. // this needs to be a value in the future - RTFM for this method!
  20133. jassert (millisecondCounterToStartAt > 0);
  20134. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20135. MidiBuffer::Iterator i (buffer);
  20136. const uint8* data;
  20137. int len, time;
  20138. while (i.getNextEvent (data, len, time))
  20139. {
  20140. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20141. PendingMessage* const m
  20142. = new PendingMessage (data, len, eventTime);
  20143. const ScopedLock sl (lock);
  20144. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20145. {
  20146. m->next = firstMessage;
  20147. firstMessage = m;
  20148. }
  20149. else
  20150. {
  20151. PendingMessage* mm = firstMessage;
  20152. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20153. mm = mm->next;
  20154. m->next = mm->next;
  20155. mm->next = m;
  20156. }
  20157. }
  20158. notify();
  20159. }
  20160. void MidiOutput::clearAllPendingMessages()
  20161. {
  20162. const ScopedLock sl (lock);
  20163. while (firstMessage != 0)
  20164. {
  20165. PendingMessage* const m = firstMessage;
  20166. firstMessage = firstMessage->next;
  20167. delete m;
  20168. }
  20169. }
  20170. void MidiOutput::startBackgroundThread()
  20171. {
  20172. startThread (9);
  20173. }
  20174. void MidiOutput::stopBackgroundThread()
  20175. {
  20176. stopThread (5000);
  20177. }
  20178. void MidiOutput::run()
  20179. {
  20180. while (! threadShouldExit())
  20181. {
  20182. uint32 now = Time::getMillisecondCounter();
  20183. uint32 eventTime = 0;
  20184. uint32 timeToWait = 500;
  20185. PendingMessage* message;
  20186. {
  20187. const ScopedLock sl (lock);
  20188. message = firstMessage;
  20189. if (message != 0)
  20190. {
  20191. eventTime = roundToInt (message->message.getTimeStamp());
  20192. if (eventTime > now + 20)
  20193. {
  20194. timeToWait = eventTime - (now + 20);
  20195. message = 0;
  20196. }
  20197. else
  20198. {
  20199. firstMessage = message->next;
  20200. }
  20201. }
  20202. }
  20203. if (message != 0)
  20204. {
  20205. if (eventTime > now)
  20206. {
  20207. Time::waitForMillisecondCounter (eventTime);
  20208. if (threadShouldExit())
  20209. break;
  20210. }
  20211. if (eventTime > now - 200)
  20212. sendMessageNow (message->message);
  20213. delete message;
  20214. }
  20215. else
  20216. {
  20217. jassert (timeToWait < 1000 * 30);
  20218. wait (timeToWait);
  20219. }
  20220. }
  20221. clearAllPendingMessages();
  20222. }
  20223. END_JUCE_NAMESPACE
  20224. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20225. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20226. BEGIN_JUCE_NAMESPACE
  20227. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20228. {
  20229. const double maxVal = (double) 0x7fff;
  20230. char* intData = static_cast <char*> (dest);
  20231. if (dest != (void*) source || destBytesPerSample <= 4)
  20232. {
  20233. for (int i = 0; i < numSamples; ++i)
  20234. {
  20235. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20236. intData += destBytesPerSample;
  20237. }
  20238. }
  20239. else
  20240. {
  20241. intData += destBytesPerSample * numSamples;
  20242. for (int i = numSamples; --i >= 0;)
  20243. {
  20244. intData -= destBytesPerSample;
  20245. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20246. }
  20247. }
  20248. }
  20249. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20250. {
  20251. const double maxVal = (double) 0x7fff;
  20252. char* intData = static_cast <char*> (dest);
  20253. if (dest != (void*) source || destBytesPerSample <= 4)
  20254. {
  20255. for (int i = 0; i < numSamples; ++i)
  20256. {
  20257. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20258. intData += destBytesPerSample;
  20259. }
  20260. }
  20261. else
  20262. {
  20263. intData += destBytesPerSample * numSamples;
  20264. for (int i = numSamples; --i >= 0;)
  20265. {
  20266. intData -= destBytesPerSample;
  20267. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20268. }
  20269. }
  20270. }
  20271. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20272. {
  20273. const double maxVal = (double) 0x7fffff;
  20274. char* intData = static_cast <char*> (dest);
  20275. if (dest != (void*) source || destBytesPerSample <= 4)
  20276. {
  20277. for (int i = 0; i < numSamples; ++i)
  20278. {
  20279. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20280. intData += destBytesPerSample;
  20281. }
  20282. }
  20283. else
  20284. {
  20285. intData += destBytesPerSample * numSamples;
  20286. for (int i = numSamples; --i >= 0;)
  20287. {
  20288. intData -= destBytesPerSample;
  20289. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20290. }
  20291. }
  20292. }
  20293. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20294. {
  20295. const double maxVal = (double) 0x7fffff;
  20296. char* intData = static_cast <char*> (dest);
  20297. if (dest != (void*) source || destBytesPerSample <= 4)
  20298. {
  20299. for (int i = 0; i < numSamples; ++i)
  20300. {
  20301. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20302. intData += destBytesPerSample;
  20303. }
  20304. }
  20305. else
  20306. {
  20307. intData += destBytesPerSample * numSamples;
  20308. for (int i = numSamples; --i >= 0;)
  20309. {
  20310. intData -= destBytesPerSample;
  20311. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20312. }
  20313. }
  20314. }
  20315. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20316. {
  20317. const double maxVal = (double) 0x7fffffff;
  20318. char* intData = static_cast <char*> (dest);
  20319. if (dest != (void*) source || destBytesPerSample <= 4)
  20320. {
  20321. for (int i = 0; i < numSamples; ++i)
  20322. {
  20323. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20324. intData += destBytesPerSample;
  20325. }
  20326. }
  20327. else
  20328. {
  20329. intData += destBytesPerSample * numSamples;
  20330. for (int i = numSamples; --i >= 0;)
  20331. {
  20332. intData -= destBytesPerSample;
  20333. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20334. }
  20335. }
  20336. }
  20337. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20338. {
  20339. const double maxVal = (double) 0x7fffffff;
  20340. char* intData = static_cast <char*> (dest);
  20341. if (dest != (void*) source || destBytesPerSample <= 4)
  20342. {
  20343. for (int i = 0; i < numSamples; ++i)
  20344. {
  20345. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20346. intData += destBytesPerSample;
  20347. }
  20348. }
  20349. else
  20350. {
  20351. intData += destBytesPerSample * numSamples;
  20352. for (int i = numSamples; --i >= 0;)
  20353. {
  20354. intData -= destBytesPerSample;
  20355. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20356. }
  20357. }
  20358. }
  20359. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20360. {
  20361. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20362. char* d = static_cast <char*> (dest);
  20363. for (int i = 0; i < numSamples; ++i)
  20364. {
  20365. *(float*) d = source[i];
  20366. #if JUCE_BIG_ENDIAN
  20367. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20368. #endif
  20369. d += destBytesPerSample;
  20370. }
  20371. }
  20372. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20373. {
  20374. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20375. char* d = static_cast <char*> (dest);
  20376. for (int i = 0; i < numSamples; ++i)
  20377. {
  20378. *(float*) d = source[i];
  20379. #if JUCE_LITTLE_ENDIAN
  20380. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20381. #endif
  20382. d += destBytesPerSample;
  20383. }
  20384. }
  20385. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20386. {
  20387. const float scale = 1.0f / 0x7fff;
  20388. const char* intData = static_cast <const char*> (source);
  20389. if (source != (void*) dest || srcBytesPerSample >= 4)
  20390. {
  20391. for (int i = 0; i < numSamples; ++i)
  20392. {
  20393. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20394. intData += srcBytesPerSample;
  20395. }
  20396. }
  20397. else
  20398. {
  20399. intData += srcBytesPerSample * numSamples;
  20400. for (int i = numSamples; --i >= 0;)
  20401. {
  20402. intData -= srcBytesPerSample;
  20403. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20404. }
  20405. }
  20406. }
  20407. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20408. {
  20409. const float scale = 1.0f / 0x7fff;
  20410. const char* intData = static_cast <const char*> (source);
  20411. if (source != (void*) dest || srcBytesPerSample >= 4)
  20412. {
  20413. for (int i = 0; i < numSamples; ++i)
  20414. {
  20415. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20416. intData += srcBytesPerSample;
  20417. }
  20418. }
  20419. else
  20420. {
  20421. intData += srcBytesPerSample * numSamples;
  20422. for (int i = numSamples; --i >= 0;)
  20423. {
  20424. intData -= srcBytesPerSample;
  20425. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20426. }
  20427. }
  20428. }
  20429. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20430. {
  20431. const float scale = 1.0f / 0x7fffff;
  20432. const char* intData = static_cast <const char*> (source);
  20433. if (source != (void*) dest || srcBytesPerSample >= 4)
  20434. {
  20435. for (int i = 0; i < numSamples; ++i)
  20436. {
  20437. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20438. intData += srcBytesPerSample;
  20439. }
  20440. }
  20441. else
  20442. {
  20443. intData += srcBytesPerSample * numSamples;
  20444. for (int i = numSamples; --i >= 0;)
  20445. {
  20446. intData -= srcBytesPerSample;
  20447. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20448. }
  20449. }
  20450. }
  20451. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20452. {
  20453. const float scale = 1.0f / 0x7fffff;
  20454. const char* intData = static_cast <const char*> (source);
  20455. if (source != (void*) dest || srcBytesPerSample >= 4)
  20456. {
  20457. for (int i = 0; i < numSamples; ++i)
  20458. {
  20459. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20460. intData += srcBytesPerSample;
  20461. }
  20462. }
  20463. else
  20464. {
  20465. intData += srcBytesPerSample * numSamples;
  20466. for (int i = numSamples; --i >= 0;)
  20467. {
  20468. intData -= srcBytesPerSample;
  20469. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20470. }
  20471. }
  20472. }
  20473. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20474. {
  20475. const float scale = 1.0f / 0x7fffffff;
  20476. const char* intData = static_cast <const char*> (source);
  20477. if (source != (void*) dest || srcBytesPerSample >= 4)
  20478. {
  20479. for (int i = 0; i < numSamples; ++i)
  20480. {
  20481. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20482. intData += srcBytesPerSample;
  20483. }
  20484. }
  20485. else
  20486. {
  20487. intData += srcBytesPerSample * numSamples;
  20488. for (int i = numSamples; --i >= 0;)
  20489. {
  20490. intData -= srcBytesPerSample;
  20491. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20492. }
  20493. }
  20494. }
  20495. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20496. {
  20497. const float scale = 1.0f / 0x7fffffff;
  20498. const char* intData = static_cast <const char*> (source);
  20499. if (source != (void*) dest || srcBytesPerSample >= 4)
  20500. {
  20501. for (int i = 0; i < numSamples; ++i)
  20502. {
  20503. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20504. intData += srcBytesPerSample;
  20505. }
  20506. }
  20507. else
  20508. {
  20509. intData += srcBytesPerSample * numSamples;
  20510. for (int i = numSamples; --i >= 0;)
  20511. {
  20512. intData -= srcBytesPerSample;
  20513. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20514. }
  20515. }
  20516. }
  20517. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20518. {
  20519. const char* s = static_cast <const char*> (source);
  20520. for (int i = 0; i < numSamples; ++i)
  20521. {
  20522. dest[i] = *(float*)s;
  20523. #if JUCE_BIG_ENDIAN
  20524. uint32* const d = (uint32*) (dest + i);
  20525. *d = ByteOrder::swap (*d);
  20526. #endif
  20527. s += srcBytesPerSample;
  20528. }
  20529. }
  20530. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20531. {
  20532. const char* s = static_cast <const char*> (source);
  20533. for (int i = 0; i < numSamples; ++i)
  20534. {
  20535. dest[i] = *(float*)s;
  20536. #if JUCE_LITTLE_ENDIAN
  20537. uint32* const d = (uint32*) (dest + i);
  20538. *d = ByteOrder::swap (*d);
  20539. #endif
  20540. s += srcBytesPerSample;
  20541. }
  20542. }
  20543. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20544. const float* const source,
  20545. void* const dest,
  20546. const int numSamples)
  20547. {
  20548. switch (destFormat)
  20549. {
  20550. case int16LE:
  20551. convertFloatToInt16LE (source, dest, numSamples);
  20552. break;
  20553. case int16BE:
  20554. convertFloatToInt16BE (source, dest, numSamples);
  20555. break;
  20556. case int24LE:
  20557. convertFloatToInt24LE (source, dest, numSamples);
  20558. break;
  20559. case int24BE:
  20560. convertFloatToInt24BE (source, dest, numSamples);
  20561. break;
  20562. case int32LE:
  20563. convertFloatToInt32LE (source, dest, numSamples);
  20564. break;
  20565. case int32BE:
  20566. convertFloatToInt32BE (source, dest, numSamples);
  20567. break;
  20568. case float32LE:
  20569. convertFloatToFloat32LE (source, dest, numSamples);
  20570. break;
  20571. case float32BE:
  20572. convertFloatToFloat32BE (source, dest, numSamples);
  20573. break;
  20574. default:
  20575. jassertfalse;
  20576. break;
  20577. }
  20578. }
  20579. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20580. const void* const source,
  20581. float* const dest,
  20582. const int numSamples)
  20583. {
  20584. switch (sourceFormat)
  20585. {
  20586. case int16LE:
  20587. convertInt16LEToFloat (source, dest, numSamples);
  20588. break;
  20589. case int16BE:
  20590. convertInt16BEToFloat (source, dest, numSamples);
  20591. break;
  20592. case int24LE:
  20593. convertInt24LEToFloat (source, dest, numSamples);
  20594. break;
  20595. case int24BE:
  20596. convertInt24BEToFloat (source, dest, numSamples);
  20597. break;
  20598. case int32LE:
  20599. convertInt32LEToFloat (source, dest, numSamples);
  20600. break;
  20601. case int32BE:
  20602. convertInt32BEToFloat (source, dest, numSamples);
  20603. break;
  20604. case float32LE:
  20605. convertFloat32LEToFloat (source, dest, numSamples);
  20606. break;
  20607. case float32BE:
  20608. convertFloat32BEToFloat (source, dest, numSamples);
  20609. break;
  20610. default:
  20611. jassertfalse;
  20612. break;
  20613. }
  20614. }
  20615. void AudioDataConverters::interleaveSamples (const float** const source,
  20616. float* const dest,
  20617. const int numSamples,
  20618. const int numChannels)
  20619. {
  20620. for (int chan = 0; chan < numChannels; ++chan)
  20621. {
  20622. int i = chan;
  20623. const float* src = source [chan];
  20624. for (int j = 0; j < numSamples; ++j)
  20625. {
  20626. dest [i] = src [j];
  20627. i += numChannels;
  20628. }
  20629. }
  20630. }
  20631. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20632. float** const dest,
  20633. const int numSamples,
  20634. const int numChannels)
  20635. {
  20636. for (int chan = 0; chan < numChannels; ++chan)
  20637. {
  20638. int i = chan;
  20639. float* dst = dest [chan];
  20640. for (int j = 0; j < numSamples; ++j)
  20641. {
  20642. dst [j] = source [i];
  20643. i += numChannels;
  20644. }
  20645. }
  20646. }
  20647. END_JUCE_NAMESPACE
  20648. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20649. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20650. BEGIN_JUCE_NAMESPACE
  20651. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20652. const int numSamples) throw()
  20653. : numChannels (numChannels_),
  20654. size (numSamples)
  20655. {
  20656. jassert (numSamples >= 0);
  20657. jassert (numChannels_ > 0);
  20658. allocateData();
  20659. }
  20660. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20661. : numChannels (other.numChannels),
  20662. size (other.size)
  20663. {
  20664. allocateData();
  20665. const size_t numBytes = size * sizeof (float);
  20666. for (int i = 0; i < numChannels; ++i)
  20667. memcpy (channels[i], other.channels[i], numBytes);
  20668. }
  20669. void AudioSampleBuffer::allocateData()
  20670. {
  20671. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20672. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20673. allocatedData.malloc (allocatedBytes);
  20674. channels = reinterpret_cast <float**> (allocatedData.getData());
  20675. float* chan = (float*) (allocatedData + channelListSize);
  20676. for (int i = 0; i < numChannels; ++i)
  20677. {
  20678. channels[i] = chan;
  20679. chan += size;
  20680. }
  20681. channels [numChannels] = 0;
  20682. }
  20683. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20684. const int numChannels_,
  20685. const int numSamples) throw()
  20686. : numChannels (numChannels_),
  20687. size (numSamples),
  20688. allocatedBytes (0)
  20689. {
  20690. jassert (numChannels_ > 0);
  20691. allocateChannels (dataToReferTo);
  20692. }
  20693. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20694. const int newNumChannels,
  20695. const int newNumSamples) throw()
  20696. {
  20697. jassert (newNumChannels > 0);
  20698. allocatedBytes = 0;
  20699. allocatedData.free();
  20700. numChannels = newNumChannels;
  20701. size = newNumSamples;
  20702. allocateChannels (dataToReferTo);
  20703. }
  20704. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20705. {
  20706. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20707. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20708. {
  20709. channels = static_cast <float**> (preallocatedChannelSpace);
  20710. }
  20711. else
  20712. {
  20713. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20714. channels = reinterpret_cast <float**> (allocatedData.getData());
  20715. }
  20716. for (int i = 0; i < numChannels; ++i)
  20717. {
  20718. // you have to pass in the same number of valid pointers as numChannels
  20719. jassert (dataToReferTo[i] != 0);
  20720. channels[i] = dataToReferTo[i];
  20721. }
  20722. channels [numChannels] = 0;
  20723. }
  20724. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20725. {
  20726. if (this != &other)
  20727. {
  20728. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20729. const size_t numBytes = size * sizeof (float);
  20730. for (int i = 0; i < numChannels; ++i)
  20731. memcpy (channels[i], other.channels[i], numBytes);
  20732. }
  20733. return *this;
  20734. }
  20735. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20736. {
  20737. }
  20738. void AudioSampleBuffer::setSize (const int newNumChannels,
  20739. const int newNumSamples,
  20740. const bool keepExistingContent,
  20741. const bool clearExtraSpace,
  20742. const bool avoidReallocating) throw()
  20743. {
  20744. jassert (newNumChannels > 0);
  20745. if (newNumSamples != size || newNumChannels != numChannels)
  20746. {
  20747. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20748. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20749. if (keepExistingContent)
  20750. {
  20751. HeapBlock <char> newData;
  20752. newData.allocate (newTotalBytes, clearExtraSpace);
  20753. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20754. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20755. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20756. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20757. for (int i = 0; i < numChansToCopy; ++i)
  20758. {
  20759. memcpy (newChan, channels[i], numBytesToCopy);
  20760. newChannels[i] = newChan;
  20761. newChan += newNumSamples;
  20762. }
  20763. allocatedData.swapWith (newData);
  20764. allocatedBytes = (int) newTotalBytes;
  20765. channels = newChannels;
  20766. }
  20767. else
  20768. {
  20769. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20770. {
  20771. if (clearExtraSpace)
  20772. zeromem (allocatedData, newTotalBytes);
  20773. }
  20774. else
  20775. {
  20776. allocatedBytes = newTotalBytes;
  20777. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20778. channels = reinterpret_cast <float**> (allocatedData.getData());
  20779. }
  20780. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20781. for (int i = 0; i < newNumChannels; ++i)
  20782. {
  20783. channels[i] = chan;
  20784. chan += newNumSamples;
  20785. }
  20786. }
  20787. channels [newNumChannels] = 0;
  20788. size = newNumSamples;
  20789. numChannels = newNumChannels;
  20790. }
  20791. }
  20792. void AudioSampleBuffer::clear() throw()
  20793. {
  20794. for (int i = 0; i < numChannels; ++i)
  20795. zeromem (channels[i], size * sizeof (float));
  20796. }
  20797. void AudioSampleBuffer::clear (const int startSample,
  20798. const int numSamples) throw()
  20799. {
  20800. jassert (startSample >= 0 && startSample + numSamples <= size);
  20801. for (int i = 0; i < numChannels; ++i)
  20802. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20803. }
  20804. void AudioSampleBuffer::clear (const int channel,
  20805. const int startSample,
  20806. const int numSamples) throw()
  20807. {
  20808. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20809. jassert (startSample >= 0 && startSample + numSamples <= size);
  20810. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20811. }
  20812. void AudioSampleBuffer::applyGain (const int channel,
  20813. const int startSample,
  20814. int numSamples,
  20815. const float gain) throw()
  20816. {
  20817. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20818. jassert (startSample >= 0 && startSample + numSamples <= size);
  20819. if (gain != 1.0f)
  20820. {
  20821. float* d = channels [channel] + startSample;
  20822. if (gain == 0.0f)
  20823. {
  20824. zeromem (d, sizeof (float) * numSamples);
  20825. }
  20826. else
  20827. {
  20828. while (--numSamples >= 0)
  20829. *d++ *= gain;
  20830. }
  20831. }
  20832. }
  20833. void AudioSampleBuffer::applyGainRamp (const int channel,
  20834. const int startSample,
  20835. int numSamples,
  20836. float startGain,
  20837. float endGain) throw()
  20838. {
  20839. if (startGain == endGain)
  20840. {
  20841. applyGain (channel, startSample, numSamples, startGain);
  20842. }
  20843. else
  20844. {
  20845. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20846. jassert (startSample >= 0 && startSample + numSamples <= size);
  20847. const float increment = (endGain - startGain) / numSamples;
  20848. float* d = channels [channel] + startSample;
  20849. while (--numSamples >= 0)
  20850. {
  20851. *d++ *= startGain;
  20852. startGain += increment;
  20853. }
  20854. }
  20855. }
  20856. void AudioSampleBuffer::applyGain (const int startSample,
  20857. const int numSamples,
  20858. const float gain) throw()
  20859. {
  20860. for (int i = 0; i < numChannels; ++i)
  20861. applyGain (i, startSample, numSamples, gain);
  20862. }
  20863. void AudioSampleBuffer::addFrom (const int destChannel,
  20864. const int destStartSample,
  20865. const AudioSampleBuffer& source,
  20866. const int sourceChannel,
  20867. const int sourceStartSample,
  20868. int numSamples,
  20869. const float gain) throw()
  20870. {
  20871. jassert (&source != this || sourceChannel != destChannel);
  20872. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20873. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20874. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20875. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20876. if (gain != 0.0f && numSamples > 0)
  20877. {
  20878. float* d = channels [destChannel] + destStartSample;
  20879. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20880. if (gain != 1.0f)
  20881. {
  20882. while (--numSamples >= 0)
  20883. *d++ += gain * *s++;
  20884. }
  20885. else
  20886. {
  20887. while (--numSamples >= 0)
  20888. *d++ += *s++;
  20889. }
  20890. }
  20891. }
  20892. void AudioSampleBuffer::addFrom (const int destChannel,
  20893. const int destStartSample,
  20894. const float* source,
  20895. int numSamples,
  20896. const float gain) throw()
  20897. {
  20898. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20899. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20900. jassert (source != 0);
  20901. if (gain != 0.0f && numSamples > 0)
  20902. {
  20903. float* d = channels [destChannel] + destStartSample;
  20904. if (gain != 1.0f)
  20905. {
  20906. while (--numSamples >= 0)
  20907. *d++ += gain * *source++;
  20908. }
  20909. else
  20910. {
  20911. while (--numSamples >= 0)
  20912. *d++ += *source++;
  20913. }
  20914. }
  20915. }
  20916. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20917. const int destStartSample,
  20918. const float* source,
  20919. int numSamples,
  20920. float startGain,
  20921. const float endGain) throw()
  20922. {
  20923. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20924. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20925. jassert (source != 0);
  20926. if (startGain == endGain)
  20927. {
  20928. addFrom (destChannel,
  20929. destStartSample,
  20930. source,
  20931. numSamples,
  20932. startGain);
  20933. }
  20934. else
  20935. {
  20936. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20937. {
  20938. const float increment = (endGain - startGain) / numSamples;
  20939. float* d = channels [destChannel] + destStartSample;
  20940. while (--numSamples >= 0)
  20941. {
  20942. *d++ += startGain * *source++;
  20943. startGain += increment;
  20944. }
  20945. }
  20946. }
  20947. }
  20948. void AudioSampleBuffer::copyFrom (const int destChannel,
  20949. const int destStartSample,
  20950. const AudioSampleBuffer& source,
  20951. const int sourceChannel,
  20952. const int sourceStartSample,
  20953. int numSamples) throw()
  20954. {
  20955. jassert (&source != this || sourceChannel != destChannel);
  20956. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20957. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20958. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20959. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20960. if (numSamples > 0)
  20961. {
  20962. memcpy (channels [destChannel] + destStartSample,
  20963. source.channels [sourceChannel] + sourceStartSample,
  20964. sizeof (float) * numSamples);
  20965. }
  20966. }
  20967. void AudioSampleBuffer::copyFrom (const int destChannel,
  20968. const int destStartSample,
  20969. const float* source,
  20970. int numSamples) throw()
  20971. {
  20972. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20973. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20974. jassert (source != 0);
  20975. if (numSamples > 0)
  20976. {
  20977. memcpy (channels [destChannel] + destStartSample,
  20978. source,
  20979. sizeof (float) * numSamples);
  20980. }
  20981. }
  20982. void AudioSampleBuffer::copyFrom (const int destChannel,
  20983. const int destStartSample,
  20984. const float* source,
  20985. int numSamples,
  20986. const float gain) throw()
  20987. {
  20988. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20989. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20990. jassert (source != 0);
  20991. if (numSamples > 0)
  20992. {
  20993. float* d = channels [destChannel] + destStartSample;
  20994. if (gain != 1.0f)
  20995. {
  20996. if (gain == 0)
  20997. {
  20998. zeromem (d, sizeof (float) * numSamples);
  20999. }
  21000. else
  21001. {
  21002. while (--numSamples >= 0)
  21003. *d++ = gain * *source++;
  21004. }
  21005. }
  21006. else
  21007. {
  21008. memcpy (d, source, sizeof (float) * numSamples);
  21009. }
  21010. }
  21011. }
  21012. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21013. const int destStartSample,
  21014. const float* source,
  21015. int numSamples,
  21016. float startGain,
  21017. float endGain) throw()
  21018. {
  21019. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21020. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21021. jassert (source != 0);
  21022. if (startGain == endGain)
  21023. {
  21024. copyFrom (destChannel,
  21025. destStartSample,
  21026. source,
  21027. numSamples,
  21028. startGain);
  21029. }
  21030. else
  21031. {
  21032. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21033. {
  21034. const float increment = (endGain - startGain) / numSamples;
  21035. float* d = channels [destChannel] + destStartSample;
  21036. while (--numSamples >= 0)
  21037. {
  21038. *d++ = startGain * *source++;
  21039. startGain += increment;
  21040. }
  21041. }
  21042. }
  21043. }
  21044. void AudioSampleBuffer::findMinMax (const int channel,
  21045. const int startSample,
  21046. int numSamples,
  21047. float& minVal,
  21048. float& maxVal) const throw()
  21049. {
  21050. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21051. jassert (startSample >= 0 && startSample + numSamples <= size);
  21052. if (numSamples <= 0)
  21053. {
  21054. minVal = 0.0f;
  21055. maxVal = 0.0f;
  21056. }
  21057. else
  21058. {
  21059. const float* d = channels [channel] + startSample;
  21060. float mn = *d++;
  21061. float mx = mn;
  21062. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21063. {
  21064. const float samp = *d++;
  21065. if (samp > mx)
  21066. mx = samp;
  21067. if (samp < mn)
  21068. mn = samp;
  21069. }
  21070. maxVal = mx;
  21071. minVal = mn;
  21072. }
  21073. }
  21074. float AudioSampleBuffer::getMagnitude (const int channel,
  21075. const int startSample,
  21076. const int numSamples) const throw()
  21077. {
  21078. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21079. jassert (startSample >= 0 && startSample + numSamples <= size);
  21080. float mn, mx;
  21081. findMinMax (channel, startSample, numSamples, mn, mx);
  21082. return jmax (mn, -mn, mx, -mx);
  21083. }
  21084. float AudioSampleBuffer::getMagnitude (const int startSample,
  21085. const int numSamples) const throw()
  21086. {
  21087. float mag = 0.0f;
  21088. for (int i = 0; i < numChannels; ++i)
  21089. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21090. return mag;
  21091. }
  21092. float AudioSampleBuffer::getRMSLevel (const int channel,
  21093. const int startSample,
  21094. const int numSamples) const throw()
  21095. {
  21096. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21097. jassert (startSample >= 0 && startSample + numSamples <= size);
  21098. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21099. return 0.0f;
  21100. const float* const data = channels [channel] + startSample;
  21101. double sum = 0.0;
  21102. for (int i = 0; i < numSamples; ++i)
  21103. {
  21104. const float sample = data [i];
  21105. sum += sample * sample;
  21106. }
  21107. return (float) std::sqrt (sum / numSamples);
  21108. }
  21109. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21110. const int startSample,
  21111. const int numSamples,
  21112. const int readerStartSample,
  21113. const bool useLeftChan,
  21114. const bool useRightChan) throw()
  21115. {
  21116. jassert (reader != 0);
  21117. jassert (startSample >= 0 && startSample + numSamples <= size);
  21118. if (numSamples > 0)
  21119. {
  21120. int* chans[3];
  21121. if (useLeftChan == useRightChan)
  21122. {
  21123. chans[0] = (int*) getSampleData (0, startSample);
  21124. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21125. }
  21126. else if (useLeftChan || (reader->numChannels == 1))
  21127. {
  21128. chans[0] = (int*) getSampleData (0, startSample);
  21129. chans[1] = 0;
  21130. }
  21131. else if (useRightChan)
  21132. {
  21133. chans[0] = 0;
  21134. chans[1] = (int*) getSampleData (0, startSample);
  21135. }
  21136. chans[2] = 0;
  21137. reader->read (chans, 2, readerStartSample, numSamples, true);
  21138. if (! reader->usesFloatingPointData)
  21139. {
  21140. for (int j = 0; j < 2; ++j)
  21141. {
  21142. float* const d = reinterpret_cast <float*> (chans[j]);
  21143. if (d != 0)
  21144. {
  21145. const float multiplier = 1.0f / 0x7fffffff;
  21146. for (int i = 0; i < numSamples; ++i)
  21147. d[i] = *(int*)(d + i) * multiplier;
  21148. }
  21149. }
  21150. }
  21151. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21152. {
  21153. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21154. memcpy (getSampleData (1, startSample),
  21155. getSampleData (0, startSample),
  21156. sizeof (float) * numSamples);
  21157. }
  21158. }
  21159. }
  21160. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21161. const int startSample,
  21162. const int numSamples) const throw()
  21163. {
  21164. jassert (startSample >= 0 && startSample + numSamples <= size);
  21165. if (numSamples > 0)
  21166. {
  21167. int* chans [3];
  21168. if (writer->isFloatingPoint())
  21169. {
  21170. chans[0] = (int*) getSampleData (0, startSample);
  21171. if (numChannels > 1)
  21172. chans[1] = (int*) getSampleData (1, startSample);
  21173. else
  21174. chans[1] = 0;
  21175. chans[2] = 0;
  21176. writer->write ((const int**) chans, numSamples);
  21177. }
  21178. else
  21179. {
  21180. HeapBlock <int> tempBuffer (numSamples * 2);
  21181. chans[0] = tempBuffer;
  21182. if (numChannels > 1)
  21183. chans[1] = chans[0] + numSamples;
  21184. else
  21185. chans[1] = 0;
  21186. chans[2] = 0;
  21187. for (int j = 0; j < 2; ++j)
  21188. {
  21189. int* const dest = chans[j];
  21190. if (dest != 0)
  21191. {
  21192. const float* const src = channels [j] + startSample;
  21193. for (int i = 0; i < numSamples; ++i)
  21194. {
  21195. const double samp = src[i];
  21196. if (samp <= -1.0)
  21197. dest[i] = std::numeric_limits<int>::min();
  21198. else if (samp >= 1.0)
  21199. dest[i] = std::numeric_limits<int>::max();
  21200. else
  21201. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21202. }
  21203. }
  21204. }
  21205. writer->write ((const int**) chans, numSamples);
  21206. }
  21207. }
  21208. }
  21209. END_JUCE_NAMESPACE
  21210. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21211. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21212. BEGIN_JUCE_NAMESPACE
  21213. IIRFilter::IIRFilter()
  21214. : active (false)
  21215. {
  21216. reset();
  21217. }
  21218. IIRFilter::IIRFilter (const IIRFilter& other)
  21219. : active (other.active)
  21220. {
  21221. const ScopedLock sl (other.processLock);
  21222. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21223. reset();
  21224. }
  21225. IIRFilter::~IIRFilter()
  21226. {
  21227. }
  21228. void IIRFilter::reset() throw()
  21229. {
  21230. const ScopedLock sl (processLock);
  21231. x1 = 0;
  21232. x2 = 0;
  21233. y1 = 0;
  21234. y2 = 0;
  21235. }
  21236. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21237. {
  21238. float out = coefficients[0] * in
  21239. + coefficients[1] * x1
  21240. + coefficients[2] * x2
  21241. - coefficients[4] * y1
  21242. - coefficients[5] * y2;
  21243. #if JUCE_INTEL
  21244. if (! (out < -1.0e-8 || out > 1.0e-8))
  21245. out = 0;
  21246. #endif
  21247. x2 = x1;
  21248. x1 = in;
  21249. y2 = y1;
  21250. y1 = out;
  21251. return out;
  21252. }
  21253. void IIRFilter::processSamples (float* const samples,
  21254. const int numSamples) throw()
  21255. {
  21256. const ScopedLock sl (processLock);
  21257. if (active)
  21258. {
  21259. for (int i = 0; i < numSamples; ++i)
  21260. {
  21261. const float in = samples[i];
  21262. float out = coefficients[0] * in
  21263. + coefficients[1] * x1
  21264. + coefficients[2] * x2
  21265. - coefficients[4] * y1
  21266. - coefficients[5] * y2;
  21267. #if JUCE_INTEL
  21268. if (! (out < -1.0e-8 || out > 1.0e-8))
  21269. out = 0;
  21270. #endif
  21271. x2 = x1;
  21272. x1 = in;
  21273. y2 = y1;
  21274. y1 = out;
  21275. samples[i] = out;
  21276. }
  21277. }
  21278. }
  21279. void IIRFilter::makeLowPass (const double sampleRate,
  21280. const double frequency) throw()
  21281. {
  21282. jassert (sampleRate > 0);
  21283. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21284. const double nSquared = n * n;
  21285. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21286. setCoefficients (c1,
  21287. c1 * 2.0f,
  21288. c1,
  21289. 1.0,
  21290. c1 * 2.0 * (1.0 - nSquared),
  21291. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21292. }
  21293. void IIRFilter::makeHighPass (const double sampleRate,
  21294. const double frequency) throw()
  21295. {
  21296. const double n = tan (double_Pi * frequency / sampleRate);
  21297. const double nSquared = n * n;
  21298. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21299. setCoefficients (c1,
  21300. c1 * -2.0f,
  21301. c1,
  21302. 1.0,
  21303. c1 * 2.0 * (nSquared - 1.0),
  21304. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21305. }
  21306. void IIRFilter::makeLowShelf (const double sampleRate,
  21307. const double cutOffFrequency,
  21308. const double Q,
  21309. const float gainFactor) throw()
  21310. {
  21311. jassert (sampleRate > 0);
  21312. jassert (Q > 0);
  21313. const double A = jmax (0.0f, gainFactor);
  21314. const double aminus1 = A - 1.0;
  21315. const double aplus1 = A + 1.0;
  21316. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21317. const double coso = std::cos (omega);
  21318. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21319. const double aminus1TimesCoso = aminus1 * coso;
  21320. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21321. A * 2.0 * (aminus1 - aplus1 * coso),
  21322. A * (aplus1 - aminus1TimesCoso - beta),
  21323. aplus1 + aminus1TimesCoso + beta,
  21324. -2.0 * (aminus1 + aplus1 * coso),
  21325. aplus1 + aminus1TimesCoso - beta);
  21326. }
  21327. void IIRFilter::makeHighShelf (const double sampleRate,
  21328. const double cutOffFrequency,
  21329. const double Q,
  21330. const float gainFactor) throw()
  21331. {
  21332. jassert (sampleRate > 0);
  21333. jassert (Q > 0);
  21334. const double A = jmax (0.0f, gainFactor);
  21335. const double aminus1 = A - 1.0;
  21336. const double aplus1 = A + 1.0;
  21337. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21338. const double coso = std::cos (omega);
  21339. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21340. const double aminus1TimesCoso = aminus1 * coso;
  21341. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21342. A * -2.0 * (aminus1 + aplus1 * coso),
  21343. A * (aplus1 + aminus1TimesCoso - beta),
  21344. aplus1 - aminus1TimesCoso + beta,
  21345. 2.0 * (aminus1 - aplus1 * coso),
  21346. aplus1 - aminus1TimesCoso - beta);
  21347. }
  21348. void IIRFilter::makeBandPass (const double sampleRate,
  21349. const double centreFrequency,
  21350. const double Q,
  21351. const float gainFactor) throw()
  21352. {
  21353. jassert (sampleRate > 0);
  21354. jassert (Q > 0);
  21355. const double A = jmax (0.0f, gainFactor);
  21356. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21357. const double alpha = 0.5 * std::sin (omega) / Q;
  21358. const double c2 = -2.0 * std::cos (omega);
  21359. const double alphaTimesA = alpha * A;
  21360. const double alphaOverA = alpha / A;
  21361. setCoefficients (1.0 + alphaTimesA,
  21362. c2,
  21363. 1.0 - alphaTimesA,
  21364. 1.0 + alphaOverA,
  21365. c2,
  21366. 1.0 - alphaOverA);
  21367. }
  21368. void IIRFilter::makeInactive() throw()
  21369. {
  21370. const ScopedLock sl (processLock);
  21371. active = false;
  21372. }
  21373. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21374. {
  21375. const ScopedLock sl (processLock);
  21376. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21377. active = other.active;
  21378. }
  21379. void IIRFilter::setCoefficients (double c1,
  21380. double c2,
  21381. double c3,
  21382. double c4,
  21383. double c5,
  21384. double c6) throw()
  21385. {
  21386. const double a = 1.0 / c4;
  21387. c1 *= a;
  21388. c2 *= a;
  21389. c3 *= a;
  21390. c5 *= a;
  21391. c6 *= a;
  21392. const ScopedLock sl (processLock);
  21393. coefficients[0] = (float) c1;
  21394. coefficients[1] = (float) c2;
  21395. coefficients[2] = (float) c3;
  21396. coefficients[3] = (float) c4;
  21397. coefficients[4] = (float) c5;
  21398. coefficients[5] = (float) c6;
  21399. active = true;
  21400. }
  21401. END_JUCE_NAMESPACE
  21402. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21403. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21404. BEGIN_JUCE_NAMESPACE
  21405. MidiBuffer::MidiBuffer() throw()
  21406. : bytesUsed (0)
  21407. {
  21408. }
  21409. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21410. : bytesUsed (0)
  21411. {
  21412. addEvent (message, 0);
  21413. }
  21414. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21415. : data (other.data),
  21416. bytesUsed (other.bytesUsed)
  21417. {
  21418. }
  21419. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21420. {
  21421. bytesUsed = other.bytesUsed;
  21422. data = other.data;
  21423. return *this;
  21424. }
  21425. void MidiBuffer::swapWith (MidiBuffer& other)
  21426. {
  21427. data.swapWith (other.data);
  21428. swapVariables <int> (bytesUsed, other.bytesUsed);
  21429. }
  21430. MidiBuffer::~MidiBuffer() throw()
  21431. {
  21432. }
  21433. inline uint8* MidiBuffer::getData() const throw()
  21434. {
  21435. return static_cast <uint8*> (data.getData());
  21436. }
  21437. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21438. {
  21439. return *static_cast <const int*> (d);
  21440. }
  21441. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21442. {
  21443. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21444. }
  21445. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21446. {
  21447. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21448. }
  21449. void MidiBuffer::clear() throw()
  21450. {
  21451. bytesUsed = 0;
  21452. }
  21453. void MidiBuffer::clear (const int startSample,
  21454. const int numSamples) throw()
  21455. {
  21456. uint8* const start = findEventAfter (getData(), startSample - 1);
  21457. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21458. if (end > start)
  21459. {
  21460. const int bytesToMove = bytesUsed - (int) (end - getData());
  21461. if (bytesToMove > 0)
  21462. memmove (start, end, bytesToMove);
  21463. bytesUsed -= (int) (end - start);
  21464. }
  21465. }
  21466. void MidiBuffer::addEvent (const MidiMessage& m,
  21467. const int sampleNumber) throw()
  21468. {
  21469. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21470. }
  21471. static int findActualEventLength (const uint8* const data,
  21472. const int maxBytes) throw()
  21473. {
  21474. unsigned int byte = (unsigned int) *data;
  21475. int size = 0;
  21476. if (byte == 0xf0 || byte == 0xf7)
  21477. {
  21478. const uint8* d = data + 1;
  21479. while (d < data + maxBytes)
  21480. if (*d++ == 0xf7)
  21481. break;
  21482. size = (int) (d - data);
  21483. }
  21484. else if (byte == 0xff)
  21485. {
  21486. int n;
  21487. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21488. size = jmin (maxBytes, n + 2 + bytesLeft);
  21489. }
  21490. else if (byte >= 0x80)
  21491. {
  21492. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21493. }
  21494. return size;
  21495. }
  21496. void MidiBuffer::addEvent (const uint8* const newData,
  21497. const int maxBytes,
  21498. const int sampleNumber) throw()
  21499. {
  21500. const int numBytes = findActualEventLength (newData, maxBytes);
  21501. if (numBytes > 0)
  21502. {
  21503. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21504. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21505. uint8* d = findEventAfter (getData(), sampleNumber);
  21506. const int bytesToMove = bytesUsed - (int) (d - getData());
  21507. if (bytesToMove > 0)
  21508. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21509. *reinterpret_cast <int*> (d) = sampleNumber;
  21510. d += sizeof (int);
  21511. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21512. d += sizeof (uint16);
  21513. memcpy (d, newData, numBytes);
  21514. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21515. }
  21516. }
  21517. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21518. const int startSample,
  21519. const int numSamples,
  21520. const int sampleDeltaToAdd) throw()
  21521. {
  21522. Iterator i (otherBuffer);
  21523. i.setNextSamplePosition (startSample);
  21524. const uint8* eventData;
  21525. int eventSize, position;
  21526. while (i.getNextEvent (eventData, eventSize, position)
  21527. && (position < startSample + numSamples || numSamples < 0))
  21528. {
  21529. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21530. }
  21531. }
  21532. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21533. {
  21534. data.ensureSize (minimumNumBytes);
  21535. }
  21536. bool MidiBuffer::isEmpty() const throw()
  21537. {
  21538. return bytesUsed == 0;
  21539. }
  21540. int MidiBuffer::getNumEvents() const throw()
  21541. {
  21542. int n = 0;
  21543. const uint8* d = getData();
  21544. const uint8* const end = d + bytesUsed;
  21545. while (d < end)
  21546. {
  21547. d += getEventTotalSize (d);
  21548. ++n;
  21549. }
  21550. return n;
  21551. }
  21552. int MidiBuffer::getFirstEventTime() const throw()
  21553. {
  21554. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21555. }
  21556. int MidiBuffer::getLastEventTime() const throw()
  21557. {
  21558. if (bytesUsed == 0)
  21559. return 0;
  21560. const uint8* d = getData();
  21561. const uint8* const endData = d + bytesUsed;
  21562. for (;;)
  21563. {
  21564. const uint8* const nextOne = d + getEventTotalSize (d);
  21565. if (nextOne >= endData)
  21566. return getEventTime (d);
  21567. d = nextOne;
  21568. }
  21569. }
  21570. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21571. {
  21572. const uint8* const endData = getData() + bytesUsed;
  21573. while (d < endData && getEventTime (d) <= samplePosition)
  21574. d += getEventTotalSize (d);
  21575. return d;
  21576. }
  21577. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21578. : buffer (buffer_),
  21579. data (buffer_.getData())
  21580. {
  21581. }
  21582. MidiBuffer::Iterator::~Iterator() throw()
  21583. {
  21584. }
  21585. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21586. {
  21587. data = buffer.getData();
  21588. const uint8* dataEnd = data + buffer.bytesUsed;
  21589. while (data < dataEnd && getEventTime (data) < samplePosition)
  21590. data += getEventTotalSize (data);
  21591. }
  21592. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21593. {
  21594. if (data >= buffer.getData() + buffer.bytesUsed)
  21595. return false;
  21596. samplePosition = getEventTime (data);
  21597. numBytes = getEventDataSize (data);
  21598. data += sizeof (int) + sizeof (uint16);
  21599. midiData = data;
  21600. data += numBytes;
  21601. return true;
  21602. }
  21603. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21604. {
  21605. if (data >= buffer.getData() + buffer.bytesUsed)
  21606. return false;
  21607. samplePosition = getEventTime (data);
  21608. const int numBytes = getEventDataSize (data);
  21609. data += sizeof (int) + sizeof (uint16);
  21610. result = MidiMessage (data, numBytes, samplePosition);
  21611. data += numBytes;
  21612. return true;
  21613. }
  21614. END_JUCE_NAMESPACE
  21615. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21616. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21617. BEGIN_JUCE_NAMESPACE
  21618. namespace MidiFileHelpers
  21619. {
  21620. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21621. {
  21622. unsigned int buffer = v & 0x7F;
  21623. while ((v >>= 7) != 0)
  21624. {
  21625. buffer <<= 8;
  21626. buffer |= ((v & 0x7F) | 0x80);
  21627. }
  21628. for (;;)
  21629. {
  21630. out.writeByte ((char) buffer);
  21631. if (buffer & 0x80)
  21632. buffer >>= 8;
  21633. else
  21634. break;
  21635. }
  21636. }
  21637. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21638. {
  21639. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21640. data += 4;
  21641. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21642. {
  21643. bool ok = false;
  21644. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21645. {
  21646. for (int i = 0; i < 8; ++i)
  21647. {
  21648. ch = ByteOrder::bigEndianInt (data);
  21649. data += 4;
  21650. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21651. {
  21652. ok = true;
  21653. break;
  21654. }
  21655. }
  21656. }
  21657. if (! ok)
  21658. return false;
  21659. }
  21660. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21661. data += 4;
  21662. fileType = (short) ByteOrder::bigEndianShort (data);
  21663. data += 2;
  21664. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21665. data += 2;
  21666. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21667. data += 2;
  21668. bytesRemaining -= 6;
  21669. data += bytesRemaining;
  21670. return true;
  21671. }
  21672. static double convertTicksToSeconds (const double time,
  21673. const MidiMessageSequence& tempoEvents,
  21674. const int timeFormat)
  21675. {
  21676. if (timeFormat > 0)
  21677. {
  21678. int numer = 4, denom = 4;
  21679. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21680. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21681. double secsPerTick = 0.5 * tickLen;
  21682. const int numEvents = tempoEvents.getNumEvents();
  21683. for (int i = 0; i < numEvents; ++i)
  21684. {
  21685. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21686. if (time <= m.getTimeStamp())
  21687. break;
  21688. if (timeFormat > 0)
  21689. {
  21690. correctedTempoTime = correctedTempoTime
  21691. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21692. }
  21693. else
  21694. {
  21695. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21696. }
  21697. tempoTime = m.getTimeStamp();
  21698. if (m.isTempoMetaEvent())
  21699. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21700. else if (m.isTimeSignatureMetaEvent())
  21701. m.getTimeSignatureInfo (numer, denom);
  21702. while (i + 1 < numEvents)
  21703. {
  21704. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21705. if (m2.getTimeStamp() == tempoTime)
  21706. {
  21707. ++i;
  21708. if (m2.isTempoMetaEvent())
  21709. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21710. else if (m2.isTimeSignatureMetaEvent())
  21711. m2.getTimeSignatureInfo (numer, denom);
  21712. }
  21713. else
  21714. {
  21715. break;
  21716. }
  21717. }
  21718. }
  21719. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21720. }
  21721. else
  21722. {
  21723. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21724. }
  21725. }
  21726. }
  21727. MidiFile::MidiFile()
  21728. : timeFormat ((short) (unsigned short) 0xe728)
  21729. {
  21730. }
  21731. MidiFile::~MidiFile()
  21732. {
  21733. clear();
  21734. }
  21735. void MidiFile::clear()
  21736. {
  21737. tracks.clear();
  21738. }
  21739. int MidiFile::getNumTracks() const throw()
  21740. {
  21741. return tracks.size();
  21742. }
  21743. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21744. {
  21745. return tracks [index];
  21746. }
  21747. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21748. {
  21749. tracks.add (new MidiMessageSequence (trackSequence));
  21750. }
  21751. short MidiFile::getTimeFormat() const throw()
  21752. {
  21753. return timeFormat;
  21754. }
  21755. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21756. {
  21757. timeFormat = (short) ticks;
  21758. }
  21759. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21760. const int subframeResolution) throw()
  21761. {
  21762. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21763. }
  21764. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21765. {
  21766. for (int i = tracks.size(); --i >= 0;)
  21767. {
  21768. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21769. for (int j = 0; j < numEvents; ++j)
  21770. {
  21771. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21772. if (m.isTempoMetaEvent())
  21773. tempoChangeEvents.addEvent (m);
  21774. }
  21775. }
  21776. }
  21777. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21778. {
  21779. for (int i = tracks.size(); --i >= 0;)
  21780. {
  21781. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21782. for (int j = 0; j < numEvents; ++j)
  21783. {
  21784. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21785. if (m.isTimeSignatureMetaEvent())
  21786. timeSigEvents.addEvent (m);
  21787. }
  21788. }
  21789. }
  21790. double MidiFile::getLastTimestamp() const
  21791. {
  21792. double t = 0.0;
  21793. for (int i = tracks.size(); --i >= 0;)
  21794. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21795. return t;
  21796. }
  21797. bool MidiFile::readFrom (InputStream& sourceStream)
  21798. {
  21799. clear();
  21800. MemoryBlock data;
  21801. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21802. // (put a sanity-check on the file size, as midi files are generally small)
  21803. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21804. {
  21805. size_t size = data.getSize();
  21806. const uint8* d = static_cast <const uint8*> (data.getData());
  21807. short fileType, expectedTracks;
  21808. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21809. {
  21810. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21811. int track = 0;
  21812. while (size > 0 && track < expectedTracks)
  21813. {
  21814. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21815. d += 4;
  21816. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21817. d += 4;
  21818. if (chunkSize <= 0)
  21819. break;
  21820. if (size < 0)
  21821. return false;
  21822. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21823. {
  21824. readNextTrack (d, chunkSize);
  21825. }
  21826. size -= chunkSize + 8;
  21827. d += chunkSize;
  21828. ++track;
  21829. }
  21830. return true;
  21831. }
  21832. }
  21833. return false;
  21834. }
  21835. // a comparator that puts all the note-offs before note-ons that have the same time
  21836. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21837. const MidiMessageSequence::MidiEventHolder* const second)
  21838. {
  21839. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21840. if (diff == 0)
  21841. {
  21842. if (first->message.isNoteOff() && second->message.isNoteOn())
  21843. return -1;
  21844. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21845. return 1;
  21846. else
  21847. return 0;
  21848. }
  21849. else
  21850. {
  21851. return (diff > 0) ? 1 : -1;
  21852. }
  21853. }
  21854. void MidiFile::readNextTrack (const uint8* data, int size)
  21855. {
  21856. double time = 0;
  21857. char lastStatusByte = 0;
  21858. MidiMessageSequence result;
  21859. while (size > 0)
  21860. {
  21861. int bytesUsed;
  21862. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21863. data += bytesUsed;
  21864. size -= bytesUsed;
  21865. time += delay;
  21866. int messSize = 0;
  21867. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21868. if (messSize <= 0)
  21869. break;
  21870. size -= messSize;
  21871. data += messSize;
  21872. result.addEvent (mm);
  21873. const char firstByte = *(mm.getRawData());
  21874. if ((firstByte & 0xf0) != 0xf0)
  21875. lastStatusByte = firstByte;
  21876. }
  21877. // use a sort that puts all the note-offs before note-ons that have the same time
  21878. result.list.sort (*this, true);
  21879. result.updateMatchedPairs();
  21880. addTrack (result);
  21881. }
  21882. void MidiFile::convertTimestampTicksToSeconds()
  21883. {
  21884. MidiMessageSequence tempoEvents;
  21885. findAllTempoEvents (tempoEvents);
  21886. findAllTimeSigEvents (tempoEvents);
  21887. for (int i = 0; i < tracks.size(); ++i)
  21888. {
  21889. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21890. for (int j = ms.getNumEvents(); --j >= 0;)
  21891. {
  21892. MidiMessage& m = ms.getEventPointer(j)->message;
  21893. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21894. tempoEvents,
  21895. timeFormat));
  21896. }
  21897. }
  21898. }
  21899. bool MidiFile::writeTo (OutputStream& out)
  21900. {
  21901. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21902. out.writeIntBigEndian (6);
  21903. out.writeShortBigEndian (1); // type
  21904. out.writeShortBigEndian ((short) tracks.size());
  21905. out.writeShortBigEndian (timeFormat);
  21906. for (int i = 0; i < tracks.size(); ++i)
  21907. writeTrack (out, i);
  21908. out.flush();
  21909. return true;
  21910. }
  21911. void MidiFile::writeTrack (OutputStream& mainOut,
  21912. const int trackNum)
  21913. {
  21914. MemoryOutputStream out;
  21915. const MidiMessageSequence& ms = *tracks[trackNum];
  21916. int lastTick = 0;
  21917. char lastStatusByte = 0;
  21918. for (int i = 0; i < ms.getNumEvents(); ++i)
  21919. {
  21920. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21921. const int tick = roundToInt (mm.getTimeStamp());
  21922. const int delta = jmax (0, tick - lastTick);
  21923. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21924. lastTick = tick;
  21925. const char statusByte = *(mm.getRawData());
  21926. if ((statusByte == lastStatusByte)
  21927. && ((statusByte & 0xf0) != 0xf0)
  21928. && i > 0
  21929. && mm.getRawDataSize() > 1)
  21930. {
  21931. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21932. }
  21933. else
  21934. {
  21935. out.write (mm.getRawData(), mm.getRawDataSize());
  21936. }
  21937. lastStatusByte = statusByte;
  21938. }
  21939. out.writeByte (0);
  21940. const MidiMessage m (MidiMessage::endOfTrack());
  21941. out.write (m.getRawData(),
  21942. m.getRawDataSize());
  21943. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21944. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21945. mainOut.write (out.getData(), (int) out.getDataSize());
  21946. }
  21947. END_JUCE_NAMESPACE
  21948. /*** End of inlined file: juce_MidiFile.cpp ***/
  21949. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21950. BEGIN_JUCE_NAMESPACE
  21951. MidiKeyboardState::MidiKeyboardState()
  21952. {
  21953. zerostruct (noteStates);
  21954. }
  21955. MidiKeyboardState::~MidiKeyboardState()
  21956. {
  21957. }
  21958. void MidiKeyboardState::reset()
  21959. {
  21960. const ScopedLock sl (lock);
  21961. zerostruct (noteStates);
  21962. eventsToAdd.clear();
  21963. }
  21964. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21965. {
  21966. jassert (midiChannel >= 0 && midiChannel <= 16);
  21967. return ((unsigned int) n) < 128
  21968. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21969. }
  21970. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21971. {
  21972. return ((unsigned int) n) < 128
  21973. && (noteStates[n] & midiChannelMask) != 0;
  21974. }
  21975. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21976. {
  21977. jassert (midiChannel >= 0 && midiChannel <= 16);
  21978. jassert (((unsigned int) midiNoteNumber) < 128);
  21979. const ScopedLock sl (lock);
  21980. if (((unsigned int) midiNoteNumber) < 128)
  21981. {
  21982. const int timeNow = (int) Time::getMillisecondCounter();
  21983. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21984. eventsToAdd.clear (0, timeNow - 500);
  21985. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21986. }
  21987. }
  21988. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21989. {
  21990. if (((unsigned int) midiNoteNumber) < 128)
  21991. {
  21992. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21993. for (int i = listeners.size(); --i >= 0;)
  21994. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21995. }
  21996. }
  21997. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21998. {
  21999. const ScopedLock sl (lock);
  22000. if (isNoteOn (midiChannel, midiNoteNumber))
  22001. {
  22002. const int timeNow = (int) Time::getMillisecondCounter();
  22003. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22004. eventsToAdd.clear (0, timeNow - 500);
  22005. noteOffInternal (midiChannel, midiNoteNumber);
  22006. }
  22007. }
  22008. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22009. {
  22010. if (isNoteOn (midiChannel, midiNoteNumber))
  22011. {
  22012. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22013. for (int i = listeners.size(); --i >= 0;)
  22014. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22015. }
  22016. }
  22017. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22018. {
  22019. const ScopedLock sl (lock);
  22020. if (midiChannel <= 0)
  22021. {
  22022. for (int i = 1; i <= 16; ++i)
  22023. allNotesOff (i);
  22024. }
  22025. else
  22026. {
  22027. for (int i = 0; i < 128; ++i)
  22028. noteOff (midiChannel, i);
  22029. }
  22030. }
  22031. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22032. {
  22033. if (message.isNoteOn())
  22034. {
  22035. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22036. }
  22037. else if (message.isNoteOff())
  22038. {
  22039. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22040. }
  22041. else if (message.isAllNotesOff())
  22042. {
  22043. for (int i = 0; i < 128; ++i)
  22044. noteOffInternal (message.getChannel(), i);
  22045. }
  22046. }
  22047. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22048. const int startSample,
  22049. const int numSamples,
  22050. const bool injectIndirectEvents)
  22051. {
  22052. MidiBuffer::Iterator i (buffer);
  22053. MidiMessage message (0xf4, 0.0);
  22054. int time;
  22055. const ScopedLock sl (lock);
  22056. while (i.getNextEvent (message, time))
  22057. processNextMidiEvent (message);
  22058. if (injectIndirectEvents)
  22059. {
  22060. MidiBuffer::Iterator i2 (eventsToAdd);
  22061. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22062. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22063. while (i2.getNextEvent (message, time))
  22064. {
  22065. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22066. buffer.addEvent (message, startSample + pos);
  22067. }
  22068. }
  22069. eventsToAdd.clear();
  22070. }
  22071. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22072. {
  22073. const ScopedLock sl (lock);
  22074. listeners.addIfNotAlreadyThere (listener);
  22075. }
  22076. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22077. {
  22078. const ScopedLock sl (lock);
  22079. listeners.removeValue (listener);
  22080. }
  22081. END_JUCE_NAMESPACE
  22082. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22083. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22084. BEGIN_JUCE_NAMESPACE
  22085. int MidiMessage::readVariableLengthVal (const uint8* data,
  22086. int& numBytesUsed) throw()
  22087. {
  22088. numBytesUsed = 0;
  22089. int v = 0;
  22090. int i;
  22091. do
  22092. {
  22093. i = (int) *data++;
  22094. if (++numBytesUsed > 6)
  22095. break;
  22096. v = (v << 7) + (i & 0x7f);
  22097. } while (i & 0x80);
  22098. return v;
  22099. }
  22100. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22101. {
  22102. // this method only works for valid starting bytes of a short midi message
  22103. jassert (firstByte >= 0x80
  22104. && firstByte != 0xf0
  22105. && firstByte != 0xf7);
  22106. static const char messageLengths[] =
  22107. {
  22108. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22109. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22110. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22111. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22112. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22113. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22114. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22115. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22116. };
  22117. return messageLengths [firstByte & 0x7f];
  22118. }
  22119. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22120. : timeStamp (t),
  22121. size (dataSize)
  22122. {
  22123. jassert (dataSize > 0);
  22124. if (dataSize <= 4)
  22125. data = static_cast<uint8*> (preallocatedData.asBytes);
  22126. else
  22127. data = new uint8 [dataSize];
  22128. memcpy (data, d, dataSize);
  22129. // check that the length matches the data..
  22130. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22131. }
  22132. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22133. : timeStamp (t),
  22134. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22135. size (1)
  22136. {
  22137. data[0] = (uint8) byte1;
  22138. // check that the length matches the data..
  22139. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22140. }
  22141. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22142. : timeStamp (t),
  22143. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22144. size (2)
  22145. {
  22146. data[0] = (uint8) byte1;
  22147. data[1] = (uint8) byte2;
  22148. // check that the length matches the data..
  22149. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22150. }
  22151. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22152. : timeStamp (t),
  22153. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22154. size (3)
  22155. {
  22156. data[0] = (uint8) byte1;
  22157. data[1] = (uint8) byte2;
  22158. data[2] = (uint8) byte3;
  22159. // check that the length matches the data..
  22160. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22161. }
  22162. MidiMessage::MidiMessage (const MidiMessage& other)
  22163. : timeStamp (other.timeStamp),
  22164. size (other.size)
  22165. {
  22166. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22167. {
  22168. data = new uint8 [size];
  22169. memcpy (data, other.data, size);
  22170. }
  22171. else
  22172. {
  22173. data = static_cast<uint8*> (preallocatedData.asBytes);
  22174. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22175. }
  22176. }
  22177. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22178. : timeStamp (newTimeStamp),
  22179. size (other.size)
  22180. {
  22181. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22182. {
  22183. data = new uint8 [size];
  22184. memcpy (data, other.data, size);
  22185. }
  22186. else
  22187. {
  22188. data = static_cast<uint8*> (preallocatedData.asBytes);
  22189. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22190. }
  22191. }
  22192. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22193. : timeStamp (t),
  22194. data (static_cast<uint8*> (preallocatedData.asBytes))
  22195. {
  22196. const uint8* src = static_cast <const uint8*> (src_);
  22197. unsigned int byte = (unsigned int) *src;
  22198. if (byte < 0x80)
  22199. {
  22200. byte = (unsigned int) (uint8) lastStatusByte;
  22201. numBytesUsed = -1;
  22202. }
  22203. else
  22204. {
  22205. numBytesUsed = 0;
  22206. --sz;
  22207. ++src;
  22208. }
  22209. if (byte >= 0x80)
  22210. {
  22211. if (byte == 0xf0)
  22212. {
  22213. const uint8* d = src;
  22214. while (d < src + sz)
  22215. {
  22216. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22217. {
  22218. if (*d == 0xf7) // include an 0xf7 if we hit one
  22219. ++d;
  22220. break;
  22221. }
  22222. ++d;
  22223. }
  22224. size = 1 + (int) (d - src);
  22225. data = new uint8 [size];
  22226. *data = (uint8) byte;
  22227. memcpy (data + 1, src, size - 1);
  22228. }
  22229. else if (byte == 0xff)
  22230. {
  22231. int n;
  22232. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22233. size = jmin (sz + 1, n + 2 + bytesLeft);
  22234. data = new uint8 [size];
  22235. *data = (uint8) byte;
  22236. memcpy (data + 1, src, size - 1);
  22237. }
  22238. else
  22239. {
  22240. preallocatedData.asInt32 = 0;
  22241. size = getMessageLengthFromFirstByte ((uint8) byte);
  22242. data[0] = (uint8) byte;
  22243. if (size > 1)
  22244. {
  22245. data[1] = src[0];
  22246. if (size > 2)
  22247. data[2] = src[1];
  22248. }
  22249. }
  22250. numBytesUsed += size;
  22251. }
  22252. else
  22253. {
  22254. preallocatedData.asInt32 = 0;
  22255. size = 0;
  22256. }
  22257. }
  22258. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22259. {
  22260. if (this != &other)
  22261. {
  22262. timeStamp = other.timeStamp;
  22263. size = other.size;
  22264. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22265. delete[] data;
  22266. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22267. {
  22268. data = new uint8 [size];
  22269. memcpy (data, other.data, size);
  22270. }
  22271. else
  22272. {
  22273. data = static_cast<uint8*> (preallocatedData.asBytes);
  22274. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22275. }
  22276. }
  22277. return *this;
  22278. }
  22279. MidiMessage::~MidiMessage()
  22280. {
  22281. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22282. delete[] data;
  22283. }
  22284. int MidiMessage::getChannel() const throw()
  22285. {
  22286. if ((data[0] & 0xf0) != 0xf0)
  22287. return (data[0] & 0xf) + 1;
  22288. else
  22289. return 0;
  22290. }
  22291. bool MidiMessage::isForChannel (const int channel) const throw()
  22292. {
  22293. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22294. return ((data[0] & 0xf) == channel - 1)
  22295. && ((data[0] & 0xf0) != 0xf0);
  22296. }
  22297. void MidiMessage::setChannel (const int channel) throw()
  22298. {
  22299. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22300. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22301. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22302. | (uint8)(channel - 1));
  22303. }
  22304. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22305. {
  22306. return ((data[0] & 0xf0) == 0x90)
  22307. && (returnTrueForVelocity0 || data[2] != 0);
  22308. }
  22309. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22310. {
  22311. return ((data[0] & 0xf0) == 0x80)
  22312. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22313. }
  22314. bool MidiMessage::isNoteOnOrOff() const throw()
  22315. {
  22316. const int d = data[0] & 0xf0;
  22317. return (d == 0x90) || (d == 0x80);
  22318. }
  22319. int MidiMessage::getNoteNumber() const throw()
  22320. {
  22321. return data[1];
  22322. }
  22323. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22324. {
  22325. if (isNoteOnOrOff())
  22326. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22327. }
  22328. uint8 MidiMessage::getVelocity() const throw()
  22329. {
  22330. if (isNoteOnOrOff())
  22331. return data[2];
  22332. else
  22333. return 0;
  22334. }
  22335. float MidiMessage::getFloatVelocity() const throw()
  22336. {
  22337. return getVelocity() * (1.0f / 127.0f);
  22338. }
  22339. void MidiMessage::setVelocity (const float newVelocity) throw()
  22340. {
  22341. if (isNoteOnOrOff())
  22342. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22343. }
  22344. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22345. {
  22346. if (isNoteOnOrOff())
  22347. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22348. }
  22349. bool MidiMessage::isAftertouch() const throw()
  22350. {
  22351. return (data[0] & 0xf0) == 0xa0;
  22352. }
  22353. int MidiMessage::getAfterTouchValue() const throw()
  22354. {
  22355. return data[2];
  22356. }
  22357. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22358. const int noteNum,
  22359. const int aftertouchValue) throw()
  22360. {
  22361. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22362. jassert (((unsigned int) noteNum) <= 127);
  22363. jassert (((unsigned int) aftertouchValue) <= 127);
  22364. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22365. noteNum & 0x7f,
  22366. aftertouchValue & 0x7f);
  22367. }
  22368. bool MidiMessage::isChannelPressure() const throw()
  22369. {
  22370. return (data[0] & 0xf0) == 0xd0;
  22371. }
  22372. int MidiMessage::getChannelPressureValue() const throw()
  22373. {
  22374. jassert (isChannelPressure());
  22375. return data[1];
  22376. }
  22377. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22378. const int pressure) throw()
  22379. {
  22380. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22381. jassert (((unsigned int) pressure) <= 127);
  22382. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22383. pressure & 0x7f);
  22384. }
  22385. bool MidiMessage::isProgramChange() const throw()
  22386. {
  22387. return (data[0] & 0xf0) == 0xc0;
  22388. }
  22389. int MidiMessage::getProgramChangeNumber() const throw()
  22390. {
  22391. return data[1];
  22392. }
  22393. const MidiMessage MidiMessage::programChange (const int channel,
  22394. const int programNumber) throw()
  22395. {
  22396. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22397. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22398. programNumber & 0x7f);
  22399. }
  22400. bool MidiMessage::isPitchWheel() const throw()
  22401. {
  22402. return (data[0] & 0xf0) == 0xe0;
  22403. }
  22404. int MidiMessage::getPitchWheelValue() const throw()
  22405. {
  22406. return data[1] | (data[2] << 7);
  22407. }
  22408. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22409. const int position) throw()
  22410. {
  22411. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22412. jassert (((unsigned int) position) <= 0x3fff);
  22413. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22414. position & 127,
  22415. (position >> 7) & 127);
  22416. }
  22417. bool MidiMessage::isController() const throw()
  22418. {
  22419. return (data[0] & 0xf0) == 0xb0;
  22420. }
  22421. int MidiMessage::getControllerNumber() const throw()
  22422. {
  22423. jassert (isController());
  22424. return data[1];
  22425. }
  22426. int MidiMessage::getControllerValue() const throw()
  22427. {
  22428. jassert (isController());
  22429. return data[2];
  22430. }
  22431. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22432. const int controllerType,
  22433. const int value) throw()
  22434. {
  22435. // the channel must be between 1 and 16 inclusive
  22436. jassert (channel > 0 && channel <= 16);
  22437. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22438. controllerType & 127,
  22439. value & 127);
  22440. }
  22441. const MidiMessage MidiMessage::noteOn (const int channel,
  22442. const int noteNumber,
  22443. const float velocity) throw()
  22444. {
  22445. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22446. }
  22447. const MidiMessage MidiMessage::noteOn (const int channel,
  22448. const int noteNumber,
  22449. const uint8 velocity) throw()
  22450. {
  22451. jassert (channel > 0 && channel <= 16);
  22452. jassert (((unsigned int) noteNumber) <= 127);
  22453. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22454. noteNumber & 127,
  22455. jlimit (0, 127, roundToInt (velocity)));
  22456. }
  22457. const MidiMessage MidiMessage::noteOff (const int channel,
  22458. const int noteNumber) throw()
  22459. {
  22460. jassert (channel > 0 && channel <= 16);
  22461. jassert (((unsigned int) noteNumber) <= 127);
  22462. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22463. }
  22464. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22465. {
  22466. jassert (channel > 0 && channel <= 16);
  22467. return controllerEvent (channel, 123, 0);
  22468. }
  22469. bool MidiMessage::isAllNotesOff() const throw()
  22470. {
  22471. return (data[0] & 0xf0) == 0xb0
  22472. && data[1] == 123;
  22473. }
  22474. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22475. {
  22476. return controllerEvent (channel, 120, 0);
  22477. }
  22478. bool MidiMessage::isAllSoundOff() const throw()
  22479. {
  22480. return (data[0] & 0xf0) == 0xb0
  22481. && data[1] == 120;
  22482. }
  22483. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22484. {
  22485. return controllerEvent (channel, 121, 0);
  22486. }
  22487. const MidiMessage MidiMessage::masterVolume (const float volume)
  22488. {
  22489. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22490. uint8 buf[8];
  22491. buf[0] = 0xf0;
  22492. buf[1] = 0x7f;
  22493. buf[2] = 0x7f;
  22494. buf[3] = 0x04;
  22495. buf[4] = 0x01;
  22496. buf[5] = (uint8) (vol & 0x7f);
  22497. buf[6] = (uint8) (vol >> 7);
  22498. buf[7] = 0xf7;
  22499. return MidiMessage (buf, 8);
  22500. }
  22501. bool MidiMessage::isSysEx() const throw()
  22502. {
  22503. return *data == 0xf0;
  22504. }
  22505. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22506. {
  22507. MemoryBlock mm (dataSize + 2);
  22508. uint8* const m = static_cast <uint8*> (mm.getData());
  22509. m[0] = 0xf0;
  22510. memcpy (m + 1, sysexData, dataSize);
  22511. m[dataSize + 1] = 0xf7;
  22512. return MidiMessage (m, dataSize + 2);
  22513. }
  22514. const uint8* MidiMessage::getSysExData() const throw()
  22515. {
  22516. return (isSysEx()) ? getRawData() + 1 : 0;
  22517. }
  22518. int MidiMessage::getSysExDataSize() const throw()
  22519. {
  22520. return (isSysEx()) ? size - 2 : 0;
  22521. }
  22522. bool MidiMessage::isMetaEvent() const throw()
  22523. {
  22524. return *data == 0xff;
  22525. }
  22526. bool MidiMessage::isActiveSense() const throw()
  22527. {
  22528. return *data == 0xfe;
  22529. }
  22530. int MidiMessage::getMetaEventType() const throw()
  22531. {
  22532. if (*data != 0xff)
  22533. return -1;
  22534. else
  22535. return data[1];
  22536. }
  22537. int MidiMessage::getMetaEventLength() const throw()
  22538. {
  22539. if (*data == 0xff)
  22540. {
  22541. int n;
  22542. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22543. }
  22544. return 0;
  22545. }
  22546. const uint8* MidiMessage::getMetaEventData() const throw()
  22547. {
  22548. int n;
  22549. const uint8* d = data + 2;
  22550. readVariableLengthVal (d, n);
  22551. return d + n;
  22552. }
  22553. bool MidiMessage::isTrackMetaEvent() const throw()
  22554. {
  22555. return getMetaEventType() == 0;
  22556. }
  22557. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22558. {
  22559. return getMetaEventType() == 47;
  22560. }
  22561. bool MidiMessage::isTextMetaEvent() const throw()
  22562. {
  22563. const int t = getMetaEventType();
  22564. return t > 0 && t < 16;
  22565. }
  22566. const String MidiMessage::getTextFromTextMetaEvent() const
  22567. {
  22568. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22569. }
  22570. bool MidiMessage::isTrackNameEvent() const throw()
  22571. {
  22572. return (data[1] == 3)
  22573. && (*data == 0xff);
  22574. }
  22575. bool MidiMessage::isTempoMetaEvent() const throw()
  22576. {
  22577. return (data[1] == 81)
  22578. && (*data == 0xff);
  22579. }
  22580. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22581. {
  22582. return (data[1] == 0x20)
  22583. && (*data == 0xff)
  22584. && (data[2] == 1);
  22585. }
  22586. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22587. {
  22588. return data[3] + 1;
  22589. }
  22590. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22591. {
  22592. if (! isTempoMetaEvent())
  22593. return 0.0;
  22594. const uint8* const d = getMetaEventData();
  22595. return (((unsigned int) d[0] << 16)
  22596. | ((unsigned int) d[1] << 8)
  22597. | d[2])
  22598. / 1000000.0;
  22599. }
  22600. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22601. {
  22602. if (timeFormat > 0)
  22603. {
  22604. if (! isTempoMetaEvent())
  22605. return 0.5 / timeFormat;
  22606. return getTempoSecondsPerQuarterNote() / timeFormat;
  22607. }
  22608. else
  22609. {
  22610. const int frameCode = (-timeFormat) >> 8;
  22611. double framesPerSecond;
  22612. switch (frameCode)
  22613. {
  22614. case 24: framesPerSecond = 24.0; break;
  22615. case 25: framesPerSecond = 25.0; break;
  22616. case 29: framesPerSecond = 29.97; break;
  22617. case 30: framesPerSecond = 30.0; break;
  22618. default: framesPerSecond = 30.0; break;
  22619. }
  22620. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22621. }
  22622. }
  22623. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22624. {
  22625. uint8 d[8];
  22626. d[0] = 0xff;
  22627. d[1] = 81;
  22628. d[2] = 3;
  22629. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22630. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22631. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22632. return MidiMessage (d, 6, 0.0);
  22633. }
  22634. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22635. {
  22636. return (data[1] == 0x58)
  22637. && (*data == (uint8) 0xff);
  22638. }
  22639. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22640. {
  22641. if (isTimeSignatureMetaEvent())
  22642. {
  22643. const uint8* const d = getMetaEventData();
  22644. numerator = d[0];
  22645. denominator = 1 << d[1];
  22646. }
  22647. else
  22648. {
  22649. numerator = 4;
  22650. denominator = 4;
  22651. }
  22652. }
  22653. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22654. {
  22655. uint8 d[8];
  22656. d[0] = 0xff;
  22657. d[1] = 0x58;
  22658. d[2] = 0x04;
  22659. d[3] = (uint8) numerator;
  22660. int n = 1;
  22661. int powerOfTwo = 0;
  22662. while (n < denominator)
  22663. {
  22664. n <<= 1;
  22665. ++powerOfTwo;
  22666. }
  22667. d[4] = (uint8) powerOfTwo;
  22668. d[5] = 0x01;
  22669. d[6] = 96;
  22670. return MidiMessage (d, 7, 0.0);
  22671. }
  22672. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22673. {
  22674. uint8 d[8];
  22675. d[0] = 0xff;
  22676. d[1] = 0x20;
  22677. d[2] = 0x01;
  22678. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22679. return MidiMessage (d, 4, 0.0);
  22680. }
  22681. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22682. {
  22683. return getMetaEventType() == 89;
  22684. }
  22685. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22686. {
  22687. return (int) *getMetaEventData();
  22688. }
  22689. const MidiMessage MidiMessage::endOfTrack() throw()
  22690. {
  22691. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22692. }
  22693. bool MidiMessage::isSongPositionPointer() const throw()
  22694. {
  22695. return *data == 0xf2;
  22696. }
  22697. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22698. {
  22699. return data[1] | (data[2] << 7);
  22700. }
  22701. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22702. {
  22703. return MidiMessage (0xf2,
  22704. positionInMidiBeats & 127,
  22705. (positionInMidiBeats >> 7) & 127);
  22706. }
  22707. bool MidiMessage::isMidiStart() const throw()
  22708. {
  22709. return *data == 0xfa;
  22710. }
  22711. const MidiMessage MidiMessage::midiStart() throw()
  22712. {
  22713. return MidiMessage (0xfa);
  22714. }
  22715. bool MidiMessage::isMidiContinue() const throw()
  22716. {
  22717. return *data == 0xfb;
  22718. }
  22719. const MidiMessage MidiMessage::midiContinue() throw()
  22720. {
  22721. return MidiMessage (0xfb);
  22722. }
  22723. bool MidiMessage::isMidiStop() const throw()
  22724. {
  22725. return *data == 0xfc;
  22726. }
  22727. const MidiMessage MidiMessage::midiStop() throw()
  22728. {
  22729. return MidiMessage (0xfc);
  22730. }
  22731. bool MidiMessage::isMidiClock() const throw()
  22732. {
  22733. return *data == 0xf8;
  22734. }
  22735. const MidiMessage MidiMessage::midiClock() throw()
  22736. {
  22737. return MidiMessage (0xf8);
  22738. }
  22739. bool MidiMessage::isQuarterFrame() const throw()
  22740. {
  22741. return *data == 0xf1;
  22742. }
  22743. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22744. {
  22745. return ((int) data[1]) >> 4;
  22746. }
  22747. int MidiMessage::getQuarterFrameValue() const throw()
  22748. {
  22749. return ((int) data[1]) & 0x0f;
  22750. }
  22751. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22752. const int value) throw()
  22753. {
  22754. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22755. }
  22756. bool MidiMessage::isFullFrame() const throw()
  22757. {
  22758. return data[0] == 0xf0
  22759. && data[1] == 0x7f
  22760. && size >= 10
  22761. && data[3] == 0x01
  22762. && data[4] == 0x01;
  22763. }
  22764. void MidiMessage::getFullFrameParameters (int& hours,
  22765. int& minutes,
  22766. int& seconds,
  22767. int& frames,
  22768. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22769. {
  22770. jassert (isFullFrame());
  22771. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22772. hours = data[5] & 0x1f;
  22773. minutes = data[6];
  22774. seconds = data[7];
  22775. frames = data[8];
  22776. }
  22777. const MidiMessage MidiMessage::fullFrame (const int hours,
  22778. const int minutes,
  22779. const int seconds,
  22780. const int frames,
  22781. MidiMessage::SmpteTimecodeType timecodeType)
  22782. {
  22783. uint8 d[10];
  22784. d[0] = 0xf0;
  22785. d[1] = 0x7f;
  22786. d[2] = 0x7f;
  22787. d[3] = 0x01;
  22788. d[4] = 0x01;
  22789. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22790. d[6] = (uint8) minutes;
  22791. d[7] = (uint8) seconds;
  22792. d[8] = (uint8) frames;
  22793. d[9] = 0xf7;
  22794. return MidiMessage (d, 10, 0.0);
  22795. }
  22796. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22797. {
  22798. return data[0] == 0xf0
  22799. && data[1] == 0x7f
  22800. && data[3] == 0x06
  22801. && size > 5;
  22802. }
  22803. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22804. {
  22805. jassert (isMidiMachineControlMessage());
  22806. return (MidiMachineControlCommand) data[4];
  22807. }
  22808. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22809. {
  22810. uint8 d[6];
  22811. d[0] = 0xf0;
  22812. d[1] = 0x7f;
  22813. d[2] = 0x00;
  22814. d[3] = 0x06;
  22815. d[4] = (uint8) command;
  22816. d[5] = 0xf7;
  22817. return MidiMessage (d, 6, 0.0);
  22818. }
  22819. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22820. int& minutes,
  22821. int& seconds,
  22822. int& frames) const throw()
  22823. {
  22824. if (size >= 12
  22825. && data[0] == 0xf0
  22826. && data[1] == 0x7f
  22827. && data[3] == 0x06
  22828. && data[4] == 0x44
  22829. && data[5] == 0x06
  22830. && data[6] == 0x01)
  22831. {
  22832. hours = data[7] % 24; // (that some machines send out hours > 24)
  22833. minutes = data[8];
  22834. seconds = data[9];
  22835. frames = data[10];
  22836. return true;
  22837. }
  22838. return false;
  22839. }
  22840. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22841. int minutes,
  22842. int seconds,
  22843. int frames)
  22844. {
  22845. uint8 d[12];
  22846. d[0] = 0xf0;
  22847. d[1] = 0x7f;
  22848. d[2] = 0x00;
  22849. d[3] = 0x06;
  22850. d[4] = 0x44;
  22851. d[5] = 0x06;
  22852. d[6] = 0x01;
  22853. d[7] = (uint8) hours;
  22854. d[8] = (uint8) minutes;
  22855. d[9] = (uint8) seconds;
  22856. d[10] = (uint8) frames;
  22857. d[11] = 0xf7;
  22858. return MidiMessage (d, 12, 0.0);
  22859. }
  22860. const String MidiMessage::getMidiNoteName (int note,
  22861. bool useSharps,
  22862. bool includeOctaveNumber,
  22863. int octaveNumForMiddleC) throw()
  22864. {
  22865. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22866. "F", "F#", "G", "G#", "A",
  22867. "A#", "B" };
  22868. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22869. "F", "Gb", "G", "Ab", "A",
  22870. "Bb", "B" };
  22871. if (((unsigned int) note) < 128)
  22872. {
  22873. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22874. : flatNoteNames [note % 12]);
  22875. if (includeOctaveNumber)
  22876. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22877. else
  22878. return s;
  22879. }
  22880. return String::empty;
  22881. }
  22882. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22883. {
  22884. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22885. return 440.0 * pow (2.0, noteNumber / 12.0);
  22886. }
  22887. const String MidiMessage::getGMInstrumentName (int n) throw()
  22888. {
  22889. const char *names[] =
  22890. {
  22891. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22892. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22893. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22894. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22895. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22896. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22897. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22898. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22899. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22900. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22901. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22902. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22903. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22904. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22905. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22906. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22907. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22908. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22909. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22910. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22911. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22912. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22913. "Applause", "Gunshot"
  22914. };
  22915. return (((unsigned int) n) < 128) ? names[n]
  22916. : (const char*)0;
  22917. }
  22918. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22919. {
  22920. const char* names[] =
  22921. {
  22922. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22923. "Bass", "Strings", "Ensemble", "Brass",
  22924. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22925. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22926. };
  22927. return (((unsigned int) n) <= 15) ? names[n]
  22928. : (const char*)0;
  22929. }
  22930. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22931. {
  22932. const char* names[] =
  22933. {
  22934. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22935. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22936. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22937. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22938. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22939. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22940. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22941. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22942. "Mute Triangle", "Open Triangle"
  22943. };
  22944. return (n >= 35 && n <= 81) ? names [n - 35]
  22945. : (const char*)0;
  22946. }
  22947. const String MidiMessage::getControllerName (int n) throw()
  22948. {
  22949. const char* names[] =
  22950. {
  22951. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22952. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22953. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22954. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22955. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22956. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22957. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22958. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22959. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22960. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22961. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22962. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22963. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22964. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22965. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22966. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22967. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22968. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22969. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22971. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22972. "Poly Operation"
  22973. };
  22974. return (((unsigned int) n) < 128) ? names[n]
  22975. : (const char*)0;
  22976. }
  22977. END_JUCE_NAMESPACE
  22978. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22979. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22980. BEGIN_JUCE_NAMESPACE
  22981. MidiMessageCollector::MidiMessageCollector()
  22982. : lastCallbackTime (0),
  22983. sampleRate (44100.0001)
  22984. {
  22985. }
  22986. MidiMessageCollector::~MidiMessageCollector()
  22987. {
  22988. }
  22989. void MidiMessageCollector::reset (const double sampleRate_)
  22990. {
  22991. jassert (sampleRate_ > 0);
  22992. const ScopedLock sl (midiCallbackLock);
  22993. sampleRate = sampleRate_;
  22994. incomingMessages.clear();
  22995. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22996. }
  22997. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22998. {
  22999. // you need to call reset() to set the correct sample rate before using this object
  23000. jassert (sampleRate != 44100.0001);
  23001. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23002. // for details of what the number should be.
  23003. jassert (message.getTimeStamp() != 0);
  23004. const ScopedLock sl (midiCallbackLock);
  23005. const int sampleNumber
  23006. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23007. incomingMessages.addEvent (message, sampleNumber);
  23008. // if the messages don't get used for over a second, we'd better
  23009. // get rid of any old ones to avoid the queue getting too big
  23010. if (sampleNumber > sampleRate)
  23011. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23012. }
  23013. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23014. const int numSamples)
  23015. {
  23016. // you need to call reset() to set the correct sample rate before using this object
  23017. jassert (sampleRate != 44100.0001);
  23018. const double timeNow = Time::getMillisecondCounterHiRes();
  23019. const double msElapsed = timeNow - lastCallbackTime;
  23020. const ScopedLock sl (midiCallbackLock);
  23021. lastCallbackTime = timeNow;
  23022. if (! incomingMessages.isEmpty())
  23023. {
  23024. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23025. int startSample = 0;
  23026. int scale = 1 << 16;
  23027. const uint8* midiData;
  23028. int numBytes, samplePosition;
  23029. MidiBuffer::Iterator iter (incomingMessages);
  23030. if (numSourceSamples > numSamples)
  23031. {
  23032. // if our list of events is longer than the buffer we're being
  23033. // asked for, scale them down to squeeze them all in..
  23034. const int maxBlockLengthToUse = numSamples << 5;
  23035. if (numSourceSamples > maxBlockLengthToUse)
  23036. {
  23037. startSample = numSourceSamples - maxBlockLengthToUse;
  23038. numSourceSamples = maxBlockLengthToUse;
  23039. iter.setNextSamplePosition (startSample);
  23040. }
  23041. scale = (numSamples << 10) / numSourceSamples;
  23042. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23043. {
  23044. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23045. destBuffer.addEvent (midiData, numBytes,
  23046. jlimit (0, numSamples - 1, samplePosition));
  23047. }
  23048. }
  23049. else
  23050. {
  23051. // if our event list is shorter than the number we need, put them
  23052. // towards the end of the buffer
  23053. startSample = numSamples - numSourceSamples;
  23054. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23055. {
  23056. destBuffer.addEvent (midiData, numBytes,
  23057. jlimit (0, numSamples - 1, samplePosition + startSample));
  23058. }
  23059. }
  23060. incomingMessages.clear();
  23061. }
  23062. }
  23063. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23064. {
  23065. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23066. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23067. addMessageToQueue (m);
  23068. }
  23069. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23070. {
  23071. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23072. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23073. addMessageToQueue (m);
  23074. }
  23075. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23076. {
  23077. addMessageToQueue (message);
  23078. }
  23079. END_JUCE_NAMESPACE
  23080. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23081. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23082. BEGIN_JUCE_NAMESPACE
  23083. MidiMessageSequence::MidiMessageSequence()
  23084. {
  23085. }
  23086. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23087. {
  23088. list.ensureStorageAllocated (other.list.size());
  23089. for (int i = 0; i < other.list.size(); ++i)
  23090. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23091. }
  23092. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23093. {
  23094. MidiMessageSequence otherCopy (other);
  23095. swapWith (otherCopy);
  23096. return *this;
  23097. }
  23098. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23099. {
  23100. list.swapWithArray (other.list);
  23101. }
  23102. MidiMessageSequence::~MidiMessageSequence()
  23103. {
  23104. }
  23105. void MidiMessageSequence::clear()
  23106. {
  23107. list.clear();
  23108. }
  23109. int MidiMessageSequence::getNumEvents() const
  23110. {
  23111. return list.size();
  23112. }
  23113. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23114. {
  23115. return list [index];
  23116. }
  23117. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23118. {
  23119. const MidiEventHolder* const meh = list [index];
  23120. if (meh != 0 && meh->noteOffObject != 0)
  23121. return meh->noteOffObject->message.getTimeStamp();
  23122. else
  23123. return 0.0;
  23124. }
  23125. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23126. {
  23127. const MidiEventHolder* const meh = list [index];
  23128. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23129. }
  23130. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23131. {
  23132. return list.indexOf (event);
  23133. }
  23134. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23135. {
  23136. const int numEvents = list.size();
  23137. int i;
  23138. for (i = 0; i < numEvents; ++i)
  23139. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23140. break;
  23141. return i;
  23142. }
  23143. double MidiMessageSequence::getStartTime() const
  23144. {
  23145. if (list.size() > 0)
  23146. return list.getUnchecked(0)->message.getTimeStamp();
  23147. else
  23148. return 0;
  23149. }
  23150. double MidiMessageSequence::getEndTime() const
  23151. {
  23152. if (list.size() > 0)
  23153. return list.getLast()->message.getTimeStamp();
  23154. else
  23155. return 0;
  23156. }
  23157. double MidiMessageSequence::getEventTime (const int index) const
  23158. {
  23159. if (((unsigned int) index) < (unsigned int) list.size())
  23160. return list.getUnchecked (index)->message.getTimeStamp();
  23161. return 0.0;
  23162. }
  23163. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23164. double timeAdjustment)
  23165. {
  23166. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23167. timeAdjustment += newMessage.getTimeStamp();
  23168. newOne->message.setTimeStamp (timeAdjustment);
  23169. int i;
  23170. for (i = list.size(); --i >= 0;)
  23171. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23172. break;
  23173. list.insert (i + 1, newOne);
  23174. }
  23175. void MidiMessageSequence::deleteEvent (const int index,
  23176. const bool deleteMatchingNoteUp)
  23177. {
  23178. if (((unsigned int) index) < (unsigned int) list.size())
  23179. {
  23180. if (deleteMatchingNoteUp)
  23181. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23182. list.remove (index);
  23183. }
  23184. }
  23185. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23186. double timeAdjustment,
  23187. double firstAllowableTime,
  23188. double endOfAllowableDestTimes)
  23189. {
  23190. firstAllowableTime -= timeAdjustment;
  23191. endOfAllowableDestTimes -= timeAdjustment;
  23192. for (int i = 0; i < other.list.size(); ++i)
  23193. {
  23194. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23195. const double t = m.getTimeStamp();
  23196. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23197. {
  23198. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23199. newOne->message.setTimeStamp (timeAdjustment + t);
  23200. list.add (newOne);
  23201. }
  23202. }
  23203. sort();
  23204. }
  23205. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23206. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23207. {
  23208. const double diff = first->message.getTimeStamp()
  23209. - second->message.getTimeStamp();
  23210. return (diff > 0) - (diff < 0);
  23211. }
  23212. void MidiMessageSequence::sort()
  23213. {
  23214. list.sort (*this, true);
  23215. }
  23216. void MidiMessageSequence::updateMatchedPairs()
  23217. {
  23218. for (int i = 0; i < list.size(); ++i)
  23219. {
  23220. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23221. if (m1.isNoteOn())
  23222. {
  23223. list.getUnchecked(i)->noteOffObject = 0;
  23224. const int note = m1.getNoteNumber();
  23225. const int chan = m1.getChannel();
  23226. const int len = list.size();
  23227. for (int j = i + 1; j < len; ++j)
  23228. {
  23229. const MidiMessage& m = list.getUnchecked(j)->message;
  23230. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23231. {
  23232. if (m.isNoteOff())
  23233. {
  23234. list.getUnchecked(i)->noteOffObject = list[j];
  23235. break;
  23236. }
  23237. else if (m.isNoteOn())
  23238. {
  23239. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23240. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23241. list.getUnchecked(i)->noteOffObject = list[j];
  23242. break;
  23243. }
  23244. }
  23245. }
  23246. }
  23247. }
  23248. }
  23249. void MidiMessageSequence::addTimeToMessages (const double delta)
  23250. {
  23251. for (int i = list.size(); --i >= 0;)
  23252. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23253. + delta);
  23254. }
  23255. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23256. MidiMessageSequence& destSequence,
  23257. const bool alsoIncludeMetaEvents) const
  23258. {
  23259. for (int i = 0; i < list.size(); ++i)
  23260. {
  23261. const MidiMessage& mm = list.getUnchecked(i)->message;
  23262. if (mm.isForChannel (channelNumberToExtract)
  23263. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23264. {
  23265. destSequence.addEvent (mm);
  23266. }
  23267. }
  23268. }
  23269. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23270. {
  23271. for (int i = 0; i < list.size(); ++i)
  23272. {
  23273. const MidiMessage& mm = list.getUnchecked(i)->message;
  23274. if (mm.isSysEx())
  23275. destSequence.addEvent (mm);
  23276. }
  23277. }
  23278. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23279. {
  23280. for (int i = list.size(); --i >= 0;)
  23281. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23282. list.remove(i);
  23283. }
  23284. void MidiMessageSequence::deleteSysExMessages()
  23285. {
  23286. for (int i = list.size(); --i >= 0;)
  23287. if (list.getUnchecked(i)->message.isSysEx())
  23288. list.remove(i);
  23289. }
  23290. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23291. const double time,
  23292. OwnedArray<MidiMessage>& dest)
  23293. {
  23294. bool doneProg = false;
  23295. bool donePitchWheel = false;
  23296. Array <int> doneControllers;
  23297. doneControllers.ensureStorageAllocated (32);
  23298. for (int i = list.size(); --i >= 0;)
  23299. {
  23300. const MidiMessage& mm = list.getUnchecked(i)->message;
  23301. if (mm.isForChannel (channelNumber)
  23302. && mm.getTimeStamp() <= time)
  23303. {
  23304. if (mm.isProgramChange())
  23305. {
  23306. if (! doneProg)
  23307. {
  23308. dest.add (new MidiMessage (mm, 0.0));
  23309. doneProg = true;
  23310. }
  23311. }
  23312. else if (mm.isController())
  23313. {
  23314. if (! doneControllers.contains (mm.getControllerNumber()))
  23315. {
  23316. dest.add (new MidiMessage (mm, 0.0));
  23317. doneControllers.add (mm.getControllerNumber());
  23318. }
  23319. }
  23320. else if (mm.isPitchWheel())
  23321. {
  23322. if (! donePitchWheel)
  23323. {
  23324. dest.add (new MidiMessage (mm, 0.0));
  23325. donePitchWheel = true;
  23326. }
  23327. }
  23328. }
  23329. }
  23330. }
  23331. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23332. : message (message_),
  23333. noteOffObject (0)
  23334. {
  23335. }
  23336. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23337. {
  23338. }
  23339. END_JUCE_NAMESPACE
  23340. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23341. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23342. BEGIN_JUCE_NAMESPACE
  23343. AudioPluginFormat::AudioPluginFormat() throw()
  23344. {
  23345. }
  23346. AudioPluginFormat::~AudioPluginFormat()
  23347. {
  23348. }
  23349. END_JUCE_NAMESPACE
  23350. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23351. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23352. BEGIN_JUCE_NAMESPACE
  23353. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23354. {
  23355. }
  23356. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23357. {
  23358. clearSingletonInstance();
  23359. }
  23360. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23361. void AudioPluginFormatManager::addDefaultFormats()
  23362. {
  23363. #if JUCE_DEBUG
  23364. // you should only call this method once!
  23365. for (int i = formats.size(); --i >= 0;)
  23366. {
  23367. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23368. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23369. #endif
  23370. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23371. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23372. #endif
  23373. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23374. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23375. #endif
  23376. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23377. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23378. #endif
  23379. }
  23380. #endif
  23381. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23382. formats.add (new AudioUnitPluginFormat());
  23383. #endif
  23384. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23385. formats.add (new VSTPluginFormat());
  23386. #endif
  23387. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23388. formats.add (new DirectXPluginFormat());
  23389. #endif
  23390. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23391. formats.add (new LADSPAPluginFormat());
  23392. #endif
  23393. }
  23394. int AudioPluginFormatManager::getNumFormats() throw()
  23395. {
  23396. return formats.size();
  23397. }
  23398. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23399. {
  23400. return formats [index];
  23401. }
  23402. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23403. {
  23404. formats.add (format);
  23405. }
  23406. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23407. String& errorMessage) const
  23408. {
  23409. AudioPluginInstance* result = 0;
  23410. for (int i = 0; i < formats.size(); ++i)
  23411. {
  23412. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23413. if (result != 0)
  23414. break;
  23415. }
  23416. if (result == 0)
  23417. {
  23418. if (! doesPluginStillExist (description))
  23419. errorMessage = TRANS ("This plug-in file no longer exists");
  23420. else
  23421. errorMessage = TRANS ("This plug-in failed to load correctly");
  23422. }
  23423. return result;
  23424. }
  23425. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23426. {
  23427. for (int i = 0; i < formats.size(); ++i)
  23428. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23429. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23430. return false;
  23431. }
  23432. END_JUCE_NAMESPACE
  23433. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23434. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23435. #define JUCE_PLUGIN_HOST 1
  23436. BEGIN_JUCE_NAMESPACE
  23437. AudioPluginInstance::AudioPluginInstance()
  23438. {
  23439. }
  23440. AudioPluginInstance::~AudioPluginInstance()
  23441. {
  23442. }
  23443. END_JUCE_NAMESPACE
  23444. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23445. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23446. BEGIN_JUCE_NAMESPACE
  23447. KnownPluginList::KnownPluginList()
  23448. {
  23449. }
  23450. KnownPluginList::~KnownPluginList()
  23451. {
  23452. }
  23453. void KnownPluginList::clear()
  23454. {
  23455. if (types.size() > 0)
  23456. {
  23457. types.clear();
  23458. sendChangeMessage (this);
  23459. }
  23460. }
  23461. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23462. {
  23463. for (int i = 0; i < types.size(); ++i)
  23464. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23465. return types.getUnchecked(i);
  23466. return 0;
  23467. }
  23468. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23469. {
  23470. for (int i = 0; i < types.size(); ++i)
  23471. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23472. return types.getUnchecked(i);
  23473. return 0;
  23474. }
  23475. bool KnownPluginList::addType (const PluginDescription& type)
  23476. {
  23477. for (int i = types.size(); --i >= 0;)
  23478. {
  23479. if (types.getUnchecked(i)->isDuplicateOf (type))
  23480. {
  23481. // strange - found a duplicate plugin with different info..
  23482. jassert (types.getUnchecked(i)->name == type.name);
  23483. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23484. *types.getUnchecked(i) = type;
  23485. return false;
  23486. }
  23487. }
  23488. types.add (new PluginDescription (type));
  23489. sendChangeMessage (this);
  23490. return true;
  23491. }
  23492. void KnownPluginList::removeType (const int index) throw()
  23493. {
  23494. types.remove (index);
  23495. sendChangeMessage (this);
  23496. }
  23497. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23498. {
  23499. if (fileOrIdentifier.startsWithChar ('/')
  23500. || fileOrIdentifier[1] == ':')
  23501. {
  23502. return File (fileOrIdentifier).getLastModificationTime();
  23503. }
  23504. return Time (0);
  23505. }
  23506. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23507. {
  23508. return t1 != t2 || t1 == Time (0);
  23509. }
  23510. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23511. {
  23512. if (getTypeForFile (fileOrIdentifier) == 0)
  23513. return false;
  23514. for (int i = types.size(); --i >= 0;)
  23515. {
  23516. const PluginDescription* const d = types.getUnchecked(i);
  23517. if (d->fileOrIdentifier == fileOrIdentifier
  23518. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23519. {
  23520. return false;
  23521. }
  23522. }
  23523. return true;
  23524. }
  23525. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23526. const bool dontRescanIfAlreadyInList,
  23527. OwnedArray <PluginDescription>& typesFound,
  23528. AudioPluginFormat& format)
  23529. {
  23530. bool addedOne = false;
  23531. if (dontRescanIfAlreadyInList
  23532. && getTypeForFile (fileOrIdentifier) != 0)
  23533. {
  23534. bool needsRescanning = false;
  23535. for (int i = types.size(); --i >= 0;)
  23536. {
  23537. const PluginDescription* const d = types.getUnchecked(i);
  23538. if (d->fileOrIdentifier == fileOrIdentifier)
  23539. {
  23540. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23541. needsRescanning = true;
  23542. else
  23543. typesFound.add (new PluginDescription (*d));
  23544. }
  23545. }
  23546. if (! needsRescanning)
  23547. return false;
  23548. }
  23549. OwnedArray <PluginDescription> found;
  23550. format.findAllTypesForFile (found, fileOrIdentifier);
  23551. for (int i = 0; i < found.size(); ++i)
  23552. {
  23553. PluginDescription* const desc = found.getUnchecked(i);
  23554. jassert (desc != 0);
  23555. if (addType (*desc))
  23556. addedOne = true;
  23557. typesFound.add (new PluginDescription (*desc));
  23558. }
  23559. return addedOne;
  23560. }
  23561. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23562. OwnedArray <PluginDescription>& typesFound)
  23563. {
  23564. for (int i = 0; i < files.size(); ++i)
  23565. {
  23566. bool loaded = false;
  23567. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23568. {
  23569. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23570. if (scanAndAddFile (files[i], true, typesFound, *format))
  23571. loaded = true;
  23572. }
  23573. if (! loaded)
  23574. {
  23575. const File f (files[i]);
  23576. if (f.isDirectory())
  23577. {
  23578. StringArray s;
  23579. {
  23580. Array<File> subFiles;
  23581. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23582. for (int j = 0; j < subFiles.size(); ++j)
  23583. s.add (subFiles.getReference(j).getFullPathName());
  23584. }
  23585. scanAndAddDragAndDroppedFiles (s, typesFound);
  23586. }
  23587. }
  23588. }
  23589. }
  23590. class PluginSorter
  23591. {
  23592. public:
  23593. KnownPluginList::SortMethod method;
  23594. PluginSorter() throw() {}
  23595. int compareElements (const PluginDescription* const first,
  23596. const PluginDescription* const second) const throw()
  23597. {
  23598. int diff = 0;
  23599. if (method == KnownPluginList::sortByCategory)
  23600. diff = first->category.compareLexicographically (second->category);
  23601. else if (method == KnownPluginList::sortByManufacturer)
  23602. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23603. else if (method == KnownPluginList::sortByFileSystemLocation)
  23604. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23605. .upToLastOccurrenceOf ("/", false, false)
  23606. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23607. .upToLastOccurrenceOf ("/", false, false));
  23608. if (diff == 0)
  23609. diff = first->name.compareLexicographically (second->name);
  23610. return diff;
  23611. }
  23612. };
  23613. void KnownPluginList::sort (const SortMethod method)
  23614. {
  23615. if (method != defaultOrder)
  23616. {
  23617. PluginSorter sorter;
  23618. sorter.method = method;
  23619. types.sort (sorter, true);
  23620. sendChangeMessage (this);
  23621. }
  23622. }
  23623. XmlElement* KnownPluginList::createXml() const
  23624. {
  23625. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23626. for (int i = 0; i < types.size(); ++i)
  23627. e->addChildElement (types.getUnchecked(i)->createXml());
  23628. return e;
  23629. }
  23630. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23631. {
  23632. clear();
  23633. if (xml.hasTagName ("KNOWNPLUGINS"))
  23634. {
  23635. forEachXmlChildElement (xml, e)
  23636. {
  23637. PluginDescription info;
  23638. if (info.loadFromXml (*e))
  23639. addType (info);
  23640. }
  23641. }
  23642. }
  23643. const int menuIdBase = 0x324503f4;
  23644. // This is used to turn a bunch of paths into a nested menu structure.
  23645. struct PluginFilesystemTree
  23646. {
  23647. private:
  23648. String folder;
  23649. OwnedArray <PluginFilesystemTree> subFolders;
  23650. Array <PluginDescription*> plugins;
  23651. void addPlugin (PluginDescription* const pd, const String& path)
  23652. {
  23653. if (path.isEmpty())
  23654. {
  23655. plugins.add (pd);
  23656. }
  23657. else
  23658. {
  23659. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23660. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23661. for (int i = subFolders.size(); --i >= 0;)
  23662. {
  23663. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23664. {
  23665. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23666. return;
  23667. }
  23668. }
  23669. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23670. newFolder->folder = firstSubFolder;
  23671. subFolders.add (newFolder);
  23672. newFolder->addPlugin (pd, remainingPath);
  23673. }
  23674. }
  23675. // removes any deeply nested folders that don't contain any actual plugins
  23676. void optimise()
  23677. {
  23678. for (int i = subFolders.size(); --i >= 0;)
  23679. {
  23680. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23681. sub->optimise();
  23682. if (sub->plugins.size() == 0)
  23683. {
  23684. for (int j = 0; j < sub->subFolders.size(); ++j)
  23685. subFolders.add (sub->subFolders.getUnchecked(j));
  23686. sub->subFolders.clear (false);
  23687. subFolders.remove (i);
  23688. }
  23689. }
  23690. }
  23691. public:
  23692. void buildTree (const Array <PluginDescription*>& allPlugins)
  23693. {
  23694. for (int i = 0; i < allPlugins.size(); ++i)
  23695. {
  23696. String path (allPlugins.getUnchecked(i)
  23697. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23698. .upToLastOccurrenceOf ("/", false, false));
  23699. if (path.substring (1, 2) == ":")
  23700. path = path.substring (2);
  23701. addPlugin (allPlugins.getUnchecked(i), path);
  23702. }
  23703. optimise();
  23704. }
  23705. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23706. {
  23707. int i;
  23708. for (i = 0; i < subFolders.size(); ++i)
  23709. {
  23710. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23711. PopupMenu subMenu;
  23712. sub->addToMenu (subMenu, allPlugins);
  23713. #if JUCE_MAC
  23714. // avoid the special AU formatting nonsense on Mac..
  23715. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23716. #else
  23717. m.addSubMenu (sub->folder, subMenu);
  23718. #endif
  23719. }
  23720. for (i = 0; i < plugins.size(); ++i)
  23721. {
  23722. PluginDescription* const plugin = plugins.getUnchecked(i);
  23723. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23724. plugin->name, true, false);
  23725. }
  23726. }
  23727. };
  23728. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23729. {
  23730. Array <PluginDescription*> sorted;
  23731. {
  23732. PluginSorter sorter;
  23733. sorter.method = sortMethod;
  23734. for (int i = 0; i < types.size(); ++i)
  23735. sorted.addSorted (sorter, types.getUnchecked(i));
  23736. }
  23737. if (sortMethod == sortByCategory
  23738. || sortMethod == sortByManufacturer)
  23739. {
  23740. String lastSubMenuName;
  23741. PopupMenu sub;
  23742. for (int i = 0; i < sorted.size(); ++i)
  23743. {
  23744. const PluginDescription* const pd = sorted.getUnchecked(i);
  23745. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23746. : pd->manufacturerName);
  23747. if (! thisSubMenuName.containsNonWhitespaceChars())
  23748. thisSubMenuName = "Other";
  23749. if (thisSubMenuName != lastSubMenuName)
  23750. {
  23751. if (sub.getNumItems() > 0)
  23752. {
  23753. menu.addSubMenu (lastSubMenuName, sub);
  23754. sub.clear();
  23755. }
  23756. lastSubMenuName = thisSubMenuName;
  23757. }
  23758. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23759. }
  23760. if (sub.getNumItems() > 0)
  23761. menu.addSubMenu (lastSubMenuName, sub);
  23762. }
  23763. else if (sortMethod == sortByFileSystemLocation)
  23764. {
  23765. PluginFilesystemTree root;
  23766. root.buildTree (sorted);
  23767. root.addToMenu (menu, types);
  23768. }
  23769. else
  23770. {
  23771. for (int i = 0; i < sorted.size(); ++i)
  23772. {
  23773. const PluginDescription* const pd = sorted.getUnchecked(i);
  23774. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23775. }
  23776. }
  23777. }
  23778. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23779. {
  23780. const int i = menuResultCode - menuIdBase;
  23781. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23782. }
  23783. END_JUCE_NAMESPACE
  23784. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23785. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23786. BEGIN_JUCE_NAMESPACE
  23787. PluginDescription::PluginDescription() throw()
  23788. : uid (0),
  23789. isInstrument (false),
  23790. numInputChannels (0),
  23791. numOutputChannels (0)
  23792. {
  23793. }
  23794. PluginDescription::~PluginDescription() throw()
  23795. {
  23796. }
  23797. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23798. : name (other.name),
  23799. pluginFormatName (other.pluginFormatName),
  23800. category (other.category),
  23801. manufacturerName (other.manufacturerName),
  23802. version (other.version),
  23803. fileOrIdentifier (other.fileOrIdentifier),
  23804. lastFileModTime (other.lastFileModTime),
  23805. uid (other.uid),
  23806. isInstrument (other.isInstrument),
  23807. numInputChannels (other.numInputChannels),
  23808. numOutputChannels (other.numOutputChannels)
  23809. {
  23810. }
  23811. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23812. {
  23813. name = other.name;
  23814. pluginFormatName = other.pluginFormatName;
  23815. category = other.category;
  23816. manufacturerName = other.manufacturerName;
  23817. version = other.version;
  23818. fileOrIdentifier = other.fileOrIdentifier;
  23819. uid = other.uid;
  23820. isInstrument = other.isInstrument;
  23821. lastFileModTime = other.lastFileModTime;
  23822. numInputChannels = other.numInputChannels;
  23823. numOutputChannels = other.numOutputChannels;
  23824. return *this;
  23825. }
  23826. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23827. {
  23828. return fileOrIdentifier == other.fileOrIdentifier
  23829. && uid == other.uid;
  23830. }
  23831. const String PluginDescription::createIdentifierString() const throw()
  23832. {
  23833. return pluginFormatName
  23834. + "-" + name
  23835. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23836. + "-" + String::toHexString (uid);
  23837. }
  23838. XmlElement* PluginDescription::createXml() const
  23839. {
  23840. XmlElement* const e = new XmlElement ("PLUGIN");
  23841. e->setAttribute ("name", name);
  23842. e->setAttribute ("format", pluginFormatName);
  23843. e->setAttribute ("category", category);
  23844. e->setAttribute ("manufacturer", manufacturerName);
  23845. e->setAttribute ("version", version);
  23846. e->setAttribute ("file", fileOrIdentifier);
  23847. e->setAttribute ("uid", String::toHexString (uid));
  23848. e->setAttribute ("isInstrument", isInstrument);
  23849. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23850. e->setAttribute ("numInputs", numInputChannels);
  23851. e->setAttribute ("numOutputs", numOutputChannels);
  23852. return e;
  23853. }
  23854. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23855. {
  23856. if (xml.hasTagName ("PLUGIN"))
  23857. {
  23858. name = xml.getStringAttribute ("name");
  23859. pluginFormatName = xml.getStringAttribute ("format");
  23860. category = xml.getStringAttribute ("category");
  23861. manufacturerName = xml.getStringAttribute ("manufacturer");
  23862. version = xml.getStringAttribute ("version");
  23863. fileOrIdentifier = xml.getStringAttribute ("file");
  23864. uid = xml.getStringAttribute ("uid").getHexValue32();
  23865. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23866. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23867. numInputChannels = xml.getIntAttribute ("numInputs");
  23868. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23869. return true;
  23870. }
  23871. return false;
  23872. }
  23873. END_JUCE_NAMESPACE
  23874. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23875. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23876. BEGIN_JUCE_NAMESPACE
  23877. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23878. AudioPluginFormat& formatToLookFor,
  23879. FileSearchPath directoriesToSearch,
  23880. const bool recursive,
  23881. const File& deadMansPedalFile_)
  23882. : list (listToAddTo),
  23883. format (formatToLookFor),
  23884. deadMansPedalFile (deadMansPedalFile_),
  23885. nextIndex (0),
  23886. progress (0)
  23887. {
  23888. directoriesToSearch.removeRedundantPaths();
  23889. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23890. // If any plugins have crashed recently when being loaded, move them to the
  23891. // end of the list to give the others a chance to load correctly..
  23892. const StringArray crashedPlugins (getDeadMansPedalFile());
  23893. for (int i = 0; i < crashedPlugins.size(); ++i)
  23894. {
  23895. const String f = crashedPlugins[i];
  23896. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23897. if (f == filesOrIdentifiersToScan[j])
  23898. filesOrIdentifiersToScan.move (j, -1);
  23899. }
  23900. }
  23901. PluginDirectoryScanner::~PluginDirectoryScanner()
  23902. {
  23903. }
  23904. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23905. {
  23906. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23907. }
  23908. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23909. {
  23910. String file (filesOrIdentifiersToScan [nextIndex]);
  23911. if (file.isNotEmpty())
  23912. {
  23913. if (! list.isListingUpToDate (file))
  23914. {
  23915. OwnedArray <PluginDescription> typesFound;
  23916. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23917. StringArray crashedPlugins (getDeadMansPedalFile());
  23918. crashedPlugins.removeString (file);
  23919. crashedPlugins.add (file);
  23920. setDeadMansPedalFile (crashedPlugins);
  23921. list.scanAndAddFile (file,
  23922. dontRescanIfAlreadyInList,
  23923. typesFound,
  23924. format);
  23925. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23926. crashedPlugins.removeString (file);
  23927. setDeadMansPedalFile (crashedPlugins);
  23928. if (typesFound.size() == 0)
  23929. failedFiles.add (file);
  23930. }
  23931. ++nextIndex;
  23932. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23933. }
  23934. return nextIndex < filesOrIdentifiersToScan.size();
  23935. }
  23936. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23937. {
  23938. StringArray lines;
  23939. if (deadMansPedalFile != File::nonexistent)
  23940. {
  23941. lines.addLines (deadMansPedalFile.loadFileAsString());
  23942. lines.removeEmptyStrings();
  23943. }
  23944. return lines;
  23945. }
  23946. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23947. {
  23948. if (deadMansPedalFile != File::nonexistent)
  23949. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23950. }
  23951. END_JUCE_NAMESPACE
  23952. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23953. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23954. BEGIN_JUCE_NAMESPACE
  23955. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23956. const File& deadMansPedalFile_,
  23957. PropertiesFile* const propertiesToUse_)
  23958. : list (listToEdit),
  23959. deadMansPedalFile (deadMansPedalFile_),
  23960. propertiesToUse (propertiesToUse_)
  23961. {
  23962. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23963. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23964. optionsButton->addButtonListener (this);
  23965. optionsButton->setTriggeredOnMouseDown (true);
  23966. setSize (400, 600);
  23967. list.addChangeListener (this);
  23968. }
  23969. PluginListComponent::~PluginListComponent()
  23970. {
  23971. list.removeChangeListener (this);
  23972. deleteAllChildren();
  23973. }
  23974. void PluginListComponent::resized()
  23975. {
  23976. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23977. optionsButton->changeWidthToFitText (24);
  23978. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23979. }
  23980. void PluginListComponent::changeListenerCallback (void*)
  23981. {
  23982. listBox->updateContent();
  23983. listBox->repaint();
  23984. }
  23985. int PluginListComponent::getNumRows()
  23986. {
  23987. return list.getNumTypes();
  23988. }
  23989. void PluginListComponent::paintListBoxItem (int row,
  23990. Graphics& g,
  23991. int width, int height,
  23992. bool rowIsSelected)
  23993. {
  23994. if (rowIsSelected)
  23995. g.fillAll (findColour (TextEditor::highlightColourId));
  23996. const PluginDescription* const pd = list.getType (row);
  23997. if (pd != 0)
  23998. {
  23999. GlyphArrangement ga;
  24000. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24001. g.setColour (Colours::black);
  24002. ga.draw (g);
  24003. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24004. String desc;
  24005. desc << pd->pluginFormatName
  24006. << (pd->isInstrument ? " instrument" : " effect")
  24007. << " - "
  24008. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24009. << " / "
  24010. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24011. if (pd->manufacturerName.isNotEmpty())
  24012. desc << " - " << pd->manufacturerName;
  24013. if (pd->version.isNotEmpty())
  24014. desc << " - " << pd->version;
  24015. if (pd->category.isNotEmpty())
  24016. desc << " - category: '" << pd->category << '\'';
  24017. g.setColour (Colours::grey);
  24018. ga.clear();
  24019. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24020. ga.draw (g);
  24021. }
  24022. }
  24023. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24024. {
  24025. list.removeType (lastRowSelected);
  24026. }
  24027. void PluginListComponent::buttonClicked (Button* b)
  24028. {
  24029. if (optionsButton == b)
  24030. {
  24031. PopupMenu menu;
  24032. menu.addItem (1, TRANS("Clear list"));
  24033. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24034. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24035. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24036. menu.addSeparator();
  24037. menu.addItem (2, TRANS("Sort alphabetically"));
  24038. menu.addItem (3, TRANS("Sort by category"));
  24039. menu.addItem (4, TRANS("Sort by manufacturer"));
  24040. menu.addSeparator();
  24041. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24042. {
  24043. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24044. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24045. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24046. }
  24047. const int r = menu.showAt (optionsButton);
  24048. if (r == 1)
  24049. {
  24050. list.clear();
  24051. }
  24052. else if (r == 2)
  24053. {
  24054. list.sort (KnownPluginList::sortAlphabetically);
  24055. }
  24056. else if (r == 3)
  24057. {
  24058. list.sort (KnownPluginList::sortByCategory);
  24059. }
  24060. else if (r == 4)
  24061. {
  24062. list.sort (KnownPluginList::sortByManufacturer);
  24063. }
  24064. else if (r == 5)
  24065. {
  24066. const SparseSet <int> selected (listBox->getSelectedRows());
  24067. for (int i = list.getNumTypes(); --i >= 0;)
  24068. if (selected.contains (i))
  24069. list.removeType (i);
  24070. }
  24071. else if (r == 6)
  24072. {
  24073. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24074. if (desc != 0)
  24075. {
  24076. if (File (desc->fileOrIdentifier).existsAsFile())
  24077. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24078. }
  24079. }
  24080. else if (r == 7)
  24081. {
  24082. for (int i = list.getNumTypes(); --i >= 0;)
  24083. {
  24084. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24085. {
  24086. list.removeType (i);
  24087. }
  24088. }
  24089. }
  24090. else if (r != 0)
  24091. {
  24092. typeToScan = r - 10;
  24093. startTimer (1);
  24094. }
  24095. }
  24096. }
  24097. void PluginListComponent::timerCallback()
  24098. {
  24099. stopTimer();
  24100. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24101. }
  24102. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24103. {
  24104. return true;
  24105. }
  24106. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24107. {
  24108. OwnedArray <PluginDescription> typesFound;
  24109. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24110. }
  24111. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24112. {
  24113. if (format == 0)
  24114. return;
  24115. FileSearchPath path (format->getDefaultLocationsToSearch());
  24116. if (propertiesToUse != 0)
  24117. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24118. {
  24119. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24120. FileSearchPathListComponent pathList;
  24121. pathList.setSize (500, 300);
  24122. pathList.setPath (path);
  24123. aw.addCustomComponent (&pathList);
  24124. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24125. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24126. if (aw.runModalLoop() == 0)
  24127. return;
  24128. path = pathList.getPath();
  24129. }
  24130. if (propertiesToUse != 0)
  24131. {
  24132. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24133. propertiesToUse->saveIfNeeded();
  24134. }
  24135. double progress = 0.0;
  24136. AlertWindow aw (TRANS("Scanning for plugins..."),
  24137. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24138. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24139. aw.addProgressBarComponent (progress);
  24140. aw.enterModalState();
  24141. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24142. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24143. for (;;)
  24144. {
  24145. aw.setMessage (TRANS("Testing:\n\n")
  24146. + scanner.getNextPluginFileThatWillBeScanned());
  24147. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24148. if (! scanner.scanNextFile (true))
  24149. break;
  24150. if (! aw.isCurrentlyModal())
  24151. break;
  24152. progress = scanner.getProgress();
  24153. }
  24154. if (scanner.getFailedFiles().size() > 0)
  24155. {
  24156. StringArray shortNames;
  24157. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24158. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24159. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24160. TRANS("Scan complete"),
  24161. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24162. + shortNames.joinIntoString (", "));
  24163. }
  24164. }
  24165. END_JUCE_NAMESPACE
  24166. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24167. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24168. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24169. #include <AudioUnit/AudioUnit.h>
  24170. #include <AudioUnit/AUCocoaUIView.h>
  24171. #include <CoreAudioKit/AUGenericView.h>
  24172. #if JUCE_SUPPORT_CARBON
  24173. #include <AudioToolbox/AudioUnitUtilities.h>
  24174. #include <AudioUnit/AudioUnitCarbonView.h>
  24175. #endif
  24176. BEGIN_JUCE_NAMESPACE
  24177. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24178. #endif
  24179. #if JUCE_MAC
  24180. // Change this to disable logging of various activities
  24181. #ifndef AU_LOGGING
  24182. #define AU_LOGGING 1
  24183. #endif
  24184. #if AU_LOGGING
  24185. #define log(a) Logger::writeToLog(a);
  24186. #else
  24187. #define log(a)
  24188. #endif
  24189. namespace AudioUnitFormatHelpers
  24190. {
  24191. static int insideCallback = 0;
  24192. static const String osTypeToString (OSType type)
  24193. {
  24194. char s[4];
  24195. s[0] = (char) (((uint32) type) >> 24);
  24196. s[1] = (char) (((uint32) type) >> 16);
  24197. s[2] = (char) (((uint32) type) >> 8);
  24198. s[3] = (char) ((uint32) type);
  24199. return String (s, 4);
  24200. }
  24201. static OSType stringToOSType (const String& s1)
  24202. {
  24203. const String s (s1 + " ");
  24204. return (((OSType) (unsigned char) s[0]) << 24)
  24205. | (((OSType) (unsigned char) s[1]) << 16)
  24206. | (((OSType) (unsigned char) s[2]) << 8)
  24207. | ((OSType) (unsigned char) s[3]);
  24208. }
  24209. static const char* auIdentifierPrefix = "AudioUnit:";
  24210. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24211. {
  24212. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24213. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24214. String s (auIdentifierPrefix);
  24215. if (desc.componentType == kAudioUnitType_MusicDevice)
  24216. s << "Synths/";
  24217. else if (desc.componentType == kAudioUnitType_MusicEffect
  24218. || desc.componentType == kAudioUnitType_Effect)
  24219. s << "Effects/";
  24220. else if (desc.componentType == kAudioUnitType_Generator)
  24221. s << "Generators/";
  24222. else if (desc.componentType == kAudioUnitType_Panner)
  24223. s << "Panners/";
  24224. s << osTypeToString (desc.componentType) << ","
  24225. << osTypeToString (desc.componentSubType) << ","
  24226. << osTypeToString (desc.componentManufacturer);
  24227. return s;
  24228. }
  24229. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24230. {
  24231. Handle componentNameHandle = NewHandle (sizeof (void*));
  24232. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24233. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24234. {
  24235. ComponentDescription desc;
  24236. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24237. {
  24238. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24239. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24240. if (nameString != 0 && nameString[0] != 0)
  24241. {
  24242. const String all ((const char*) nameString + 1, nameString[0]);
  24243. DBG ("name: "+ all);
  24244. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24245. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24246. }
  24247. if (infoString != 0 && infoString[0] != 0)
  24248. {
  24249. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24250. }
  24251. if (name.isEmpty())
  24252. name = "<Unknown>";
  24253. }
  24254. DisposeHandle (componentNameHandle);
  24255. DisposeHandle (componentInfoHandle);
  24256. }
  24257. }
  24258. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24259. String& name, String& version, String& manufacturer)
  24260. {
  24261. zerostruct (desc);
  24262. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24263. {
  24264. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24265. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24266. StringArray tokens;
  24267. tokens.addTokens (s, ",", String::empty);
  24268. tokens.trim();
  24269. tokens.removeEmptyStrings();
  24270. if (tokens.size() == 3)
  24271. {
  24272. desc.componentType = stringToOSType (tokens[0]);
  24273. desc.componentSubType = stringToOSType (tokens[1]);
  24274. desc.componentManufacturer = stringToOSType (tokens[2]);
  24275. ComponentRecord* comp = FindNextComponent (0, &desc);
  24276. if (comp != 0)
  24277. {
  24278. getAUDetails (comp, name, manufacturer);
  24279. return true;
  24280. }
  24281. }
  24282. }
  24283. return false;
  24284. }
  24285. }
  24286. class AudioUnitPluginWindowCarbon;
  24287. class AudioUnitPluginWindowCocoa;
  24288. class AudioUnitPluginInstance : public AudioPluginInstance
  24289. {
  24290. public:
  24291. ~AudioUnitPluginInstance();
  24292. // AudioPluginInstance methods:
  24293. void fillInPluginDescription (PluginDescription& desc) const
  24294. {
  24295. desc.name = pluginName;
  24296. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24297. desc.uid = ((int) componentDesc.componentType)
  24298. ^ ((int) componentDesc.componentSubType)
  24299. ^ ((int) componentDesc.componentManufacturer);
  24300. desc.lastFileModTime = 0;
  24301. desc.pluginFormatName = "AudioUnit";
  24302. desc.category = getCategory();
  24303. desc.manufacturerName = manufacturer;
  24304. desc.version = version;
  24305. desc.numInputChannels = getNumInputChannels();
  24306. desc.numOutputChannels = getNumOutputChannels();
  24307. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24308. }
  24309. const String getName() const { return pluginName; }
  24310. bool acceptsMidi() const { return wantsMidiMessages; }
  24311. bool producesMidi() const { return false; }
  24312. // AudioProcessor methods:
  24313. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24314. void releaseResources();
  24315. void processBlock (AudioSampleBuffer& buffer,
  24316. MidiBuffer& midiMessages);
  24317. AudioProcessorEditor* createEditor();
  24318. const String getInputChannelName (const int index) const;
  24319. bool isInputChannelStereoPair (int index) const;
  24320. const String getOutputChannelName (const int index) const;
  24321. bool isOutputChannelStereoPair (int index) const;
  24322. int getNumParameters();
  24323. float getParameter (int index);
  24324. void setParameter (int index, float newValue);
  24325. const String getParameterName (int index);
  24326. const String getParameterText (int index);
  24327. bool isParameterAutomatable (int index) const;
  24328. int getNumPrograms();
  24329. int getCurrentProgram();
  24330. void setCurrentProgram (int index);
  24331. const String getProgramName (int index);
  24332. void changeProgramName (int index, const String& newName);
  24333. void getStateInformation (MemoryBlock& destData);
  24334. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24335. void setStateInformation (const void* data, int sizeInBytes);
  24336. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24337. juce_UseDebuggingNewOperator
  24338. private:
  24339. friend class AudioUnitPluginWindowCarbon;
  24340. friend class AudioUnitPluginWindowCocoa;
  24341. friend class AudioUnitPluginFormat;
  24342. ComponentDescription componentDesc;
  24343. String pluginName, manufacturer, version;
  24344. String fileOrIdentifier;
  24345. CriticalSection lock;
  24346. bool initialised, wantsMidiMessages, wasPlaying;
  24347. HeapBlock <AudioBufferList> outputBufferList;
  24348. AudioTimeStamp timeStamp;
  24349. AudioSampleBuffer* currentBuffer;
  24350. AudioUnit audioUnit;
  24351. Array <int> parameterIds;
  24352. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24353. void initialise();
  24354. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24355. const AudioTimeStamp* inTimeStamp,
  24356. UInt32 inBusNumber,
  24357. UInt32 inNumberFrames,
  24358. AudioBufferList* ioData) const;
  24359. static OSStatus renderGetInputCallback (void* inRefCon,
  24360. AudioUnitRenderActionFlags* ioActionFlags,
  24361. const AudioTimeStamp* inTimeStamp,
  24362. UInt32 inBusNumber,
  24363. UInt32 inNumberFrames,
  24364. AudioBufferList* ioData)
  24365. {
  24366. return ((AudioUnitPluginInstance*) inRefCon)
  24367. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24368. }
  24369. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24370. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24371. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24372. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24373. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24374. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24375. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24376. {
  24377. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24378. }
  24379. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24380. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24381. Float64* outCurrentMeasureDownBeat)
  24382. {
  24383. return ((AudioUnitPluginInstance*) inHostUserData)
  24384. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24385. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24386. }
  24387. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24388. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24389. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24390. {
  24391. return ((AudioUnitPluginInstance*) inHostUserData)
  24392. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24393. outCurrentSampleInTimeLine, outIsCycling,
  24394. outCycleStartBeat, outCycleEndBeat);
  24395. }
  24396. void getNumChannels (int& numIns, int& numOuts)
  24397. {
  24398. numIns = 0;
  24399. numOuts = 0;
  24400. AUChannelInfo supportedChannels [128];
  24401. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24402. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24403. 0, supportedChannels, &supportedChannelsSize) == noErr
  24404. && supportedChannelsSize > 0)
  24405. {
  24406. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24407. {
  24408. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24409. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24410. }
  24411. }
  24412. else
  24413. {
  24414. // (this really means the plugin will take any number of ins/outs as long
  24415. // as they are the same)
  24416. numIns = numOuts = 2;
  24417. }
  24418. }
  24419. const String getCategory() const;
  24420. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24421. };
  24422. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24423. : fileOrIdentifier (fileOrIdentifier),
  24424. initialised (false),
  24425. wantsMidiMessages (false),
  24426. audioUnit (0),
  24427. currentBuffer (0)
  24428. {
  24429. using namespace AudioUnitFormatHelpers;
  24430. try
  24431. {
  24432. ++insideCallback;
  24433. log ("Opening AU: " + fileOrIdentifier);
  24434. if (getComponentDescFromFile (fileOrIdentifier))
  24435. {
  24436. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24437. if (comp != 0)
  24438. {
  24439. audioUnit = (AudioUnit) OpenComponent (comp);
  24440. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24441. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24442. }
  24443. }
  24444. --insideCallback;
  24445. }
  24446. catch (...)
  24447. {
  24448. --insideCallback;
  24449. }
  24450. }
  24451. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24452. {
  24453. const ScopedLock sl (lock);
  24454. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  24455. if (audioUnit != 0)
  24456. {
  24457. AudioUnitUninitialize (audioUnit);
  24458. CloseComponent (audioUnit);
  24459. audioUnit = 0;
  24460. }
  24461. }
  24462. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24463. {
  24464. zerostruct (componentDesc);
  24465. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24466. return true;
  24467. const File file (fileOrIdentifier);
  24468. if (! file.hasFileExtension (".component"))
  24469. return false;
  24470. const char* const utf8 = fileOrIdentifier.toUTF8();
  24471. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24472. strlen (utf8), file.isDirectory());
  24473. if (url != 0)
  24474. {
  24475. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24476. CFRelease (url);
  24477. if (bundleRef != 0)
  24478. {
  24479. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24480. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24481. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24482. if (pluginName.isEmpty())
  24483. pluginName = file.getFileNameWithoutExtension();
  24484. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24485. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24486. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24487. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24488. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24489. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24490. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24491. UseResFile (resFileId);
  24492. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24493. {
  24494. Handle h = Get1IndResource ('thng', i);
  24495. if (h != 0)
  24496. {
  24497. HLock (h);
  24498. const uint32* const types = (const uint32*) *h;
  24499. if (types[0] == kAudioUnitType_MusicDevice
  24500. || types[0] == kAudioUnitType_MusicEffect
  24501. || types[0] == kAudioUnitType_Effect
  24502. || types[0] == kAudioUnitType_Generator
  24503. || types[0] == kAudioUnitType_Panner)
  24504. {
  24505. componentDesc.componentType = types[0];
  24506. componentDesc.componentSubType = types[1];
  24507. componentDesc.componentManufacturer = types[2];
  24508. break;
  24509. }
  24510. HUnlock (h);
  24511. ReleaseResource (h);
  24512. }
  24513. }
  24514. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24515. CFRelease (bundleRef);
  24516. }
  24517. }
  24518. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24519. }
  24520. void AudioUnitPluginInstance::initialise()
  24521. {
  24522. if (initialised || audioUnit == 0)
  24523. return;
  24524. log ("Initialising AU: " + pluginName);
  24525. parameterIds.clear();
  24526. {
  24527. UInt32 paramListSize = 0;
  24528. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24529. 0, 0, &paramListSize);
  24530. if (paramListSize > 0)
  24531. {
  24532. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24533. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24534. 0, &parameterIds.getReference(0), &paramListSize);
  24535. }
  24536. }
  24537. {
  24538. AURenderCallbackStruct info;
  24539. zerostruct (info);
  24540. info.inputProcRefCon = this;
  24541. info.inputProc = renderGetInputCallback;
  24542. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24543. 0, &info, sizeof (info));
  24544. }
  24545. {
  24546. HostCallbackInfo info;
  24547. zerostruct (info);
  24548. info.hostUserData = this;
  24549. info.beatAndTempoProc = getBeatAndTempoCallback;
  24550. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24551. info.transportStateProc = getTransportStateCallback;
  24552. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24553. 0, &info, sizeof (info));
  24554. }
  24555. int numIns, numOuts;
  24556. getNumChannels (numIns, numOuts);
  24557. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24558. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24559. setLatencySamples (0);
  24560. }
  24561. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24562. int samplesPerBlockExpected)
  24563. {
  24564. if (audioUnit != 0)
  24565. {
  24566. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24567. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24568. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24569. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24570. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24571. {
  24572. if (initialised)
  24573. {
  24574. AudioUnitUninitialize (audioUnit);
  24575. initialised = false;
  24576. }
  24577. Float64 sr = sampleRate_;
  24578. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24579. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24580. }
  24581. }
  24582. initialise();
  24583. if (initialised)
  24584. {
  24585. int numIns, numOuts;
  24586. getNumChannels (numIns, numOuts);
  24587. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24588. Float64 latencySecs = 0.0;
  24589. UInt32 latencySize = sizeof (latencySecs);
  24590. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24591. 0, &latencySecs, &latencySize);
  24592. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24593. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24594. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24595. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24596. AudioStreamBasicDescription stream;
  24597. zerostruct (stream);
  24598. stream.mSampleRate = sampleRate_;
  24599. stream.mFormatID = kAudioFormatLinearPCM;
  24600. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24601. stream.mFramesPerPacket = 1;
  24602. stream.mBytesPerPacket = 4;
  24603. stream.mBytesPerFrame = 4;
  24604. stream.mBitsPerChannel = 32;
  24605. stream.mChannelsPerFrame = numIns;
  24606. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24607. 0, &stream, sizeof (stream));
  24608. stream.mChannelsPerFrame = numOuts;
  24609. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24610. 0, &stream, sizeof (stream));
  24611. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24612. outputBufferList->mNumberBuffers = numOuts;
  24613. for (int i = numOuts; --i >= 0;)
  24614. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24615. zerostruct (timeStamp);
  24616. timeStamp.mSampleTime = 0;
  24617. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24618. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24619. currentBuffer = 0;
  24620. wasPlaying = false;
  24621. }
  24622. }
  24623. void AudioUnitPluginInstance::releaseResources()
  24624. {
  24625. if (initialised)
  24626. {
  24627. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24628. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24629. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24630. outputBufferList.free();
  24631. currentBuffer = 0;
  24632. }
  24633. }
  24634. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24635. const AudioTimeStamp* inTimeStamp,
  24636. UInt32 inBusNumber,
  24637. UInt32 inNumberFrames,
  24638. AudioBufferList* ioData) const
  24639. {
  24640. if (inBusNumber == 0
  24641. && currentBuffer != 0)
  24642. {
  24643. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24644. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24645. {
  24646. if (i < currentBuffer->getNumChannels())
  24647. {
  24648. memcpy (ioData->mBuffers[i].mData,
  24649. currentBuffer->getSampleData (i, 0),
  24650. sizeof (float) * inNumberFrames);
  24651. }
  24652. else
  24653. {
  24654. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24655. }
  24656. }
  24657. }
  24658. return noErr;
  24659. }
  24660. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24661. MidiBuffer& midiMessages)
  24662. {
  24663. const int numSamples = buffer.getNumSamples();
  24664. if (initialised)
  24665. {
  24666. AudioUnitRenderActionFlags flags = 0;
  24667. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24668. for (int i = getNumOutputChannels(); --i >= 0;)
  24669. {
  24670. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24671. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24672. }
  24673. currentBuffer = &buffer;
  24674. if (wantsMidiMessages)
  24675. {
  24676. const uint8* midiEventData;
  24677. int midiEventSize, midiEventPosition;
  24678. MidiBuffer::Iterator i (midiMessages);
  24679. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24680. {
  24681. if (midiEventSize <= 3)
  24682. MusicDeviceMIDIEvent (audioUnit,
  24683. midiEventData[0], midiEventData[1], midiEventData[2],
  24684. midiEventPosition);
  24685. else
  24686. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24687. }
  24688. midiMessages.clear();
  24689. }
  24690. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24691. 0, numSamples, outputBufferList);
  24692. timeStamp.mSampleTime += numSamples;
  24693. }
  24694. else
  24695. {
  24696. // Not initialised, so just bypass..
  24697. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24698. buffer.clear (i, 0, buffer.getNumSamples());
  24699. }
  24700. }
  24701. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24702. {
  24703. AudioPlayHead* const ph = getPlayHead();
  24704. AudioPlayHead::CurrentPositionInfo result;
  24705. if (ph != 0 && ph->getCurrentPosition (result))
  24706. {
  24707. if (outCurrentBeat != 0)
  24708. *outCurrentBeat = result.ppqPosition;
  24709. if (outCurrentTempo != 0)
  24710. *outCurrentTempo = result.bpm;
  24711. }
  24712. else
  24713. {
  24714. if (outCurrentBeat != 0)
  24715. *outCurrentBeat = 0;
  24716. if (outCurrentTempo != 0)
  24717. *outCurrentTempo = 120.0;
  24718. }
  24719. return noErr;
  24720. }
  24721. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24722. Float32* outTimeSig_Numerator,
  24723. UInt32* outTimeSig_Denominator,
  24724. Float64* outCurrentMeasureDownBeat) const
  24725. {
  24726. AudioPlayHead* const ph = getPlayHead();
  24727. AudioPlayHead::CurrentPositionInfo result;
  24728. if (ph != 0 && ph->getCurrentPosition (result))
  24729. {
  24730. if (outTimeSig_Numerator != 0)
  24731. *outTimeSig_Numerator = result.timeSigNumerator;
  24732. if (outTimeSig_Denominator != 0)
  24733. *outTimeSig_Denominator = result.timeSigDenominator;
  24734. if (outDeltaSampleOffsetToNextBeat != 0)
  24735. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24736. if (outCurrentMeasureDownBeat != 0)
  24737. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24738. }
  24739. else
  24740. {
  24741. if (outDeltaSampleOffsetToNextBeat != 0)
  24742. *outDeltaSampleOffsetToNextBeat = 0;
  24743. if (outTimeSig_Numerator != 0)
  24744. *outTimeSig_Numerator = 4;
  24745. if (outTimeSig_Denominator != 0)
  24746. *outTimeSig_Denominator = 4;
  24747. if (outCurrentMeasureDownBeat != 0)
  24748. *outCurrentMeasureDownBeat = 0;
  24749. }
  24750. return noErr;
  24751. }
  24752. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24753. Boolean* outTransportStateChanged,
  24754. Float64* outCurrentSampleInTimeLine,
  24755. Boolean* outIsCycling,
  24756. Float64* outCycleStartBeat,
  24757. Float64* outCycleEndBeat)
  24758. {
  24759. AudioPlayHead* const ph = getPlayHead();
  24760. AudioPlayHead::CurrentPositionInfo result;
  24761. if (ph != 0 && ph->getCurrentPosition (result))
  24762. {
  24763. if (outIsPlaying != 0)
  24764. *outIsPlaying = result.isPlaying;
  24765. if (outTransportStateChanged != 0)
  24766. {
  24767. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24768. wasPlaying = result.isPlaying;
  24769. }
  24770. if (outCurrentSampleInTimeLine != 0)
  24771. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24772. if (outIsCycling != 0)
  24773. *outIsCycling = false;
  24774. if (outCycleStartBeat != 0)
  24775. *outCycleStartBeat = 0;
  24776. if (outCycleEndBeat != 0)
  24777. *outCycleEndBeat = 0;
  24778. }
  24779. else
  24780. {
  24781. if (outIsPlaying != 0)
  24782. *outIsPlaying = false;
  24783. if (outTransportStateChanged != 0)
  24784. *outTransportStateChanged = false;
  24785. if (outCurrentSampleInTimeLine != 0)
  24786. *outCurrentSampleInTimeLine = 0;
  24787. if (outIsCycling != 0)
  24788. *outIsCycling = false;
  24789. if (outCycleStartBeat != 0)
  24790. *outCycleStartBeat = 0;
  24791. if (outCycleEndBeat != 0)
  24792. *outCycleEndBeat = 0;
  24793. }
  24794. return noErr;
  24795. }
  24796. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24797. {
  24798. public:
  24799. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24800. : AudioProcessorEditor (&plugin_),
  24801. plugin (plugin_),
  24802. wrapper (0)
  24803. {
  24804. addAndMakeVisible (wrapper = new NSViewComponent());
  24805. setOpaque (true);
  24806. setVisible (true);
  24807. setSize (100, 100);
  24808. createView (createGenericViewIfNeeded);
  24809. }
  24810. ~AudioUnitPluginWindowCocoa()
  24811. {
  24812. const bool wasValid = isValid();
  24813. wrapper->setView (0);
  24814. if (wasValid)
  24815. plugin.editorBeingDeleted (this);
  24816. delete wrapper;
  24817. }
  24818. bool isValid() const { return wrapper->getView() != 0; }
  24819. void paint (Graphics& g)
  24820. {
  24821. g.fillAll (Colours::white);
  24822. }
  24823. void resized()
  24824. {
  24825. wrapper->setSize (getWidth(), getHeight());
  24826. }
  24827. private:
  24828. AudioUnitPluginInstance& plugin;
  24829. NSViewComponent* wrapper;
  24830. bool createView (const bool createGenericViewIfNeeded)
  24831. {
  24832. NSView* pluginView = 0;
  24833. UInt32 dataSize = 0;
  24834. Boolean isWritable = false;
  24835. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24836. 0, &dataSize, &isWritable) == noErr
  24837. && dataSize != 0
  24838. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24839. 0, &dataSize, &isWritable) == noErr)
  24840. {
  24841. HeapBlock <AudioUnitCocoaViewInfo> info;
  24842. info.calloc (dataSize, 1);
  24843. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24844. 0, info, &dataSize) == noErr)
  24845. {
  24846. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24847. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24848. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24849. Class viewClass = [viewBundle classNamed: viewClassName];
  24850. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24851. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24852. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24853. {
  24854. id factory = [[[viewClass alloc] init] autorelease];
  24855. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24856. withSize: NSMakeSize (getWidth(), getHeight())];
  24857. }
  24858. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24859. {
  24860. CFRelease (info->mCocoaAUViewClass[i]);
  24861. CFRelease (info->mCocoaAUViewBundleLocation);
  24862. }
  24863. }
  24864. }
  24865. if (createGenericViewIfNeeded && (pluginView == 0))
  24866. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24867. wrapper->setView (pluginView);
  24868. if (pluginView != 0)
  24869. setSize ([pluginView frame].size.width,
  24870. [pluginView frame].size.height);
  24871. return pluginView != 0;
  24872. }
  24873. };
  24874. #if JUCE_SUPPORT_CARBON
  24875. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24876. {
  24877. public:
  24878. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24879. : AudioProcessorEditor (&plugin_),
  24880. plugin (plugin_),
  24881. viewComponent (0)
  24882. {
  24883. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24884. setOpaque (true);
  24885. setVisible (true);
  24886. setSize (400, 300);
  24887. ComponentDescription viewList [16];
  24888. UInt32 viewListSize = sizeof (viewList);
  24889. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24890. 0, &viewList, &viewListSize);
  24891. componentRecord = FindNextComponent (0, &viewList[0]);
  24892. }
  24893. ~AudioUnitPluginWindowCarbon()
  24894. {
  24895. innerWrapper = 0;
  24896. if (isValid())
  24897. plugin.editorBeingDeleted (this);
  24898. }
  24899. bool isValid() const throw() { return componentRecord != 0; }
  24900. void paint (Graphics& g)
  24901. {
  24902. g.fillAll (Colours::black);
  24903. }
  24904. void resized()
  24905. {
  24906. innerWrapper->setSize (getWidth(), getHeight());
  24907. }
  24908. bool keyStateChanged (bool)
  24909. {
  24910. return false;
  24911. }
  24912. bool keyPressed (const KeyPress&)
  24913. {
  24914. return false;
  24915. }
  24916. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24917. AudioUnitCarbonView getViewComponent()
  24918. {
  24919. if (viewComponent == 0 && componentRecord != 0)
  24920. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24921. return viewComponent;
  24922. }
  24923. void closeViewComponent()
  24924. {
  24925. if (viewComponent != 0)
  24926. {
  24927. CloseComponent (viewComponent);
  24928. viewComponent = 0;
  24929. }
  24930. }
  24931. juce_UseDebuggingNewOperator
  24932. private:
  24933. AudioUnitPluginInstance& plugin;
  24934. ComponentRecord* componentRecord;
  24935. AudioUnitCarbonView viewComponent;
  24936. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24937. {
  24938. public:
  24939. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24940. : owner (owner_)
  24941. {
  24942. }
  24943. ~InnerWrapperComponent()
  24944. {
  24945. deleteWindow();
  24946. }
  24947. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24948. {
  24949. log ("Opening AU GUI: " + owner->plugin.getName());
  24950. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24951. if (viewComponent == 0)
  24952. return 0;
  24953. Float32Point pos = { 0, 0 };
  24954. Float32Point size = { 250, 200 };
  24955. HIViewRef pluginView = 0;
  24956. AudioUnitCarbonViewCreate (viewComponent,
  24957. owner->getAudioUnit(),
  24958. windowRef,
  24959. rootView,
  24960. &pos,
  24961. &size,
  24962. (ControlRef*) &pluginView);
  24963. return pluginView;
  24964. }
  24965. void removeView (HIViewRef)
  24966. {
  24967. log ("Closing AU GUI: " + owner->plugin.getName());
  24968. owner->closeViewComponent();
  24969. }
  24970. private:
  24971. AudioUnitPluginWindowCarbon* const owner;
  24972. };
  24973. friend class InnerWrapperComponent;
  24974. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24975. };
  24976. #endif
  24977. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24978. {
  24979. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24980. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24981. w = 0;
  24982. #if JUCE_SUPPORT_CARBON
  24983. if (w == 0)
  24984. {
  24985. w = new AudioUnitPluginWindowCarbon (*this);
  24986. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24987. w = 0;
  24988. }
  24989. #endif
  24990. if (w == 0)
  24991. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24992. return w.release();
  24993. }
  24994. const String AudioUnitPluginInstance::getCategory() const
  24995. {
  24996. const char* result = 0;
  24997. switch (componentDesc.componentType)
  24998. {
  24999. case kAudioUnitType_Effect:
  25000. case kAudioUnitType_MusicEffect:
  25001. result = "Effect";
  25002. break;
  25003. case kAudioUnitType_MusicDevice:
  25004. result = "Synth";
  25005. break;
  25006. case kAudioUnitType_Generator:
  25007. result = "Generator";
  25008. break;
  25009. case kAudioUnitType_Panner:
  25010. result = "Panner";
  25011. break;
  25012. default:
  25013. break;
  25014. }
  25015. return result;
  25016. }
  25017. int AudioUnitPluginInstance::getNumParameters()
  25018. {
  25019. return parameterIds.size();
  25020. }
  25021. float AudioUnitPluginInstance::getParameter (int index)
  25022. {
  25023. const ScopedLock sl (lock);
  25024. Float32 value = 0.0f;
  25025. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25026. {
  25027. AudioUnitGetParameter (audioUnit,
  25028. (UInt32) parameterIds.getUnchecked (index),
  25029. kAudioUnitScope_Global, 0,
  25030. &value);
  25031. }
  25032. return value;
  25033. }
  25034. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25035. {
  25036. const ScopedLock sl (lock);
  25037. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25038. {
  25039. AudioUnitSetParameter (audioUnit,
  25040. (UInt32) parameterIds.getUnchecked (index),
  25041. kAudioUnitScope_Global, 0,
  25042. newValue, 0);
  25043. }
  25044. }
  25045. const String AudioUnitPluginInstance::getParameterName (int index)
  25046. {
  25047. AudioUnitParameterInfo info;
  25048. zerostruct (info);
  25049. UInt32 sz = sizeof (info);
  25050. String name;
  25051. if (AudioUnitGetProperty (audioUnit,
  25052. kAudioUnitProperty_ParameterInfo,
  25053. kAudioUnitScope_Global,
  25054. parameterIds [index], &info, &sz) == noErr)
  25055. {
  25056. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25057. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25058. else
  25059. name = String (info.name, sizeof (info.name));
  25060. }
  25061. return name;
  25062. }
  25063. const String AudioUnitPluginInstance::getParameterText (int index)
  25064. {
  25065. return String (getParameter (index));
  25066. }
  25067. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25068. {
  25069. AudioUnitParameterInfo info;
  25070. UInt32 sz = sizeof (info);
  25071. if (AudioUnitGetProperty (audioUnit,
  25072. kAudioUnitProperty_ParameterInfo,
  25073. kAudioUnitScope_Global,
  25074. parameterIds [index], &info, &sz) == noErr)
  25075. {
  25076. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25077. }
  25078. return true;
  25079. }
  25080. int AudioUnitPluginInstance::getNumPrograms()
  25081. {
  25082. CFArrayRef presets;
  25083. UInt32 sz = sizeof (CFArrayRef);
  25084. int num = 0;
  25085. if (AudioUnitGetProperty (audioUnit,
  25086. kAudioUnitProperty_FactoryPresets,
  25087. kAudioUnitScope_Global,
  25088. 0, &presets, &sz) == noErr)
  25089. {
  25090. num = (int) CFArrayGetCount (presets);
  25091. CFRelease (presets);
  25092. }
  25093. return num;
  25094. }
  25095. int AudioUnitPluginInstance::getCurrentProgram()
  25096. {
  25097. AUPreset current;
  25098. current.presetNumber = 0;
  25099. UInt32 sz = sizeof (AUPreset);
  25100. AudioUnitGetProperty (audioUnit,
  25101. kAudioUnitProperty_FactoryPresets,
  25102. kAudioUnitScope_Global,
  25103. 0, &current, &sz);
  25104. return current.presetNumber;
  25105. }
  25106. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25107. {
  25108. AUPreset current;
  25109. current.presetNumber = newIndex;
  25110. current.presetName = 0;
  25111. AudioUnitSetProperty (audioUnit,
  25112. kAudioUnitProperty_FactoryPresets,
  25113. kAudioUnitScope_Global,
  25114. 0, &current, sizeof (AUPreset));
  25115. }
  25116. const String AudioUnitPluginInstance::getProgramName (int index)
  25117. {
  25118. String s;
  25119. CFArrayRef presets;
  25120. UInt32 sz = sizeof (CFArrayRef);
  25121. if (AudioUnitGetProperty (audioUnit,
  25122. kAudioUnitProperty_FactoryPresets,
  25123. kAudioUnitScope_Global,
  25124. 0, &presets, &sz) == noErr)
  25125. {
  25126. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25127. {
  25128. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25129. if (p != 0 && p->presetNumber == index)
  25130. {
  25131. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25132. break;
  25133. }
  25134. }
  25135. CFRelease (presets);
  25136. }
  25137. return s;
  25138. }
  25139. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25140. {
  25141. jassertfalse; // xxx not implemented!
  25142. }
  25143. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25144. {
  25145. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25146. return "Input " + String (index + 1);
  25147. return String::empty;
  25148. }
  25149. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25150. {
  25151. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25152. return false;
  25153. return true;
  25154. }
  25155. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25156. {
  25157. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25158. return "Output " + String (index + 1);
  25159. return String::empty;
  25160. }
  25161. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25162. {
  25163. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25164. return false;
  25165. return true;
  25166. }
  25167. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25168. {
  25169. getCurrentProgramStateInformation (destData);
  25170. }
  25171. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25172. {
  25173. CFPropertyListRef propertyList = 0;
  25174. UInt32 sz = sizeof (CFPropertyListRef);
  25175. if (AudioUnitGetProperty (audioUnit,
  25176. kAudioUnitProperty_ClassInfo,
  25177. kAudioUnitScope_Global,
  25178. 0, &propertyList, &sz) == noErr)
  25179. {
  25180. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25181. CFWriteStreamOpen (stream);
  25182. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25183. CFWriteStreamClose (stream);
  25184. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25185. destData.setSize (bytesWritten);
  25186. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25187. CFRelease (data);
  25188. CFRelease (stream);
  25189. CFRelease (propertyList);
  25190. }
  25191. }
  25192. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25193. {
  25194. setCurrentProgramStateInformation (data, sizeInBytes);
  25195. }
  25196. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25197. {
  25198. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25199. (const UInt8*) data,
  25200. sizeInBytes,
  25201. kCFAllocatorNull);
  25202. CFReadStreamOpen (stream);
  25203. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25204. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25205. stream,
  25206. 0,
  25207. kCFPropertyListImmutable,
  25208. &format,
  25209. 0);
  25210. CFRelease (stream);
  25211. if (propertyList != 0)
  25212. AudioUnitSetProperty (audioUnit,
  25213. kAudioUnitProperty_ClassInfo,
  25214. kAudioUnitScope_Global,
  25215. 0, &propertyList, sizeof (propertyList));
  25216. }
  25217. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25218. {
  25219. }
  25220. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25221. {
  25222. }
  25223. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25224. const String& fileOrIdentifier)
  25225. {
  25226. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25227. return;
  25228. PluginDescription desc;
  25229. desc.fileOrIdentifier = fileOrIdentifier;
  25230. desc.uid = 0;
  25231. try
  25232. {
  25233. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25234. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25235. if (auInstance != 0)
  25236. {
  25237. auInstance->fillInPluginDescription (desc);
  25238. results.add (new PluginDescription (desc));
  25239. }
  25240. }
  25241. catch (...)
  25242. {
  25243. // crashed while loading...
  25244. }
  25245. }
  25246. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25247. {
  25248. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25249. {
  25250. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25251. if (result->audioUnit != 0)
  25252. {
  25253. result->initialise();
  25254. return result.release();
  25255. }
  25256. }
  25257. return 0;
  25258. }
  25259. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25260. const bool /*recursive*/)
  25261. {
  25262. StringArray result;
  25263. ComponentRecord* comp = 0;
  25264. ComponentDescription desc;
  25265. zerostruct (desc);
  25266. for (;;)
  25267. {
  25268. zerostruct (desc);
  25269. comp = FindNextComponent (comp, &desc);
  25270. if (comp == 0)
  25271. break;
  25272. GetComponentInfo (comp, &desc, 0, 0, 0);
  25273. if (desc.componentType == kAudioUnitType_MusicDevice
  25274. || desc.componentType == kAudioUnitType_MusicEffect
  25275. || desc.componentType == kAudioUnitType_Effect
  25276. || desc.componentType == kAudioUnitType_Generator
  25277. || desc.componentType == kAudioUnitType_Panner)
  25278. {
  25279. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25280. DBG (s);
  25281. result.add (s);
  25282. }
  25283. }
  25284. return result;
  25285. }
  25286. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25287. {
  25288. ComponentDescription desc;
  25289. String name, version, manufacturer;
  25290. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25291. return FindNextComponent (0, &desc) != 0;
  25292. const File f (fileOrIdentifier);
  25293. return f.hasFileExtension (".component")
  25294. && f.isDirectory();
  25295. }
  25296. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25297. {
  25298. ComponentDescription desc;
  25299. String name, version, manufacturer;
  25300. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25301. if (name.isEmpty())
  25302. name = fileOrIdentifier;
  25303. return name;
  25304. }
  25305. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25306. {
  25307. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  25308. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25309. else
  25310. return File (desc.fileOrIdentifier).exists();
  25311. }
  25312. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25313. {
  25314. return FileSearchPath ("/(Default AudioUnit locations)");
  25315. }
  25316. #endif
  25317. END_JUCE_NAMESPACE
  25318. #undef log
  25319. #endif
  25320. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25321. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25322. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25323. #define JUCE_MAC_VST_INCLUDED 1
  25324. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25325. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25326. #if JUCE_WINDOWS
  25327. #undef _WIN32_WINNT
  25328. #define _WIN32_WINNT 0x500
  25329. #undef STRICT
  25330. #define STRICT
  25331. #include <windows.h>
  25332. #include <float.h>
  25333. #pragma warning (disable : 4312 4355)
  25334. #elif JUCE_LINUX
  25335. #include <float.h>
  25336. #include <sys/time.h>
  25337. #include <X11/Xlib.h>
  25338. #include <X11/Xutil.h>
  25339. #include <X11/Xatom.h>
  25340. #undef Font
  25341. #undef KeyPress
  25342. #undef Drawable
  25343. #undef Time
  25344. #else
  25345. #include <Cocoa/Cocoa.h>
  25346. #include <Carbon/Carbon.h>
  25347. #endif
  25348. #if ! (JUCE_MAC && JUCE_64BIT)
  25349. BEGIN_JUCE_NAMESPACE
  25350. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25351. #endif
  25352. #undef PRAGMA_ALIGN_SUPPORTED
  25353. #define VST_FORCE_DEPRECATED 0
  25354. #if JUCE_MSVC
  25355. #pragma warning (push)
  25356. #pragma warning (disable: 4996)
  25357. #endif
  25358. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25359. your include path if you want to add VST support.
  25360. If you're not interested in VSTs, you can disable them by changing the
  25361. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25362. */
  25363. #include "pluginterfaces/vst2.x/aeffectx.h"
  25364. #if JUCE_MSVC
  25365. #pragma warning (pop)
  25366. #endif
  25367. #if JUCE_LINUX
  25368. #define Font JUCE_NAMESPACE::Font
  25369. #define KeyPress JUCE_NAMESPACE::KeyPress
  25370. #define Drawable JUCE_NAMESPACE::Drawable
  25371. #define Time JUCE_NAMESPACE::Time
  25372. #endif
  25373. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25374. #ifdef __aeffect__
  25375. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25376. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25377. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25378. events to the list.
  25379. This is used by both the VST hosting code and the plugin wrapper.
  25380. */
  25381. class VSTMidiEventList
  25382. {
  25383. public:
  25384. VSTMidiEventList()
  25385. : numEventsUsed (0), numEventsAllocated (0)
  25386. {
  25387. }
  25388. ~VSTMidiEventList()
  25389. {
  25390. freeEvents();
  25391. }
  25392. void clear()
  25393. {
  25394. numEventsUsed = 0;
  25395. if (events != 0)
  25396. events->numEvents = 0;
  25397. }
  25398. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25399. {
  25400. ensureSize (numEventsUsed + 1);
  25401. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25402. events->numEvents = ++numEventsUsed;
  25403. if (numBytes <= 4)
  25404. {
  25405. if (e->type == kVstSysExType)
  25406. {
  25407. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25408. e->type = kVstMidiType;
  25409. e->byteSize = sizeof (VstMidiEvent);
  25410. e->noteLength = 0;
  25411. e->noteOffset = 0;
  25412. e->detune = 0;
  25413. e->noteOffVelocity = 0;
  25414. }
  25415. e->deltaFrames = frameOffset;
  25416. memcpy (e->midiData, midiData, numBytes);
  25417. }
  25418. else
  25419. {
  25420. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25421. if (se->type == kVstSysExType)
  25422. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25423. else
  25424. se->sysexDump = (char*) juce_malloc (numBytes);
  25425. memcpy (se->sysexDump, midiData, numBytes);
  25426. se->type = kVstSysExType;
  25427. se->byteSize = sizeof (VstMidiSysexEvent);
  25428. se->deltaFrames = frameOffset;
  25429. se->flags = 0;
  25430. se->dumpBytes = numBytes;
  25431. se->resvd1 = 0;
  25432. se->resvd2 = 0;
  25433. }
  25434. }
  25435. // Handy method to pull the events out of an event buffer supplied by the host
  25436. // or plugin.
  25437. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25438. {
  25439. for (int i = 0; i < events->numEvents; ++i)
  25440. {
  25441. const VstEvent* const e = events->events[i];
  25442. if (e != 0)
  25443. {
  25444. if (e->type == kVstMidiType)
  25445. {
  25446. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25447. 4, e->deltaFrames);
  25448. }
  25449. else if (e->type == kVstSysExType)
  25450. {
  25451. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25452. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25453. e->deltaFrames);
  25454. }
  25455. }
  25456. }
  25457. }
  25458. void ensureSize (int numEventsNeeded)
  25459. {
  25460. if (numEventsNeeded > numEventsAllocated)
  25461. {
  25462. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25463. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25464. if (events == 0)
  25465. events.calloc (size, 1);
  25466. else
  25467. events.realloc (size, 1);
  25468. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25469. {
  25470. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25471. (int) sizeof (VstMidiSysexEvent)));
  25472. e->type = kVstMidiType;
  25473. e->byteSize = sizeof (VstMidiEvent);
  25474. events->events[i] = (VstEvent*) e;
  25475. }
  25476. numEventsAllocated = numEventsNeeded;
  25477. }
  25478. }
  25479. void freeEvents()
  25480. {
  25481. if (events != 0)
  25482. {
  25483. for (int i = numEventsAllocated; --i >= 0;)
  25484. {
  25485. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25486. if (e->type == kVstSysExType)
  25487. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25488. juce_free (e);
  25489. }
  25490. events.free();
  25491. numEventsUsed = 0;
  25492. numEventsAllocated = 0;
  25493. }
  25494. }
  25495. HeapBlock <VstEvents> events;
  25496. private:
  25497. int numEventsUsed, numEventsAllocated;
  25498. };
  25499. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25500. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25501. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25502. #if ! JUCE_WINDOWS
  25503. static void _fpreset() {}
  25504. static void _clearfp() {}
  25505. #endif
  25506. extern void juce_callAnyTimersSynchronously();
  25507. const int fxbVersionNum = 1;
  25508. struct fxProgram
  25509. {
  25510. long chunkMagic; // 'CcnK'
  25511. long byteSize; // of this chunk, excl. magic + byteSize
  25512. long fxMagic; // 'FxCk'
  25513. long version;
  25514. long fxID; // fx unique id
  25515. long fxVersion;
  25516. long numParams;
  25517. char prgName[28];
  25518. float params[1]; // variable no. of parameters
  25519. };
  25520. struct fxSet
  25521. {
  25522. long chunkMagic; // 'CcnK'
  25523. long byteSize; // of this chunk, excl. magic + byteSize
  25524. long fxMagic; // 'FxBk'
  25525. long version;
  25526. long fxID; // fx unique id
  25527. long fxVersion;
  25528. long numPrograms;
  25529. char future[128];
  25530. fxProgram programs[1]; // variable no. of programs
  25531. };
  25532. struct fxChunkSet
  25533. {
  25534. long chunkMagic; // 'CcnK'
  25535. long byteSize; // of this chunk, excl. magic + byteSize
  25536. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25537. long version;
  25538. long fxID; // fx unique id
  25539. long fxVersion;
  25540. long numPrograms;
  25541. char future[128];
  25542. long chunkSize;
  25543. char chunk[8]; // variable
  25544. };
  25545. struct fxProgramSet
  25546. {
  25547. long chunkMagic; // 'CcnK'
  25548. long byteSize; // of this chunk, excl. magic + byteSize
  25549. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25550. long version;
  25551. long fxID; // fx unique id
  25552. long fxVersion;
  25553. long numPrograms;
  25554. char name[28];
  25555. long chunkSize;
  25556. char chunk[8]; // variable
  25557. };
  25558. static long vst_swap (const long x) throw()
  25559. {
  25560. #ifdef JUCE_LITTLE_ENDIAN
  25561. return (long) ByteOrder::swap ((uint32) x);
  25562. #else
  25563. return x;
  25564. #endif
  25565. }
  25566. static float vst_swapFloat (const float x) throw()
  25567. {
  25568. #ifdef JUCE_LITTLE_ENDIAN
  25569. union { uint32 asInt; float asFloat; } n;
  25570. n.asFloat = x;
  25571. n.asInt = ByteOrder::swap (n.asInt);
  25572. return n.asFloat;
  25573. #else
  25574. return x;
  25575. #endif
  25576. }
  25577. typedef AEffect* (*MainCall) (audioMasterCallback);
  25578. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25579. static int shellUIDToCreate = 0;
  25580. static int insideVSTCallback = 0;
  25581. class VSTPluginWindow;
  25582. // Change this to disable logging of various VST activities
  25583. #ifndef VST_LOGGING
  25584. #define VST_LOGGING 1
  25585. #endif
  25586. #if VST_LOGGING
  25587. #define log(a) Logger::writeToLog(a);
  25588. #else
  25589. #define log(a)
  25590. #endif
  25591. #if JUCE_MAC && JUCE_PPC
  25592. static void* NewCFMFromMachO (void* const machofp) throw()
  25593. {
  25594. void* result = juce_malloc (8);
  25595. ((void**) result)[0] = machofp;
  25596. ((void**) result)[1] = result;
  25597. return result;
  25598. }
  25599. #endif
  25600. #if JUCE_LINUX
  25601. extern Display* display;
  25602. extern XContext windowHandleXContext;
  25603. typedef void (*EventProcPtr) (XEvent* ev);
  25604. static bool xErrorTriggered;
  25605. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25606. {
  25607. xErrorTriggered = true;
  25608. return 0;
  25609. }
  25610. static int getPropertyFromXWindow (Window handle, Atom atom)
  25611. {
  25612. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25613. xErrorTriggered = false;
  25614. int userSize;
  25615. unsigned long bytes, userCount;
  25616. unsigned char* data;
  25617. Atom userType;
  25618. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25619. &userType, &userSize, &userCount, &bytes, &data);
  25620. XSetErrorHandler (oldErrorHandler);
  25621. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25622. : 0;
  25623. }
  25624. static Window getChildWindow (Window windowToCheck)
  25625. {
  25626. Window rootWindow, parentWindow;
  25627. Window* childWindows;
  25628. unsigned int numChildren;
  25629. XQueryTree (display,
  25630. windowToCheck,
  25631. &rootWindow,
  25632. &parentWindow,
  25633. &childWindows,
  25634. &numChildren);
  25635. if (numChildren > 0)
  25636. return childWindows [0];
  25637. return 0;
  25638. }
  25639. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25640. {
  25641. if (e.mods.isLeftButtonDown())
  25642. {
  25643. ev.xbutton.button = Button1;
  25644. ev.xbutton.state |= Button1Mask;
  25645. }
  25646. else if (e.mods.isRightButtonDown())
  25647. {
  25648. ev.xbutton.button = Button3;
  25649. ev.xbutton.state |= Button3Mask;
  25650. }
  25651. else if (e.mods.isMiddleButtonDown())
  25652. {
  25653. ev.xbutton.button = Button2;
  25654. ev.xbutton.state |= Button2Mask;
  25655. }
  25656. }
  25657. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25658. {
  25659. if (e.mods.isLeftButtonDown())
  25660. ev.xmotion.state |= Button1Mask;
  25661. else if (e.mods.isRightButtonDown())
  25662. ev.xmotion.state |= Button3Mask;
  25663. else if (e.mods.isMiddleButtonDown())
  25664. ev.xmotion.state |= Button2Mask;
  25665. }
  25666. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25667. {
  25668. if (e.mods.isLeftButtonDown())
  25669. ev.xcrossing.state |= Button1Mask;
  25670. else if (e.mods.isRightButtonDown())
  25671. ev.xcrossing.state |= Button3Mask;
  25672. else if (e.mods.isMiddleButtonDown())
  25673. ev.xcrossing.state |= Button2Mask;
  25674. }
  25675. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25676. {
  25677. if (increment < 0)
  25678. {
  25679. ev.xbutton.button = Button5;
  25680. ev.xbutton.state |= Button5Mask;
  25681. }
  25682. else if (increment > 0)
  25683. {
  25684. ev.xbutton.button = Button4;
  25685. ev.xbutton.state |= Button4Mask;
  25686. }
  25687. }
  25688. #endif
  25689. class ModuleHandle : public ReferenceCountedObject
  25690. {
  25691. public:
  25692. File file;
  25693. MainCall moduleMain;
  25694. String pluginName;
  25695. static Array <ModuleHandle*>& getActiveModules()
  25696. {
  25697. static Array <ModuleHandle*> activeModules;
  25698. return activeModules;
  25699. }
  25700. static ModuleHandle* findOrCreateModule (const File& file)
  25701. {
  25702. for (int i = getActiveModules().size(); --i >= 0;)
  25703. {
  25704. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25705. if (module->file == file)
  25706. return module;
  25707. }
  25708. _fpreset(); // (doesn't do any harm)
  25709. ++insideVSTCallback;
  25710. shellUIDToCreate = 0;
  25711. log ("Attempting to load VST: " + file.getFullPathName());
  25712. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25713. if (! m->open())
  25714. m = 0;
  25715. --insideVSTCallback;
  25716. _fpreset(); // (doesn't do any harm)
  25717. return m.release();
  25718. }
  25719. ModuleHandle (const File& file_)
  25720. : file (file_),
  25721. moduleMain (0),
  25722. #if JUCE_WINDOWS || JUCE_LINUX
  25723. hModule (0)
  25724. #elif JUCE_MAC
  25725. fragId (0),
  25726. resHandle (0),
  25727. bundleRef (0),
  25728. resFileId (0)
  25729. #endif
  25730. {
  25731. getActiveModules().add (this);
  25732. #if JUCE_WINDOWS || JUCE_LINUX
  25733. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25734. #elif JUCE_MAC
  25735. FSRef ref;
  25736. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25737. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25738. #endif
  25739. }
  25740. ~ModuleHandle()
  25741. {
  25742. getActiveModules().removeValue (this);
  25743. close();
  25744. }
  25745. juce_UseDebuggingNewOperator
  25746. #if JUCE_WINDOWS || JUCE_LINUX
  25747. void* hModule;
  25748. String fullParentDirectoryPathName;
  25749. bool open()
  25750. {
  25751. #if JUCE_WINDOWS
  25752. static bool timePeriodSet = false;
  25753. if (! timePeriodSet)
  25754. {
  25755. timePeriodSet = true;
  25756. timeBeginPeriod (2);
  25757. }
  25758. #endif
  25759. pluginName = file.getFileNameWithoutExtension();
  25760. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25761. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25762. if (moduleMain == 0)
  25763. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25764. return moduleMain != 0;
  25765. }
  25766. void close()
  25767. {
  25768. _fpreset(); // (doesn't do any harm)
  25769. PlatformUtilities::freeDynamicLibrary (hModule);
  25770. }
  25771. void closeEffect (AEffect* eff)
  25772. {
  25773. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25774. }
  25775. #else
  25776. CFragConnectionID fragId;
  25777. Handle resHandle;
  25778. CFBundleRef bundleRef;
  25779. FSSpec parentDirFSSpec;
  25780. short resFileId;
  25781. bool open()
  25782. {
  25783. bool ok = false;
  25784. const String filename (file.getFullPathName());
  25785. if (file.hasFileExtension (".vst"))
  25786. {
  25787. const char* const utf8 = filename.toUTF8();
  25788. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25789. strlen (utf8), file.isDirectory());
  25790. if (url != 0)
  25791. {
  25792. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25793. CFRelease (url);
  25794. if (bundleRef != 0)
  25795. {
  25796. if (CFBundleLoadExecutable (bundleRef))
  25797. {
  25798. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25799. if (moduleMain == 0)
  25800. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25801. if (moduleMain != 0)
  25802. {
  25803. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25804. if (name != 0)
  25805. {
  25806. if (CFGetTypeID (name) == CFStringGetTypeID())
  25807. {
  25808. char buffer[1024];
  25809. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25810. pluginName = buffer;
  25811. }
  25812. }
  25813. if (pluginName.isEmpty())
  25814. pluginName = file.getFileNameWithoutExtension();
  25815. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25816. ok = true;
  25817. }
  25818. }
  25819. if (! ok)
  25820. {
  25821. CFBundleUnloadExecutable (bundleRef);
  25822. CFRelease (bundleRef);
  25823. bundleRef = 0;
  25824. }
  25825. }
  25826. }
  25827. }
  25828. #if JUCE_PPC
  25829. else
  25830. {
  25831. FSRef fn;
  25832. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25833. {
  25834. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25835. if (resFileId != -1)
  25836. {
  25837. const int numEffs = Count1Resources ('aEff');
  25838. for (int i = 0; i < numEffs; ++i)
  25839. {
  25840. resHandle = Get1IndResource ('aEff', i + 1);
  25841. if (resHandle != 0)
  25842. {
  25843. OSType type;
  25844. Str255 name;
  25845. SInt16 id;
  25846. GetResInfo (resHandle, &id, &type, name);
  25847. pluginName = String ((const char*) name + 1, name[0]);
  25848. DetachResource (resHandle);
  25849. HLock (resHandle);
  25850. Ptr ptr;
  25851. Str255 errorText;
  25852. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25853. name, kPrivateCFragCopy,
  25854. &fragId, &ptr, errorText);
  25855. if (err == noErr)
  25856. {
  25857. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25858. ok = true;
  25859. }
  25860. else
  25861. {
  25862. HUnlock (resHandle);
  25863. }
  25864. break;
  25865. }
  25866. }
  25867. if (! ok)
  25868. CloseResFile (resFileId);
  25869. }
  25870. }
  25871. }
  25872. #endif
  25873. return ok;
  25874. }
  25875. void close()
  25876. {
  25877. #if JUCE_PPC
  25878. if (fragId != 0)
  25879. {
  25880. if (moduleMain != 0)
  25881. disposeMachOFromCFM ((void*) moduleMain);
  25882. CloseConnection (&fragId);
  25883. HUnlock (resHandle);
  25884. if (resFileId != 0)
  25885. CloseResFile (resFileId);
  25886. }
  25887. else
  25888. #endif
  25889. if (bundleRef != 0)
  25890. {
  25891. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25892. if (CFGetRetainCount (bundleRef) == 1)
  25893. CFBundleUnloadExecutable (bundleRef);
  25894. if (CFGetRetainCount (bundleRef) > 0)
  25895. CFRelease (bundleRef);
  25896. }
  25897. }
  25898. void closeEffect (AEffect* eff)
  25899. {
  25900. #if JUCE_PPC
  25901. if (fragId != 0)
  25902. {
  25903. Array<void*> thingsToDelete;
  25904. thingsToDelete.add ((void*) eff->dispatcher);
  25905. thingsToDelete.add ((void*) eff->process);
  25906. thingsToDelete.add ((void*) eff->setParameter);
  25907. thingsToDelete.add ((void*) eff->getParameter);
  25908. thingsToDelete.add ((void*) eff->processReplacing);
  25909. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25910. for (int i = thingsToDelete.size(); --i >= 0;)
  25911. disposeMachOFromCFM (thingsToDelete[i]);
  25912. }
  25913. else
  25914. #endif
  25915. {
  25916. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25917. }
  25918. }
  25919. #if JUCE_PPC
  25920. static void* newMachOFromCFM (void* cfmfp)
  25921. {
  25922. if (cfmfp == 0)
  25923. return 0;
  25924. UInt32* const mfp = new UInt32[6];
  25925. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25926. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25927. mfp[2] = 0x800c0000;
  25928. mfp[3] = 0x804c0004;
  25929. mfp[4] = 0x7c0903a6;
  25930. mfp[5] = 0x4e800420;
  25931. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25932. return mfp;
  25933. }
  25934. static void disposeMachOFromCFM (void* ptr)
  25935. {
  25936. delete[] static_cast <UInt32*> (ptr);
  25937. }
  25938. void coerceAEffectFunctionCalls (AEffect* eff)
  25939. {
  25940. if (fragId != 0)
  25941. {
  25942. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25943. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25944. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25945. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25946. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25947. }
  25948. }
  25949. #endif
  25950. #endif
  25951. };
  25952. /**
  25953. An instance of a plugin, created by a VSTPluginFormat.
  25954. */
  25955. class VSTPluginInstance : public AudioPluginInstance,
  25956. private Timer,
  25957. private AsyncUpdater
  25958. {
  25959. public:
  25960. ~VSTPluginInstance();
  25961. // AudioPluginInstance methods:
  25962. void fillInPluginDescription (PluginDescription& desc) const
  25963. {
  25964. desc.name = name;
  25965. desc.fileOrIdentifier = module->file.getFullPathName();
  25966. desc.uid = getUID();
  25967. desc.lastFileModTime = module->file.getLastModificationTime();
  25968. desc.pluginFormatName = "VST";
  25969. desc.category = getCategory();
  25970. {
  25971. char buffer [kVstMaxVendorStrLen + 8];
  25972. zerostruct (buffer);
  25973. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25974. desc.manufacturerName = buffer;
  25975. }
  25976. desc.version = getVersion();
  25977. desc.numInputChannels = getNumInputChannels();
  25978. desc.numOutputChannels = getNumOutputChannels();
  25979. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25980. }
  25981. const String getName() const { return name; }
  25982. int getUID() const throw();
  25983. bool acceptsMidi() const { return wantsMidiMessages; }
  25984. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25985. // AudioProcessor methods:
  25986. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25987. void releaseResources();
  25988. void processBlock (AudioSampleBuffer& buffer,
  25989. MidiBuffer& midiMessages);
  25990. AudioProcessorEditor* createEditor();
  25991. const String getInputChannelName (const int index) const;
  25992. bool isInputChannelStereoPair (int index) const;
  25993. const String getOutputChannelName (const int index) const;
  25994. bool isOutputChannelStereoPair (int index) const;
  25995. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25996. float getParameter (int index);
  25997. void setParameter (int index, float newValue);
  25998. const String getParameterName (int index);
  25999. const String getParameterText (int index);
  26000. bool isParameterAutomatable (int index) const;
  26001. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26002. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26003. void setCurrentProgram (int index);
  26004. const String getProgramName (int index);
  26005. void changeProgramName (int index, const String& newName);
  26006. void getStateInformation (MemoryBlock& destData);
  26007. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26008. void setStateInformation (const void* data, int sizeInBytes);
  26009. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26010. void timerCallback();
  26011. void handleAsyncUpdate();
  26012. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26013. juce_UseDebuggingNewOperator
  26014. private:
  26015. friend class VSTPluginWindow;
  26016. friend class VSTPluginFormat;
  26017. AEffect* effect;
  26018. String name;
  26019. CriticalSection lock;
  26020. bool wantsMidiMessages, initialised, isPowerOn;
  26021. mutable StringArray programNames;
  26022. AudioSampleBuffer tempBuffer;
  26023. CriticalSection midiInLock;
  26024. MidiBuffer incomingMidi;
  26025. VSTMidiEventList midiEventsToSend;
  26026. VstTimeInfo vstHostTime;
  26027. HeapBlock <float*> channels;
  26028. ReferenceCountedObjectPtr <ModuleHandle> module;
  26029. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26030. bool restoreProgramSettings (const fxProgram* const prog);
  26031. const String getCurrentProgramName();
  26032. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26033. void updateStoredProgramNames();
  26034. void initialise();
  26035. void handleMidiFromPlugin (const VstEvents* const events);
  26036. void createTempParameterStore (MemoryBlock& dest);
  26037. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26038. const String getParameterLabel (int index) const;
  26039. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26040. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26041. void setChunkData (const char* data, int size, bool isPreset);
  26042. bool loadFromFXBFile (const void* data, int numBytes);
  26043. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26044. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26045. const String getVersion() const throw();
  26046. const String getCategory() const throw();
  26047. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26048. void setPower (const bool on);
  26049. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26050. };
  26051. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26052. : effect (0),
  26053. wantsMidiMessages (false),
  26054. initialised (false),
  26055. isPowerOn (false),
  26056. tempBuffer (1, 1),
  26057. module (module_)
  26058. {
  26059. try
  26060. {
  26061. _fpreset();
  26062. ++insideVSTCallback;
  26063. name = module->pluginName;
  26064. log ("Creating VST instance: " + name);
  26065. #if JUCE_MAC
  26066. if (module->resFileId != 0)
  26067. UseResFile (module->resFileId);
  26068. #if JUCE_PPC
  26069. if (module->fragId != 0)
  26070. {
  26071. static void* audioMasterCoerced = 0;
  26072. if (audioMasterCoerced == 0)
  26073. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26074. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26075. }
  26076. else
  26077. #endif
  26078. #endif
  26079. {
  26080. effect = module->moduleMain (&audioMaster);
  26081. }
  26082. --insideVSTCallback;
  26083. if (effect != 0 && effect->magic == kEffectMagic)
  26084. {
  26085. #if JUCE_PPC
  26086. module->coerceAEffectFunctionCalls (effect);
  26087. #endif
  26088. jassert (effect->resvd2 == 0);
  26089. jassert (effect->object != 0);
  26090. _fpreset(); // some dodgy plugs fuck around with this
  26091. }
  26092. else
  26093. {
  26094. effect = 0;
  26095. }
  26096. }
  26097. catch (...)
  26098. {
  26099. --insideVSTCallback;
  26100. }
  26101. }
  26102. VSTPluginInstance::~VSTPluginInstance()
  26103. {
  26104. {
  26105. const ScopedLock sl (lock);
  26106. jassert (insideVSTCallback == 0);
  26107. if (effect != 0 && effect->magic == kEffectMagic)
  26108. {
  26109. try
  26110. {
  26111. #if JUCE_MAC
  26112. if (module->resFileId != 0)
  26113. UseResFile (module->resFileId);
  26114. #endif
  26115. // Must delete any editors before deleting the plugin instance!
  26116. jassert (getActiveEditor() == 0);
  26117. _fpreset(); // some dodgy plugs fuck around with this
  26118. module->closeEffect (effect);
  26119. }
  26120. catch (...)
  26121. {}
  26122. }
  26123. module = 0;
  26124. effect = 0;
  26125. }
  26126. }
  26127. void VSTPluginInstance::initialise()
  26128. {
  26129. if (initialised || effect == 0)
  26130. return;
  26131. log ("Initialising VST: " + module->pluginName);
  26132. initialised = true;
  26133. dispatch (effIdentify, 0, 0, 0, 0);
  26134. // this code would ask the plugin for its name, but so few plugins
  26135. // actually bother implementing this correctly, that it's better to
  26136. // just ignore it and use the file name instead.
  26137. /* {
  26138. char buffer [256];
  26139. zerostruct (buffer);
  26140. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26141. name = String (buffer).trim();
  26142. if (name.isEmpty())
  26143. name = module->pluginName;
  26144. }
  26145. */
  26146. if (getSampleRate() > 0)
  26147. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26148. if (getBlockSize() > 0)
  26149. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26150. dispatch (effOpen, 0, 0, 0, 0);
  26151. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26152. getSampleRate(), getBlockSize());
  26153. if (getNumPrograms() > 1)
  26154. setCurrentProgram (0);
  26155. else
  26156. dispatch (effSetProgram, 0, 0, 0, 0);
  26157. int i;
  26158. for (i = effect->numInputs; --i >= 0;)
  26159. dispatch (effConnectInput, i, 1, 0, 0);
  26160. for (i = effect->numOutputs; --i >= 0;)
  26161. dispatch (effConnectOutput, i, 1, 0, 0);
  26162. updateStoredProgramNames();
  26163. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26164. setLatencySamples (effect->initialDelay);
  26165. }
  26166. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26167. int samplesPerBlockExpected)
  26168. {
  26169. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26170. sampleRate_, samplesPerBlockExpected);
  26171. setLatencySamples (effect->initialDelay);
  26172. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26173. vstHostTime.tempo = 120.0;
  26174. vstHostTime.timeSigNumerator = 4;
  26175. vstHostTime.timeSigDenominator = 4;
  26176. vstHostTime.sampleRate = sampleRate_;
  26177. vstHostTime.samplePos = 0;
  26178. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26179. initialise();
  26180. if (initialised)
  26181. {
  26182. wantsMidiMessages = wantsMidiMessages
  26183. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26184. if (wantsMidiMessages)
  26185. midiEventsToSend.ensureSize (256);
  26186. else
  26187. midiEventsToSend.freeEvents();
  26188. incomingMidi.clear();
  26189. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26190. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26191. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26192. if (! isPowerOn)
  26193. setPower (true);
  26194. // dodgy hack to force some plugins to initialise the sample rate..
  26195. if ((! hasEditor()) && getNumParameters() > 0)
  26196. {
  26197. const float old = getParameter (0);
  26198. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26199. setParameter (0, old);
  26200. }
  26201. dispatch (effStartProcess, 0, 0, 0, 0);
  26202. }
  26203. }
  26204. void VSTPluginInstance::releaseResources()
  26205. {
  26206. if (initialised)
  26207. {
  26208. dispatch (effStopProcess, 0, 0, 0, 0);
  26209. setPower (false);
  26210. }
  26211. tempBuffer.setSize (1, 1);
  26212. incomingMidi.clear();
  26213. midiEventsToSend.freeEvents();
  26214. channels.free();
  26215. }
  26216. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26217. MidiBuffer& midiMessages)
  26218. {
  26219. const int numSamples = buffer.getNumSamples();
  26220. if (initialised)
  26221. {
  26222. AudioPlayHead* playHead = getPlayHead();
  26223. if (playHead != 0)
  26224. {
  26225. AudioPlayHead::CurrentPositionInfo position;
  26226. playHead->getCurrentPosition (position);
  26227. vstHostTime.tempo = position.bpm;
  26228. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26229. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26230. vstHostTime.ppqPos = position.ppqPosition;
  26231. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26232. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26233. if (position.isPlaying)
  26234. vstHostTime.flags |= kVstTransportPlaying;
  26235. else
  26236. vstHostTime.flags &= ~kVstTransportPlaying;
  26237. }
  26238. #if JUCE_WINDOWS
  26239. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26240. #elif JUCE_LINUX
  26241. timeval micro;
  26242. gettimeofday (&micro, 0);
  26243. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26244. #elif JUCE_MAC
  26245. UnsignedWide micro;
  26246. Microseconds (&micro);
  26247. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26248. #endif
  26249. if (wantsMidiMessages)
  26250. {
  26251. midiEventsToSend.clear();
  26252. midiEventsToSend.ensureSize (1);
  26253. MidiBuffer::Iterator iter (midiMessages);
  26254. const uint8* midiData;
  26255. int numBytesOfMidiData, samplePosition;
  26256. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26257. {
  26258. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26259. jlimit (0, numSamples - 1, samplePosition));
  26260. }
  26261. try
  26262. {
  26263. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26264. }
  26265. catch (...)
  26266. {}
  26267. }
  26268. int i;
  26269. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26270. for (i = 0; i < maxChans; ++i)
  26271. channels[i] = buffer.getSampleData (i);
  26272. channels [maxChans] = 0;
  26273. _clearfp();
  26274. if ((effect->flags & effFlagsCanReplacing) != 0)
  26275. {
  26276. try
  26277. {
  26278. effect->processReplacing (effect, channels, channels, numSamples);
  26279. }
  26280. catch (...)
  26281. {}
  26282. }
  26283. else
  26284. {
  26285. tempBuffer.setSize (effect->numOutputs, numSamples);
  26286. tempBuffer.clear();
  26287. float* outs [64];
  26288. for (i = effect->numOutputs; --i >= 0;)
  26289. outs[i] = tempBuffer.getSampleData (i);
  26290. outs [effect->numOutputs] = 0;
  26291. try
  26292. {
  26293. effect->process (effect, channels, outs, numSamples);
  26294. }
  26295. catch (...)
  26296. {}
  26297. for (i = effect->numOutputs; --i >= 0;)
  26298. buffer.copyFrom (i, 0, outs[i], numSamples);
  26299. }
  26300. }
  26301. else
  26302. {
  26303. // Not initialised, so just bypass..
  26304. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26305. buffer.clear (i, 0, buffer.getNumSamples());
  26306. }
  26307. {
  26308. // copy any incoming midi..
  26309. const ScopedLock sl (midiInLock);
  26310. midiMessages.swapWith (incomingMidi);
  26311. incomingMidi.clear();
  26312. }
  26313. }
  26314. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26315. {
  26316. if (events != 0)
  26317. {
  26318. const ScopedLock sl (midiInLock);
  26319. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26320. }
  26321. }
  26322. static Array <VSTPluginWindow*> activeVSTWindows;
  26323. class VSTPluginWindow : public AudioProcessorEditor,
  26324. #if ! JUCE_MAC
  26325. public ComponentMovementWatcher,
  26326. #endif
  26327. public Timer
  26328. {
  26329. public:
  26330. VSTPluginWindow (VSTPluginInstance& plugin_)
  26331. : AudioProcessorEditor (&plugin_),
  26332. #if ! JUCE_MAC
  26333. ComponentMovementWatcher (this),
  26334. #endif
  26335. plugin (plugin_),
  26336. isOpen (false),
  26337. wasShowing (false),
  26338. pluginRefusesToResize (false),
  26339. pluginWantsKeys (false),
  26340. alreadyInside (false),
  26341. recursiveResize (false)
  26342. {
  26343. #if JUCE_WINDOWS
  26344. sizeCheckCount = 0;
  26345. pluginHWND = 0;
  26346. #elif JUCE_LINUX
  26347. pluginWindow = None;
  26348. pluginProc = None;
  26349. #else
  26350. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26351. #endif
  26352. activeVSTWindows.add (this);
  26353. setSize (1, 1);
  26354. setOpaque (true);
  26355. setVisible (true);
  26356. }
  26357. ~VSTPluginWindow()
  26358. {
  26359. #if JUCE_MAC
  26360. innerWrapper = 0;
  26361. #else
  26362. closePluginWindow();
  26363. #endif
  26364. activeVSTWindows.removeValue (this);
  26365. plugin.editorBeingDeleted (this);
  26366. }
  26367. #if ! JUCE_MAC
  26368. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26369. {
  26370. if (recursiveResize)
  26371. return;
  26372. Component* const topComp = getTopLevelComponent();
  26373. if (topComp->getPeer() != 0)
  26374. {
  26375. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26376. recursiveResize = true;
  26377. #if JUCE_WINDOWS
  26378. if (pluginHWND != 0)
  26379. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26380. #elif JUCE_LINUX
  26381. if (pluginWindow != 0)
  26382. {
  26383. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26384. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26385. XMapRaised (display, pluginWindow);
  26386. }
  26387. #endif
  26388. recursiveResize = false;
  26389. }
  26390. }
  26391. void componentVisibilityChanged (Component&)
  26392. {
  26393. const bool isShowingNow = isShowing();
  26394. if (wasShowing != isShowingNow)
  26395. {
  26396. wasShowing = isShowingNow;
  26397. if (isShowingNow)
  26398. openPluginWindow();
  26399. else
  26400. closePluginWindow();
  26401. }
  26402. componentMovedOrResized (true, true);
  26403. }
  26404. void componentPeerChanged()
  26405. {
  26406. closePluginWindow();
  26407. openPluginWindow();
  26408. }
  26409. #endif
  26410. bool keyStateChanged (bool)
  26411. {
  26412. return pluginWantsKeys;
  26413. }
  26414. bool keyPressed (const KeyPress&)
  26415. {
  26416. return pluginWantsKeys;
  26417. }
  26418. #if JUCE_MAC
  26419. void paint (Graphics& g)
  26420. {
  26421. g.fillAll (Colours::black);
  26422. }
  26423. #else
  26424. void paint (Graphics& g)
  26425. {
  26426. if (isOpen)
  26427. {
  26428. ComponentPeer* const peer = getPeer();
  26429. if (peer != 0)
  26430. {
  26431. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26432. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26433. #if JUCE_LINUX
  26434. if (pluginWindow != 0)
  26435. {
  26436. const Rectangle<int> clip (g.getClipBounds());
  26437. XEvent ev;
  26438. zerostruct (ev);
  26439. ev.xexpose.type = Expose;
  26440. ev.xexpose.display = display;
  26441. ev.xexpose.window = pluginWindow;
  26442. ev.xexpose.x = clip.getX();
  26443. ev.xexpose.y = clip.getY();
  26444. ev.xexpose.width = clip.getWidth();
  26445. ev.xexpose.height = clip.getHeight();
  26446. sendEventToChild (&ev);
  26447. }
  26448. #endif
  26449. }
  26450. }
  26451. else
  26452. {
  26453. g.fillAll (Colours::black);
  26454. }
  26455. }
  26456. #endif
  26457. void timerCallback()
  26458. {
  26459. #if JUCE_WINDOWS
  26460. if (--sizeCheckCount <= 0)
  26461. {
  26462. sizeCheckCount = 10;
  26463. checkPluginWindowSize();
  26464. }
  26465. #endif
  26466. try
  26467. {
  26468. static bool reentrant = false;
  26469. if (! reentrant)
  26470. {
  26471. reentrant = true;
  26472. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26473. reentrant = false;
  26474. }
  26475. }
  26476. catch (...)
  26477. {}
  26478. }
  26479. void mouseDown (const MouseEvent& e)
  26480. {
  26481. #if JUCE_LINUX
  26482. if (pluginWindow == 0)
  26483. return;
  26484. toFront (true);
  26485. XEvent ev;
  26486. zerostruct (ev);
  26487. ev.xbutton.display = display;
  26488. ev.xbutton.type = ButtonPress;
  26489. ev.xbutton.window = pluginWindow;
  26490. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26491. ev.xbutton.time = CurrentTime;
  26492. ev.xbutton.x = e.x;
  26493. ev.xbutton.y = e.y;
  26494. ev.xbutton.x_root = e.getScreenX();
  26495. ev.xbutton.y_root = e.getScreenY();
  26496. translateJuceToXButtonModifiers (e, ev);
  26497. sendEventToChild (&ev);
  26498. #elif JUCE_WINDOWS
  26499. (void) e;
  26500. toFront (true);
  26501. #endif
  26502. }
  26503. void broughtToFront()
  26504. {
  26505. activeVSTWindows.removeValue (this);
  26506. activeVSTWindows.add (this);
  26507. #if JUCE_MAC
  26508. dispatch (effEditTop, 0, 0, 0, 0);
  26509. #endif
  26510. }
  26511. juce_UseDebuggingNewOperator
  26512. private:
  26513. VSTPluginInstance& plugin;
  26514. bool isOpen, wasShowing, recursiveResize;
  26515. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26516. #if JUCE_WINDOWS
  26517. HWND pluginHWND;
  26518. void* originalWndProc;
  26519. int sizeCheckCount;
  26520. #elif JUCE_LINUX
  26521. Window pluginWindow;
  26522. EventProcPtr pluginProc;
  26523. #endif
  26524. #if JUCE_MAC
  26525. void openPluginWindow (WindowRef parentWindow)
  26526. {
  26527. if (isOpen || parentWindow == 0)
  26528. return;
  26529. isOpen = true;
  26530. ERect* rect = 0;
  26531. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26532. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26533. // do this before and after like in the steinberg example
  26534. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26535. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26536. // Install keyboard hooks
  26537. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26538. // double-check it's not too tiny
  26539. int w = 250, h = 150;
  26540. if (rect != 0)
  26541. {
  26542. w = rect->right - rect->left;
  26543. h = rect->bottom - rect->top;
  26544. if (w == 0 || h == 0)
  26545. {
  26546. w = 250;
  26547. h = 150;
  26548. }
  26549. }
  26550. w = jmax (w, 32);
  26551. h = jmax (h, 32);
  26552. setSize (w, h);
  26553. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26554. repaint();
  26555. }
  26556. #else
  26557. void openPluginWindow()
  26558. {
  26559. if (isOpen || getWindowHandle() == 0)
  26560. return;
  26561. log ("Opening VST UI: " + plugin.name);
  26562. isOpen = true;
  26563. ERect* rect = 0;
  26564. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26565. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26566. // do this before and after like in the steinberg example
  26567. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26568. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26569. // Install keyboard hooks
  26570. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26571. #if JUCE_WINDOWS
  26572. originalWndProc = 0;
  26573. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26574. if (pluginHWND == 0)
  26575. {
  26576. isOpen = false;
  26577. setSize (300, 150);
  26578. return;
  26579. }
  26580. #pragma warning (push)
  26581. #pragma warning (disable: 4244)
  26582. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26583. if (! pluginWantsKeys)
  26584. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26585. #pragma warning (pop)
  26586. int w, h;
  26587. RECT r;
  26588. GetWindowRect (pluginHWND, &r);
  26589. w = r.right - r.left;
  26590. h = r.bottom - r.top;
  26591. if (rect != 0)
  26592. {
  26593. const int rw = rect->right - rect->left;
  26594. const int rh = rect->bottom - rect->top;
  26595. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26596. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26597. {
  26598. // very dodgy logic to decide which size is right.
  26599. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26600. {
  26601. SetWindowPos (pluginHWND, 0,
  26602. 0, 0, rw, rh,
  26603. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26604. GetWindowRect (pluginHWND, &r);
  26605. w = r.right - r.left;
  26606. h = r.bottom - r.top;
  26607. pluginRefusesToResize = (w != rw) || (h != rh);
  26608. w = rw;
  26609. h = rh;
  26610. }
  26611. }
  26612. }
  26613. #elif JUCE_LINUX
  26614. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26615. if (pluginWindow != 0)
  26616. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26617. XInternAtom (display, "_XEventProc", False));
  26618. int w = 250, h = 150;
  26619. if (rect != 0)
  26620. {
  26621. w = rect->right - rect->left;
  26622. h = rect->bottom - rect->top;
  26623. if (w == 0 || h == 0)
  26624. {
  26625. w = 250;
  26626. h = 150;
  26627. }
  26628. }
  26629. if (pluginWindow != 0)
  26630. XMapRaised (display, pluginWindow);
  26631. #endif
  26632. // double-check it's not too tiny
  26633. w = jmax (w, 32);
  26634. h = jmax (h, 32);
  26635. setSize (w, h);
  26636. #if JUCE_WINDOWS
  26637. checkPluginWindowSize();
  26638. #endif
  26639. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26640. repaint();
  26641. }
  26642. #endif
  26643. #if ! JUCE_MAC
  26644. void closePluginWindow()
  26645. {
  26646. if (isOpen)
  26647. {
  26648. log ("Closing VST UI: " + plugin.getName());
  26649. isOpen = false;
  26650. dispatch (effEditClose, 0, 0, 0, 0);
  26651. #if JUCE_WINDOWS
  26652. #pragma warning (push)
  26653. #pragma warning (disable: 4244)
  26654. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26655. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26656. #pragma warning (pop)
  26657. stopTimer();
  26658. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26659. DestroyWindow (pluginHWND);
  26660. pluginHWND = 0;
  26661. #elif JUCE_LINUX
  26662. stopTimer();
  26663. pluginWindow = 0;
  26664. pluginProc = 0;
  26665. #endif
  26666. }
  26667. }
  26668. #endif
  26669. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26670. {
  26671. return plugin.dispatch (opcode, index, value, ptr, opt);
  26672. }
  26673. #if JUCE_WINDOWS
  26674. void checkPluginWindowSize() throw()
  26675. {
  26676. RECT r;
  26677. GetWindowRect (pluginHWND, &r);
  26678. const int w = r.right - r.left;
  26679. const int h = r.bottom - r.top;
  26680. if (isShowing() && w > 0 && h > 0
  26681. && (w != getWidth() || h != getHeight())
  26682. && ! pluginRefusesToResize)
  26683. {
  26684. setSize (w, h);
  26685. sizeCheckCount = 0;
  26686. }
  26687. }
  26688. // hooks to get keyboard events from VST windows..
  26689. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26690. {
  26691. for (int i = activeVSTWindows.size(); --i >= 0;)
  26692. {
  26693. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26694. if (w->pluginHWND == hW)
  26695. {
  26696. if (message == WM_CHAR
  26697. || message == WM_KEYDOWN
  26698. || message == WM_SYSKEYDOWN
  26699. || message == WM_KEYUP
  26700. || message == WM_SYSKEYUP
  26701. || message == WM_APPCOMMAND)
  26702. {
  26703. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26704. message, wParam, lParam);
  26705. }
  26706. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26707. (HWND) w->pluginHWND,
  26708. message,
  26709. wParam,
  26710. lParam);
  26711. }
  26712. }
  26713. return DefWindowProc (hW, message, wParam, lParam);
  26714. }
  26715. #endif
  26716. #if JUCE_LINUX
  26717. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26718. void sendEventToChild (XEvent* event)
  26719. {
  26720. if (pluginProc != 0)
  26721. {
  26722. // if the plugin publishes an event procedure, pass the event directly..
  26723. pluginProc (event);
  26724. }
  26725. else if (pluginWindow != 0)
  26726. {
  26727. // if the plugin has a window, then send the event to the window so that
  26728. // its message thread will pick it up..
  26729. XSendEvent (display, pluginWindow, False, 0L, event);
  26730. XFlush (display);
  26731. }
  26732. }
  26733. void mouseEnter (const MouseEvent& e)
  26734. {
  26735. if (pluginWindow != 0)
  26736. {
  26737. XEvent ev;
  26738. zerostruct (ev);
  26739. ev.xcrossing.display = display;
  26740. ev.xcrossing.type = EnterNotify;
  26741. ev.xcrossing.window = pluginWindow;
  26742. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26743. ev.xcrossing.time = CurrentTime;
  26744. ev.xcrossing.x = e.x;
  26745. ev.xcrossing.y = e.y;
  26746. ev.xcrossing.x_root = e.getScreenX();
  26747. ev.xcrossing.y_root = e.getScreenY();
  26748. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26749. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26750. translateJuceToXCrossingModifiers (e, ev);
  26751. sendEventToChild (&ev);
  26752. }
  26753. }
  26754. void mouseExit (const MouseEvent& e)
  26755. {
  26756. if (pluginWindow != 0)
  26757. {
  26758. XEvent ev;
  26759. zerostruct (ev);
  26760. ev.xcrossing.display = display;
  26761. ev.xcrossing.type = LeaveNotify;
  26762. ev.xcrossing.window = pluginWindow;
  26763. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26764. ev.xcrossing.time = CurrentTime;
  26765. ev.xcrossing.x = e.x;
  26766. ev.xcrossing.y = e.y;
  26767. ev.xcrossing.x_root = e.getScreenX();
  26768. ev.xcrossing.y_root = e.getScreenY();
  26769. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26770. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26771. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26772. translateJuceToXCrossingModifiers (e, ev);
  26773. sendEventToChild (&ev);
  26774. }
  26775. }
  26776. void mouseMove (const MouseEvent& e)
  26777. {
  26778. if (pluginWindow != 0)
  26779. {
  26780. XEvent ev;
  26781. zerostruct (ev);
  26782. ev.xmotion.display = display;
  26783. ev.xmotion.type = MotionNotify;
  26784. ev.xmotion.window = pluginWindow;
  26785. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26786. ev.xmotion.time = CurrentTime;
  26787. ev.xmotion.is_hint = NotifyNormal;
  26788. ev.xmotion.x = e.x;
  26789. ev.xmotion.y = e.y;
  26790. ev.xmotion.x_root = e.getScreenX();
  26791. ev.xmotion.y_root = e.getScreenY();
  26792. sendEventToChild (&ev);
  26793. }
  26794. }
  26795. void mouseDrag (const MouseEvent& e)
  26796. {
  26797. if (pluginWindow != 0)
  26798. {
  26799. XEvent ev;
  26800. zerostruct (ev);
  26801. ev.xmotion.display = display;
  26802. ev.xmotion.type = MotionNotify;
  26803. ev.xmotion.window = pluginWindow;
  26804. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26805. ev.xmotion.time = CurrentTime;
  26806. ev.xmotion.x = e.x ;
  26807. ev.xmotion.y = e.y;
  26808. ev.xmotion.x_root = e.getScreenX();
  26809. ev.xmotion.y_root = e.getScreenY();
  26810. ev.xmotion.is_hint = NotifyNormal;
  26811. translateJuceToXMotionModifiers (e, ev);
  26812. sendEventToChild (&ev);
  26813. }
  26814. }
  26815. void mouseUp (const MouseEvent& e)
  26816. {
  26817. if (pluginWindow != 0)
  26818. {
  26819. XEvent ev;
  26820. zerostruct (ev);
  26821. ev.xbutton.display = display;
  26822. ev.xbutton.type = ButtonRelease;
  26823. ev.xbutton.window = pluginWindow;
  26824. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26825. ev.xbutton.time = CurrentTime;
  26826. ev.xbutton.x = e.x;
  26827. ev.xbutton.y = e.y;
  26828. ev.xbutton.x_root = e.getScreenX();
  26829. ev.xbutton.y_root = e.getScreenY();
  26830. translateJuceToXButtonModifiers (e, ev);
  26831. sendEventToChild (&ev);
  26832. }
  26833. }
  26834. void mouseWheelMove (const MouseEvent& e,
  26835. float incrementX,
  26836. float incrementY)
  26837. {
  26838. if (pluginWindow != 0)
  26839. {
  26840. XEvent ev;
  26841. zerostruct (ev);
  26842. ev.xbutton.display = display;
  26843. ev.xbutton.type = ButtonPress;
  26844. ev.xbutton.window = pluginWindow;
  26845. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26846. ev.xbutton.time = CurrentTime;
  26847. ev.xbutton.x = e.x;
  26848. ev.xbutton.y = e.y;
  26849. ev.xbutton.x_root = e.getScreenX();
  26850. ev.xbutton.y_root = e.getScreenY();
  26851. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26852. sendEventToChild (&ev);
  26853. // TODO - put a usleep here ?
  26854. ev.xbutton.type = ButtonRelease;
  26855. sendEventToChild (&ev);
  26856. }
  26857. }
  26858. #endif
  26859. #if JUCE_MAC
  26860. #if ! JUCE_SUPPORT_CARBON
  26861. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26862. #endif
  26863. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26864. {
  26865. public:
  26866. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26867. : owner (owner_),
  26868. alreadyInside (false)
  26869. {
  26870. }
  26871. ~InnerWrapperComponent()
  26872. {
  26873. deleteWindow();
  26874. }
  26875. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26876. {
  26877. owner->openPluginWindow (windowRef);
  26878. return 0;
  26879. }
  26880. void removeView (HIViewRef)
  26881. {
  26882. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26883. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26884. }
  26885. bool getEmbeddedViewSize (int& w, int& h)
  26886. {
  26887. ERect* rect = 0;
  26888. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26889. w = rect->right - rect->left;
  26890. h = rect->bottom - rect->top;
  26891. return true;
  26892. }
  26893. void mouseDown (int x, int y)
  26894. {
  26895. if (! alreadyInside)
  26896. {
  26897. alreadyInside = true;
  26898. getTopLevelComponent()->toFront (true);
  26899. owner->dispatch (effEditMouse, x, y, 0, 0);
  26900. alreadyInside = false;
  26901. }
  26902. else
  26903. {
  26904. PostEvent (::mouseDown, 0);
  26905. }
  26906. }
  26907. void paint()
  26908. {
  26909. ComponentPeer* const peer = getPeer();
  26910. if (peer != 0)
  26911. {
  26912. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26913. ERect r;
  26914. r.left = pos.getX();
  26915. r.right = r.left + getWidth();
  26916. r.top = pos.getY();
  26917. r.bottom = r.top + getHeight();
  26918. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26919. }
  26920. }
  26921. private:
  26922. VSTPluginWindow* const owner;
  26923. bool alreadyInside;
  26924. };
  26925. friend class InnerWrapperComponent;
  26926. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26927. void resized()
  26928. {
  26929. innerWrapper->setSize (getWidth(), getHeight());
  26930. }
  26931. #endif
  26932. };
  26933. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26934. {
  26935. if (hasEditor())
  26936. return new VSTPluginWindow (*this);
  26937. return 0;
  26938. }
  26939. void VSTPluginInstance::handleAsyncUpdate()
  26940. {
  26941. // indicates that something about the plugin has changed..
  26942. updateHostDisplay();
  26943. }
  26944. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26945. {
  26946. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26947. {
  26948. changeProgramName (getCurrentProgram(), prog->prgName);
  26949. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26950. setParameter (i, vst_swapFloat (prog->params[i]));
  26951. return true;
  26952. }
  26953. return false;
  26954. }
  26955. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26956. const int dataSize)
  26957. {
  26958. if (dataSize < 28)
  26959. return false;
  26960. const fxSet* const set = (const fxSet*) data;
  26961. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26962. || vst_swap (set->version) > fxbVersionNum)
  26963. return false;
  26964. if (vst_swap (set->fxMagic) == 'FxBk')
  26965. {
  26966. // bank of programs
  26967. if (vst_swap (set->numPrograms) >= 0)
  26968. {
  26969. const int oldProg = getCurrentProgram();
  26970. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26971. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26972. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26973. {
  26974. if (i != oldProg)
  26975. {
  26976. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26977. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26978. return false;
  26979. if (vst_swap (set->numPrograms) > 0)
  26980. setCurrentProgram (i);
  26981. if (! restoreProgramSettings (prog))
  26982. return false;
  26983. }
  26984. }
  26985. if (vst_swap (set->numPrograms) > 0)
  26986. setCurrentProgram (oldProg);
  26987. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26988. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26989. return false;
  26990. if (! restoreProgramSettings (prog))
  26991. return false;
  26992. }
  26993. }
  26994. else if (vst_swap (set->fxMagic) == 'FxCk')
  26995. {
  26996. // single program
  26997. const fxProgram* const prog = (const fxProgram*) data;
  26998. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26999. return false;
  27000. changeProgramName (getCurrentProgram(), prog->prgName);
  27001. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27002. setParameter (i, vst_swapFloat (prog->params[i]));
  27003. }
  27004. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27005. {
  27006. // non-preset chunk
  27007. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27008. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27009. return false;
  27010. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27011. }
  27012. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27013. {
  27014. // preset chunk
  27015. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27016. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27017. return false;
  27018. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27019. changeProgramName (getCurrentProgram(), cset->name);
  27020. }
  27021. else
  27022. {
  27023. return false;
  27024. }
  27025. return true;
  27026. }
  27027. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27028. {
  27029. const int numParams = getNumParameters();
  27030. prog->chunkMagic = vst_swap ('CcnK');
  27031. prog->byteSize = 0;
  27032. prog->fxMagic = vst_swap ('FxCk');
  27033. prog->version = vst_swap (fxbVersionNum);
  27034. prog->fxID = vst_swap (getUID());
  27035. prog->fxVersion = vst_swap (getVersionNumber());
  27036. prog->numParams = vst_swap (numParams);
  27037. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27038. for (int i = 0; i < numParams; ++i)
  27039. prog->params[i] = vst_swapFloat (getParameter (i));
  27040. }
  27041. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27042. {
  27043. const int numPrograms = getNumPrograms();
  27044. const int numParams = getNumParameters();
  27045. if (usesChunks())
  27046. {
  27047. if (isFXB)
  27048. {
  27049. MemoryBlock chunk;
  27050. getChunkData (chunk, false, maxSizeMB);
  27051. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27052. dest.setSize (totalLen, true);
  27053. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27054. set->chunkMagic = vst_swap ('CcnK');
  27055. set->byteSize = 0;
  27056. set->fxMagic = vst_swap ('FBCh');
  27057. set->version = vst_swap (fxbVersionNum);
  27058. set->fxID = vst_swap (getUID());
  27059. set->fxVersion = vst_swap (getVersionNumber());
  27060. set->numPrograms = vst_swap (numPrograms);
  27061. set->chunkSize = vst_swap ((long) chunk.getSize());
  27062. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27063. }
  27064. else
  27065. {
  27066. MemoryBlock chunk;
  27067. getChunkData (chunk, true, maxSizeMB);
  27068. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27069. dest.setSize (totalLen, true);
  27070. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27071. set->chunkMagic = vst_swap ('CcnK');
  27072. set->byteSize = 0;
  27073. set->fxMagic = vst_swap ('FPCh');
  27074. set->version = vst_swap (fxbVersionNum);
  27075. set->fxID = vst_swap (getUID());
  27076. set->fxVersion = vst_swap (getVersionNumber());
  27077. set->numPrograms = vst_swap (numPrograms);
  27078. set->chunkSize = vst_swap ((long) chunk.getSize());
  27079. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27080. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27081. }
  27082. }
  27083. else
  27084. {
  27085. if (isFXB)
  27086. {
  27087. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27088. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27089. dest.setSize (len, true);
  27090. fxSet* const set = (fxSet*) dest.getData();
  27091. set->chunkMagic = vst_swap ('CcnK');
  27092. set->byteSize = 0;
  27093. set->fxMagic = vst_swap ('FxBk');
  27094. set->version = vst_swap (fxbVersionNum);
  27095. set->fxID = vst_swap (getUID());
  27096. set->fxVersion = vst_swap (getVersionNumber());
  27097. set->numPrograms = vst_swap (numPrograms);
  27098. const int oldProgram = getCurrentProgram();
  27099. MemoryBlock oldSettings;
  27100. createTempParameterStore (oldSettings);
  27101. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27102. for (int i = 0; i < numPrograms; ++i)
  27103. {
  27104. if (i != oldProgram)
  27105. {
  27106. setCurrentProgram (i);
  27107. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27108. }
  27109. }
  27110. setCurrentProgram (oldProgram);
  27111. restoreFromTempParameterStore (oldSettings);
  27112. }
  27113. else
  27114. {
  27115. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27116. dest.setSize (totalLen, true);
  27117. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27118. }
  27119. }
  27120. return true;
  27121. }
  27122. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27123. {
  27124. if (usesChunks())
  27125. {
  27126. void* data = 0;
  27127. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27128. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27129. {
  27130. mb.setSize (bytes);
  27131. mb.copyFrom (data, 0, bytes);
  27132. }
  27133. }
  27134. }
  27135. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27136. {
  27137. if (size > 0 && usesChunks())
  27138. {
  27139. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27140. if (! isPreset)
  27141. updateStoredProgramNames();
  27142. }
  27143. }
  27144. void VSTPluginInstance::timerCallback()
  27145. {
  27146. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27147. stopTimer();
  27148. }
  27149. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27150. {
  27151. const ScopedLock sl (lock);
  27152. ++insideVSTCallback;
  27153. int result = 0;
  27154. try
  27155. {
  27156. if (effect != 0)
  27157. {
  27158. #if JUCE_MAC
  27159. if (module->resFileId != 0)
  27160. UseResFile (module->resFileId);
  27161. CGrafPtr oldPort;
  27162. if (getActiveEditor() != 0)
  27163. {
  27164. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27165. GetPort (&oldPort);
  27166. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27167. SetOrigin (-pos.getX(), -pos.getY());
  27168. }
  27169. #endif
  27170. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27171. #if JUCE_MAC
  27172. if (getActiveEditor() != 0)
  27173. SetPort (oldPort);
  27174. module->resFileId = CurResFile();
  27175. #endif
  27176. --insideVSTCallback;
  27177. return result;
  27178. }
  27179. }
  27180. catch (...)
  27181. {
  27182. }
  27183. --insideVSTCallback;
  27184. return result;
  27185. }
  27186. // handles non plugin-specific callbacks..
  27187. static const int defaultVSTSampleRateValue = 16384;
  27188. static const int defaultVSTBlockSizeValue = 512;
  27189. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27190. {
  27191. (void) index;
  27192. (void) value;
  27193. (void) opt;
  27194. switch (opcode)
  27195. {
  27196. case audioMasterCanDo:
  27197. {
  27198. static const char* canDos[] = { "supplyIdle",
  27199. "sendVstEvents",
  27200. "sendVstMidiEvent",
  27201. "sendVstTimeInfo",
  27202. "receiveVstEvents",
  27203. "receiveVstMidiEvent",
  27204. "supportShell",
  27205. "shellCategory" };
  27206. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27207. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27208. return 1;
  27209. return 0;
  27210. }
  27211. case audioMasterVersion:
  27212. return 0x2400;
  27213. case audioMasterCurrentId:
  27214. return shellUIDToCreate;
  27215. case audioMasterGetNumAutomatableParameters:
  27216. return 0;
  27217. case audioMasterGetAutomationState:
  27218. return 1;
  27219. case audioMasterGetVendorVersion:
  27220. return 0x0101;
  27221. case audioMasterGetVendorString:
  27222. case audioMasterGetProductString:
  27223. {
  27224. String hostName ("Juce VST Host");
  27225. if (JUCEApplication::getInstance() != 0)
  27226. hostName = JUCEApplication::getInstance()->getApplicationName();
  27227. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27228. }
  27229. break;
  27230. case audioMasterGetSampleRate:
  27231. return (VstIntPtr) defaultVSTSampleRateValue;
  27232. case audioMasterGetBlockSize:
  27233. return (VstIntPtr) defaultVSTBlockSizeValue;
  27234. case audioMasterSetOutputSampleRate:
  27235. return 0;
  27236. default:
  27237. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27238. break;
  27239. }
  27240. return 0;
  27241. }
  27242. // handles callbacks for a specific plugin
  27243. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27244. {
  27245. switch (opcode)
  27246. {
  27247. case audioMasterAutomate:
  27248. sendParamChangeMessageToListeners (index, opt);
  27249. break;
  27250. case audioMasterProcessEvents:
  27251. handleMidiFromPlugin ((const VstEvents*) ptr);
  27252. break;
  27253. case audioMasterGetTime:
  27254. #if JUCE_MSVC
  27255. #pragma warning (push)
  27256. #pragma warning (disable: 4311)
  27257. #endif
  27258. return (VstIntPtr) &vstHostTime;
  27259. #if JUCE_MSVC
  27260. #pragma warning (pop)
  27261. #endif
  27262. break;
  27263. case audioMasterIdle:
  27264. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27265. {
  27266. ++insideVSTCallback;
  27267. #if JUCE_MAC
  27268. if (getActiveEditor() != 0)
  27269. dispatch (effEditIdle, 0, 0, 0, 0);
  27270. #endif
  27271. juce_callAnyTimersSynchronously();
  27272. handleUpdateNowIfNeeded();
  27273. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27274. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27275. --insideVSTCallback;
  27276. }
  27277. break;
  27278. case audioMasterUpdateDisplay:
  27279. triggerAsyncUpdate();
  27280. break;
  27281. case audioMasterTempoAt:
  27282. // returns (10000 * bpm)
  27283. break;
  27284. case audioMasterNeedIdle:
  27285. startTimer (50);
  27286. break;
  27287. case audioMasterSizeWindow:
  27288. if (getActiveEditor() != 0)
  27289. getActiveEditor()->setSize (index, value);
  27290. return 1;
  27291. case audioMasterGetSampleRate:
  27292. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27293. case audioMasterGetBlockSize:
  27294. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27295. case audioMasterWantMidi:
  27296. wantsMidiMessages = true;
  27297. break;
  27298. case audioMasterGetDirectory:
  27299. #if JUCE_MAC
  27300. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27301. #else
  27302. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27303. #endif
  27304. case audioMasterGetAutomationState:
  27305. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27306. break;
  27307. // none of these are handled (yet)..
  27308. case audioMasterBeginEdit:
  27309. case audioMasterEndEdit:
  27310. case audioMasterSetTime:
  27311. case audioMasterPinConnected:
  27312. case audioMasterGetParameterQuantization:
  27313. case audioMasterIOChanged:
  27314. case audioMasterGetInputLatency:
  27315. case audioMasterGetOutputLatency:
  27316. case audioMasterGetPreviousPlug:
  27317. case audioMasterGetNextPlug:
  27318. case audioMasterWillReplaceOrAccumulate:
  27319. case audioMasterGetCurrentProcessLevel:
  27320. case audioMasterOfflineStart:
  27321. case audioMasterOfflineRead:
  27322. case audioMasterOfflineWrite:
  27323. case audioMasterOfflineGetCurrentPass:
  27324. case audioMasterOfflineGetCurrentMetaPass:
  27325. case audioMasterVendorSpecific:
  27326. case audioMasterSetIcon:
  27327. case audioMasterGetLanguage:
  27328. case audioMasterOpenWindow:
  27329. case audioMasterCloseWindow:
  27330. break;
  27331. default:
  27332. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27333. }
  27334. return 0;
  27335. }
  27336. // entry point for all callbacks from the plugin
  27337. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27338. {
  27339. try
  27340. {
  27341. if (effect != 0 && effect->resvd2 != 0)
  27342. {
  27343. return ((VSTPluginInstance*)(effect->resvd2))
  27344. ->handleCallback (opcode, index, value, ptr, opt);
  27345. }
  27346. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27347. }
  27348. catch (...)
  27349. {
  27350. return 0;
  27351. }
  27352. }
  27353. const String VSTPluginInstance::getVersion() const throw()
  27354. {
  27355. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27356. String s;
  27357. if (v == 0 || v == -1)
  27358. v = getVersionNumber();
  27359. if (v != 0)
  27360. {
  27361. int versionBits[4];
  27362. int n = 0;
  27363. while (v != 0)
  27364. {
  27365. versionBits [n++] = (v & 0xff);
  27366. v >>= 8;
  27367. }
  27368. s << 'V';
  27369. while (n > 0)
  27370. {
  27371. s << versionBits [--n];
  27372. if (n > 0)
  27373. s << '.';
  27374. }
  27375. }
  27376. return s;
  27377. }
  27378. int VSTPluginInstance::getUID() const throw()
  27379. {
  27380. int uid = effect != 0 ? effect->uniqueID : 0;
  27381. if (uid == 0)
  27382. uid = module->file.hashCode();
  27383. return uid;
  27384. }
  27385. const String VSTPluginInstance::getCategory() const throw()
  27386. {
  27387. const char* result = 0;
  27388. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27389. {
  27390. case kPlugCategEffect:
  27391. result = "Effect";
  27392. break;
  27393. case kPlugCategSynth:
  27394. result = "Synth";
  27395. break;
  27396. case kPlugCategAnalysis:
  27397. result = "Anaylsis";
  27398. break;
  27399. case kPlugCategMastering:
  27400. result = "Mastering";
  27401. break;
  27402. case kPlugCategSpacializer:
  27403. result = "Spacial";
  27404. break;
  27405. case kPlugCategRoomFx:
  27406. result = "Reverb";
  27407. break;
  27408. case kPlugSurroundFx:
  27409. result = "Surround";
  27410. break;
  27411. case kPlugCategRestoration:
  27412. result = "Restoration";
  27413. break;
  27414. case kPlugCategGenerator:
  27415. result = "Tone generation";
  27416. break;
  27417. default:
  27418. break;
  27419. }
  27420. return result;
  27421. }
  27422. float VSTPluginInstance::getParameter (int index)
  27423. {
  27424. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27425. {
  27426. try
  27427. {
  27428. const ScopedLock sl (lock);
  27429. return effect->getParameter (effect, index);
  27430. }
  27431. catch (...)
  27432. {
  27433. }
  27434. }
  27435. return 0.0f;
  27436. }
  27437. void VSTPluginInstance::setParameter (int index, float newValue)
  27438. {
  27439. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27440. {
  27441. try
  27442. {
  27443. const ScopedLock sl (lock);
  27444. if (effect->getParameter (effect, index) != newValue)
  27445. effect->setParameter (effect, index, newValue);
  27446. }
  27447. catch (...)
  27448. {
  27449. }
  27450. }
  27451. }
  27452. const String VSTPluginInstance::getParameterName (int index)
  27453. {
  27454. if (effect != 0)
  27455. {
  27456. jassert (index >= 0 && index < effect->numParams);
  27457. char nm [256];
  27458. zerostruct (nm);
  27459. dispatch (effGetParamName, index, 0, nm, 0);
  27460. return String (nm).trim();
  27461. }
  27462. return String::empty;
  27463. }
  27464. const String VSTPluginInstance::getParameterLabel (int index) const
  27465. {
  27466. if (effect != 0)
  27467. {
  27468. jassert (index >= 0 && index < effect->numParams);
  27469. char nm [256];
  27470. zerostruct (nm);
  27471. dispatch (effGetParamLabel, index, 0, nm, 0);
  27472. return String (nm).trim();
  27473. }
  27474. return String::empty;
  27475. }
  27476. const String VSTPluginInstance::getParameterText (int index)
  27477. {
  27478. if (effect != 0)
  27479. {
  27480. jassert (index >= 0 && index < effect->numParams);
  27481. char nm [256];
  27482. zerostruct (nm);
  27483. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27484. return String (nm).trim();
  27485. }
  27486. return String::empty;
  27487. }
  27488. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27489. {
  27490. if (effect != 0)
  27491. {
  27492. jassert (index >= 0 && index < effect->numParams);
  27493. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27494. }
  27495. return false;
  27496. }
  27497. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27498. {
  27499. dest.setSize (64 + 4 * getNumParameters());
  27500. dest.fillWith (0);
  27501. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27502. float* const p = (float*) (((char*) dest.getData()) + 64);
  27503. for (int i = 0; i < getNumParameters(); ++i)
  27504. p[i] = getParameter(i);
  27505. }
  27506. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27507. {
  27508. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27509. float* p = (float*) (((char*) m.getData()) + 64);
  27510. for (int i = 0; i < getNumParameters(); ++i)
  27511. setParameter (i, p[i]);
  27512. }
  27513. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27514. {
  27515. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27516. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27517. }
  27518. const String VSTPluginInstance::getProgramName (int index)
  27519. {
  27520. if (index == getCurrentProgram())
  27521. {
  27522. return getCurrentProgramName();
  27523. }
  27524. else if (effect != 0)
  27525. {
  27526. char nm [256];
  27527. zerostruct (nm);
  27528. if (dispatch (effGetProgramNameIndexed,
  27529. jlimit (0, getNumPrograms(), index),
  27530. -1, nm, 0) != 0)
  27531. {
  27532. return String (nm).trim();
  27533. }
  27534. }
  27535. return programNames [index];
  27536. }
  27537. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27538. {
  27539. if (index == getCurrentProgram())
  27540. {
  27541. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27542. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27543. }
  27544. else
  27545. {
  27546. jassertfalse; // xxx not implemented!
  27547. }
  27548. }
  27549. void VSTPluginInstance::updateStoredProgramNames()
  27550. {
  27551. if (effect != 0 && getNumPrograms() > 0)
  27552. {
  27553. char nm [256];
  27554. zerostruct (nm);
  27555. // only do this if the plugin can't use indexed names..
  27556. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27557. {
  27558. const int oldProgram = getCurrentProgram();
  27559. MemoryBlock oldSettings;
  27560. createTempParameterStore (oldSettings);
  27561. for (int i = 0; i < getNumPrograms(); ++i)
  27562. {
  27563. setCurrentProgram (i);
  27564. getCurrentProgramName(); // (this updates the list)
  27565. }
  27566. setCurrentProgram (oldProgram);
  27567. restoreFromTempParameterStore (oldSettings);
  27568. }
  27569. }
  27570. }
  27571. const String VSTPluginInstance::getCurrentProgramName()
  27572. {
  27573. if (effect != 0)
  27574. {
  27575. char nm [256];
  27576. zerostruct (nm);
  27577. dispatch (effGetProgramName, 0, 0, nm, 0);
  27578. const int index = getCurrentProgram();
  27579. if (programNames[index].isEmpty())
  27580. {
  27581. while (programNames.size() < index)
  27582. programNames.add (String::empty);
  27583. programNames.set (index, String (nm).trim());
  27584. }
  27585. return String (nm).trim();
  27586. }
  27587. return String::empty;
  27588. }
  27589. const String VSTPluginInstance::getInputChannelName (const int index) const
  27590. {
  27591. if (index >= 0 && index < getNumInputChannels())
  27592. {
  27593. VstPinProperties pinProps;
  27594. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27595. return String (pinProps.label, sizeof (pinProps.label));
  27596. }
  27597. return String::empty;
  27598. }
  27599. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27600. {
  27601. if (index < 0 || index >= getNumInputChannels())
  27602. return false;
  27603. VstPinProperties pinProps;
  27604. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27605. return (pinProps.flags & kVstPinIsStereo) != 0;
  27606. return true;
  27607. }
  27608. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27609. {
  27610. if (index >= 0 && index < getNumOutputChannels())
  27611. {
  27612. VstPinProperties pinProps;
  27613. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27614. return String (pinProps.label, sizeof (pinProps.label));
  27615. }
  27616. return String::empty;
  27617. }
  27618. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27619. {
  27620. if (index < 0 || index >= getNumOutputChannels())
  27621. return false;
  27622. VstPinProperties pinProps;
  27623. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27624. return (pinProps.flags & kVstPinIsStereo) != 0;
  27625. return true;
  27626. }
  27627. void VSTPluginInstance::setPower (const bool on)
  27628. {
  27629. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27630. isPowerOn = on;
  27631. }
  27632. const int defaultMaxSizeMB = 64;
  27633. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27634. {
  27635. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27636. }
  27637. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27638. {
  27639. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27640. }
  27641. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27642. {
  27643. loadFromFXBFile (data, sizeInBytes);
  27644. }
  27645. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27646. {
  27647. loadFromFXBFile (data, sizeInBytes);
  27648. }
  27649. VSTPluginFormat::VSTPluginFormat()
  27650. {
  27651. }
  27652. VSTPluginFormat::~VSTPluginFormat()
  27653. {
  27654. }
  27655. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27656. const String& fileOrIdentifier)
  27657. {
  27658. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27659. return;
  27660. PluginDescription desc;
  27661. desc.fileOrIdentifier = fileOrIdentifier;
  27662. desc.uid = 0;
  27663. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27664. if (instance == 0)
  27665. return;
  27666. try
  27667. {
  27668. #if JUCE_MAC
  27669. if (instance->module->resFileId != 0)
  27670. UseResFile (instance->module->resFileId);
  27671. #endif
  27672. instance->fillInPluginDescription (desc);
  27673. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27674. if (category != kPlugCategShell)
  27675. {
  27676. // Normal plugin...
  27677. results.add (new PluginDescription (desc));
  27678. ++insideVSTCallback;
  27679. instance->dispatch (effOpen, 0, 0, 0, 0);
  27680. --insideVSTCallback;
  27681. }
  27682. else
  27683. {
  27684. // It's a shell plugin, so iterate all the subtypes...
  27685. char shellEffectName [64];
  27686. for (;;)
  27687. {
  27688. zerostruct (shellEffectName);
  27689. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27690. if (uid == 0)
  27691. {
  27692. break;
  27693. }
  27694. else
  27695. {
  27696. desc.uid = uid;
  27697. desc.name = shellEffectName;
  27698. bool alreadyThere = false;
  27699. for (int i = results.size(); --i >= 0;)
  27700. {
  27701. PluginDescription* const d = results.getUnchecked(i);
  27702. if (d->isDuplicateOf (desc))
  27703. {
  27704. alreadyThere = true;
  27705. break;
  27706. }
  27707. }
  27708. if (! alreadyThere)
  27709. results.add (new PluginDescription (desc));
  27710. }
  27711. }
  27712. }
  27713. }
  27714. catch (...)
  27715. {
  27716. // crashed while loading...
  27717. }
  27718. }
  27719. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27720. {
  27721. ScopedPointer <VSTPluginInstance> result;
  27722. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27723. {
  27724. File file (desc.fileOrIdentifier);
  27725. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27726. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27727. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27728. if (module != 0)
  27729. {
  27730. shellUIDToCreate = desc.uid;
  27731. result = new VSTPluginInstance (module);
  27732. if (result->effect != 0)
  27733. {
  27734. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27735. result->initialise();
  27736. }
  27737. else
  27738. {
  27739. result = 0;
  27740. }
  27741. }
  27742. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27743. }
  27744. return result.release();
  27745. }
  27746. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27747. {
  27748. const File f (fileOrIdentifier);
  27749. #if JUCE_MAC
  27750. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27751. return true;
  27752. #if JUCE_PPC
  27753. FSRef fileRef;
  27754. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27755. {
  27756. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27757. if (resFileId != -1)
  27758. {
  27759. const int numEffects = Count1Resources ('aEff');
  27760. CloseResFile (resFileId);
  27761. if (numEffects > 0)
  27762. return true;
  27763. }
  27764. }
  27765. #endif
  27766. return false;
  27767. #elif JUCE_WINDOWS
  27768. return f.existsAsFile()
  27769. && f.hasFileExtension (".dll");
  27770. #elif JUCE_LINUX
  27771. return f.existsAsFile()
  27772. && f.hasFileExtension (".so");
  27773. #endif
  27774. }
  27775. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27776. {
  27777. return fileOrIdentifier;
  27778. }
  27779. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27780. {
  27781. return File (desc.fileOrIdentifier).exists();
  27782. }
  27783. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27784. {
  27785. StringArray results;
  27786. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27787. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27788. return results;
  27789. }
  27790. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27791. {
  27792. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27793. // .component or .vst directories.
  27794. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27795. while (iter.next())
  27796. {
  27797. const File f (iter.getFile());
  27798. bool isPlugin = false;
  27799. if (fileMightContainThisPluginType (f.getFullPathName()))
  27800. {
  27801. isPlugin = true;
  27802. results.add (f.getFullPathName());
  27803. }
  27804. if (recursive && (! isPlugin) && f.isDirectory())
  27805. recursiveFileSearch (results, f, true);
  27806. }
  27807. }
  27808. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27809. {
  27810. #if JUCE_MAC
  27811. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27812. #elif JUCE_WINDOWS
  27813. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27814. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27815. #elif JUCE_LINUX
  27816. return FileSearchPath ("/usr/lib/vst");
  27817. #endif
  27818. }
  27819. END_JUCE_NAMESPACE
  27820. #endif
  27821. #undef log
  27822. #endif
  27823. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27824. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27825. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27826. BEGIN_JUCE_NAMESPACE
  27827. AudioProcessor::AudioProcessor()
  27828. : playHead (0),
  27829. activeEditor (0),
  27830. sampleRate (0),
  27831. blockSize (0),
  27832. numInputChannels (0),
  27833. numOutputChannels (0),
  27834. latencySamples (0),
  27835. suspended (false),
  27836. nonRealtime (false)
  27837. {
  27838. }
  27839. AudioProcessor::~AudioProcessor()
  27840. {
  27841. // ooh, nasty - the editor should have been deleted before the filter
  27842. // that it refers to is deleted..
  27843. jassert (activeEditor == 0);
  27844. #if JUCE_DEBUG
  27845. // This will fail if you've called beginParameterChangeGesture() for one
  27846. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27847. jassert (changingParams.countNumberOfSetBits() == 0);
  27848. #endif
  27849. }
  27850. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27851. {
  27852. playHead = newPlayHead;
  27853. }
  27854. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27855. {
  27856. const ScopedLock sl (listenerLock);
  27857. listeners.addIfNotAlreadyThere (newListener);
  27858. }
  27859. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27860. {
  27861. const ScopedLock sl (listenerLock);
  27862. listeners.removeValue (listenerToRemove);
  27863. }
  27864. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27865. const int numOuts,
  27866. const double sampleRate_,
  27867. const int blockSize_) throw()
  27868. {
  27869. numInputChannels = numIns;
  27870. numOutputChannels = numOuts;
  27871. sampleRate = sampleRate_;
  27872. blockSize = blockSize_;
  27873. }
  27874. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27875. {
  27876. nonRealtime = nonRealtime_;
  27877. }
  27878. void AudioProcessor::setLatencySamples (const int newLatency)
  27879. {
  27880. if (latencySamples != newLatency)
  27881. {
  27882. latencySamples = newLatency;
  27883. updateHostDisplay();
  27884. }
  27885. }
  27886. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27887. const float newValue)
  27888. {
  27889. setParameter (parameterIndex, newValue);
  27890. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27891. }
  27892. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27893. {
  27894. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27895. for (int i = listeners.size(); --i >= 0;)
  27896. {
  27897. AudioProcessorListener* l;
  27898. {
  27899. const ScopedLock sl (listenerLock);
  27900. l = listeners [i];
  27901. }
  27902. if (l != 0)
  27903. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27904. }
  27905. }
  27906. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27907. {
  27908. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27909. #if JUCE_DEBUG
  27910. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27911. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27912. jassert (! changingParams [parameterIndex]);
  27913. changingParams.setBit (parameterIndex);
  27914. #endif
  27915. for (int i = listeners.size(); --i >= 0;)
  27916. {
  27917. AudioProcessorListener* l;
  27918. {
  27919. const ScopedLock sl (listenerLock);
  27920. l = listeners [i];
  27921. }
  27922. if (l != 0)
  27923. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27924. }
  27925. }
  27926. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27927. {
  27928. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27929. #if JUCE_DEBUG
  27930. // This means you've called endParameterChangeGesture without having previously called
  27931. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27932. // calls matched correctly.
  27933. jassert (changingParams [parameterIndex]);
  27934. changingParams.clearBit (parameterIndex);
  27935. #endif
  27936. for (int i = listeners.size(); --i >= 0;)
  27937. {
  27938. AudioProcessorListener* l;
  27939. {
  27940. const ScopedLock sl (listenerLock);
  27941. l = listeners [i];
  27942. }
  27943. if (l != 0)
  27944. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27945. }
  27946. }
  27947. void AudioProcessor::updateHostDisplay()
  27948. {
  27949. for (int i = listeners.size(); --i >= 0;)
  27950. {
  27951. AudioProcessorListener* l;
  27952. {
  27953. const ScopedLock sl (listenerLock);
  27954. l = listeners [i];
  27955. }
  27956. if (l != 0)
  27957. l->audioProcessorChanged (this);
  27958. }
  27959. }
  27960. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27961. {
  27962. return true;
  27963. }
  27964. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27965. {
  27966. return false;
  27967. }
  27968. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27969. {
  27970. const ScopedLock sl (callbackLock);
  27971. suspended = shouldBeSuspended;
  27972. }
  27973. void AudioProcessor::reset()
  27974. {
  27975. }
  27976. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27977. {
  27978. const ScopedLock sl (callbackLock);
  27979. jassert (activeEditor == editor);
  27980. if (activeEditor == editor)
  27981. activeEditor = 0;
  27982. }
  27983. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27984. {
  27985. if (activeEditor != 0)
  27986. return activeEditor;
  27987. AudioProcessorEditor* const ed = createEditor();
  27988. if (ed != 0)
  27989. {
  27990. // you must give your editor comp a size before returning it..
  27991. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27992. const ScopedLock sl (callbackLock);
  27993. activeEditor = ed;
  27994. }
  27995. return ed;
  27996. }
  27997. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27998. {
  27999. getStateInformation (destData);
  28000. }
  28001. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28002. {
  28003. setStateInformation (data, sizeInBytes);
  28004. }
  28005. // magic number to identify memory blocks that we've stored as XML
  28006. const uint32 magicXmlNumber = 0x21324356;
  28007. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28008. JUCE_NAMESPACE::MemoryBlock& destData)
  28009. {
  28010. const String xmlString (xml.createDocument (String::empty, true, false));
  28011. const int stringLength = xmlString.getNumBytesAsUTF8();
  28012. destData.setSize (stringLength + 10);
  28013. char* const d = (char*) destData.getData();
  28014. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28015. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28016. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28017. }
  28018. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28019. const int sizeInBytes)
  28020. {
  28021. if (sizeInBytes > 8
  28022. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28023. {
  28024. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28025. if (stringLength > 0)
  28026. {
  28027. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28028. jmin ((sizeInBytes - 8), stringLength)));
  28029. return doc.getDocumentElement();
  28030. }
  28031. }
  28032. return 0;
  28033. }
  28034. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28035. {
  28036. }
  28037. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28038. {
  28039. }
  28040. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28041. {
  28042. return timeInSeconds == other.timeInSeconds
  28043. && ppqPosition == other.ppqPosition
  28044. && editOriginTime == other.editOriginTime
  28045. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28046. && frameRate == other.frameRate
  28047. && isPlaying == other.isPlaying
  28048. && isRecording == other.isRecording
  28049. && bpm == other.bpm
  28050. && timeSigNumerator == other.timeSigNumerator
  28051. && timeSigDenominator == other.timeSigDenominator;
  28052. }
  28053. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28054. {
  28055. return ! operator== (other);
  28056. }
  28057. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28058. {
  28059. zerostruct (*this);
  28060. timeSigNumerator = 4;
  28061. timeSigDenominator = 4;
  28062. bpm = 120;
  28063. }
  28064. END_JUCE_NAMESPACE
  28065. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28066. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28067. BEGIN_JUCE_NAMESPACE
  28068. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28069. : owner (owner_)
  28070. {
  28071. // the filter must be valid..
  28072. jassert (owner != 0);
  28073. }
  28074. AudioProcessorEditor::~AudioProcessorEditor()
  28075. {
  28076. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28077. // filter for some reason..
  28078. jassert (owner->getActiveEditor() != this);
  28079. }
  28080. END_JUCE_NAMESPACE
  28081. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28082. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28083. BEGIN_JUCE_NAMESPACE
  28084. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28085. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28086. : id (id_),
  28087. processor (processor_),
  28088. isPrepared (false)
  28089. {
  28090. jassert (processor_ != 0);
  28091. }
  28092. AudioProcessorGraph::Node::~Node()
  28093. {
  28094. delete processor;
  28095. }
  28096. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28097. AudioProcessorGraph* const graph)
  28098. {
  28099. if (! isPrepared)
  28100. {
  28101. isPrepared = true;
  28102. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28103. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28104. if (ioProc != 0)
  28105. ioProc->setParentGraph (graph);
  28106. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28107. processor->getNumOutputChannels(),
  28108. sampleRate, blockSize);
  28109. processor->prepareToPlay (sampleRate, blockSize);
  28110. }
  28111. }
  28112. void AudioProcessorGraph::Node::unprepare()
  28113. {
  28114. if (isPrepared)
  28115. {
  28116. isPrepared = false;
  28117. processor->releaseResources();
  28118. }
  28119. }
  28120. AudioProcessorGraph::AudioProcessorGraph()
  28121. : lastNodeId (0),
  28122. renderingBuffers (1, 1),
  28123. currentAudioOutputBuffer (1, 1)
  28124. {
  28125. }
  28126. AudioProcessorGraph::~AudioProcessorGraph()
  28127. {
  28128. clearRenderingSequence();
  28129. clear();
  28130. }
  28131. const String AudioProcessorGraph::getName() const
  28132. {
  28133. return "Audio Graph";
  28134. }
  28135. void AudioProcessorGraph::clear()
  28136. {
  28137. nodes.clear();
  28138. connections.clear();
  28139. triggerAsyncUpdate();
  28140. }
  28141. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28142. {
  28143. for (int i = nodes.size(); --i >= 0;)
  28144. if (nodes.getUnchecked(i)->id == nodeId)
  28145. return nodes.getUnchecked(i);
  28146. return 0;
  28147. }
  28148. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28149. uint32 nodeId)
  28150. {
  28151. if (newProcessor == 0)
  28152. {
  28153. jassertfalse;
  28154. return 0;
  28155. }
  28156. if (nodeId == 0)
  28157. {
  28158. nodeId = ++lastNodeId;
  28159. }
  28160. else
  28161. {
  28162. // you can't add a node with an id that already exists in the graph..
  28163. jassert (getNodeForId (nodeId) == 0);
  28164. removeNode (nodeId);
  28165. }
  28166. lastNodeId = nodeId;
  28167. Node* const n = new Node (nodeId, newProcessor);
  28168. nodes.add (n);
  28169. triggerAsyncUpdate();
  28170. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28171. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28172. if (ioProc != 0)
  28173. ioProc->setParentGraph (this);
  28174. return n;
  28175. }
  28176. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28177. {
  28178. disconnectNode (nodeId);
  28179. for (int i = nodes.size(); --i >= 0;)
  28180. {
  28181. if (nodes.getUnchecked(i)->id == nodeId)
  28182. {
  28183. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28184. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28185. if (ioProc != 0)
  28186. ioProc->setParentGraph (0);
  28187. nodes.remove (i);
  28188. triggerAsyncUpdate();
  28189. return true;
  28190. }
  28191. }
  28192. return false;
  28193. }
  28194. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28195. const int sourceChannelIndex,
  28196. const uint32 destNodeId,
  28197. const int destChannelIndex) const
  28198. {
  28199. for (int i = connections.size(); --i >= 0;)
  28200. {
  28201. const Connection* const c = connections.getUnchecked(i);
  28202. if (c->sourceNodeId == sourceNodeId
  28203. && c->destNodeId == destNodeId
  28204. && c->sourceChannelIndex == sourceChannelIndex
  28205. && c->destChannelIndex == destChannelIndex)
  28206. {
  28207. return c;
  28208. }
  28209. }
  28210. return 0;
  28211. }
  28212. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28213. const uint32 possibleDestNodeId) const
  28214. {
  28215. for (int i = connections.size(); --i >= 0;)
  28216. {
  28217. const Connection* const c = connections.getUnchecked(i);
  28218. if (c->sourceNodeId == possibleSourceNodeId
  28219. && c->destNodeId == possibleDestNodeId)
  28220. {
  28221. return true;
  28222. }
  28223. }
  28224. return false;
  28225. }
  28226. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28227. const int sourceChannelIndex,
  28228. const uint32 destNodeId,
  28229. const int destChannelIndex) const
  28230. {
  28231. if (sourceChannelIndex < 0
  28232. || destChannelIndex < 0
  28233. || sourceNodeId == destNodeId
  28234. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28235. return false;
  28236. const Node* const source = getNodeForId (sourceNodeId);
  28237. if (source == 0
  28238. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28239. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28240. return false;
  28241. const Node* const dest = getNodeForId (destNodeId);
  28242. if (dest == 0
  28243. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28244. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28245. return false;
  28246. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28247. destNodeId, destChannelIndex) == 0;
  28248. }
  28249. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28250. const int sourceChannelIndex,
  28251. const uint32 destNodeId,
  28252. const int destChannelIndex)
  28253. {
  28254. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28255. return false;
  28256. Connection* const c = new Connection();
  28257. c->sourceNodeId = sourceNodeId;
  28258. c->sourceChannelIndex = sourceChannelIndex;
  28259. c->destNodeId = destNodeId;
  28260. c->destChannelIndex = destChannelIndex;
  28261. connections.add (c);
  28262. triggerAsyncUpdate();
  28263. return true;
  28264. }
  28265. void AudioProcessorGraph::removeConnection (const int index)
  28266. {
  28267. connections.remove (index);
  28268. triggerAsyncUpdate();
  28269. }
  28270. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28271. const uint32 destNodeId, const int destChannelIndex)
  28272. {
  28273. bool doneAnything = false;
  28274. for (int i = connections.size(); --i >= 0;)
  28275. {
  28276. const Connection* const c = connections.getUnchecked(i);
  28277. if (c->sourceNodeId == sourceNodeId
  28278. && c->destNodeId == destNodeId
  28279. && c->sourceChannelIndex == sourceChannelIndex
  28280. && c->destChannelIndex == destChannelIndex)
  28281. {
  28282. removeConnection (i);
  28283. doneAnything = true;
  28284. triggerAsyncUpdate();
  28285. }
  28286. }
  28287. return doneAnything;
  28288. }
  28289. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28290. {
  28291. bool doneAnything = false;
  28292. for (int i = connections.size(); --i >= 0;)
  28293. {
  28294. const Connection* const c = connections.getUnchecked(i);
  28295. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28296. {
  28297. removeConnection (i);
  28298. doneAnything = true;
  28299. triggerAsyncUpdate();
  28300. }
  28301. }
  28302. return doneAnything;
  28303. }
  28304. bool AudioProcessorGraph::removeIllegalConnections()
  28305. {
  28306. bool doneAnything = false;
  28307. for (int i = connections.size(); --i >= 0;)
  28308. {
  28309. const Connection* const c = connections.getUnchecked(i);
  28310. const Node* const source = getNodeForId (c->sourceNodeId);
  28311. const Node* const dest = getNodeForId (c->destNodeId);
  28312. if (source == 0 || dest == 0
  28313. || (c->sourceChannelIndex != midiChannelIndex
  28314. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28315. || (c->sourceChannelIndex == midiChannelIndex
  28316. && ! source->processor->producesMidi())
  28317. || (c->destChannelIndex != midiChannelIndex
  28318. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28319. || (c->destChannelIndex == midiChannelIndex
  28320. && ! dest->processor->acceptsMidi()))
  28321. {
  28322. removeConnection (i);
  28323. doneAnything = true;
  28324. triggerAsyncUpdate();
  28325. }
  28326. }
  28327. return doneAnything;
  28328. }
  28329. namespace GraphRenderingOps
  28330. {
  28331. class AudioGraphRenderingOp
  28332. {
  28333. public:
  28334. AudioGraphRenderingOp() {}
  28335. virtual ~AudioGraphRenderingOp() {}
  28336. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28337. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28338. const int numSamples) = 0;
  28339. juce_UseDebuggingNewOperator
  28340. };
  28341. class ClearChannelOp : public AudioGraphRenderingOp
  28342. {
  28343. public:
  28344. ClearChannelOp (const int channelNum_)
  28345. : channelNum (channelNum_)
  28346. {}
  28347. ~ClearChannelOp() {}
  28348. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28349. {
  28350. sharedBufferChans.clear (channelNum, 0, numSamples);
  28351. }
  28352. private:
  28353. const int channelNum;
  28354. ClearChannelOp (const ClearChannelOp&);
  28355. ClearChannelOp& operator= (const ClearChannelOp&);
  28356. };
  28357. class CopyChannelOp : public AudioGraphRenderingOp
  28358. {
  28359. public:
  28360. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28361. : srcChannelNum (srcChannelNum_),
  28362. dstChannelNum (dstChannelNum_)
  28363. {}
  28364. ~CopyChannelOp() {}
  28365. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28366. {
  28367. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28368. }
  28369. private:
  28370. const int srcChannelNum, dstChannelNum;
  28371. CopyChannelOp (const CopyChannelOp&);
  28372. CopyChannelOp& operator= (const CopyChannelOp&);
  28373. };
  28374. class AddChannelOp : public AudioGraphRenderingOp
  28375. {
  28376. public:
  28377. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28378. : srcChannelNum (srcChannelNum_),
  28379. dstChannelNum (dstChannelNum_)
  28380. {}
  28381. ~AddChannelOp() {}
  28382. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28383. {
  28384. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28385. }
  28386. private:
  28387. const int srcChannelNum, dstChannelNum;
  28388. AddChannelOp (const AddChannelOp&);
  28389. AddChannelOp& operator= (const AddChannelOp&);
  28390. };
  28391. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28392. {
  28393. public:
  28394. ClearMidiBufferOp (const int bufferNum_)
  28395. : bufferNum (bufferNum_)
  28396. {}
  28397. ~ClearMidiBufferOp() {}
  28398. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28399. {
  28400. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28401. }
  28402. private:
  28403. const int bufferNum;
  28404. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28405. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28406. };
  28407. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28408. {
  28409. public:
  28410. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28411. : srcBufferNum (srcBufferNum_),
  28412. dstBufferNum (dstBufferNum_)
  28413. {}
  28414. ~CopyMidiBufferOp() {}
  28415. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28416. {
  28417. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28418. }
  28419. private:
  28420. const int srcBufferNum, dstBufferNum;
  28421. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28422. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28423. };
  28424. class AddMidiBufferOp : public AudioGraphRenderingOp
  28425. {
  28426. public:
  28427. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28428. : srcBufferNum (srcBufferNum_),
  28429. dstBufferNum (dstBufferNum_)
  28430. {}
  28431. ~AddMidiBufferOp() {}
  28432. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28433. {
  28434. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28435. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28436. }
  28437. private:
  28438. const int srcBufferNum, dstBufferNum;
  28439. AddMidiBufferOp (const AddMidiBufferOp&);
  28440. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28441. };
  28442. class ProcessBufferOp : public AudioGraphRenderingOp
  28443. {
  28444. public:
  28445. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28446. const Array <int>& audioChannelsToUse_,
  28447. const int totalChans_,
  28448. const int midiBufferToUse_)
  28449. : node (node_),
  28450. processor (node_->processor),
  28451. audioChannelsToUse (audioChannelsToUse_),
  28452. totalChans (jmax (1, totalChans_)),
  28453. midiBufferToUse (midiBufferToUse_)
  28454. {
  28455. channels.calloc (totalChans);
  28456. while (audioChannelsToUse.size() < totalChans)
  28457. audioChannelsToUse.add (0);
  28458. }
  28459. ~ProcessBufferOp()
  28460. {
  28461. }
  28462. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28463. {
  28464. for (int i = totalChans; --i >= 0;)
  28465. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28466. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28467. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28468. }
  28469. const AudioProcessorGraph::Node::Ptr node;
  28470. AudioProcessor* const processor;
  28471. private:
  28472. Array <int> audioChannelsToUse;
  28473. HeapBlock <float*> channels;
  28474. int totalChans;
  28475. int midiBufferToUse;
  28476. ProcessBufferOp (const ProcessBufferOp&);
  28477. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28478. };
  28479. /** Used to calculate the correct sequence of rendering ops needed, based on
  28480. the best re-use of shared buffers at each stage.
  28481. */
  28482. class RenderingOpSequenceCalculator
  28483. {
  28484. public:
  28485. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28486. const Array<void*>& orderedNodes_,
  28487. Array<void*>& renderingOps)
  28488. : graph (graph_),
  28489. orderedNodes (orderedNodes_)
  28490. {
  28491. nodeIds.add (-2); // first buffer is read-only zeros
  28492. channels.add (0);
  28493. midiNodeIds.add (-2);
  28494. for (int i = 0; i < orderedNodes.size(); ++i)
  28495. {
  28496. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28497. renderingOps, i);
  28498. markAnyUnusedBuffersAsFree (i);
  28499. }
  28500. }
  28501. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28502. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28503. juce_UseDebuggingNewOperator
  28504. private:
  28505. AudioProcessorGraph& graph;
  28506. const Array<void*>& orderedNodes;
  28507. Array <int> nodeIds, channels, midiNodeIds;
  28508. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28509. Array<void*>& renderingOps,
  28510. const int ourRenderingIndex)
  28511. {
  28512. const int numIns = node->processor->getNumInputChannels();
  28513. const int numOuts = node->processor->getNumOutputChannels();
  28514. const int totalChans = jmax (numIns, numOuts);
  28515. Array <int> audioChannelsToUse;
  28516. int midiBufferToUse = -1;
  28517. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28518. {
  28519. // get a list of all the inputs to this node
  28520. Array <int> sourceNodes, sourceOutputChans;
  28521. for (int i = graph.getNumConnections(); --i >= 0;)
  28522. {
  28523. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28524. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28525. {
  28526. sourceNodes.add (c->sourceNodeId);
  28527. sourceOutputChans.add (c->sourceChannelIndex);
  28528. }
  28529. }
  28530. int bufIndex = -1;
  28531. if (sourceNodes.size() == 0)
  28532. {
  28533. // unconnected input channel
  28534. if (inputChan >= numOuts)
  28535. {
  28536. bufIndex = getReadOnlyEmptyBuffer();
  28537. jassert (bufIndex >= 0);
  28538. }
  28539. else
  28540. {
  28541. bufIndex = getFreeBuffer (false);
  28542. renderingOps.add (new ClearChannelOp (bufIndex));
  28543. }
  28544. }
  28545. else if (sourceNodes.size() == 1)
  28546. {
  28547. // channel with a straightforward single input..
  28548. const int srcNode = sourceNodes.getUnchecked(0);
  28549. const int srcChan = sourceOutputChans.getUnchecked(0);
  28550. bufIndex = getBufferContaining (srcNode, srcChan);
  28551. if (bufIndex < 0)
  28552. {
  28553. // if not found, this is probably a feedback loop
  28554. bufIndex = getReadOnlyEmptyBuffer();
  28555. jassert (bufIndex >= 0);
  28556. }
  28557. if (inputChan < numOuts
  28558. && isBufferNeededLater (ourRenderingIndex,
  28559. inputChan,
  28560. srcNode, srcChan))
  28561. {
  28562. // can't mess up this channel because it's needed later by another node, so we
  28563. // need to use a copy of it..
  28564. const int newFreeBuffer = getFreeBuffer (false);
  28565. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28566. bufIndex = newFreeBuffer;
  28567. }
  28568. }
  28569. else
  28570. {
  28571. // channel with a mix of several inputs..
  28572. // try to find a re-usable channel from our inputs..
  28573. int reusableInputIndex = -1;
  28574. for (int i = 0; i < sourceNodes.size(); ++i)
  28575. {
  28576. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28577. sourceOutputChans.getUnchecked(i));
  28578. if (sourceBufIndex >= 0
  28579. && ! isBufferNeededLater (ourRenderingIndex,
  28580. inputChan,
  28581. sourceNodes.getUnchecked(i),
  28582. sourceOutputChans.getUnchecked(i)))
  28583. {
  28584. // we've found one of our input chans that can be re-used..
  28585. reusableInputIndex = i;
  28586. bufIndex = sourceBufIndex;
  28587. break;
  28588. }
  28589. }
  28590. if (reusableInputIndex < 0)
  28591. {
  28592. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28593. bufIndex = getFreeBuffer (false);
  28594. jassert (bufIndex != 0);
  28595. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28596. sourceOutputChans.getUnchecked (0));
  28597. if (srcIndex < 0)
  28598. {
  28599. // if not found, this is probably a feedback loop
  28600. renderingOps.add (new ClearChannelOp (bufIndex));
  28601. }
  28602. else
  28603. {
  28604. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28605. }
  28606. reusableInputIndex = 0;
  28607. }
  28608. for (int j = 0; j < sourceNodes.size(); ++j)
  28609. {
  28610. if (j != reusableInputIndex)
  28611. {
  28612. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28613. sourceOutputChans.getUnchecked(j));
  28614. if (srcIndex >= 0)
  28615. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28616. }
  28617. }
  28618. }
  28619. jassert (bufIndex >= 0);
  28620. audioChannelsToUse.add (bufIndex);
  28621. if (inputChan < numOuts)
  28622. markBufferAsContaining (bufIndex, node->id, inputChan);
  28623. }
  28624. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28625. {
  28626. const int bufIndex = getFreeBuffer (false);
  28627. jassert (bufIndex != 0);
  28628. audioChannelsToUse.add (bufIndex);
  28629. markBufferAsContaining (bufIndex, node->id, outputChan);
  28630. }
  28631. // Now the same thing for midi..
  28632. Array <int> midiSourceNodes;
  28633. for (int i = graph.getNumConnections(); --i >= 0;)
  28634. {
  28635. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28636. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28637. midiSourceNodes.add (c->sourceNodeId);
  28638. }
  28639. if (midiSourceNodes.size() == 0)
  28640. {
  28641. // No midi inputs..
  28642. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28643. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28644. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28645. }
  28646. else if (midiSourceNodes.size() == 1)
  28647. {
  28648. // One midi input..
  28649. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28650. AudioProcessorGraph::midiChannelIndex);
  28651. if (midiBufferToUse >= 0)
  28652. {
  28653. if (isBufferNeededLater (ourRenderingIndex,
  28654. AudioProcessorGraph::midiChannelIndex,
  28655. midiSourceNodes.getUnchecked(0),
  28656. AudioProcessorGraph::midiChannelIndex))
  28657. {
  28658. // can't mess up this channel because it's needed later by another node, so we
  28659. // need to use a copy of it..
  28660. const int newFreeBuffer = getFreeBuffer (true);
  28661. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28662. midiBufferToUse = newFreeBuffer;
  28663. }
  28664. }
  28665. else
  28666. {
  28667. // probably a feedback loop, so just use an empty one..
  28668. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28669. }
  28670. }
  28671. else
  28672. {
  28673. // More than one midi input being mixed..
  28674. int reusableInputIndex = -1;
  28675. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28676. {
  28677. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28678. AudioProcessorGraph::midiChannelIndex);
  28679. if (sourceBufIndex >= 0
  28680. && ! isBufferNeededLater (ourRenderingIndex,
  28681. AudioProcessorGraph::midiChannelIndex,
  28682. midiSourceNodes.getUnchecked(i),
  28683. AudioProcessorGraph::midiChannelIndex))
  28684. {
  28685. // we've found one of our input buffers that can be re-used..
  28686. reusableInputIndex = i;
  28687. midiBufferToUse = sourceBufIndex;
  28688. break;
  28689. }
  28690. }
  28691. if (reusableInputIndex < 0)
  28692. {
  28693. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28694. midiBufferToUse = getFreeBuffer (true);
  28695. jassert (midiBufferToUse >= 0);
  28696. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28697. AudioProcessorGraph::midiChannelIndex);
  28698. if (srcIndex >= 0)
  28699. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28700. else
  28701. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28702. reusableInputIndex = 0;
  28703. }
  28704. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28705. {
  28706. if (j != reusableInputIndex)
  28707. {
  28708. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28709. AudioProcessorGraph::midiChannelIndex);
  28710. if (srcIndex >= 0)
  28711. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28712. }
  28713. }
  28714. }
  28715. if (node->processor->producesMidi())
  28716. markBufferAsContaining (midiBufferToUse, node->id,
  28717. AudioProcessorGraph::midiChannelIndex);
  28718. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28719. totalChans, midiBufferToUse));
  28720. }
  28721. int getFreeBuffer (const bool forMidi)
  28722. {
  28723. if (forMidi)
  28724. {
  28725. for (int i = 1; i < midiNodeIds.size(); ++i)
  28726. if (midiNodeIds.getUnchecked(i) < 0)
  28727. return i;
  28728. midiNodeIds.add (-1);
  28729. return midiNodeIds.size() - 1;
  28730. }
  28731. else
  28732. {
  28733. for (int i = 1; i < nodeIds.size(); ++i)
  28734. if (nodeIds.getUnchecked(i) < 0)
  28735. return i;
  28736. nodeIds.add (-1);
  28737. channels.add (0);
  28738. return nodeIds.size() - 1;
  28739. }
  28740. }
  28741. int getReadOnlyEmptyBuffer() const
  28742. {
  28743. return 0;
  28744. }
  28745. int getBufferContaining (const int nodeId, const int outputChannel) const
  28746. {
  28747. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28748. {
  28749. for (int i = midiNodeIds.size(); --i >= 0;)
  28750. if (midiNodeIds.getUnchecked(i) == nodeId)
  28751. return i;
  28752. }
  28753. else
  28754. {
  28755. for (int i = nodeIds.size(); --i >= 0;)
  28756. if (nodeIds.getUnchecked(i) == nodeId
  28757. && channels.getUnchecked(i) == outputChannel)
  28758. return i;
  28759. }
  28760. return -1;
  28761. }
  28762. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28763. {
  28764. int i;
  28765. for (i = 0; i < nodeIds.size(); ++i)
  28766. {
  28767. if (nodeIds.getUnchecked(i) >= 0
  28768. && ! isBufferNeededLater (stepIndex, -1,
  28769. nodeIds.getUnchecked(i),
  28770. channels.getUnchecked(i)))
  28771. {
  28772. nodeIds.set (i, -1);
  28773. }
  28774. }
  28775. for (i = 0; i < midiNodeIds.size(); ++i)
  28776. {
  28777. if (midiNodeIds.getUnchecked(i) >= 0
  28778. && ! isBufferNeededLater (stepIndex, -1,
  28779. midiNodeIds.getUnchecked(i),
  28780. AudioProcessorGraph::midiChannelIndex))
  28781. {
  28782. midiNodeIds.set (i, -1);
  28783. }
  28784. }
  28785. }
  28786. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28787. int inputChannelOfIndexToIgnore,
  28788. const int nodeId,
  28789. const int outputChanIndex) const
  28790. {
  28791. while (stepIndexToSearchFrom < orderedNodes.size())
  28792. {
  28793. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28794. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28795. {
  28796. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28797. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28798. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28799. return true;
  28800. }
  28801. else
  28802. {
  28803. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28804. if (i != inputChannelOfIndexToIgnore
  28805. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28806. node->id, i) != 0)
  28807. return true;
  28808. }
  28809. inputChannelOfIndexToIgnore = -1;
  28810. ++stepIndexToSearchFrom;
  28811. }
  28812. return false;
  28813. }
  28814. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28815. {
  28816. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28817. {
  28818. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28819. midiNodeIds.set (bufferNum, nodeId);
  28820. }
  28821. else
  28822. {
  28823. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28824. nodeIds.set (bufferNum, nodeId);
  28825. channels.set (bufferNum, outputIndex);
  28826. }
  28827. }
  28828. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28829. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28830. };
  28831. }
  28832. void AudioProcessorGraph::clearRenderingSequence()
  28833. {
  28834. const ScopedLock sl (renderLock);
  28835. for (int i = renderingOps.size(); --i >= 0;)
  28836. {
  28837. GraphRenderingOps::AudioGraphRenderingOp* const r
  28838. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28839. renderingOps.remove (i);
  28840. delete r;
  28841. }
  28842. }
  28843. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28844. const uint32 possibleDestinationId,
  28845. const int recursionCheck) const
  28846. {
  28847. if (recursionCheck > 0)
  28848. {
  28849. for (int i = connections.size(); --i >= 0;)
  28850. {
  28851. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28852. if (c->destNodeId == possibleDestinationId
  28853. && (c->sourceNodeId == possibleInputId
  28854. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28855. return true;
  28856. }
  28857. }
  28858. return false;
  28859. }
  28860. void AudioProcessorGraph::buildRenderingSequence()
  28861. {
  28862. Array<void*> newRenderingOps;
  28863. int numRenderingBuffersNeeded = 2;
  28864. int numMidiBuffersNeeded = 1;
  28865. {
  28866. MessageManagerLock mml;
  28867. Array<void*> orderedNodes;
  28868. int i;
  28869. for (i = 0; i < nodes.size(); ++i)
  28870. {
  28871. Node* const node = nodes.getUnchecked(i);
  28872. node->prepare (getSampleRate(), getBlockSize(), this);
  28873. int j = 0;
  28874. for (; j < orderedNodes.size(); ++j)
  28875. if (isAnInputTo (node->id,
  28876. ((Node*) orderedNodes.getUnchecked (j))->id,
  28877. nodes.size() + 1))
  28878. break;
  28879. orderedNodes.insert (j, node);
  28880. }
  28881. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28882. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28883. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28884. }
  28885. Array<void*> oldRenderingOps (renderingOps);
  28886. {
  28887. // swap over to the new rendering sequence..
  28888. const ScopedLock sl (renderLock);
  28889. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28890. renderingBuffers.clear();
  28891. for (int i = midiBuffers.size(); --i >= 0;)
  28892. midiBuffers.getUnchecked(i)->clear();
  28893. while (midiBuffers.size() < numMidiBuffersNeeded)
  28894. midiBuffers.add (new MidiBuffer());
  28895. renderingOps = newRenderingOps;
  28896. }
  28897. for (int i = oldRenderingOps.size(); --i >= 0;)
  28898. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28899. }
  28900. void AudioProcessorGraph::handleAsyncUpdate()
  28901. {
  28902. buildRenderingSequence();
  28903. }
  28904. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28905. {
  28906. currentAudioInputBuffer = 0;
  28907. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28908. currentMidiInputBuffer = 0;
  28909. currentMidiOutputBuffer.clear();
  28910. clearRenderingSequence();
  28911. buildRenderingSequence();
  28912. }
  28913. void AudioProcessorGraph::releaseResources()
  28914. {
  28915. for (int i = 0; i < nodes.size(); ++i)
  28916. nodes.getUnchecked(i)->unprepare();
  28917. renderingBuffers.setSize (1, 1);
  28918. midiBuffers.clear();
  28919. currentAudioInputBuffer = 0;
  28920. currentAudioOutputBuffer.setSize (1, 1);
  28921. currentMidiInputBuffer = 0;
  28922. currentMidiOutputBuffer.clear();
  28923. }
  28924. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28925. {
  28926. const int numSamples = buffer.getNumSamples();
  28927. const ScopedLock sl (renderLock);
  28928. currentAudioInputBuffer = &buffer;
  28929. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28930. currentAudioOutputBuffer.clear();
  28931. currentMidiInputBuffer = &midiMessages;
  28932. currentMidiOutputBuffer.clear();
  28933. int i;
  28934. for (i = 0; i < renderingOps.size(); ++i)
  28935. {
  28936. GraphRenderingOps::AudioGraphRenderingOp* const op
  28937. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28938. op->perform (renderingBuffers, midiBuffers, numSamples);
  28939. }
  28940. for (i = 0; i < buffer.getNumChannels(); ++i)
  28941. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28942. midiMessages.clear();
  28943. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28944. }
  28945. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28946. {
  28947. return "Input " + String (channelIndex + 1);
  28948. }
  28949. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28950. {
  28951. return "Output " + String (channelIndex + 1);
  28952. }
  28953. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28954. {
  28955. return true;
  28956. }
  28957. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28958. {
  28959. return true;
  28960. }
  28961. bool AudioProcessorGraph::acceptsMidi() const
  28962. {
  28963. return true;
  28964. }
  28965. bool AudioProcessorGraph::producesMidi() const
  28966. {
  28967. return true;
  28968. }
  28969. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28970. {
  28971. }
  28972. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28973. {
  28974. }
  28975. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28976. : type (type_),
  28977. graph (0)
  28978. {
  28979. }
  28980. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28981. {
  28982. }
  28983. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28984. {
  28985. switch (type)
  28986. {
  28987. case audioOutputNode:
  28988. return "Audio Output";
  28989. case audioInputNode:
  28990. return "Audio Input";
  28991. case midiOutputNode:
  28992. return "Midi Output";
  28993. case midiInputNode:
  28994. return "Midi Input";
  28995. default:
  28996. break;
  28997. }
  28998. return String::empty;
  28999. }
  29000. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29001. {
  29002. d.name = getName();
  29003. d.uid = d.name.hashCode();
  29004. d.category = "I/O devices";
  29005. d.pluginFormatName = "Internal";
  29006. d.manufacturerName = "Raw Material Software";
  29007. d.version = "1.0";
  29008. d.isInstrument = false;
  29009. d.numInputChannels = getNumInputChannels();
  29010. if (type == audioOutputNode && graph != 0)
  29011. d.numInputChannels = graph->getNumInputChannels();
  29012. d.numOutputChannels = getNumOutputChannels();
  29013. if (type == audioInputNode && graph != 0)
  29014. d.numOutputChannels = graph->getNumOutputChannels();
  29015. }
  29016. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29017. {
  29018. jassert (graph != 0);
  29019. }
  29020. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29021. {
  29022. }
  29023. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29024. MidiBuffer& midiMessages)
  29025. {
  29026. jassert (graph != 0);
  29027. switch (type)
  29028. {
  29029. case audioOutputNode:
  29030. {
  29031. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29032. buffer.getNumChannels()); --i >= 0;)
  29033. {
  29034. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29035. }
  29036. break;
  29037. }
  29038. case audioInputNode:
  29039. {
  29040. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29041. buffer.getNumChannels()); --i >= 0;)
  29042. {
  29043. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29044. }
  29045. break;
  29046. }
  29047. case midiOutputNode:
  29048. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29049. break;
  29050. case midiInputNode:
  29051. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29052. break;
  29053. default:
  29054. break;
  29055. }
  29056. }
  29057. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29058. {
  29059. return type == midiOutputNode;
  29060. }
  29061. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29062. {
  29063. return type == midiInputNode;
  29064. }
  29065. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29066. {
  29067. switch (type)
  29068. {
  29069. case audioOutputNode:
  29070. return "Output " + String (channelIndex + 1);
  29071. case midiOutputNode:
  29072. return "Midi Output";
  29073. default:
  29074. break;
  29075. }
  29076. return String::empty;
  29077. }
  29078. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29079. {
  29080. switch (type)
  29081. {
  29082. case audioInputNode:
  29083. return "Input " + String (channelIndex + 1);
  29084. case midiInputNode:
  29085. return "Midi Input";
  29086. default:
  29087. break;
  29088. }
  29089. return String::empty;
  29090. }
  29091. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29092. {
  29093. return type == audioInputNode || type == audioOutputNode;
  29094. }
  29095. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29096. {
  29097. return isInputChannelStereoPair (index);
  29098. }
  29099. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29100. {
  29101. return type == audioInputNode || type == midiInputNode;
  29102. }
  29103. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29104. {
  29105. return type == audioOutputNode || type == midiOutputNode;
  29106. }
  29107. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29108. {
  29109. return 0;
  29110. }
  29111. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29112. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29113. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29114. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29115. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29116. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29117. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29118. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29119. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29120. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29121. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29122. {
  29123. }
  29124. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29125. {
  29126. }
  29127. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29128. {
  29129. graph = newGraph;
  29130. if (graph != 0)
  29131. {
  29132. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29133. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29134. getSampleRate(),
  29135. getBlockSize());
  29136. updateHostDisplay();
  29137. }
  29138. }
  29139. END_JUCE_NAMESPACE
  29140. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29141. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29142. BEGIN_JUCE_NAMESPACE
  29143. AudioProcessorPlayer::AudioProcessorPlayer()
  29144. : processor (0),
  29145. sampleRate (0),
  29146. blockSize (0),
  29147. isPrepared (false),
  29148. numInputChans (0),
  29149. numOutputChans (0),
  29150. tempBuffer (1, 1)
  29151. {
  29152. }
  29153. AudioProcessorPlayer::~AudioProcessorPlayer()
  29154. {
  29155. setProcessor (0);
  29156. }
  29157. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29158. {
  29159. if (processor != processorToPlay)
  29160. {
  29161. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29162. {
  29163. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29164. sampleRate, blockSize);
  29165. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29166. }
  29167. AudioProcessor* oldOne;
  29168. {
  29169. const ScopedLock sl (lock);
  29170. oldOne = isPrepared ? processor : 0;
  29171. processor = processorToPlay;
  29172. isPrepared = true;
  29173. }
  29174. if (oldOne != 0)
  29175. oldOne->releaseResources();
  29176. }
  29177. }
  29178. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29179. const int numInputChannels,
  29180. float** const outputChannelData,
  29181. const int numOutputChannels,
  29182. const int numSamples)
  29183. {
  29184. // these should have been prepared by audioDeviceAboutToStart()...
  29185. jassert (sampleRate > 0 && blockSize > 0);
  29186. incomingMidi.clear();
  29187. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29188. int i, totalNumChans = 0;
  29189. if (numInputChannels > numOutputChannels)
  29190. {
  29191. // if there aren't enough output channels for the number of
  29192. // inputs, we need to create some temporary extra ones (can't
  29193. // use the input data in case it gets written to)
  29194. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29195. false, false, true);
  29196. for (i = 0; i < numOutputChannels; ++i)
  29197. {
  29198. channels[totalNumChans] = outputChannelData[i];
  29199. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29200. ++totalNumChans;
  29201. }
  29202. for (i = numOutputChannels; i < numInputChannels; ++i)
  29203. {
  29204. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29205. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29206. ++totalNumChans;
  29207. }
  29208. }
  29209. else
  29210. {
  29211. for (i = 0; i < numInputChannels; ++i)
  29212. {
  29213. channels[totalNumChans] = outputChannelData[i];
  29214. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29215. ++totalNumChans;
  29216. }
  29217. for (i = numInputChannels; i < numOutputChannels; ++i)
  29218. {
  29219. channels[totalNumChans] = outputChannelData[i];
  29220. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29221. ++totalNumChans;
  29222. }
  29223. }
  29224. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29225. const ScopedLock sl (lock);
  29226. if (processor != 0)
  29227. {
  29228. const ScopedLock sl (processor->getCallbackLock());
  29229. if (processor->isSuspended())
  29230. {
  29231. for (i = 0; i < numOutputChannels; ++i)
  29232. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29233. }
  29234. else
  29235. {
  29236. processor->processBlock (buffer, incomingMidi);
  29237. }
  29238. }
  29239. }
  29240. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29241. {
  29242. const ScopedLock sl (lock);
  29243. sampleRate = device->getCurrentSampleRate();
  29244. blockSize = device->getCurrentBufferSizeSamples();
  29245. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29246. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29247. messageCollector.reset (sampleRate);
  29248. zeromem (channels, sizeof (channels));
  29249. if (processor != 0)
  29250. {
  29251. if (isPrepared)
  29252. processor->releaseResources();
  29253. AudioProcessor* const oldProcessor = processor;
  29254. setProcessor (0);
  29255. setProcessor (oldProcessor);
  29256. }
  29257. }
  29258. void AudioProcessorPlayer::audioDeviceStopped()
  29259. {
  29260. const ScopedLock sl (lock);
  29261. if (processor != 0 && isPrepared)
  29262. processor->releaseResources();
  29263. sampleRate = 0.0;
  29264. blockSize = 0;
  29265. isPrepared = false;
  29266. tempBuffer.setSize (1, 1);
  29267. }
  29268. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29269. {
  29270. messageCollector.addMessageToQueue (message);
  29271. }
  29272. END_JUCE_NAMESPACE
  29273. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29274. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29275. BEGIN_JUCE_NAMESPACE
  29276. class ProcessorParameterPropertyComp : public PropertyComponent,
  29277. public AudioProcessorListener,
  29278. public AsyncUpdater
  29279. {
  29280. public:
  29281. ProcessorParameterPropertyComp (const String& name,
  29282. AudioProcessor* const owner_,
  29283. const int index_)
  29284. : PropertyComponent (name),
  29285. owner (owner_),
  29286. index (index_)
  29287. {
  29288. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29289. owner_->addListener (this);
  29290. }
  29291. ~ProcessorParameterPropertyComp()
  29292. {
  29293. owner->removeListener (this);
  29294. deleteAllChildren();
  29295. }
  29296. void refresh()
  29297. {
  29298. slider->setValue (owner->getParameter (index), false);
  29299. }
  29300. void audioProcessorChanged (AudioProcessor*) {}
  29301. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29302. {
  29303. if (parameterIndex == index)
  29304. triggerAsyncUpdate();
  29305. }
  29306. void handleAsyncUpdate()
  29307. {
  29308. refresh();
  29309. }
  29310. juce_UseDebuggingNewOperator
  29311. private:
  29312. AudioProcessor* const owner;
  29313. const int index;
  29314. Slider* slider;
  29315. class ParamSlider : public Slider
  29316. {
  29317. public:
  29318. ParamSlider (AudioProcessor* const owner_, const int index_)
  29319. : Slider (String::empty),
  29320. owner (owner_),
  29321. index (index_)
  29322. {
  29323. setRange (0.0, 1.0, 0.0);
  29324. setSliderStyle (Slider::LinearBar);
  29325. setTextBoxIsEditable (false);
  29326. setScrollWheelEnabled (false);
  29327. }
  29328. ~ParamSlider()
  29329. {
  29330. }
  29331. void valueChanged()
  29332. {
  29333. const float newVal = (float) getValue();
  29334. if (owner->getParameter (index) != newVal)
  29335. owner->setParameter (index, newVal);
  29336. }
  29337. const String getTextFromValue (double /*value*/)
  29338. {
  29339. return owner->getParameterText (index);
  29340. }
  29341. juce_UseDebuggingNewOperator
  29342. private:
  29343. AudioProcessor* const owner;
  29344. const int index;
  29345. ParamSlider (const ParamSlider&);
  29346. ParamSlider& operator= (const ParamSlider&);
  29347. };
  29348. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29349. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29350. };
  29351. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29352. : AudioProcessorEditor (owner_)
  29353. {
  29354. setOpaque (true);
  29355. addAndMakeVisible (panel = new PropertyPanel());
  29356. Array <PropertyComponent*> params;
  29357. const int numParams = owner_->getNumParameters();
  29358. int totalHeight = 0;
  29359. for (int i = 0; i < numParams; ++i)
  29360. {
  29361. String name (owner_->getParameterName (i));
  29362. if (name.trim().isEmpty())
  29363. name = "Unnamed";
  29364. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29365. params.add (pc);
  29366. totalHeight += pc->getPreferredHeight();
  29367. }
  29368. panel->addProperties (params);
  29369. setSize (400, jlimit (25, 400, totalHeight));
  29370. }
  29371. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29372. {
  29373. deleteAllChildren();
  29374. }
  29375. void GenericAudioProcessorEditor::paint (Graphics& g)
  29376. {
  29377. g.fillAll (Colours::white);
  29378. }
  29379. void GenericAudioProcessorEditor::resized()
  29380. {
  29381. panel->setSize (getWidth(), getHeight());
  29382. }
  29383. END_JUCE_NAMESPACE
  29384. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29385. /*** Start of inlined file: juce_Sampler.cpp ***/
  29386. BEGIN_JUCE_NAMESPACE
  29387. SamplerSound::SamplerSound (const String& name_,
  29388. AudioFormatReader& source,
  29389. const BigInteger& midiNotes_,
  29390. const int midiNoteForNormalPitch,
  29391. const double attackTimeSecs,
  29392. const double releaseTimeSecs,
  29393. const double maxSampleLengthSeconds)
  29394. : name (name_),
  29395. midiNotes (midiNotes_),
  29396. midiRootNote (midiNoteForNormalPitch)
  29397. {
  29398. sourceSampleRate = source.sampleRate;
  29399. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29400. {
  29401. length = 0;
  29402. attackSamples = 0;
  29403. releaseSamples = 0;
  29404. }
  29405. else
  29406. {
  29407. length = jmin ((int) source.lengthInSamples,
  29408. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29409. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29410. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29411. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29412. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29413. }
  29414. }
  29415. SamplerSound::~SamplerSound()
  29416. {
  29417. }
  29418. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29419. {
  29420. return midiNotes [midiNoteNumber];
  29421. }
  29422. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29423. {
  29424. return true;
  29425. }
  29426. SamplerVoice::SamplerVoice()
  29427. : pitchRatio (0.0),
  29428. sourceSamplePosition (0.0),
  29429. lgain (0.0f),
  29430. rgain (0.0f),
  29431. isInAttack (false),
  29432. isInRelease (false)
  29433. {
  29434. }
  29435. SamplerVoice::~SamplerVoice()
  29436. {
  29437. }
  29438. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29439. {
  29440. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29441. }
  29442. void SamplerVoice::startNote (const int midiNoteNumber,
  29443. const float velocity,
  29444. SynthesiserSound* s,
  29445. const int /*currentPitchWheelPosition*/)
  29446. {
  29447. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29448. jassert (sound != 0); // this object can only play SamplerSounds!
  29449. if (sound != 0)
  29450. {
  29451. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29452. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29453. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29454. sourceSamplePosition = 0.0;
  29455. lgain = velocity;
  29456. rgain = velocity;
  29457. isInAttack = (sound->attackSamples > 0);
  29458. isInRelease = false;
  29459. if (isInAttack)
  29460. {
  29461. attackReleaseLevel = 0.0f;
  29462. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29463. }
  29464. else
  29465. {
  29466. attackReleaseLevel = 1.0f;
  29467. attackDelta = 0.0f;
  29468. }
  29469. if (sound->releaseSamples > 0)
  29470. {
  29471. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29472. }
  29473. else
  29474. {
  29475. releaseDelta = 0.0f;
  29476. }
  29477. }
  29478. }
  29479. void SamplerVoice::stopNote (const bool allowTailOff)
  29480. {
  29481. if (allowTailOff)
  29482. {
  29483. isInAttack = false;
  29484. isInRelease = true;
  29485. }
  29486. else
  29487. {
  29488. clearCurrentNote();
  29489. }
  29490. }
  29491. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29492. {
  29493. }
  29494. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29495. const int /*newValue*/)
  29496. {
  29497. }
  29498. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29499. {
  29500. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29501. if (playingSound != 0)
  29502. {
  29503. const float* const inL = playingSound->data->getSampleData (0, 0);
  29504. const float* const inR = playingSound->data->getNumChannels() > 1
  29505. ? playingSound->data->getSampleData (1, 0) : 0;
  29506. float* outL = outputBuffer.getSampleData (0, startSample);
  29507. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29508. while (--numSamples >= 0)
  29509. {
  29510. const int pos = (int) sourceSamplePosition;
  29511. const float alpha = (float) (sourceSamplePosition - pos);
  29512. const float invAlpha = 1.0f - alpha;
  29513. // just using a very simple linear interpolation here..
  29514. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29515. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29516. : l;
  29517. l *= lgain;
  29518. r *= rgain;
  29519. if (isInAttack)
  29520. {
  29521. l *= attackReleaseLevel;
  29522. r *= attackReleaseLevel;
  29523. attackReleaseLevel += attackDelta;
  29524. if (attackReleaseLevel >= 1.0f)
  29525. {
  29526. attackReleaseLevel = 1.0f;
  29527. isInAttack = false;
  29528. }
  29529. }
  29530. else if (isInRelease)
  29531. {
  29532. l *= attackReleaseLevel;
  29533. r *= attackReleaseLevel;
  29534. attackReleaseLevel += releaseDelta;
  29535. if (attackReleaseLevel <= 0.0f)
  29536. {
  29537. stopNote (false);
  29538. break;
  29539. }
  29540. }
  29541. if (outR != 0)
  29542. {
  29543. *outL++ += l;
  29544. *outR++ += r;
  29545. }
  29546. else
  29547. {
  29548. *outL++ += (l + r) * 0.5f;
  29549. }
  29550. sourceSamplePosition += pitchRatio;
  29551. if (sourceSamplePosition > playingSound->length)
  29552. {
  29553. stopNote (false);
  29554. break;
  29555. }
  29556. }
  29557. }
  29558. }
  29559. END_JUCE_NAMESPACE
  29560. /*** End of inlined file: juce_Sampler.cpp ***/
  29561. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29562. BEGIN_JUCE_NAMESPACE
  29563. SynthesiserSound::SynthesiserSound()
  29564. {
  29565. }
  29566. SynthesiserSound::~SynthesiserSound()
  29567. {
  29568. }
  29569. SynthesiserVoice::SynthesiserVoice()
  29570. : currentSampleRate (44100.0),
  29571. currentlyPlayingNote (-1),
  29572. noteOnTime (0),
  29573. currentlyPlayingSound (0)
  29574. {
  29575. }
  29576. SynthesiserVoice::~SynthesiserVoice()
  29577. {
  29578. }
  29579. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29580. {
  29581. return currentlyPlayingSound != 0
  29582. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29583. }
  29584. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29585. {
  29586. currentSampleRate = newRate;
  29587. }
  29588. void SynthesiserVoice::clearCurrentNote()
  29589. {
  29590. currentlyPlayingNote = -1;
  29591. currentlyPlayingSound = 0;
  29592. }
  29593. Synthesiser::Synthesiser()
  29594. : sampleRate (0),
  29595. lastNoteOnCounter (0),
  29596. shouldStealNotes (true)
  29597. {
  29598. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29599. lastPitchWheelValues[i] = 0x2000;
  29600. }
  29601. Synthesiser::~Synthesiser()
  29602. {
  29603. }
  29604. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29605. {
  29606. const ScopedLock sl (lock);
  29607. return voices [index];
  29608. }
  29609. void Synthesiser::clearVoices()
  29610. {
  29611. const ScopedLock sl (lock);
  29612. voices.clear();
  29613. }
  29614. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29615. {
  29616. const ScopedLock sl (lock);
  29617. voices.add (newVoice);
  29618. }
  29619. void Synthesiser::removeVoice (const int index)
  29620. {
  29621. const ScopedLock sl (lock);
  29622. voices.remove (index);
  29623. }
  29624. void Synthesiser::clearSounds()
  29625. {
  29626. const ScopedLock sl (lock);
  29627. sounds.clear();
  29628. }
  29629. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29630. {
  29631. const ScopedLock sl (lock);
  29632. sounds.add (newSound);
  29633. }
  29634. void Synthesiser::removeSound (const int index)
  29635. {
  29636. const ScopedLock sl (lock);
  29637. sounds.remove (index);
  29638. }
  29639. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29640. {
  29641. shouldStealNotes = shouldStealNotes_;
  29642. }
  29643. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29644. {
  29645. if (sampleRate != newRate)
  29646. {
  29647. const ScopedLock sl (lock);
  29648. allNotesOff (0, false);
  29649. sampleRate = newRate;
  29650. for (int i = voices.size(); --i >= 0;)
  29651. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29652. }
  29653. }
  29654. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29655. const MidiBuffer& midiData,
  29656. int startSample,
  29657. int numSamples)
  29658. {
  29659. // must set the sample rate before using this!
  29660. jassert (sampleRate != 0);
  29661. const ScopedLock sl (lock);
  29662. MidiBuffer::Iterator midiIterator (midiData);
  29663. midiIterator.setNextSamplePosition (startSample);
  29664. MidiMessage m (0xf4, 0.0);
  29665. while (numSamples > 0)
  29666. {
  29667. int midiEventPos;
  29668. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29669. && midiEventPos < startSample + numSamples;
  29670. const int numThisTime = useEvent ? midiEventPos - startSample
  29671. : numSamples;
  29672. if (numThisTime > 0)
  29673. {
  29674. for (int i = voices.size(); --i >= 0;)
  29675. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29676. }
  29677. if (useEvent)
  29678. {
  29679. if (m.isNoteOn())
  29680. {
  29681. const int channel = m.getChannel();
  29682. noteOn (channel,
  29683. m.getNoteNumber(),
  29684. m.getFloatVelocity());
  29685. }
  29686. else if (m.isNoteOff())
  29687. {
  29688. noteOff (m.getChannel(),
  29689. m.getNoteNumber(),
  29690. true);
  29691. }
  29692. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29693. {
  29694. allNotesOff (m.getChannel(), true);
  29695. }
  29696. else if (m.isPitchWheel())
  29697. {
  29698. const int channel = m.getChannel();
  29699. const int wheelPos = m.getPitchWheelValue();
  29700. lastPitchWheelValues [channel - 1] = wheelPos;
  29701. handlePitchWheel (channel, wheelPos);
  29702. }
  29703. else if (m.isController())
  29704. {
  29705. handleController (m.getChannel(),
  29706. m.getControllerNumber(),
  29707. m.getControllerValue());
  29708. }
  29709. }
  29710. startSample += numThisTime;
  29711. numSamples -= numThisTime;
  29712. }
  29713. }
  29714. void Synthesiser::noteOn (const int midiChannel,
  29715. const int midiNoteNumber,
  29716. const float velocity)
  29717. {
  29718. const ScopedLock sl (lock);
  29719. for (int i = sounds.size(); --i >= 0;)
  29720. {
  29721. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29722. if (sound->appliesToNote (midiNoteNumber)
  29723. && sound->appliesToChannel (midiChannel))
  29724. {
  29725. startVoice (findFreeVoice (sound, shouldStealNotes),
  29726. sound, midiChannel, midiNoteNumber, velocity);
  29727. }
  29728. }
  29729. }
  29730. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29731. SynthesiserSound* const sound,
  29732. const int midiChannel,
  29733. const int midiNoteNumber,
  29734. const float velocity)
  29735. {
  29736. if (voice != 0 && sound != 0)
  29737. {
  29738. if (voice->currentlyPlayingSound != 0)
  29739. voice->stopNote (false);
  29740. voice->startNote (midiNoteNumber,
  29741. velocity,
  29742. sound,
  29743. lastPitchWheelValues [midiChannel - 1]);
  29744. voice->currentlyPlayingNote = midiNoteNumber;
  29745. voice->noteOnTime = ++lastNoteOnCounter;
  29746. voice->currentlyPlayingSound = sound;
  29747. }
  29748. }
  29749. void Synthesiser::noteOff (const int midiChannel,
  29750. const int midiNoteNumber,
  29751. const bool allowTailOff)
  29752. {
  29753. const ScopedLock sl (lock);
  29754. for (int i = voices.size(); --i >= 0;)
  29755. {
  29756. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29757. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29758. {
  29759. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29760. if (sound != 0
  29761. && sound->appliesToNote (midiNoteNumber)
  29762. && sound->appliesToChannel (midiChannel))
  29763. {
  29764. voice->stopNote (allowTailOff);
  29765. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29766. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29767. }
  29768. }
  29769. }
  29770. }
  29771. void Synthesiser::allNotesOff (const int midiChannel,
  29772. const bool allowTailOff)
  29773. {
  29774. const ScopedLock sl (lock);
  29775. for (int i = voices.size(); --i >= 0;)
  29776. {
  29777. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29778. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29779. voice->stopNote (allowTailOff);
  29780. }
  29781. }
  29782. void Synthesiser::handlePitchWheel (const int midiChannel,
  29783. const int wheelValue)
  29784. {
  29785. const ScopedLock sl (lock);
  29786. for (int i = voices.size(); --i >= 0;)
  29787. {
  29788. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29789. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29790. {
  29791. voice->pitchWheelMoved (wheelValue);
  29792. }
  29793. }
  29794. }
  29795. void Synthesiser::handleController (const int midiChannel,
  29796. const int controllerNumber,
  29797. const int controllerValue)
  29798. {
  29799. const ScopedLock sl (lock);
  29800. for (int i = voices.size(); --i >= 0;)
  29801. {
  29802. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29803. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29804. voice->controllerMoved (controllerNumber, controllerValue);
  29805. }
  29806. }
  29807. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29808. const bool stealIfNoneAvailable) const
  29809. {
  29810. const ScopedLock sl (lock);
  29811. for (int i = voices.size(); --i >= 0;)
  29812. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29813. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29814. return voices.getUnchecked (i);
  29815. if (stealIfNoneAvailable)
  29816. {
  29817. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29818. SynthesiserVoice* oldest = 0;
  29819. for (int i = voices.size(); --i >= 0;)
  29820. {
  29821. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29822. if (voice->canPlaySound (soundToPlay)
  29823. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29824. oldest = voice;
  29825. }
  29826. jassert (oldest != 0);
  29827. return oldest;
  29828. }
  29829. return 0;
  29830. }
  29831. END_JUCE_NAMESPACE
  29832. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29833. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29834. BEGIN_JUCE_NAMESPACE
  29835. ActionBroadcaster::ActionBroadcaster() throw()
  29836. {
  29837. // are you trying to create this object before or after juce has been intialised??
  29838. jassert (MessageManager::instance != 0);
  29839. }
  29840. ActionBroadcaster::~ActionBroadcaster()
  29841. {
  29842. // all event-based objects must be deleted BEFORE juce is shut down!
  29843. jassert (MessageManager::instance != 0);
  29844. }
  29845. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29846. {
  29847. actionListenerList.addActionListener (listener);
  29848. }
  29849. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29850. {
  29851. jassert (actionListenerList.isValidMessageListener());
  29852. if (actionListenerList.isValidMessageListener())
  29853. actionListenerList.removeActionListener (listener);
  29854. }
  29855. void ActionBroadcaster::removeAllActionListeners()
  29856. {
  29857. actionListenerList.removeAllActionListeners();
  29858. }
  29859. void ActionBroadcaster::sendActionMessage (const String& message) const
  29860. {
  29861. actionListenerList.sendActionMessage (message);
  29862. }
  29863. END_JUCE_NAMESPACE
  29864. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29865. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29866. BEGIN_JUCE_NAMESPACE
  29867. // special message of our own with a string in it
  29868. class ActionMessage : public Message
  29869. {
  29870. public:
  29871. const String message;
  29872. ActionMessage (const String& messageText,
  29873. void* const listener_) throw()
  29874. : message (messageText)
  29875. {
  29876. pointerParameter = listener_;
  29877. }
  29878. ~ActionMessage() throw()
  29879. {
  29880. }
  29881. private:
  29882. ActionMessage (const ActionMessage&);
  29883. ActionMessage& operator= (const ActionMessage&);
  29884. };
  29885. ActionListenerList::ActionListenerList() throw()
  29886. {
  29887. }
  29888. ActionListenerList::~ActionListenerList() throw()
  29889. {
  29890. }
  29891. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29892. {
  29893. const ScopedLock sl (actionListenerLock_);
  29894. jassert (listener != 0);
  29895. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29896. if (listener != 0)
  29897. actionListeners_.add (listener);
  29898. }
  29899. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29900. {
  29901. const ScopedLock sl (actionListenerLock_);
  29902. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29903. actionListeners_.removeValue (listener);
  29904. }
  29905. void ActionListenerList::removeAllActionListeners() throw()
  29906. {
  29907. const ScopedLock sl (actionListenerLock_);
  29908. actionListeners_.clear();
  29909. }
  29910. void ActionListenerList::sendActionMessage (const String& message) const
  29911. {
  29912. const ScopedLock sl (actionListenerLock_);
  29913. for (int i = actionListeners_.size(); --i >= 0;)
  29914. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29915. }
  29916. void ActionListenerList::handleMessage (const Message& message)
  29917. {
  29918. const ActionMessage& am = (const ActionMessage&) message;
  29919. if (actionListeners_.contains (am.pointerParameter))
  29920. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29921. }
  29922. END_JUCE_NAMESPACE
  29923. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29924. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29925. BEGIN_JUCE_NAMESPACE
  29926. AsyncUpdater::AsyncUpdater() throw()
  29927. : asyncMessagePending (false)
  29928. {
  29929. internalAsyncHandler.owner = this;
  29930. }
  29931. AsyncUpdater::~AsyncUpdater()
  29932. {
  29933. }
  29934. void AsyncUpdater::triggerAsyncUpdate() throw()
  29935. {
  29936. if (! asyncMessagePending)
  29937. {
  29938. asyncMessagePending = true;
  29939. internalAsyncHandler.postMessage (new Message());
  29940. }
  29941. }
  29942. void AsyncUpdater::cancelPendingUpdate() throw()
  29943. {
  29944. asyncMessagePending = false;
  29945. }
  29946. void AsyncUpdater::handleUpdateNowIfNeeded()
  29947. {
  29948. if (asyncMessagePending)
  29949. {
  29950. asyncMessagePending = false;
  29951. handleAsyncUpdate();
  29952. }
  29953. }
  29954. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29955. {
  29956. owner->handleUpdateNowIfNeeded();
  29957. }
  29958. END_JUCE_NAMESPACE
  29959. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29960. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29961. BEGIN_JUCE_NAMESPACE
  29962. ChangeBroadcaster::ChangeBroadcaster() throw()
  29963. {
  29964. // are you trying to create this object before or after juce has been intialised??
  29965. jassert (MessageManager::instance != 0);
  29966. }
  29967. ChangeBroadcaster::~ChangeBroadcaster()
  29968. {
  29969. // all event-based objects must be deleted BEFORE juce is shut down!
  29970. jassert (MessageManager::instance != 0);
  29971. }
  29972. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29973. {
  29974. changeListenerList.addChangeListener (listener);
  29975. }
  29976. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29977. {
  29978. jassert (changeListenerList.isValidMessageListener());
  29979. if (changeListenerList.isValidMessageListener())
  29980. changeListenerList.removeChangeListener (listener);
  29981. }
  29982. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29983. {
  29984. changeListenerList.removeAllChangeListeners();
  29985. }
  29986. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29987. {
  29988. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29989. }
  29990. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29991. {
  29992. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29993. }
  29994. void ChangeBroadcaster::dispatchPendingMessages()
  29995. {
  29996. changeListenerList.dispatchPendingMessages();
  29997. }
  29998. END_JUCE_NAMESPACE
  29999. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30000. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30001. BEGIN_JUCE_NAMESPACE
  30002. ChangeListenerList::ChangeListenerList() throw()
  30003. : lastChangedObject (0),
  30004. messagePending (false)
  30005. {
  30006. }
  30007. ChangeListenerList::~ChangeListenerList() throw()
  30008. {
  30009. }
  30010. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  30011. {
  30012. const ScopedLock sl (lock);
  30013. jassert (listener != 0);
  30014. if (listener != 0)
  30015. listeners.add (listener);
  30016. }
  30017. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30018. {
  30019. const ScopedLock sl (lock);
  30020. listeners.removeValue (listener);
  30021. }
  30022. void ChangeListenerList::removeAllChangeListeners() throw()
  30023. {
  30024. const ScopedLock sl (lock);
  30025. listeners.clear();
  30026. }
  30027. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30028. {
  30029. const ScopedLock sl (lock);
  30030. if ((! messagePending) && (listeners.size() > 0))
  30031. {
  30032. lastChangedObject = objectThatHasChanged;
  30033. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30034. messagePending = true;
  30035. }
  30036. }
  30037. void ChangeListenerList::handleMessage (const Message& message)
  30038. {
  30039. sendSynchronousChangeMessage (message.pointerParameter);
  30040. }
  30041. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30042. {
  30043. const ScopedLock sl (lock);
  30044. messagePending = false;
  30045. for (int i = listeners.size(); --i >= 0;)
  30046. {
  30047. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30048. {
  30049. const ScopedUnlock tempUnlocker (lock);
  30050. l->changeListenerCallback (objectThatHasChanged);
  30051. }
  30052. i = jmin (i, listeners.size());
  30053. }
  30054. }
  30055. void ChangeListenerList::dispatchPendingMessages()
  30056. {
  30057. if (messagePending)
  30058. sendSynchronousChangeMessage (lastChangedObject);
  30059. }
  30060. END_JUCE_NAMESPACE
  30061. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30062. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30063. BEGIN_JUCE_NAMESPACE
  30064. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30065. const uint32 magicMessageHeaderNumber)
  30066. : Thread ("Juce IPC connection"),
  30067. callbackConnectionState (false),
  30068. useMessageThread (callbacksOnMessageThread),
  30069. magicMessageHeader (magicMessageHeaderNumber),
  30070. pipeReceiveMessageTimeout (-1)
  30071. {
  30072. }
  30073. InterprocessConnection::~InterprocessConnection()
  30074. {
  30075. callbackConnectionState = false;
  30076. disconnect();
  30077. }
  30078. bool InterprocessConnection::connectToSocket (const String& hostName,
  30079. const int portNumber,
  30080. const int timeOutMillisecs)
  30081. {
  30082. disconnect();
  30083. const ScopedLock sl (pipeAndSocketLock);
  30084. socket = new StreamingSocket();
  30085. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30086. {
  30087. connectionMadeInt();
  30088. startThread();
  30089. return true;
  30090. }
  30091. else
  30092. {
  30093. socket = 0;
  30094. return false;
  30095. }
  30096. }
  30097. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30098. const int pipeReceiveMessageTimeoutMs)
  30099. {
  30100. disconnect();
  30101. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30102. if (newPipe->openExisting (pipeName))
  30103. {
  30104. const ScopedLock sl (pipeAndSocketLock);
  30105. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30106. initialiseWithPipe (newPipe.release());
  30107. return true;
  30108. }
  30109. return false;
  30110. }
  30111. bool InterprocessConnection::createPipe (const String& pipeName,
  30112. const int pipeReceiveMessageTimeoutMs)
  30113. {
  30114. disconnect();
  30115. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30116. if (newPipe->createNewPipe (pipeName))
  30117. {
  30118. const ScopedLock sl (pipeAndSocketLock);
  30119. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30120. initialiseWithPipe (newPipe.release());
  30121. return true;
  30122. }
  30123. return false;
  30124. }
  30125. void InterprocessConnection::disconnect()
  30126. {
  30127. if (socket != 0)
  30128. socket->close();
  30129. if (pipe != 0)
  30130. {
  30131. pipe->cancelPendingReads();
  30132. pipe->close();
  30133. }
  30134. stopThread (4000);
  30135. {
  30136. const ScopedLock sl (pipeAndSocketLock);
  30137. socket = 0;
  30138. pipe = 0;
  30139. }
  30140. connectionLostInt();
  30141. }
  30142. bool InterprocessConnection::isConnected() const
  30143. {
  30144. const ScopedLock sl (pipeAndSocketLock);
  30145. return ((socket != 0 && socket->isConnected())
  30146. || (pipe != 0 && pipe->isOpen()))
  30147. && isThreadRunning();
  30148. }
  30149. const String InterprocessConnection::getConnectedHostName() const
  30150. {
  30151. if (pipe != 0)
  30152. {
  30153. return "localhost";
  30154. }
  30155. else if (socket != 0)
  30156. {
  30157. if (! socket->isLocal())
  30158. return socket->getHostName();
  30159. return "localhost";
  30160. }
  30161. return String::empty;
  30162. }
  30163. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30164. {
  30165. uint32 messageHeader[2];
  30166. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30167. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30168. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30169. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30170. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30171. size_t bytesWritten = 0;
  30172. const ScopedLock sl (pipeAndSocketLock);
  30173. if (socket != 0)
  30174. {
  30175. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30176. }
  30177. else if (pipe != 0)
  30178. {
  30179. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30180. }
  30181. if (bytesWritten < 0)
  30182. {
  30183. // error..
  30184. return false;
  30185. }
  30186. return (bytesWritten == messageData.getSize());
  30187. }
  30188. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30189. {
  30190. jassert (socket == 0);
  30191. socket = socket_;
  30192. connectionMadeInt();
  30193. startThread();
  30194. }
  30195. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30196. {
  30197. jassert (pipe == 0);
  30198. pipe = pipe_;
  30199. connectionMadeInt();
  30200. startThread();
  30201. }
  30202. const int messageMagicNumber = 0xb734128b;
  30203. void InterprocessConnection::handleMessage (const Message& message)
  30204. {
  30205. if (message.intParameter1 == messageMagicNumber)
  30206. {
  30207. switch (message.intParameter2)
  30208. {
  30209. case 0:
  30210. {
  30211. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30212. messageReceived (*data);
  30213. break;
  30214. }
  30215. case 1:
  30216. connectionMade();
  30217. break;
  30218. case 2:
  30219. connectionLost();
  30220. break;
  30221. }
  30222. }
  30223. }
  30224. void InterprocessConnection::connectionMadeInt()
  30225. {
  30226. if (! callbackConnectionState)
  30227. {
  30228. callbackConnectionState = true;
  30229. if (useMessageThread)
  30230. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30231. else
  30232. connectionMade();
  30233. }
  30234. }
  30235. void InterprocessConnection::connectionLostInt()
  30236. {
  30237. if (callbackConnectionState)
  30238. {
  30239. callbackConnectionState = false;
  30240. if (useMessageThread)
  30241. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30242. else
  30243. connectionLost();
  30244. }
  30245. }
  30246. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30247. {
  30248. jassert (callbackConnectionState);
  30249. if (useMessageThread)
  30250. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30251. else
  30252. messageReceived (data);
  30253. }
  30254. bool InterprocessConnection::readNextMessageInt()
  30255. {
  30256. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30257. uint32 messageHeader[2];
  30258. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30259. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30260. if (bytes == sizeof (messageHeader)
  30261. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30262. {
  30263. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30264. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30265. {
  30266. MemoryBlock messageData (bytesInMessage, true);
  30267. int bytesRead = 0;
  30268. while (bytesInMessage > 0)
  30269. {
  30270. if (threadShouldExit())
  30271. return false;
  30272. const int numThisTime = jmin (bytesInMessage, 65536);
  30273. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30274. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30275. if (bytesIn <= 0)
  30276. break;
  30277. bytesRead += bytesIn;
  30278. bytesInMessage -= bytesIn;
  30279. }
  30280. if (bytesRead >= 0)
  30281. deliverDataInt (messageData);
  30282. }
  30283. }
  30284. else if (bytes < 0)
  30285. {
  30286. {
  30287. const ScopedLock sl (pipeAndSocketLock);
  30288. socket = 0;
  30289. }
  30290. connectionLostInt();
  30291. return false;
  30292. }
  30293. return true;
  30294. }
  30295. void InterprocessConnection::run()
  30296. {
  30297. while (! threadShouldExit())
  30298. {
  30299. if (socket != 0)
  30300. {
  30301. const int ready = socket->waitUntilReady (true, 0);
  30302. if (ready < 0)
  30303. {
  30304. {
  30305. const ScopedLock sl (pipeAndSocketLock);
  30306. socket = 0;
  30307. }
  30308. connectionLostInt();
  30309. break;
  30310. }
  30311. else if (ready > 0)
  30312. {
  30313. if (! readNextMessageInt())
  30314. break;
  30315. }
  30316. else
  30317. {
  30318. Thread::sleep (2);
  30319. }
  30320. }
  30321. else if (pipe != 0)
  30322. {
  30323. if (! pipe->isOpen())
  30324. {
  30325. {
  30326. const ScopedLock sl (pipeAndSocketLock);
  30327. pipe = 0;
  30328. }
  30329. connectionLostInt();
  30330. break;
  30331. }
  30332. else
  30333. {
  30334. if (! readNextMessageInt())
  30335. break;
  30336. }
  30337. }
  30338. else
  30339. {
  30340. break;
  30341. }
  30342. }
  30343. }
  30344. END_JUCE_NAMESPACE
  30345. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30346. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30347. BEGIN_JUCE_NAMESPACE
  30348. InterprocessConnectionServer::InterprocessConnectionServer()
  30349. : Thread ("Juce IPC server")
  30350. {
  30351. }
  30352. InterprocessConnectionServer::~InterprocessConnectionServer()
  30353. {
  30354. stop();
  30355. }
  30356. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30357. {
  30358. stop();
  30359. socket = new StreamingSocket();
  30360. if (socket->createListener (portNumber))
  30361. {
  30362. startThread();
  30363. return true;
  30364. }
  30365. socket = 0;
  30366. return false;
  30367. }
  30368. void InterprocessConnectionServer::stop()
  30369. {
  30370. signalThreadShouldExit();
  30371. if (socket != 0)
  30372. socket->close();
  30373. stopThread (4000);
  30374. socket = 0;
  30375. }
  30376. void InterprocessConnectionServer::run()
  30377. {
  30378. while ((! threadShouldExit()) && socket != 0)
  30379. {
  30380. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30381. if (clientSocket != 0)
  30382. {
  30383. InterprocessConnection* newConnection = createConnectionObject();
  30384. if (newConnection != 0)
  30385. newConnection->initialiseWithSocket (clientSocket.release());
  30386. }
  30387. }
  30388. }
  30389. END_JUCE_NAMESPACE
  30390. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30391. /*** Start of inlined file: juce_Message.cpp ***/
  30392. BEGIN_JUCE_NAMESPACE
  30393. Message::Message() throw()
  30394. : intParameter1 (0),
  30395. intParameter2 (0),
  30396. intParameter3 (0),
  30397. pointerParameter (0)
  30398. {
  30399. }
  30400. Message::Message (const int intParameter1_,
  30401. const int intParameter2_,
  30402. const int intParameter3_,
  30403. void* const pointerParameter_) throw()
  30404. : intParameter1 (intParameter1_),
  30405. intParameter2 (intParameter2_),
  30406. intParameter3 (intParameter3_),
  30407. pointerParameter (pointerParameter_)
  30408. {
  30409. }
  30410. Message::~Message() throw()
  30411. {
  30412. }
  30413. END_JUCE_NAMESPACE
  30414. /*** End of inlined file: juce_Message.cpp ***/
  30415. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30416. BEGIN_JUCE_NAMESPACE
  30417. MessageListener::MessageListener() throw()
  30418. {
  30419. // are you trying to create a messagelistener before or after juce has been intialised??
  30420. jassert (MessageManager::instance != 0);
  30421. if (MessageManager::instance != 0)
  30422. MessageManager::instance->messageListeners.add (this);
  30423. }
  30424. MessageListener::~MessageListener()
  30425. {
  30426. if (MessageManager::instance != 0)
  30427. MessageManager::instance->messageListeners.removeValue (this);
  30428. }
  30429. void MessageListener::postMessage (Message* const message) const throw()
  30430. {
  30431. message->messageRecipient = const_cast <MessageListener*> (this);
  30432. if (MessageManager::instance == 0)
  30433. MessageManager::getInstance();
  30434. MessageManager::instance->postMessageToQueue (message);
  30435. }
  30436. bool MessageListener::isValidMessageListener() const throw()
  30437. {
  30438. return (MessageManager::instance != 0)
  30439. && MessageManager::instance->messageListeners.contains (this);
  30440. }
  30441. END_JUCE_NAMESPACE
  30442. /*** End of inlined file: juce_MessageListener.cpp ***/
  30443. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30444. BEGIN_JUCE_NAMESPACE
  30445. // platform-specific functions..
  30446. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30447. bool juce_postMessageToSystemQueue (Message* message);
  30448. MessageManager* MessageManager::instance = 0;
  30449. static const int quitMessageId = 0xfffff321;
  30450. MessageManager::MessageManager() throw()
  30451. : quitMessagePosted (false),
  30452. quitMessageReceived (false),
  30453. threadWithLock (0)
  30454. {
  30455. messageThreadId = Thread::getCurrentThreadId();
  30456. }
  30457. MessageManager::~MessageManager() throw()
  30458. {
  30459. broadcastListeners = 0;
  30460. doPlatformSpecificShutdown();
  30461. jassert (instance == this);
  30462. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30463. }
  30464. MessageManager* MessageManager::getInstance() throw()
  30465. {
  30466. if (instance == 0)
  30467. {
  30468. instance = new MessageManager();
  30469. doPlatformSpecificInitialisation();
  30470. }
  30471. return instance;
  30472. }
  30473. void MessageManager::postMessageToQueue (Message* const message)
  30474. {
  30475. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30476. delete message;
  30477. }
  30478. CallbackMessage::CallbackMessage() throw() {}
  30479. CallbackMessage::~CallbackMessage() throw() {}
  30480. void CallbackMessage::post()
  30481. {
  30482. if (MessageManager::instance != 0)
  30483. MessageManager::instance->postCallbackMessage (this);
  30484. }
  30485. void MessageManager::postCallbackMessage (Message* const message)
  30486. {
  30487. message->messageRecipient = 0;
  30488. postMessageToQueue (message);
  30489. }
  30490. // not for public use..
  30491. void MessageManager::deliverMessage (Message* const message)
  30492. {
  30493. const ScopedPointer <Message> messageDeleter (message);
  30494. MessageListener* const recipient = message->messageRecipient;
  30495. JUCE_TRY
  30496. {
  30497. if (messageListeners.contains (recipient))
  30498. {
  30499. recipient->handleMessage (*message);
  30500. }
  30501. else if (recipient == 0)
  30502. {
  30503. if (message->intParameter1 == quitMessageId)
  30504. {
  30505. quitMessageReceived = true;
  30506. }
  30507. else
  30508. {
  30509. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  30510. if (cm != 0)
  30511. cm->messageCallback();
  30512. }
  30513. }
  30514. }
  30515. JUCE_CATCH_EXCEPTION
  30516. }
  30517. #if ! (JUCE_MAC || JUCE_IPHONE)
  30518. void MessageManager::runDispatchLoop()
  30519. {
  30520. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30521. runDispatchLoopUntil (-1);
  30522. }
  30523. void MessageManager::stopDispatchLoop()
  30524. {
  30525. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30526. m->messageRecipient = 0;
  30527. postMessageToQueue (m);
  30528. quitMessagePosted = true;
  30529. }
  30530. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30531. {
  30532. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30533. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30534. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30535. && ! quitMessageReceived)
  30536. {
  30537. JUCE_TRY
  30538. {
  30539. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30540. {
  30541. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30542. if (msToWait > 0)
  30543. Thread::sleep (jmin (5, msToWait));
  30544. }
  30545. }
  30546. JUCE_CATCH_EXCEPTION
  30547. }
  30548. return ! quitMessageReceived;
  30549. }
  30550. #endif
  30551. void MessageManager::deliverBroadcastMessage (const String& value)
  30552. {
  30553. if (broadcastListeners != 0)
  30554. broadcastListeners->sendActionMessage (value);
  30555. }
  30556. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30557. {
  30558. if (broadcastListeners == 0)
  30559. broadcastListeners = new ActionListenerList();
  30560. broadcastListeners->addActionListener (listener);
  30561. }
  30562. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30563. {
  30564. if (broadcastListeners != 0)
  30565. broadcastListeners->removeActionListener (listener);
  30566. }
  30567. bool MessageManager::isThisTheMessageThread() const throw()
  30568. {
  30569. return Thread::getCurrentThreadId() == messageThreadId;
  30570. }
  30571. void MessageManager::setCurrentThreadAsMessageThread()
  30572. {
  30573. if (messageThreadId != Thread::getCurrentThreadId())
  30574. {
  30575. messageThreadId = Thread::getCurrentThreadId();
  30576. // This is needed on windows to make sure the message window is created by this thread
  30577. doPlatformSpecificShutdown();
  30578. doPlatformSpecificInitialisation();
  30579. }
  30580. }
  30581. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30582. {
  30583. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30584. return thisThread == messageThreadId || thisThread == threadWithLock;
  30585. }
  30586. /* The only safe way to lock the message thread while another thread does
  30587. some work is by posting a special message, whose purpose is to tie up the event
  30588. loop until the other thread has finished its business.
  30589. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30590. get locked before making an event callback, because if the same OS lock gets indirectly
  30591. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30592. in Cocoa).
  30593. */
  30594. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30595. {
  30596. public:
  30597. SharedEvents() {}
  30598. ~SharedEvents() {}
  30599. /* This class just holds a couple of events to communicate between the BlockingMessage
  30600. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30601. this shared data must be kept in a separate, ref-counted container. */
  30602. WaitableEvent lockedEvent, releaseEvent;
  30603. private:
  30604. SharedEvents (const SharedEvents&);
  30605. SharedEvents& operator= (const SharedEvents&);
  30606. };
  30607. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30608. {
  30609. public:
  30610. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30611. ~BlockingMessage() throw() {}
  30612. void messageCallback()
  30613. {
  30614. events->lockedEvent.signal();
  30615. events->releaseEvent.wait();
  30616. }
  30617. juce_UseDebuggingNewOperator
  30618. private:
  30619. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30620. BlockingMessage (const BlockingMessage&);
  30621. BlockingMessage& operator= (const BlockingMessage&);
  30622. };
  30623. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30624. : sharedEvents (0),
  30625. locked (false)
  30626. {
  30627. init (threadToCheck, 0);
  30628. }
  30629. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30630. : sharedEvents (0),
  30631. locked (false)
  30632. {
  30633. init (0, jobToCheckForExitSignal);
  30634. }
  30635. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30636. {
  30637. if (MessageManager::instance != 0)
  30638. {
  30639. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30640. {
  30641. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30642. }
  30643. else
  30644. {
  30645. if (threadToCheck == 0 && job == 0)
  30646. {
  30647. MessageManager::instance->lockingLock.enter();
  30648. }
  30649. else
  30650. {
  30651. while (! MessageManager::instance->lockingLock.tryEnter())
  30652. {
  30653. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30654. || (job != 0 && job->shouldExit()))
  30655. return;
  30656. Thread::sleep (1);
  30657. }
  30658. }
  30659. sharedEvents = new SharedEvents();
  30660. sharedEvents->incReferenceCount();
  30661. (new BlockingMessage (sharedEvents))->post();
  30662. while (! sharedEvents->lockedEvent.wait (50))
  30663. {
  30664. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30665. || (job != 0 && job->shouldExit()))
  30666. {
  30667. sharedEvents->releaseEvent.signal();
  30668. sharedEvents->decReferenceCount();
  30669. sharedEvents = 0;
  30670. MessageManager::instance->lockingLock.exit();
  30671. return;
  30672. }
  30673. }
  30674. jassert (MessageManager::instance->threadWithLock == 0);
  30675. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30676. locked = true;
  30677. }
  30678. }
  30679. }
  30680. MessageManagerLock::~MessageManagerLock() throw()
  30681. {
  30682. if (sharedEvents != 0)
  30683. {
  30684. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30685. sharedEvents->releaseEvent.signal();
  30686. sharedEvents->decReferenceCount();
  30687. if (MessageManager::instance != 0)
  30688. {
  30689. MessageManager::instance->threadWithLock = 0;
  30690. MessageManager::instance->lockingLock.exit();
  30691. }
  30692. }
  30693. }
  30694. END_JUCE_NAMESPACE
  30695. /*** End of inlined file: juce_MessageManager.cpp ***/
  30696. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30697. BEGIN_JUCE_NAMESPACE
  30698. class MultiTimer::MultiTimerCallback : public Timer
  30699. {
  30700. public:
  30701. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30702. : timerId (timerId_),
  30703. owner (owner_)
  30704. {
  30705. }
  30706. ~MultiTimerCallback()
  30707. {
  30708. }
  30709. void timerCallback()
  30710. {
  30711. owner.timerCallback (timerId);
  30712. }
  30713. const int timerId;
  30714. private:
  30715. MultiTimer& owner;
  30716. };
  30717. MultiTimer::MultiTimer() throw()
  30718. {
  30719. }
  30720. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30721. {
  30722. }
  30723. MultiTimer::~MultiTimer()
  30724. {
  30725. const ScopedLock sl (timerListLock);
  30726. timers.clear();
  30727. }
  30728. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30729. {
  30730. const ScopedLock sl (timerListLock);
  30731. for (int i = timers.size(); --i >= 0;)
  30732. {
  30733. MultiTimerCallback* const t = timers.getUnchecked(i);
  30734. if (t->timerId == timerId)
  30735. {
  30736. t->startTimer (intervalInMilliseconds);
  30737. return;
  30738. }
  30739. }
  30740. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30741. timers.add (newTimer);
  30742. newTimer->startTimer (intervalInMilliseconds);
  30743. }
  30744. void MultiTimer::stopTimer (const int timerId) throw()
  30745. {
  30746. const ScopedLock sl (timerListLock);
  30747. for (int i = timers.size(); --i >= 0;)
  30748. {
  30749. MultiTimerCallback* const t = timers.getUnchecked(i);
  30750. if (t->timerId == timerId)
  30751. t->stopTimer();
  30752. }
  30753. }
  30754. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30755. {
  30756. const ScopedLock sl (timerListLock);
  30757. for (int i = timers.size(); --i >= 0;)
  30758. {
  30759. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30760. if (t->timerId == timerId)
  30761. return t->isTimerRunning();
  30762. }
  30763. return false;
  30764. }
  30765. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30766. {
  30767. const ScopedLock sl (timerListLock);
  30768. for (int i = timers.size(); --i >= 0;)
  30769. {
  30770. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30771. if (t->timerId == timerId)
  30772. return t->getTimerInterval();
  30773. }
  30774. return 0;
  30775. }
  30776. END_JUCE_NAMESPACE
  30777. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30778. /*** Start of inlined file: juce_Timer.cpp ***/
  30779. BEGIN_JUCE_NAMESPACE
  30780. class InternalTimerThread : private Thread,
  30781. private MessageListener,
  30782. private DeletedAtShutdown,
  30783. private AsyncUpdater
  30784. {
  30785. public:
  30786. InternalTimerThread()
  30787. : Thread ("Juce Timer"),
  30788. firstTimer (0),
  30789. callbackNeeded (0)
  30790. {
  30791. triggerAsyncUpdate();
  30792. }
  30793. ~InternalTimerThread() throw()
  30794. {
  30795. stopThread (4000);
  30796. jassert (instance == this || instance == 0);
  30797. if (instance == this)
  30798. instance = 0;
  30799. }
  30800. void run()
  30801. {
  30802. uint32 lastTime = Time::getMillisecondCounter();
  30803. while (! threadShouldExit())
  30804. {
  30805. const uint32 now = Time::getMillisecondCounter();
  30806. if (now <= lastTime)
  30807. {
  30808. wait (2);
  30809. continue;
  30810. }
  30811. const int elapsed = now - lastTime;
  30812. lastTime = now;
  30813. int timeUntilFirstTimer = 1000;
  30814. {
  30815. const ScopedLock sl (lock);
  30816. decrementAllCounters (elapsed);
  30817. if (firstTimer != 0)
  30818. timeUntilFirstTimer = firstTimer->countdownMs;
  30819. }
  30820. if (timeUntilFirstTimer <= 0)
  30821. {
  30822. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30823. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30824. but if it fails it means the message-thread changed the value from under us so at least
  30825. some processing is happenening and we can just loop around and try again
  30826. */
  30827. if (callbackNeeded.compareAndSetBool (1, 0))
  30828. {
  30829. postMessage (new Message());
  30830. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30831. when the app has a modal loop), so this is how long to wait before assuming the
  30832. message has been lost and trying again.
  30833. */
  30834. const uint32 messageDeliveryTimeout = now + 2000;
  30835. while (callbackNeeded.get() != 0)
  30836. {
  30837. wait (4);
  30838. if (threadShouldExit())
  30839. return;
  30840. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30841. break;
  30842. }
  30843. }
  30844. }
  30845. else
  30846. {
  30847. // don't wait for too long because running this loop also helps keep the
  30848. // Time::getApproximateMillisecondTimer value stay up-to-date
  30849. wait (jlimit (1, 50, timeUntilFirstTimer));
  30850. }
  30851. }
  30852. }
  30853. void callTimers()
  30854. {
  30855. const ScopedLock sl (lock);
  30856. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30857. {
  30858. Timer* const t = firstTimer;
  30859. t->countdownMs = t->periodMs;
  30860. removeTimer (t);
  30861. addTimer (t);
  30862. const ScopedUnlock ul (lock);
  30863. JUCE_TRY
  30864. {
  30865. t->timerCallback();
  30866. }
  30867. JUCE_CATCH_EXCEPTION
  30868. }
  30869. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30870. before the boolean is set. This set should never fail since if it was false in the first place,
  30871. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30872. get a message then the value is true and the other thread can only set it to true again and
  30873. we will get another callback to set it to false.
  30874. */
  30875. callbackNeeded.set (0);
  30876. }
  30877. void handleMessage (const Message&)
  30878. {
  30879. callTimers();
  30880. }
  30881. void callTimersSynchronously()
  30882. {
  30883. if (! isThreadRunning())
  30884. {
  30885. // (This is relied on by some plugins in cases where the MM has
  30886. // had to restart and the async callback never started)
  30887. cancelPendingUpdate();
  30888. triggerAsyncUpdate();
  30889. }
  30890. callTimers();
  30891. }
  30892. static void callAnyTimersSynchronously()
  30893. {
  30894. if (InternalTimerThread::instance != 0)
  30895. InternalTimerThread::instance->callTimersSynchronously();
  30896. }
  30897. static inline void add (Timer* const tim) throw()
  30898. {
  30899. if (instance == 0)
  30900. instance = new InternalTimerThread();
  30901. const ScopedLock sl (instance->lock);
  30902. instance->addTimer (tim);
  30903. }
  30904. static inline void remove (Timer* const tim) throw()
  30905. {
  30906. if (instance != 0)
  30907. {
  30908. const ScopedLock sl (instance->lock);
  30909. instance->removeTimer (tim);
  30910. }
  30911. }
  30912. static inline void resetCounter (Timer* const tim,
  30913. const int newCounter) throw()
  30914. {
  30915. if (instance != 0)
  30916. {
  30917. tim->countdownMs = newCounter;
  30918. tim->periodMs = newCounter;
  30919. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30920. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30921. {
  30922. const ScopedLock sl (instance->lock);
  30923. instance->removeTimer (tim);
  30924. instance->addTimer (tim);
  30925. }
  30926. }
  30927. }
  30928. private:
  30929. friend class Timer;
  30930. static InternalTimerThread* instance;
  30931. static CriticalSection lock;
  30932. Timer* volatile firstTimer;
  30933. Atomic <int> callbackNeeded;
  30934. void addTimer (Timer* const t) throw()
  30935. {
  30936. #if JUCE_DEBUG
  30937. Timer* tt = firstTimer;
  30938. while (tt != 0)
  30939. {
  30940. // trying to add a timer that's already here - shouldn't get to this point,
  30941. // so if you get this assertion, let me know!
  30942. jassert (tt != t);
  30943. tt = tt->next;
  30944. }
  30945. jassert (t->previous == 0 && t->next == 0);
  30946. #endif
  30947. Timer* i = firstTimer;
  30948. if (i == 0 || i->countdownMs > t->countdownMs)
  30949. {
  30950. t->next = firstTimer;
  30951. firstTimer = t;
  30952. }
  30953. else
  30954. {
  30955. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30956. i = i->next;
  30957. jassert (i != 0);
  30958. t->next = i->next;
  30959. t->previous = i;
  30960. i->next = t;
  30961. }
  30962. if (t->next != 0)
  30963. t->next->previous = t;
  30964. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30965. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30966. notify();
  30967. }
  30968. void removeTimer (Timer* const t) throw()
  30969. {
  30970. #if JUCE_DEBUG
  30971. Timer* tt = firstTimer;
  30972. bool found = false;
  30973. while (tt != 0)
  30974. {
  30975. if (tt == t)
  30976. {
  30977. found = true;
  30978. break;
  30979. }
  30980. tt = tt->next;
  30981. }
  30982. // trying to remove a timer that's not here - shouldn't get to this point,
  30983. // so if you get this assertion, let me know!
  30984. jassert (found);
  30985. #endif
  30986. if (t->previous != 0)
  30987. {
  30988. jassert (firstTimer != t);
  30989. t->previous->next = t->next;
  30990. }
  30991. else
  30992. {
  30993. jassert (firstTimer == t);
  30994. firstTimer = t->next;
  30995. }
  30996. if (t->next != 0)
  30997. t->next->previous = t->previous;
  30998. t->next = 0;
  30999. t->previous = 0;
  31000. }
  31001. void decrementAllCounters (const int numMillisecs) const
  31002. {
  31003. Timer* t = firstTimer;
  31004. while (t != 0)
  31005. {
  31006. t->countdownMs -= numMillisecs;
  31007. t = t->next;
  31008. }
  31009. }
  31010. void handleAsyncUpdate()
  31011. {
  31012. startThread (7);
  31013. }
  31014. InternalTimerThread (const InternalTimerThread&);
  31015. InternalTimerThread& operator= (const InternalTimerThread&);
  31016. };
  31017. InternalTimerThread* InternalTimerThread::instance = 0;
  31018. CriticalSection InternalTimerThread::lock;
  31019. void juce_callAnyTimersSynchronously()
  31020. {
  31021. InternalTimerThread::callAnyTimersSynchronously();
  31022. }
  31023. #if JUCE_DEBUG
  31024. static SortedSet <Timer*> activeTimers;
  31025. #endif
  31026. Timer::Timer() throw()
  31027. : countdownMs (0),
  31028. periodMs (0),
  31029. previous (0),
  31030. next (0)
  31031. {
  31032. #if JUCE_DEBUG
  31033. activeTimers.add (this);
  31034. #endif
  31035. }
  31036. Timer::Timer (const Timer&) throw()
  31037. : countdownMs (0),
  31038. periodMs (0),
  31039. previous (0),
  31040. next (0)
  31041. {
  31042. #if JUCE_DEBUG
  31043. activeTimers.add (this);
  31044. #endif
  31045. }
  31046. Timer::~Timer()
  31047. {
  31048. stopTimer();
  31049. #if JUCE_DEBUG
  31050. activeTimers.removeValue (this);
  31051. #endif
  31052. }
  31053. void Timer::startTimer (const int interval) throw()
  31054. {
  31055. const ScopedLock sl (InternalTimerThread::lock);
  31056. #if JUCE_DEBUG
  31057. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31058. jassert (activeTimers.contains (this));
  31059. #endif
  31060. if (periodMs == 0)
  31061. {
  31062. countdownMs = interval;
  31063. periodMs = jmax (1, interval);
  31064. InternalTimerThread::add (this);
  31065. }
  31066. else
  31067. {
  31068. InternalTimerThread::resetCounter (this, interval);
  31069. }
  31070. }
  31071. void Timer::stopTimer() throw()
  31072. {
  31073. const ScopedLock sl (InternalTimerThread::lock);
  31074. #if JUCE_DEBUG
  31075. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31076. jassert (activeTimers.contains (this));
  31077. #endif
  31078. if (periodMs > 0)
  31079. {
  31080. InternalTimerThread::remove (this);
  31081. periodMs = 0;
  31082. }
  31083. }
  31084. END_JUCE_NAMESPACE
  31085. /*** End of inlined file: juce_Timer.cpp ***/
  31086. #endif
  31087. #if JUCE_BUILD_GUI
  31088. /*** Start of inlined file: juce_Component.cpp ***/
  31089. BEGIN_JUCE_NAMESPACE
  31090. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31091. enum ComponentMessageNumbers
  31092. {
  31093. customCommandMessage = 0x7fff0001,
  31094. exitModalStateMessage = 0x7fff0002
  31095. };
  31096. static uint32 nextComponentUID = 0;
  31097. Component* Component::currentlyFocusedComponent = 0;
  31098. Component::Component()
  31099. : parentComponent_ (0),
  31100. componentUID (++nextComponentUID),
  31101. numDeepMouseListeners (0),
  31102. lookAndFeel_ (0),
  31103. effect_ (0),
  31104. bufferedImage_ (0),
  31105. mouseListeners_ (0),
  31106. keyListeners_ (0),
  31107. componentFlags_ (0)
  31108. {
  31109. }
  31110. Component::Component (const String& name)
  31111. : componentName_ (name),
  31112. parentComponent_ (0),
  31113. componentUID (++nextComponentUID),
  31114. numDeepMouseListeners (0),
  31115. lookAndFeel_ (0),
  31116. effect_ (0),
  31117. bufferedImage_ (0),
  31118. mouseListeners_ (0),
  31119. keyListeners_ (0),
  31120. componentFlags_ (0)
  31121. {
  31122. }
  31123. Component::~Component()
  31124. {
  31125. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31126. if (parentComponent_ != 0)
  31127. {
  31128. parentComponent_->removeChildComponent (this);
  31129. }
  31130. else if ((currentlyFocusedComponent == this)
  31131. || isParentOf (currentlyFocusedComponent))
  31132. {
  31133. giveAwayFocus();
  31134. }
  31135. if (flags.hasHeavyweightPeerFlag)
  31136. removeFromDesktop();
  31137. for (int i = childComponentList_.size(); --i >= 0;)
  31138. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31139. delete mouseListeners_;
  31140. delete keyListeners_;
  31141. }
  31142. void Component::setName (const String& name)
  31143. {
  31144. // if component methods are being called from threads other than the message
  31145. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31146. checkMessageManagerIsLocked
  31147. if (componentName_ != name)
  31148. {
  31149. componentName_ = name;
  31150. if (flags.hasHeavyweightPeerFlag)
  31151. {
  31152. ComponentPeer* const peer = getPeer();
  31153. jassert (peer != 0);
  31154. if (peer != 0)
  31155. peer->setTitle (name);
  31156. }
  31157. BailOutChecker checker (this);
  31158. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31159. }
  31160. }
  31161. void Component::setVisible (bool shouldBeVisible)
  31162. {
  31163. if (flags.visibleFlag != shouldBeVisible)
  31164. {
  31165. // if component methods are being called from threads other than the message
  31166. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31167. checkMessageManagerIsLocked
  31168. SafePointer<Component> safePointer (this);
  31169. flags.visibleFlag = shouldBeVisible;
  31170. internalRepaint (0, 0, getWidth(), getHeight());
  31171. sendFakeMouseMove();
  31172. if (! shouldBeVisible)
  31173. {
  31174. if (currentlyFocusedComponent == this
  31175. || isParentOf (currentlyFocusedComponent))
  31176. {
  31177. if (parentComponent_ != 0)
  31178. parentComponent_->grabKeyboardFocus();
  31179. else
  31180. giveAwayFocus();
  31181. }
  31182. }
  31183. if (safePointer != 0)
  31184. {
  31185. sendVisibilityChangeMessage();
  31186. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31187. {
  31188. ComponentPeer* const peer = getPeer();
  31189. jassert (peer != 0);
  31190. if (peer != 0)
  31191. {
  31192. peer->setVisible (shouldBeVisible);
  31193. internalHierarchyChanged();
  31194. }
  31195. }
  31196. }
  31197. }
  31198. }
  31199. void Component::visibilityChanged()
  31200. {
  31201. }
  31202. void Component::sendVisibilityChangeMessage()
  31203. {
  31204. BailOutChecker checker (this);
  31205. visibilityChanged();
  31206. if (! checker.shouldBailOut())
  31207. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31208. }
  31209. bool Component::isShowing() const
  31210. {
  31211. if (flags.visibleFlag)
  31212. {
  31213. if (parentComponent_ != 0)
  31214. {
  31215. return parentComponent_->isShowing();
  31216. }
  31217. else
  31218. {
  31219. const ComponentPeer* const peer = getPeer();
  31220. return peer != 0 && ! peer->isMinimised();
  31221. }
  31222. }
  31223. return false;
  31224. }
  31225. class FadeOutProxyComponent : public Component,
  31226. public Timer
  31227. {
  31228. public:
  31229. FadeOutProxyComponent (Component* comp,
  31230. const int fadeLengthMs,
  31231. const int deltaXToMove,
  31232. const int deltaYToMove,
  31233. const float scaleFactorAtEnd)
  31234. : lastTime (0),
  31235. alpha (1.0f),
  31236. scale (1.0f)
  31237. {
  31238. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31239. setBounds (comp->getBounds());
  31240. comp->getParentComponent()->addAndMakeVisible (this);
  31241. toBehind (comp);
  31242. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31243. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31244. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31245. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31246. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31247. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31248. setInterceptsMouseClicks (false, false);
  31249. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31250. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31251. }
  31252. ~FadeOutProxyComponent()
  31253. {
  31254. }
  31255. void paint (Graphics& g)
  31256. {
  31257. g.setOpacity (alpha);
  31258. g.drawImage (image,
  31259. 0, 0, getWidth(), getHeight(),
  31260. 0, 0, image.getWidth(), image.getHeight());
  31261. }
  31262. void timerCallback()
  31263. {
  31264. const uint32 now = Time::getMillisecondCounter();
  31265. if (lastTime == 0)
  31266. lastTime = now;
  31267. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31268. lastTime = now;
  31269. alpha += alphaChangePerMs * msPassed;
  31270. if (alpha > 0)
  31271. {
  31272. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31273. {
  31274. centreX += xChangePerMs * msPassed;
  31275. centreY += yChangePerMs * msPassed;
  31276. scale += scaleChangePerMs * msPassed;
  31277. const int w = roundToInt (image.getWidth() * scale);
  31278. const int h = roundToInt (image.getHeight() * scale);
  31279. setBounds (roundToInt (centreX) - w / 2,
  31280. roundToInt (centreY) - h / 2,
  31281. w, h);
  31282. }
  31283. repaint();
  31284. }
  31285. else
  31286. {
  31287. delete this;
  31288. }
  31289. }
  31290. juce_UseDebuggingNewOperator
  31291. private:
  31292. Image image;
  31293. uint32 lastTime;
  31294. float alpha, alphaChangePerMs;
  31295. float centreX, xChangePerMs;
  31296. float centreY, yChangePerMs;
  31297. float scale, scaleChangePerMs;
  31298. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31299. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31300. };
  31301. void Component::fadeOutComponent (const int millisecondsToFade,
  31302. const int deltaXToMove,
  31303. const int deltaYToMove,
  31304. const float scaleFactorAtEnd)
  31305. {
  31306. //xxx won't work for comps without parents
  31307. if (isShowing() && millisecondsToFade > 0)
  31308. new FadeOutProxyComponent (this, millisecondsToFade,
  31309. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31310. setVisible (false);
  31311. }
  31312. bool Component::isValidComponent() const
  31313. {
  31314. return (this != 0) && isValidMessageListener();
  31315. }
  31316. void* Component::getWindowHandle() const
  31317. {
  31318. const ComponentPeer* const peer = getPeer();
  31319. if (peer != 0)
  31320. return peer->getNativeHandle();
  31321. return 0;
  31322. }
  31323. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31324. {
  31325. // if component methods are being called from threads other than the message
  31326. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31327. checkMessageManagerIsLocked
  31328. if (isOpaque())
  31329. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31330. else
  31331. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31332. int currentStyleFlags = 0;
  31333. // don't use getPeer(), so that we only get the peer that's specifically
  31334. // for this comp, and not for one of its parents.
  31335. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31336. if (peer != 0)
  31337. currentStyleFlags = peer->getStyleFlags();
  31338. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31339. {
  31340. SafePointer<Component> safePointer (this);
  31341. #if JUCE_LINUX
  31342. // it's wise to give the component a non-zero size before
  31343. // putting it on the desktop, as X windows get confused by this, and
  31344. // a (1, 1) minimum size is enforced here.
  31345. setSize (jmax (1, getWidth()),
  31346. jmax (1, getHeight()));
  31347. #endif
  31348. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31349. bool wasFullscreen = false;
  31350. bool wasMinimised = false;
  31351. ComponentBoundsConstrainer* currentConstainer = 0;
  31352. Rectangle<int> oldNonFullScreenBounds;
  31353. if (peer != 0)
  31354. {
  31355. wasFullscreen = peer->isFullScreen();
  31356. wasMinimised = peer->isMinimised();
  31357. currentConstainer = peer->getConstrainer();
  31358. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31359. removeFromDesktop();
  31360. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31361. }
  31362. if (parentComponent_ != 0)
  31363. parentComponent_->removeChildComponent (this);
  31364. if (safePointer != 0)
  31365. {
  31366. flags.hasHeavyweightPeerFlag = true;
  31367. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31368. Desktop::getInstance().addDesktopComponent (this);
  31369. bounds_.setPosition (topLeft);
  31370. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31371. peer->setVisible (isVisible());
  31372. if (wasFullscreen)
  31373. {
  31374. peer->setFullScreen (true);
  31375. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31376. }
  31377. if (wasMinimised)
  31378. peer->setMinimised (true);
  31379. if (isAlwaysOnTop())
  31380. peer->setAlwaysOnTop (true);
  31381. peer->setConstrainer (currentConstainer);
  31382. repaint();
  31383. }
  31384. internalHierarchyChanged();
  31385. }
  31386. }
  31387. void Component::removeFromDesktop()
  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 = ComponentPeer::getPeerFor (this);
  31395. flags.hasHeavyweightPeerFlag = false;
  31396. jassert (peer != 0);
  31397. delete peer;
  31398. Desktop::getInstance().removeDesktopComponent (this);
  31399. }
  31400. }
  31401. bool Component::isOnDesktop() const throw()
  31402. {
  31403. return flags.hasHeavyweightPeerFlag;
  31404. }
  31405. void Component::userTriedToCloseWindow()
  31406. {
  31407. /* This means that the user's trying to get rid of your window with the 'close window' system
  31408. menu option (on windows) or possibly the task manager - you should really handle this
  31409. and delete or hide your component in an appropriate way.
  31410. If you want to ignore the event and don't want to trigger this assertion, just override
  31411. this method and do nothing.
  31412. */
  31413. jassertfalse;
  31414. }
  31415. void Component::minimisationStateChanged (bool)
  31416. {
  31417. }
  31418. void Component::setOpaque (const bool shouldBeOpaque)
  31419. {
  31420. if (shouldBeOpaque != flags.opaqueFlag)
  31421. {
  31422. flags.opaqueFlag = shouldBeOpaque;
  31423. if (flags.hasHeavyweightPeerFlag)
  31424. {
  31425. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31426. if (peer != 0)
  31427. {
  31428. // to make it recreate the heavyweight window
  31429. addToDesktop (peer->getStyleFlags());
  31430. }
  31431. }
  31432. repaint();
  31433. }
  31434. }
  31435. bool Component::isOpaque() const throw()
  31436. {
  31437. return flags.opaqueFlag;
  31438. }
  31439. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31440. {
  31441. if (shouldBeBuffered != flags.bufferToImageFlag)
  31442. {
  31443. bufferedImage_ = Image();
  31444. flags.bufferToImageFlag = shouldBeBuffered;
  31445. }
  31446. }
  31447. void Component::toFront (const bool setAsForeground)
  31448. {
  31449. // if component methods are being called from threads other than the message
  31450. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31451. checkMessageManagerIsLocked
  31452. if (flags.hasHeavyweightPeerFlag)
  31453. {
  31454. ComponentPeer* const peer = getPeer();
  31455. if (peer != 0)
  31456. {
  31457. peer->toFront (setAsForeground);
  31458. if (setAsForeground && ! hasKeyboardFocus (true))
  31459. grabKeyboardFocus();
  31460. }
  31461. }
  31462. else if (parentComponent_ != 0)
  31463. {
  31464. Array<Component*>& childList = parentComponent_->childComponentList_;
  31465. if (childList.getLast() != this)
  31466. {
  31467. const int index = childList.indexOf (this);
  31468. if (index >= 0)
  31469. {
  31470. int insertIndex = -1;
  31471. if (! flags.alwaysOnTopFlag)
  31472. {
  31473. insertIndex = childList.size() - 1;
  31474. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31475. --insertIndex;
  31476. }
  31477. if (index != insertIndex)
  31478. {
  31479. childList.move (index, insertIndex);
  31480. sendFakeMouseMove();
  31481. repaintParent();
  31482. }
  31483. }
  31484. }
  31485. if (setAsForeground)
  31486. {
  31487. internalBroughtToFront();
  31488. grabKeyboardFocus();
  31489. }
  31490. }
  31491. }
  31492. void Component::toBehind (Component* const other)
  31493. {
  31494. if (other != 0 && other != this)
  31495. {
  31496. // the two components must belong to the same parent..
  31497. jassert (parentComponent_ == other->parentComponent_);
  31498. if (parentComponent_ != 0)
  31499. {
  31500. Array<Component*>& childList = parentComponent_->childComponentList_;
  31501. const int index = childList.indexOf (this);
  31502. if (index >= 0 && childList [index + 1] != other)
  31503. {
  31504. int otherIndex = childList.indexOf (other);
  31505. if (otherIndex >= 0)
  31506. {
  31507. if (index < otherIndex)
  31508. --otherIndex;
  31509. childList.move (index, otherIndex);
  31510. sendFakeMouseMove();
  31511. repaintParent();
  31512. }
  31513. }
  31514. }
  31515. else if (isOnDesktop())
  31516. {
  31517. jassert (other->isOnDesktop());
  31518. if (other->isOnDesktop())
  31519. {
  31520. ComponentPeer* const us = getPeer();
  31521. ComponentPeer* const them = other->getPeer();
  31522. jassert (us != 0 && them != 0);
  31523. if (us != 0 && them != 0)
  31524. us->toBehind (them);
  31525. }
  31526. }
  31527. }
  31528. }
  31529. void Component::toBack()
  31530. {
  31531. Array<Component*>& childList = parentComponent_->childComponentList_;
  31532. if (isOnDesktop())
  31533. {
  31534. jassertfalse; //xxx need to add this to native window
  31535. }
  31536. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31537. {
  31538. const int index = childList.indexOf (this);
  31539. if (index > 0)
  31540. {
  31541. int insertIndex = 0;
  31542. if (flags.alwaysOnTopFlag)
  31543. {
  31544. while (insertIndex < childList.size()
  31545. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31546. {
  31547. ++insertIndex;
  31548. }
  31549. }
  31550. if (index != insertIndex)
  31551. {
  31552. childList.move (index, insertIndex);
  31553. sendFakeMouseMove();
  31554. repaintParent();
  31555. }
  31556. }
  31557. }
  31558. }
  31559. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31560. {
  31561. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31562. {
  31563. flags.alwaysOnTopFlag = shouldStayOnTop;
  31564. if (isOnDesktop())
  31565. {
  31566. ComponentPeer* const peer = getPeer();
  31567. jassert (peer != 0);
  31568. if (peer != 0)
  31569. {
  31570. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31571. {
  31572. // some kinds of peer can't change their always-on-top status, so
  31573. // for these, we'll need to create a new window
  31574. const int oldFlags = peer->getStyleFlags();
  31575. removeFromDesktop();
  31576. addToDesktop (oldFlags);
  31577. }
  31578. }
  31579. }
  31580. if (shouldStayOnTop)
  31581. toFront (false);
  31582. internalHierarchyChanged();
  31583. }
  31584. }
  31585. bool Component::isAlwaysOnTop() const throw()
  31586. {
  31587. return flags.alwaysOnTopFlag;
  31588. }
  31589. int Component::proportionOfWidth (const float proportion) const throw()
  31590. {
  31591. return roundToInt (proportion * bounds_.getWidth());
  31592. }
  31593. int Component::proportionOfHeight (const float proportion) const throw()
  31594. {
  31595. return roundToInt (proportion * bounds_.getHeight());
  31596. }
  31597. int Component::getParentWidth() const throw()
  31598. {
  31599. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31600. : getParentMonitorArea().getWidth();
  31601. }
  31602. int Component::getParentHeight() const throw()
  31603. {
  31604. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31605. : getParentMonitorArea().getHeight();
  31606. }
  31607. int Component::getScreenX() const
  31608. {
  31609. return getScreenPosition().getX();
  31610. }
  31611. int Component::getScreenY() const
  31612. {
  31613. return getScreenPosition().getY();
  31614. }
  31615. const Point<int> Component::getScreenPosition() const
  31616. {
  31617. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31618. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31619. : getPosition());
  31620. }
  31621. const Rectangle<int> Component::getScreenBounds() const
  31622. {
  31623. return bounds_.withPosition (getScreenPosition());
  31624. }
  31625. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31626. {
  31627. const Component* c = this;
  31628. Point<int> p (relativePosition);
  31629. do
  31630. {
  31631. if (c->flags.hasHeavyweightPeerFlag)
  31632. return c->getPeer()->relativePositionToGlobal (p);
  31633. p += c->getPosition();
  31634. c = c->parentComponent_;
  31635. }
  31636. while (c != 0);
  31637. return p;
  31638. }
  31639. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31640. {
  31641. if (flags.hasHeavyweightPeerFlag)
  31642. {
  31643. return getPeer()->globalPositionToRelative (screenPosition);
  31644. }
  31645. else
  31646. {
  31647. if (parentComponent_ != 0)
  31648. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31649. return screenPosition - getPosition();
  31650. }
  31651. }
  31652. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31653. {
  31654. Point<int> p (positionRelativeToThis);
  31655. if (targetComponent != 0)
  31656. {
  31657. const Component* c = this;
  31658. do
  31659. {
  31660. if (c == targetComponent)
  31661. return p;
  31662. if (c->flags.hasHeavyweightPeerFlag)
  31663. {
  31664. p = c->getPeer()->relativePositionToGlobal (p);
  31665. break;
  31666. }
  31667. p += c->getPosition();
  31668. c = c->parentComponent_;
  31669. }
  31670. while (c != 0);
  31671. p = targetComponent->globalPositionToRelative (p);
  31672. }
  31673. return p;
  31674. }
  31675. void Component::setBounds (const int x, const int y, int w, int h)
  31676. {
  31677. // if component methods are being called from threads other than the message
  31678. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31679. checkMessageManagerIsLocked
  31680. if (w < 0) w = 0;
  31681. if (h < 0) h = 0;
  31682. const bool wasResized = (getWidth() != w || getHeight() != h);
  31683. const bool wasMoved = (getX() != x || getY() != y);
  31684. #if JUCE_DEBUG
  31685. // It's a very bad idea to try to resize a window during its paint() method!
  31686. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31687. #endif
  31688. if (wasMoved || wasResized)
  31689. {
  31690. if (flags.visibleFlag)
  31691. {
  31692. // send a fake mouse move to trigger enter/exit messages if needed..
  31693. sendFakeMouseMove();
  31694. if (! flags.hasHeavyweightPeerFlag)
  31695. repaintParent();
  31696. }
  31697. bounds_.setBounds (x, y, w, h);
  31698. if (wasResized)
  31699. repaint();
  31700. else if (! flags.hasHeavyweightPeerFlag)
  31701. repaintParent();
  31702. if (flags.hasHeavyweightPeerFlag)
  31703. {
  31704. ComponentPeer* const peer = getPeer();
  31705. if (peer != 0)
  31706. {
  31707. if (wasMoved && wasResized)
  31708. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31709. else if (wasMoved)
  31710. peer->setPosition (getX(), getY());
  31711. else if (wasResized)
  31712. peer->setSize (getWidth(), getHeight());
  31713. }
  31714. }
  31715. sendMovedResizedMessages (wasMoved, wasResized);
  31716. }
  31717. }
  31718. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31719. {
  31720. JUCE_TRY
  31721. {
  31722. if (wasMoved)
  31723. moved();
  31724. if (wasResized)
  31725. {
  31726. resized();
  31727. for (int i = childComponentList_.size(); --i >= 0;)
  31728. {
  31729. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31730. i = jmin (i, childComponentList_.size());
  31731. }
  31732. }
  31733. BailOutChecker checker (this);
  31734. if (parentComponent_ != 0)
  31735. parentComponent_->childBoundsChanged (this);
  31736. if (! checker.shouldBailOut())
  31737. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31738. *this, wasMoved, wasResized);
  31739. }
  31740. JUCE_CATCH_EXCEPTION
  31741. }
  31742. void Component::setSize (const int w, const int h)
  31743. {
  31744. setBounds (getX(), getY(), w, h);
  31745. }
  31746. void Component::setTopLeftPosition (const int x, const int y)
  31747. {
  31748. setBounds (x, y, getWidth(), getHeight());
  31749. }
  31750. void Component::setTopRightPosition (const int x, const int y)
  31751. {
  31752. setTopLeftPosition (x - getWidth(), y);
  31753. }
  31754. void Component::setBounds (const Rectangle<int>& r)
  31755. {
  31756. setBounds (r.getX(),
  31757. r.getY(),
  31758. r.getWidth(),
  31759. r.getHeight());
  31760. }
  31761. void Component::setBoundsRelative (const float x, const float y,
  31762. const float w, const float h)
  31763. {
  31764. const int pw = getParentWidth();
  31765. const int ph = getParentHeight();
  31766. setBounds (roundToInt (x * pw),
  31767. roundToInt (y * ph),
  31768. roundToInt (w * pw),
  31769. roundToInt (h * ph));
  31770. }
  31771. void Component::setCentrePosition (const int x, const int y)
  31772. {
  31773. setTopLeftPosition (x - getWidth() / 2,
  31774. y - getHeight() / 2);
  31775. }
  31776. void Component::setCentreRelative (const float x, const float y)
  31777. {
  31778. setCentrePosition (roundToInt (getParentWidth() * x),
  31779. roundToInt (getParentHeight() * y));
  31780. }
  31781. void Component::centreWithSize (const int width, const int height)
  31782. {
  31783. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  31784. setBounds (parentArea.getCentreX() - width / 2,
  31785. parentArea.getCentreY() - height / 2,
  31786. width, height);
  31787. }
  31788. void Component::setBoundsInset (const BorderSize& borders)
  31789. {
  31790. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  31791. }
  31792. void Component::setBoundsToFit (int x, int y, int width, int height,
  31793. const Justification& justification,
  31794. const bool onlyReduceInSize)
  31795. {
  31796. // it's no good calling this method unless both the component and
  31797. // target rectangle have a finite size.
  31798. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31799. if (getWidth() > 0 && getHeight() > 0
  31800. && width > 0 && height > 0)
  31801. {
  31802. int newW, newH;
  31803. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31804. {
  31805. newW = getWidth();
  31806. newH = getHeight();
  31807. }
  31808. else
  31809. {
  31810. const double imageRatio = getHeight() / (double) getWidth();
  31811. const double targetRatio = height / (double) width;
  31812. if (imageRatio <= targetRatio)
  31813. {
  31814. newW = width;
  31815. newH = jmin (height, roundToInt (newW * imageRatio));
  31816. }
  31817. else
  31818. {
  31819. newH = height;
  31820. newW = jmin (width, roundToInt (newH / imageRatio));
  31821. }
  31822. }
  31823. if (newW > 0 && newH > 0)
  31824. {
  31825. int newX, newY;
  31826. justification.applyToRectangle (newX, newY, newW, newH,
  31827. x, y, width, height);
  31828. setBounds (newX, newY, newW, newH);
  31829. }
  31830. }
  31831. }
  31832. bool Component::hitTest (int x, int y)
  31833. {
  31834. if (! flags.ignoresMouseClicksFlag)
  31835. return true;
  31836. if (flags.allowChildMouseClicksFlag)
  31837. {
  31838. for (int i = getNumChildComponents(); --i >= 0;)
  31839. {
  31840. Component* const c = getChildComponent (i);
  31841. if (c->isVisible()
  31842. && c->bounds_.contains (x, y)
  31843. && c->hitTest (x - c->getX(),
  31844. y - c->getY()))
  31845. {
  31846. return true;
  31847. }
  31848. }
  31849. }
  31850. return false;
  31851. }
  31852. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31853. const bool allowClicksOnChildComponents) throw()
  31854. {
  31855. flags.ignoresMouseClicksFlag = ! allowClicks;
  31856. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31857. }
  31858. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31859. bool& allowsClicksOnChildComponents) const throw()
  31860. {
  31861. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31862. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31863. }
  31864. bool Component::contains (const int x, const int y)
  31865. {
  31866. if (((unsigned int) x) < (unsigned int) getWidth()
  31867. && ((unsigned int) y) < (unsigned int) getHeight()
  31868. && hitTest (x, y))
  31869. {
  31870. if (parentComponent_ != 0)
  31871. {
  31872. return parentComponent_->contains (x + getX(),
  31873. y + getY());
  31874. }
  31875. else if (flags.hasHeavyweightPeerFlag)
  31876. {
  31877. const ComponentPeer* const peer = getPeer();
  31878. if (peer != 0)
  31879. return peer->contains (Point<int> (x, y), true);
  31880. }
  31881. }
  31882. return false;
  31883. }
  31884. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31885. {
  31886. if (! contains (x, y))
  31887. return false;
  31888. Component* p = this;
  31889. while (p->parentComponent_ != 0)
  31890. {
  31891. x += p->getX();
  31892. y += p->getY();
  31893. p = p->parentComponent_;
  31894. }
  31895. const Component* const c = p->getComponentAt (x, y);
  31896. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31897. }
  31898. Component* Component::getComponentAt (const Point<int>& position)
  31899. {
  31900. return getComponentAt (position.getX(), position.getY());
  31901. }
  31902. Component* Component::getComponentAt (const int x, const int y)
  31903. {
  31904. if (flags.visibleFlag
  31905. && ((unsigned int) x) < (unsigned int) getWidth()
  31906. && ((unsigned int) y) < (unsigned int) getHeight()
  31907. && hitTest (x, y))
  31908. {
  31909. for (int i = childComponentList_.size(); --i >= 0;)
  31910. {
  31911. Component* const child = childComponentList_.getUnchecked(i);
  31912. Component* const c = child->getComponentAt (x - child->getX(),
  31913. y - child->getY());
  31914. if (c != 0)
  31915. return c;
  31916. }
  31917. return this;
  31918. }
  31919. return 0;
  31920. }
  31921. void Component::addChildComponent (Component* const child, int zOrder)
  31922. {
  31923. // if component methods are being called from threads other than the message
  31924. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31925. checkMessageManagerIsLocked
  31926. if (child != 0 && child->parentComponent_ != this)
  31927. {
  31928. if (child->parentComponent_ != 0)
  31929. child->parentComponent_->removeChildComponent (child);
  31930. else
  31931. child->removeFromDesktop();
  31932. child->parentComponent_ = this;
  31933. if (child->isVisible())
  31934. child->repaintParent();
  31935. if (! child->isAlwaysOnTop())
  31936. {
  31937. if (zOrder < 0 || zOrder > childComponentList_.size())
  31938. zOrder = childComponentList_.size();
  31939. while (zOrder > 0)
  31940. {
  31941. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31942. break;
  31943. --zOrder;
  31944. }
  31945. }
  31946. childComponentList_.insert (zOrder, child);
  31947. child->internalHierarchyChanged();
  31948. internalChildrenChanged();
  31949. }
  31950. }
  31951. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31952. {
  31953. if (child != 0)
  31954. {
  31955. child->setVisible (true);
  31956. addChildComponent (child, zOrder);
  31957. }
  31958. }
  31959. void Component::removeChildComponent (Component* const child)
  31960. {
  31961. removeChildComponent (childComponentList_.indexOf (child));
  31962. }
  31963. Component* Component::removeChildComponent (const int index)
  31964. {
  31965. // if component methods are being called from threads other than the message
  31966. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31967. checkMessageManagerIsLocked
  31968. Component* const child = childComponentList_ [index];
  31969. if (child != 0)
  31970. {
  31971. sendFakeMouseMove();
  31972. child->repaintParent();
  31973. childComponentList_.remove (index);
  31974. child->parentComponent_ = 0;
  31975. JUCE_TRY
  31976. {
  31977. if ((currentlyFocusedComponent == child)
  31978. || child->isParentOf (currentlyFocusedComponent))
  31979. {
  31980. // get rid first to force the grabKeyboardFocus to change to us.
  31981. giveAwayFocus();
  31982. grabKeyboardFocus();
  31983. }
  31984. }
  31985. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31986. catch (const std::exception& e)
  31987. {
  31988. currentlyFocusedComponent = 0;
  31989. Desktop::getInstance().triggerFocusCallback();
  31990. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31991. }
  31992. catch (...)
  31993. {
  31994. currentlyFocusedComponent = 0;
  31995. Desktop::getInstance().triggerFocusCallback();
  31996. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31997. }
  31998. #endif
  31999. child->internalHierarchyChanged();
  32000. internalChildrenChanged();
  32001. }
  32002. return child;
  32003. }
  32004. void Component::removeAllChildren()
  32005. {
  32006. while (childComponentList_.size() > 0)
  32007. removeChildComponent (childComponentList_.size() - 1);
  32008. }
  32009. void Component::deleteAllChildren()
  32010. {
  32011. while (childComponentList_.size() > 0)
  32012. delete (removeChildComponent (childComponentList_.size() - 1));
  32013. }
  32014. int Component::getNumChildComponents() const throw()
  32015. {
  32016. return childComponentList_.size();
  32017. }
  32018. Component* Component::getChildComponent (const int index) const throw()
  32019. {
  32020. return childComponentList_ [index];
  32021. }
  32022. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32023. {
  32024. return childComponentList_.indexOf (const_cast <Component*> (child));
  32025. }
  32026. Component* Component::getTopLevelComponent() const throw()
  32027. {
  32028. const Component* comp = this;
  32029. while (comp->parentComponent_ != 0)
  32030. comp = comp->parentComponent_;
  32031. return const_cast <Component*> (comp);
  32032. }
  32033. bool Component::isParentOf (const Component* possibleChild) const throw()
  32034. {
  32035. if (! possibleChild->isValidComponent())
  32036. {
  32037. jassert (possibleChild == 0);
  32038. return false;
  32039. }
  32040. while (possibleChild != 0)
  32041. {
  32042. possibleChild = possibleChild->parentComponent_;
  32043. if (possibleChild == this)
  32044. return true;
  32045. }
  32046. return false;
  32047. }
  32048. void Component::parentHierarchyChanged()
  32049. {
  32050. }
  32051. void Component::childrenChanged()
  32052. {
  32053. }
  32054. void Component::internalChildrenChanged()
  32055. {
  32056. if (componentListeners.isEmpty())
  32057. {
  32058. childrenChanged();
  32059. }
  32060. else
  32061. {
  32062. BailOutChecker checker (this);
  32063. childrenChanged();
  32064. if (! checker.shouldBailOut())
  32065. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32066. }
  32067. }
  32068. void Component::internalHierarchyChanged()
  32069. {
  32070. BailOutChecker checker (this);
  32071. parentHierarchyChanged();
  32072. if (checker.shouldBailOut())
  32073. return;
  32074. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32075. if (checker.shouldBailOut())
  32076. return;
  32077. for (int i = childComponentList_.size(); --i >= 0;)
  32078. {
  32079. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32080. if (checker.shouldBailOut())
  32081. {
  32082. // you really shouldn't delete the parent component during a callback telling you
  32083. // that it's changed..
  32084. jassertfalse;
  32085. return;
  32086. }
  32087. i = jmin (i, childComponentList_.size());
  32088. }
  32089. }
  32090. void* Component::runModalLoopCallback (void* userData)
  32091. {
  32092. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32093. }
  32094. int Component::runModalLoop()
  32095. {
  32096. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32097. {
  32098. // use a callback so this can be called from non-gui threads
  32099. return (int) (pointer_sized_int) MessageManager::getInstance()
  32100. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32101. }
  32102. if (! isCurrentlyModal())
  32103. enterModalState (true);
  32104. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32105. }
  32106. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32107. {
  32108. // if component methods are being called from threads other than the message
  32109. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32110. checkMessageManagerIsLocked
  32111. // Check for an attempt to make a component modal when it already is!
  32112. // This can cause nasty problems..
  32113. jassert (! flags.currentlyModalFlag);
  32114. if (! isCurrentlyModal())
  32115. {
  32116. ModalComponentManager::getInstance()->startModal (this, callback);
  32117. flags.currentlyModalFlag = true;
  32118. setVisible (true);
  32119. if (takeKeyboardFocus_)
  32120. grabKeyboardFocus();
  32121. }
  32122. }
  32123. void Component::exitModalState (const int returnValue)
  32124. {
  32125. if (isCurrentlyModal())
  32126. {
  32127. if (MessageManager::getInstance()->isThisTheMessageThread())
  32128. {
  32129. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32130. flags.currentlyModalFlag = false;
  32131. bringModalComponentToFront();
  32132. }
  32133. else
  32134. {
  32135. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32136. }
  32137. }
  32138. }
  32139. bool Component::isCurrentlyModal() const throw()
  32140. {
  32141. return flags.currentlyModalFlag
  32142. && getCurrentlyModalComponent() == this;
  32143. }
  32144. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32145. {
  32146. Component* const mc = getCurrentlyModalComponent();
  32147. return mc != 0
  32148. && mc != this
  32149. && (! mc->isParentOf (this))
  32150. && ! mc->canModalEventBeSentToComponent (this);
  32151. }
  32152. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32153. {
  32154. return ModalComponentManager::getInstance()->getNumModalComponents();
  32155. }
  32156. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32157. {
  32158. return ModalComponentManager::getInstance()->getModalComponent (index);
  32159. }
  32160. void Component::bringModalComponentToFront()
  32161. {
  32162. ComponentPeer* lastOne = 0;
  32163. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32164. {
  32165. Component* const c = getCurrentlyModalComponent (i);
  32166. if (c == 0)
  32167. break;
  32168. ComponentPeer* peer = c->getPeer();
  32169. if (peer != 0 && peer != lastOne)
  32170. {
  32171. if (lastOne == 0)
  32172. {
  32173. peer->toFront (true);
  32174. peer->grabFocus();
  32175. }
  32176. else
  32177. peer->toBehind (lastOne);
  32178. lastOne = peer;
  32179. }
  32180. }
  32181. }
  32182. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32183. {
  32184. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32185. }
  32186. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32187. {
  32188. return flags.bringToFrontOnClickFlag;
  32189. }
  32190. void Component::setMouseCursor (const MouseCursor& cursor)
  32191. {
  32192. if (cursor_ != cursor)
  32193. {
  32194. cursor_ = cursor;
  32195. if (flags.visibleFlag)
  32196. updateMouseCursor();
  32197. }
  32198. }
  32199. const MouseCursor Component::getMouseCursor()
  32200. {
  32201. return cursor_;
  32202. }
  32203. void Component::updateMouseCursor() const
  32204. {
  32205. sendFakeMouseMove();
  32206. }
  32207. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32208. {
  32209. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32210. }
  32211. void Component::repaintParent()
  32212. {
  32213. if (flags.visibleFlag)
  32214. internalRepaint (0, 0, getWidth(), getHeight());
  32215. }
  32216. void Component::repaint()
  32217. {
  32218. repaint (0, 0, getWidth(), getHeight());
  32219. }
  32220. void Component::repaint (const int x, const int y,
  32221. const int w, const int h)
  32222. {
  32223. bufferedImage_ = Image();
  32224. if (flags.visibleFlag)
  32225. internalRepaint (x, y, w, h);
  32226. }
  32227. void Component::repaint (const Rectangle<int>& area)
  32228. {
  32229. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32230. }
  32231. void Component::internalRepaint (int x, int y, int w, int h)
  32232. {
  32233. // if component methods are being called from threads other than the message
  32234. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32235. checkMessageManagerIsLocked
  32236. if (x < 0)
  32237. {
  32238. w += x;
  32239. x = 0;
  32240. }
  32241. if (x + w > getWidth())
  32242. w = getWidth() - x;
  32243. if (w > 0)
  32244. {
  32245. if (y < 0)
  32246. {
  32247. h += y;
  32248. y = 0;
  32249. }
  32250. if (y + h > getHeight())
  32251. h = getHeight() - y;
  32252. if (h > 0)
  32253. {
  32254. if (parentComponent_ != 0)
  32255. {
  32256. x += getX();
  32257. y += getY();
  32258. if (parentComponent_->flags.visibleFlag)
  32259. parentComponent_->internalRepaint (x, y, w, h);
  32260. }
  32261. else if (flags.hasHeavyweightPeerFlag)
  32262. {
  32263. ComponentPeer* const peer = getPeer();
  32264. if (peer != 0)
  32265. peer->repaint (Rectangle<int> (x, y, w, h));
  32266. }
  32267. }
  32268. }
  32269. }
  32270. void Component::renderComponent (Graphics& g)
  32271. {
  32272. const Rectangle<int> clipBounds (g.getClipBounds());
  32273. g.saveState();
  32274. clipObscuredRegions (g, clipBounds, 0, 0);
  32275. if (! g.isClipEmpty())
  32276. {
  32277. if (flags.bufferToImageFlag)
  32278. {
  32279. if (bufferedImage_.isNull())
  32280. {
  32281. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32282. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32283. Graphics imG (bufferedImage_);
  32284. paint (imG);
  32285. }
  32286. g.setColour (Colours::black);
  32287. g.drawImageAt (bufferedImage_, 0, 0);
  32288. }
  32289. else
  32290. {
  32291. paint (g);
  32292. }
  32293. }
  32294. g.restoreState();
  32295. for (int i = 0; i < childComponentList_.size(); ++i)
  32296. {
  32297. Component* const child = childComponentList_.getUnchecked (i);
  32298. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32299. {
  32300. g.saveState();
  32301. if (g.reduceClipRegion (child->getX(), child->getY(),
  32302. child->getWidth(), child->getHeight()))
  32303. {
  32304. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32305. {
  32306. const Component* const sibling = childComponentList_.getUnchecked (j);
  32307. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32308. g.excludeClipRegion (sibling->getBounds());
  32309. }
  32310. if (! g.isClipEmpty())
  32311. {
  32312. g.setOrigin (child->getX(), child->getY());
  32313. child->paintEntireComponent (g);
  32314. }
  32315. }
  32316. g.restoreState();
  32317. }
  32318. }
  32319. g.saveState();
  32320. paintOverChildren (g);
  32321. g.restoreState();
  32322. }
  32323. void Component::paintEntireComponent (Graphics& g)
  32324. {
  32325. jassert (! g.isClipEmpty());
  32326. #if JUCE_DEBUG
  32327. flags.isInsidePaintCall = true;
  32328. #endif
  32329. if (effect_ != 0)
  32330. {
  32331. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32332. getWidth(), getHeight(),
  32333. ! flags.opaqueFlag, Image::NativeImage);
  32334. {
  32335. Graphics g2 (effectImage);
  32336. renderComponent (g2);
  32337. }
  32338. effect_->applyEffect (effectImage, g);
  32339. }
  32340. else
  32341. {
  32342. renderComponent (g);
  32343. }
  32344. #if JUCE_DEBUG
  32345. flags.isInsidePaintCall = false;
  32346. #endif
  32347. }
  32348. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32349. const bool clipImageToComponentBounds)
  32350. {
  32351. Rectangle<int> r (areaToGrab);
  32352. if (clipImageToComponentBounds)
  32353. r = r.getIntersection (getLocalBounds());
  32354. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32355. jmax (1, r.getWidth()),
  32356. jmax (1, r.getHeight()),
  32357. true);
  32358. Graphics imageContext (componentImage);
  32359. imageContext.setOrigin (-r.getX(), -r.getY());
  32360. paintEntireComponent (imageContext);
  32361. return componentImage;
  32362. }
  32363. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32364. {
  32365. if (effect_ != effect)
  32366. {
  32367. effect_ = effect;
  32368. repaint();
  32369. }
  32370. }
  32371. LookAndFeel& Component::getLookAndFeel() const throw()
  32372. {
  32373. const Component* c = this;
  32374. do
  32375. {
  32376. if (c->lookAndFeel_ != 0)
  32377. return *(c->lookAndFeel_);
  32378. c = c->parentComponent_;
  32379. }
  32380. while (c != 0);
  32381. return LookAndFeel::getDefaultLookAndFeel();
  32382. }
  32383. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32384. {
  32385. if (lookAndFeel_ != newLookAndFeel)
  32386. {
  32387. lookAndFeel_ = newLookAndFeel;
  32388. sendLookAndFeelChange();
  32389. }
  32390. }
  32391. void Component::lookAndFeelChanged()
  32392. {
  32393. }
  32394. void Component::sendLookAndFeelChange()
  32395. {
  32396. repaint();
  32397. lookAndFeelChanged();
  32398. // (it's not a great idea to do anything that would delete this component
  32399. // during the lookAndFeelChanged() callback)
  32400. jassert (isValidComponent());
  32401. SafePointer<Component> safePointer (this);
  32402. for (int i = childComponentList_.size(); --i >= 0;)
  32403. {
  32404. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32405. if (safePointer == 0)
  32406. return;
  32407. i = jmin (i, childComponentList_.size());
  32408. }
  32409. }
  32410. static const Identifier getColourPropertyId (const int colourId)
  32411. {
  32412. String s;
  32413. s.preallocateStorage (18);
  32414. s << "jcclr_" << String::toHexString (colourId);
  32415. return s;
  32416. }
  32417. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32418. {
  32419. var* v = properties.getItem (getColourPropertyId (colourId));
  32420. if (v != 0)
  32421. return Colour ((int) *v);
  32422. if (inheritFromParent && parentComponent_ != 0)
  32423. return parentComponent_->findColour (colourId, true);
  32424. return getLookAndFeel().findColour (colourId);
  32425. }
  32426. bool Component::isColourSpecified (const int colourId) const
  32427. {
  32428. return properties.contains (getColourPropertyId (colourId));
  32429. }
  32430. void Component::removeColour (const int colourId)
  32431. {
  32432. if (properties.remove (getColourPropertyId (colourId)))
  32433. colourChanged();
  32434. }
  32435. void Component::setColour (const int colourId, const Colour& colour)
  32436. {
  32437. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32438. colourChanged();
  32439. }
  32440. void Component::copyAllExplicitColoursTo (Component& target) const
  32441. {
  32442. bool changed = false;
  32443. for (int i = properties.size(); --i >= 0;)
  32444. {
  32445. const Identifier name (properties.getName(i));
  32446. if (name.toString().startsWith ("jcclr_"))
  32447. if (target.properties.set (name, properties [name]))
  32448. changed = true;
  32449. }
  32450. if (changed)
  32451. target.colourChanged();
  32452. }
  32453. void Component::colourChanged()
  32454. {
  32455. }
  32456. const Rectangle<int> Component::getLocalBounds() const throw()
  32457. {
  32458. return Rectangle<int> (getWidth(), getHeight());
  32459. }
  32460. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  32461. {
  32462. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  32463. : Desktop::getInstance().getMainMonitorArea();
  32464. }
  32465. const Rectangle<int> Component::getUnclippedArea() const
  32466. {
  32467. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32468. Component* p = parentComponent_;
  32469. int px = getX();
  32470. int py = getY();
  32471. while (p != 0)
  32472. {
  32473. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32474. return Rectangle<int>();
  32475. px += p->getX();
  32476. py += p->getY();
  32477. p = p->parentComponent_;
  32478. }
  32479. return Rectangle<int> (x, y, w, h);
  32480. }
  32481. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32482. const int deltaX, const int deltaY) const
  32483. {
  32484. for (int i = childComponentList_.size(); --i >= 0;)
  32485. {
  32486. const Component* const c = childComponentList_.getUnchecked(i);
  32487. if (c->isVisible())
  32488. {
  32489. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32490. if (! newClip.isEmpty())
  32491. {
  32492. if (c->isOpaque())
  32493. {
  32494. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32495. }
  32496. else
  32497. {
  32498. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32499. c->getX() + deltaX,
  32500. c->getY() + deltaY);
  32501. }
  32502. }
  32503. }
  32504. }
  32505. }
  32506. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32507. {
  32508. result.clear();
  32509. const Rectangle<int> unclipped (getUnclippedArea());
  32510. if (! unclipped.isEmpty())
  32511. {
  32512. result.add (unclipped);
  32513. if (includeSiblings)
  32514. {
  32515. const Component* const c = getTopLevelComponent();
  32516. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32517. c->getLocalBounds(), this);
  32518. }
  32519. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32520. result.consolidate();
  32521. }
  32522. }
  32523. void Component::subtractObscuredRegions (RectangleList& result,
  32524. const Point<int>& delta,
  32525. const Rectangle<int>& clipRect,
  32526. const Component* const compToAvoid) const
  32527. {
  32528. for (int i = childComponentList_.size(); --i >= 0;)
  32529. {
  32530. const Component* const c = childComponentList_.getUnchecked(i);
  32531. if (c != compToAvoid && c->isVisible())
  32532. {
  32533. if (c->isOpaque())
  32534. {
  32535. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32536. childBounds.translate (delta.getX(), delta.getY());
  32537. result.subtract (childBounds);
  32538. }
  32539. else
  32540. {
  32541. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32542. newClip.translate (-c->getX(), -c->getY());
  32543. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32544. newClip, compToAvoid);
  32545. }
  32546. }
  32547. }
  32548. }
  32549. void Component::mouseEnter (const MouseEvent&)
  32550. {
  32551. // base class does nothing
  32552. }
  32553. void Component::mouseExit (const MouseEvent&)
  32554. {
  32555. // base class does nothing
  32556. }
  32557. void Component::mouseDown (const MouseEvent&)
  32558. {
  32559. // base class does nothing
  32560. }
  32561. void Component::mouseUp (const MouseEvent&)
  32562. {
  32563. // base class does nothing
  32564. }
  32565. void Component::mouseDrag (const MouseEvent&)
  32566. {
  32567. // base class does nothing
  32568. }
  32569. void Component::mouseMove (const MouseEvent&)
  32570. {
  32571. // base class does nothing
  32572. }
  32573. void Component::mouseDoubleClick (const MouseEvent&)
  32574. {
  32575. // base class does nothing
  32576. }
  32577. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32578. {
  32579. // the base class just passes this event up to its parent..
  32580. if (parentComponent_ != 0)
  32581. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32582. wheelIncrementX, wheelIncrementY);
  32583. }
  32584. void Component::resized()
  32585. {
  32586. // base class does nothing
  32587. }
  32588. void Component::moved()
  32589. {
  32590. // base class does nothing
  32591. }
  32592. void Component::childBoundsChanged (Component*)
  32593. {
  32594. // base class does nothing
  32595. }
  32596. void Component::parentSizeChanged()
  32597. {
  32598. // base class does nothing
  32599. }
  32600. void Component::addComponentListener (ComponentListener* const newListener)
  32601. {
  32602. jassert (isValidComponent());
  32603. componentListeners.add (newListener);
  32604. }
  32605. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32606. {
  32607. jassert (isValidComponent());
  32608. componentListeners.remove (listenerToRemove);
  32609. }
  32610. void Component::inputAttemptWhenModal()
  32611. {
  32612. bringModalComponentToFront();
  32613. getLookAndFeel().playAlertSound();
  32614. }
  32615. bool Component::canModalEventBeSentToComponent (const Component*)
  32616. {
  32617. return false;
  32618. }
  32619. void Component::internalModalInputAttempt()
  32620. {
  32621. Component* const current = getCurrentlyModalComponent();
  32622. if (current != 0)
  32623. current->inputAttemptWhenModal();
  32624. }
  32625. void Component::paint (Graphics&)
  32626. {
  32627. // all painting is done in the subclasses
  32628. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32629. }
  32630. void Component::paintOverChildren (Graphics&)
  32631. {
  32632. // all painting is done in the subclasses
  32633. }
  32634. void Component::handleMessage (const Message& message)
  32635. {
  32636. if (message.intParameter1 == exitModalStateMessage)
  32637. {
  32638. exitModalState (message.intParameter2);
  32639. }
  32640. else if (message.intParameter1 == customCommandMessage)
  32641. {
  32642. handleCommandMessage (message.intParameter2);
  32643. }
  32644. }
  32645. void Component::postCommandMessage (const int commandId)
  32646. {
  32647. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32648. }
  32649. void Component::handleCommandMessage (int)
  32650. {
  32651. // used by subclasses
  32652. }
  32653. void Component::addMouseListener (MouseListener* const newListener,
  32654. const bool wantsEventsForAllNestedChildComponents)
  32655. {
  32656. // if component methods are being called from threads other than the message
  32657. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32658. checkMessageManagerIsLocked
  32659. if (mouseListeners_ == 0)
  32660. mouseListeners_ = new Array<MouseListener*>();
  32661. if (! mouseListeners_->contains (newListener))
  32662. {
  32663. if (wantsEventsForAllNestedChildComponents)
  32664. {
  32665. mouseListeners_->insert (0, newListener);
  32666. ++numDeepMouseListeners;
  32667. }
  32668. else
  32669. {
  32670. mouseListeners_->add (newListener);
  32671. }
  32672. }
  32673. }
  32674. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32675. {
  32676. // if component methods are being called from threads other than the message
  32677. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32678. checkMessageManagerIsLocked
  32679. if (mouseListeners_ != 0)
  32680. {
  32681. const int index = mouseListeners_->indexOf (listenerToRemove);
  32682. if (index >= 0)
  32683. {
  32684. if (index < numDeepMouseListeners)
  32685. --numDeepMouseListeners;
  32686. mouseListeners_->remove (index);
  32687. }
  32688. }
  32689. }
  32690. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32691. {
  32692. if (isCurrentlyBlockedByAnotherModalComponent())
  32693. {
  32694. // if something else is modal, always just show a normal mouse cursor
  32695. source.showMouseCursor (MouseCursor::NormalCursor);
  32696. return;
  32697. }
  32698. if (! flags.mouseInsideFlag)
  32699. {
  32700. flags.mouseInsideFlag = true;
  32701. flags.mouseOverFlag = true;
  32702. flags.draggingFlag = false;
  32703. BailOutChecker checker (this);
  32704. if (flags.repaintOnMouseActivityFlag)
  32705. repaint();
  32706. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32707. this, this, time, relativePos,
  32708. time, 0, false);
  32709. mouseEnter (me);
  32710. if (checker.shouldBailOut())
  32711. return;
  32712. Desktop::getInstance().resetTimer();
  32713. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32714. if (checker.shouldBailOut())
  32715. return;
  32716. if (mouseListeners_ != 0)
  32717. {
  32718. for (int i = mouseListeners_->size(); --i >= 0;)
  32719. {
  32720. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32721. if (checker.shouldBailOut())
  32722. return;
  32723. i = jmin (i, mouseListeners_->size());
  32724. }
  32725. }
  32726. Component* p = parentComponent_;
  32727. while (p != 0)
  32728. {
  32729. if (p->numDeepMouseListeners > 0)
  32730. {
  32731. BailOutChecker checker2 (this, p);
  32732. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32733. {
  32734. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32735. if (checker2.shouldBailOut())
  32736. return;
  32737. i = jmin (i, p->numDeepMouseListeners);
  32738. }
  32739. }
  32740. p = p->parentComponent_;
  32741. }
  32742. }
  32743. }
  32744. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32745. {
  32746. BailOutChecker checker (this);
  32747. if (flags.draggingFlag)
  32748. {
  32749. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32750. if (checker.shouldBailOut())
  32751. return;
  32752. }
  32753. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32754. {
  32755. flags.mouseInsideFlag = false;
  32756. flags.mouseOverFlag = false;
  32757. flags.draggingFlag = false;
  32758. if (flags.repaintOnMouseActivityFlag)
  32759. repaint();
  32760. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32761. this, this, time, relativePos,
  32762. time, 0, false);
  32763. mouseExit (me);
  32764. if (checker.shouldBailOut())
  32765. return;
  32766. Desktop::getInstance().resetTimer();
  32767. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32768. if (checker.shouldBailOut())
  32769. return;
  32770. if (mouseListeners_ != 0)
  32771. {
  32772. for (int i = mouseListeners_->size(); --i >= 0;)
  32773. {
  32774. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32775. if (checker.shouldBailOut())
  32776. return;
  32777. i = jmin (i, mouseListeners_->size());
  32778. }
  32779. }
  32780. Component* p = parentComponent_;
  32781. while (p != 0)
  32782. {
  32783. if (p->numDeepMouseListeners > 0)
  32784. {
  32785. BailOutChecker checker2 (this, p);
  32786. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32787. {
  32788. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32789. if (checker2.shouldBailOut())
  32790. return;
  32791. i = jmin (i, p->numDeepMouseListeners);
  32792. }
  32793. }
  32794. p = p->parentComponent_;
  32795. }
  32796. }
  32797. }
  32798. class InternalDragRepeater : public Timer
  32799. {
  32800. public:
  32801. InternalDragRepeater()
  32802. {}
  32803. ~InternalDragRepeater()
  32804. {
  32805. clearSingletonInstance();
  32806. }
  32807. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32808. void timerCallback()
  32809. {
  32810. Desktop& desktop = Desktop::getInstance();
  32811. int numMiceDown = 0;
  32812. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32813. {
  32814. MouseInputSource* const source = desktop.getMouseSource(i);
  32815. if (source->isDragging())
  32816. {
  32817. source->triggerFakeMove();
  32818. ++numMiceDown;
  32819. }
  32820. }
  32821. if (numMiceDown == 0)
  32822. deleteInstance();
  32823. }
  32824. juce_UseDebuggingNewOperator
  32825. private:
  32826. InternalDragRepeater (const InternalDragRepeater&);
  32827. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32828. };
  32829. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32830. void Component::beginDragAutoRepeat (const int interval)
  32831. {
  32832. if (interval > 0)
  32833. {
  32834. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32835. InternalDragRepeater::getInstance()->startTimer (interval);
  32836. }
  32837. else
  32838. {
  32839. InternalDragRepeater::deleteInstance();
  32840. }
  32841. }
  32842. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32843. {
  32844. Desktop& desktop = Desktop::getInstance();
  32845. BailOutChecker checker (this);
  32846. if (isCurrentlyBlockedByAnotherModalComponent())
  32847. {
  32848. internalModalInputAttempt();
  32849. if (checker.shouldBailOut())
  32850. return;
  32851. // If processing the input attempt has exited the modal loop, we'll allow the event
  32852. // to be delivered..
  32853. if (isCurrentlyBlockedByAnotherModalComponent())
  32854. {
  32855. // allow blocked mouse-events to go to global listeners..
  32856. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32857. this, this, time, relativePos, time,
  32858. source.getNumberOfMultipleClicks(), false);
  32859. desktop.resetTimer();
  32860. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32861. return;
  32862. }
  32863. }
  32864. {
  32865. Component* c = this;
  32866. while (c != 0)
  32867. {
  32868. if (c->isBroughtToFrontOnMouseClick())
  32869. {
  32870. c->toFront (true);
  32871. if (checker.shouldBailOut())
  32872. return;
  32873. }
  32874. c = c->parentComponent_;
  32875. }
  32876. }
  32877. if (! flags.dontFocusOnMouseClickFlag)
  32878. {
  32879. grabFocusInternal (focusChangedByMouseClick);
  32880. if (checker.shouldBailOut())
  32881. return;
  32882. }
  32883. flags.draggingFlag = true;
  32884. flags.mouseOverFlag = true;
  32885. if (flags.repaintOnMouseActivityFlag)
  32886. repaint();
  32887. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32888. this, this, time, relativePos, time,
  32889. source.getNumberOfMultipleClicks(), false);
  32890. mouseDown (me);
  32891. if (checker.shouldBailOut())
  32892. return;
  32893. desktop.resetTimer();
  32894. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32895. if (checker.shouldBailOut())
  32896. return;
  32897. if (mouseListeners_ != 0)
  32898. {
  32899. for (int i = mouseListeners_->size(); --i >= 0;)
  32900. {
  32901. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32902. if (checker.shouldBailOut())
  32903. return;
  32904. i = jmin (i, mouseListeners_->size());
  32905. }
  32906. }
  32907. Component* p = parentComponent_;
  32908. while (p != 0)
  32909. {
  32910. if (p->numDeepMouseListeners > 0)
  32911. {
  32912. BailOutChecker checker2 (this, p);
  32913. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32914. {
  32915. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32916. if (checker2.shouldBailOut())
  32917. return;
  32918. i = jmin (i, p->numDeepMouseListeners);
  32919. }
  32920. }
  32921. p = p->parentComponent_;
  32922. }
  32923. }
  32924. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32925. {
  32926. if (flags.draggingFlag)
  32927. {
  32928. Desktop& desktop = Desktop::getInstance();
  32929. flags.draggingFlag = false;
  32930. BailOutChecker checker (this);
  32931. if (flags.repaintOnMouseActivityFlag)
  32932. repaint();
  32933. const MouseEvent me (source, relativePos,
  32934. oldModifiers, this, this, time,
  32935. globalPositionToRelative (source.getLastMouseDownPosition()),
  32936. source.getLastMouseDownTime(),
  32937. source.getNumberOfMultipleClicks(),
  32938. source.hasMouseMovedSignificantlySincePressed());
  32939. mouseUp (me);
  32940. if (checker.shouldBailOut())
  32941. return;
  32942. desktop.resetTimer();
  32943. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32944. if (checker.shouldBailOut())
  32945. return;
  32946. if (mouseListeners_ != 0)
  32947. {
  32948. for (int i = mouseListeners_->size(); --i >= 0;)
  32949. {
  32950. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32951. if (checker.shouldBailOut())
  32952. return;
  32953. i = jmin (i, mouseListeners_->size());
  32954. }
  32955. }
  32956. {
  32957. Component* p = parentComponent_;
  32958. while (p != 0)
  32959. {
  32960. if (p->numDeepMouseListeners > 0)
  32961. {
  32962. BailOutChecker checker2 (this, p);
  32963. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32964. {
  32965. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32966. if (checker2.shouldBailOut())
  32967. return;
  32968. i = jmin (i, p->numDeepMouseListeners);
  32969. }
  32970. }
  32971. p = p->parentComponent_;
  32972. }
  32973. }
  32974. // check for double-click
  32975. if (me.getNumberOfClicks() >= 2)
  32976. {
  32977. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32978. mouseDoubleClick (me);
  32979. if (checker.shouldBailOut())
  32980. return;
  32981. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32982. if (checker.shouldBailOut())
  32983. return;
  32984. for (int i = numListeners; --i >= 0;)
  32985. {
  32986. if (checker.shouldBailOut())
  32987. return;
  32988. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32989. if (ml != 0)
  32990. ml->mouseDoubleClick (me);
  32991. }
  32992. if (checker.shouldBailOut())
  32993. return;
  32994. Component* p = parentComponent_;
  32995. while (p != 0)
  32996. {
  32997. if (p->numDeepMouseListeners > 0)
  32998. {
  32999. BailOutChecker checker2 (this, p);
  33000. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33001. {
  33002. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33003. if (checker2.shouldBailOut())
  33004. return;
  33005. i = jmin (i, p->numDeepMouseListeners);
  33006. }
  33007. }
  33008. p = p->parentComponent_;
  33009. }
  33010. }
  33011. }
  33012. }
  33013. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33014. {
  33015. if (flags.draggingFlag)
  33016. {
  33017. Desktop& desktop = Desktop::getInstance();
  33018. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33019. BailOutChecker checker (this);
  33020. const MouseEvent me (source, relativePos,
  33021. source.getCurrentModifiers(), this, this, time,
  33022. globalPositionToRelative (source.getLastMouseDownPosition()),
  33023. source.getLastMouseDownTime(),
  33024. source.getNumberOfMultipleClicks(),
  33025. source.hasMouseMovedSignificantlySincePressed());
  33026. mouseDrag (me);
  33027. if (checker.shouldBailOut())
  33028. return;
  33029. desktop.resetTimer();
  33030. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33031. if (checker.shouldBailOut())
  33032. return;
  33033. if (mouseListeners_ != 0)
  33034. {
  33035. for (int i = mouseListeners_->size(); --i >= 0;)
  33036. {
  33037. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33038. if (checker.shouldBailOut())
  33039. return;
  33040. i = jmin (i, mouseListeners_->size());
  33041. }
  33042. }
  33043. Component* p = parentComponent_;
  33044. while (p != 0)
  33045. {
  33046. if (p->numDeepMouseListeners > 0)
  33047. {
  33048. BailOutChecker checker2 (this, p);
  33049. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33050. {
  33051. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33052. if (checker2.shouldBailOut())
  33053. return;
  33054. i = jmin (i, p->numDeepMouseListeners);
  33055. }
  33056. }
  33057. p = p->parentComponent_;
  33058. }
  33059. }
  33060. }
  33061. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33062. {
  33063. Desktop& desktop = Desktop::getInstance();
  33064. BailOutChecker checker (this);
  33065. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33066. this, this, time, relativePos,
  33067. time, 0, false);
  33068. if (isCurrentlyBlockedByAnotherModalComponent())
  33069. {
  33070. // allow blocked mouse-events to go to global listeners..
  33071. desktop.sendMouseMove();
  33072. }
  33073. else
  33074. {
  33075. flags.mouseOverFlag = true;
  33076. mouseMove (me);
  33077. if (checker.shouldBailOut())
  33078. return;
  33079. desktop.resetTimer();
  33080. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33081. if (checker.shouldBailOut())
  33082. return;
  33083. if (mouseListeners_ != 0)
  33084. {
  33085. for (int i = mouseListeners_->size(); --i >= 0;)
  33086. {
  33087. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33088. if (checker.shouldBailOut())
  33089. return;
  33090. i = jmin (i, mouseListeners_->size());
  33091. }
  33092. }
  33093. Component* p = parentComponent_;
  33094. while (p != 0)
  33095. {
  33096. if (p->numDeepMouseListeners > 0)
  33097. {
  33098. BailOutChecker checker2 (this, p);
  33099. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33100. {
  33101. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33102. if (checker2.shouldBailOut())
  33103. return;
  33104. i = jmin (i, p->numDeepMouseListeners);
  33105. }
  33106. }
  33107. p = p->parentComponent_;
  33108. }
  33109. }
  33110. }
  33111. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33112. const Time& time, const float amountX, const float amountY)
  33113. {
  33114. Desktop& desktop = Desktop::getInstance();
  33115. BailOutChecker checker (this);
  33116. const float wheelIncrementX = amountX / 256.0f;
  33117. const float wheelIncrementY = amountY / 256.0f;
  33118. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33119. this, this, time, relativePos, time, 0, false);
  33120. if (isCurrentlyBlockedByAnotherModalComponent())
  33121. {
  33122. // allow blocked mouse-events to go to global listeners..
  33123. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33124. }
  33125. else
  33126. {
  33127. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33128. if (checker.shouldBailOut())
  33129. return;
  33130. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33131. if (checker.shouldBailOut())
  33132. return;
  33133. if (mouseListeners_ != 0)
  33134. {
  33135. for (int i = mouseListeners_->size(); --i >= 0;)
  33136. {
  33137. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33138. if (checker.shouldBailOut())
  33139. return;
  33140. i = jmin (i, mouseListeners_->size());
  33141. }
  33142. }
  33143. Component* p = parentComponent_;
  33144. while (p != 0)
  33145. {
  33146. if (p->numDeepMouseListeners > 0)
  33147. {
  33148. BailOutChecker checker2 (this, p);
  33149. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33150. {
  33151. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33152. if (checker2.shouldBailOut())
  33153. return;
  33154. i = jmin (i, p->numDeepMouseListeners);
  33155. }
  33156. }
  33157. p = p->parentComponent_;
  33158. }
  33159. }
  33160. }
  33161. void Component::sendFakeMouseMove() const
  33162. {
  33163. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33164. }
  33165. void Component::broughtToFront()
  33166. {
  33167. }
  33168. void Component::internalBroughtToFront()
  33169. {
  33170. if (! isValidComponent())
  33171. return;
  33172. if (flags.hasHeavyweightPeerFlag)
  33173. Desktop::getInstance().componentBroughtToFront (this);
  33174. BailOutChecker checker (this);
  33175. broughtToFront();
  33176. if (checker.shouldBailOut())
  33177. return;
  33178. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33179. if (checker.shouldBailOut())
  33180. return;
  33181. // When brought to the front and there's a modal component blocking this one,
  33182. // we need to bring the modal one to the front instead..
  33183. Component* const cm = getCurrentlyModalComponent();
  33184. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33185. bringModalComponentToFront();
  33186. }
  33187. void Component::focusGained (FocusChangeType)
  33188. {
  33189. // base class does nothing
  33190. }
  33191. void Component::internalFocusGain (const FocusChangeType cause)
  33192. {
  33193. SafePointer<Component> safePointer (this);
  33194. focusGained (cause);
  33195. if (safePointer != 0)
  33196. internalChildFocusChange (cause);
  33197. }
  33198. void Component::focusLost (FocusChangeType)
  33199. {
  33200. // base class does nothing
  33201. }
  33202. void Component::internalFocusLoss (const FocusChangeType cause)
  33203. {
  33204. SafePointer<Component> safePointer (this);
  33205. focusLost (focusChangedDirectly);
  33206. if (safePointer != 0)
  33207. internalChildFocusChange (cause);
  33208. }
  33209. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33210. {
  33211. // base class does nothing
  33212. }
  33213. void Component::internalChildFocusChange (FocusChangeType cause)
  33214. {
  33215. const bool childIsNowFocused = hasKeyboardFocus (true);
  33216. if (flags.childCompFocusedFlag != childIsNowFocused)
  33217. {
  33218. flags.childCompFocusedFlag = childIsNowFocused;
  33219. SafePointer<Component> safePointer (this);
  33220. focusOfChildComponentChanged (cause);
  33221. if (safePointer == 0)
  33222. return;
  33223. }
  33224. if (parentComponent_ != 0)
  33225. parentComponent_->internalChildFocusChange (cause);
  33226. }
  33227. bool Component::isEnabled() const throw()
  33228. {
  33229. return (! flags.isDisabledFlag)
  33230. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33231. }
  33232. void Component::setEnabled (const bool shouldBeEnabled)
  33233. {
  33234. if (flags.isDisabledFlag == shouldBeEnabled)
  33235. {
  33236. flags.isDisabledFlag = ! shouldBeEnabled;
  33237. // if any parent components are disabled, setting our flag won't make a difference,
  33238. // so no need to send a change message
  33239. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33240. sendEnablementChangeMessage();
  33241. }
  33242. }
  33243. void Component::sendEnablementChangeMessage()
  33244. {
  33245. SafePointer<Component> safePointer (this);
  33246. enablementChanged();
  33247. if (safePointer == 0)
  33248. return;
  33249. for (int i = getNumChildComponents(); --i >= 0;)
  33250. {
  33251. Component* const c = getChildComponent (i);
  33252. if (c != 0)
  33253. {
  33254. c->sendEnablementChangeMessage();
  33255. if (safePointer == 0)
  33256. return;
  33257. }
  33258. }
  33259. }
  33260. void Component::enablementChanged()
  33261. {
  33262. }
  33263. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33264. {
  33265. flags.wantsFocusFlag = wantsFocus;
  33266. }
  33267. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33268. {
  33269. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33270. }
  33271. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33272. {
  33273. return ! flags.dontFocusOnMouseClickFlag;
  33274. }
  33275. bool Component::getWantsKeyboardFocus() const throw()
  33276. {
  33277. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33278. }
  33279. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33280. {
  33281. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33282. }
  33283. bool Component::isFocusContainer() const throw()
  33284. {
  33285. return flags.isFocusContainerFlag;
  33286. }
  33287. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33288. int Component::getExplicitFocusOrder() const
  33289. {
  33290. return properties [juce_explicitFocusOrderId];
  33291. }
  33292. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33293. {
  33294. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33295. }
  33296. KeyboardFocusTraverser* Component::createFocusTraverser()
  33297. {
  33298. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33299. return new KeyboardFocusTraverser();
  33300. return parentComponent_->createFocusTraverser();
  33301. }
  33302. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33303. {
  33304. // give the focus to this component
  33305. if (currentlyFocusedComponent != this)
  33306. {
  33307. JUCE_TRY
  33308. {
  33309. // get the focus onto our desktop window
  33310. ComponentPeer* const peer = getPeer();
  33311. if (peer != 0)
  33312. {
  33313. SafePointer<Component> safePointer (this);
  33314. peer->grabFocus();
  33315. if (peer->isFocused() && currentlyFocusedComponent != this)
  33316. {
  33317. Component* const componentLosingFocus = currentlyFocusedComponent;
  33318. currentlyFocusedComponent = this;
  33319. Desktop::getInstance().triggerFocusCallback();
  33320. // call this after setting currentlyFocusedComponent so that the one that's
  33321. // losing it has a chance to see where focus is going
  33322. if (componentLosingFocus->isValidComponent())
  33323. componentLosingFocus->internalFocusLoss (cause);
  33324. if (currentlyFocusedComponent == this)
  33325. {
  33326. focusGained (cause);
  33327. if (safePointer != 0)
  33328. internalChildFocusChange (cause);
  33329. }
  33330. }
  33331. }
  33332. }
  33333. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33334. catch (const std::exception& e)
  33335. {
  33336. currentlyFocusedComponent = 0;
  33337. Desktop::getInstance().triggerFocusCallback();
  33338. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33339. }
  33340. catch (...)
  33341. {
  33342. currentlyFocusedComponent = 0;
  33343. Desktop::getInstance().triggerFocusCallback();
  33344. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33345. }
  33346. #endif
  33347. }
  33348. }
  33349. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33350. {
  33351. if (isShowing())
  33352. {
  33353. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33354. {
  33355. takeKeyboardFocus (cause);
  33356. }
  33357. else
  33358. {
  33359. if (isParentOf (currentlyFocusedComponent)
  33360. && currentlyFocusedComponent->isShowing())
  33361. {
  33362. // do nothing if the focused component is actually a child of ours..
  33363. }
  33364. else
  33365. {
  33366. // find the default child component..
  33367. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33368. if (traverser != 0)
  33369. {
  33370. Component* const defaultComp = traverser->getDefaultComponent (this);
  33371. traverser = 0;
  33372. if (defaultComp != 0)
  33373. {
  33374. defaultComp->grabFocusInternal (cause, false);
  33375. return;
  33376. }
  33377. }
  33378. if (canTryParent && parentComponent_ != 0)
  33379. {
  33380. // if no children want it and we're allowed to try our parent comp,
  33381. // then pass up to parent, which will try our siblings.
  33382. parentComponent_->grabFocusInternal (cause, true);
  33383. }
  33384. }
  33385. }
  33386. }
  33387. }
  33388. void Component::grabKeyboardFocus()
  33389. {
  33390. // if component methods are being called from threads other than the message
  33391. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33392. checkMessageManagerIsLocked
  33393. grabFocusInternal (focusChangedDirectly);
  33394. }
  33395. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33396. {
  33397. // if component methods are being called from threads other than the message
  33398. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33399. checkMessageManagerIsLocked
  33400. if (parentComponent_ != 0)
  33401. {
  33402. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33403. if (traverser != 0)
  33404. {
  33405. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33406. : traverser->getPreviousComponent (this);
  33407. traverser = 0;
  33408. if (nextComp != 0)
  33409. {
  33410. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33411. {
  33412. SafePointer<Component> nextCompPointer (nextComp);
  33413. internalModalInputAttempt();
  33414. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33415. return;
  33416. }
  33417. nextComp->grabFocusInternal (focusChangedByTabKey);
  33418. return;
  33419. }
  33420. }
  33421. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33422. }
  33423. }
  33424. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33425. {
  33426. return (currentlyFocusedComponent == this)
  33427. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33428. }
  33429. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33430. {
  33431. return currentlyFocusedComponent;
  33432. }
  33433. void Component::giveAwayFocus()
  33434. {
  33435. // use a copy so we can clear the value before the call
  33436. Component* const componentLosingFocus = currentlyFocusedComponent;
  33437. currentlyFocusedComponent = 0;
  33438. Desktop::getInstance().triggerFocusCallback();
  33439. if (componentLosingFocus->isValidComponent())
  33440. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33441. }
  33442. bool Component::isMouseOver() const throw()
  33443. {
  33444. return flags.mouseOverFlag;
  33445. }
  33446. bool Component::isMouseButtonDown() const throw()
  33447. {
  33448. return flags.draggingFlag;
  33449. }
  33450. bool Component::isMouseOverOrDragging() const throw()
  33451. {
  33452. return flags.mouseOverFlag || flags.draggingFlag;
  33453. }
  33454. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33455. {
  33456. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33457. }
  33458. const Point<int> Component::getMouseXYRelative() const
  33459. {
  33460. return globalPositionToRelative (Desktop::getMousePosition());
  33461. }
  33462. const Rectangle<int> Component::getParentMonitorArea() const
  33463. {
  33464. return Desktop::getInstance()
  33465. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  33466. }
  33467. void Component::addKeyListener (KeyListener* const newListener)
  33468. {
  33469. if (keyListeners_ == 0)
  33470. keyListeners_ = new Array <KeyListener*>();
  33471. keyListeners_->addIfNotAlreadyThere (newListener);
  33472. }
  33473. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33474. {
  33475. if (keyListeners_ != 0)
  33476. keyListeners_->removeValue (listenerToRemove);
  33477. }
  33478. bool Component::keyPressed (const KeyPress&)
  33479. {
  33480. return false;
  33481. }
  33482. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33483. {
  33484. return false;
  33485. }
  33486. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33487. {
  33488. if (parentComponent_ != 0)
  33489. parentComponent_->modifierKeysChanged (modifiers);
  33490. }
  33491. void Component::internalModifierKeysChanged()
  33492. {
  33493. sendFakeMouseMove();
  33494. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33495. }
  33496. ComponentPeer* Component::getPeer() const
  33497. {
  33498. if (flags.hasHeavyweightPeerFlag)
  33499. return ComponentPeer::getPeerFor (this);
  33500. else if (parentComponent_ != 0)
  33501. return parentComponent_->getPeer();
  33502. else
  33503. return 0;
  33504. }
  33505. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33506. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33507. {
  33508. jassert (component1 != 0);
  33509. }
  33510. bool Component::BailOutChecker::shouldBailOut() const throw()
  33511. {
  33512. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33513. }
  33514. END_JUCE_NAMESPACE
  33515. /*** End of inlined file: juce_Component.cpp ***/
  33516. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33517. BEGIN_JUCE_NAMESPACE
  33518. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33519. void ComponentListener::componentBroughtToFront (Component&) {}
  33520. void ComponentListener::componentVisibilityChanged (Component&) {}
  33521. void ComponentListener::componentChildrenChanged (Component&) {}
  33522. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33523. void ComponentListener::componentNameChanged (Component&) {}
  33524. void ComponentListener::componentBeingDeleted (Component&) {}
  33525. END_JUCE_NAMESPACE
  33526. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33527. /*** Start of inlined file: juce_Desktop.cpp ***/
  33528. BEGIN_JUCE_NAMESPACE
  33529. Desktop::Desktop()
  33530. : mouseClickCounter (0),
  33531. kioskModeComponent (0)
  33532. {
  33533. createMouseInputSources();
  33534. refreshMonitorSizes();
  33535. }
  33536. Desktop::~Desktop()
  33537. {
  33538. jassert (instance == this);
  33539. instance = 0;
  33540. // doh! If you don't delete all your windows before exiting, you're going to
  33541. // be leaking memory!
  33542. jassert (desktopComponents.size() == 0);
  33543. }
  33544. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33545. {
  33546. if (instance == 0)
  33547. instance = new Desktop();
  33548. return *instance;
  33549. }
  33550. Desktop* Desktop::instance = 0;
  33551. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33552. const bool clipToWorkArea);
  33553. void Desktop::refreshMonitorSizes()
  33554. {
  33555. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33556. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33557. monitorCoordsClipped.clear();
  33558. monitorCoordsUnclipped.clear();
  33559. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33560. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33561. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33562. if (oldClipped != monitorCoordsClipped
  33563. || oldUnclipped != monitorCoordsUnclipped)
  33564. {
  33565. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33566. {
  33567. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33568. if (p != 0)
  33569. p->handleScreenSizeChange();
  33570. }
  33571. }
  33572. }
  33573. int Desktop::getNumDisplayMonitors() const throw()
  33574. {
  33575. return monitorCoordsClipped.size();
  33576. }
  33577. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33578. {
  33579. return clippedToWorkArea ? monitorCoordsClipped [index]
  33580. : monitorCoordsUnclipped [index];
  33581. }
  33582. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33583. {
  33584. RectangleList rl;
  33585. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33586. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33587. return rl;
  33588. }
  33589. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33590. {
  33591. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33592. }
  33593. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33594. {
  33595. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33596. double bestDistance = 1.0e10;
  33597. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33598. {
  33599. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33600. if (rect.contains (position))
  33601. return rect;
  33602. const double distance = rect.getCentre().getDistanceFrom (position);
  33603. if (distance < bestDistance)
  33604. {
  33605. bestDistance = distance;
  33606. best = rect;
  33607. }
  33608. }
  33609. return best;
  33610. }
  33611. int Desktop::getNumComponents() const throw()
  33612. {
  33613. return desktopComponents.size();
  33614. }
  33615. Component* Desktop::getComponent (const int index) const throw()
  33616. {
  33617. return desktopComponents [index];
  33618. }
  33619. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33620. {
  33621. for (int i = desktopComponents.size(); --i >= 0;)
  33622. {
  33623. Component* const c = desktopComponents.getUnchecked(i);
  33624. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33625. if (c->contains (relative.getX(), relative.getY()))
  33626. return c->getComponentAt (relative.getX(), relative.getY());
  33627. }
  33628. return 0;
  33629. }
  33630. void Desktop::addDesktopComponent (Component* const c)
  33631. {
  33632. jassert (c != 0);
  33633. jassert (! desktopComponents.contains (c));
  33634. desktopComponents.addIfNotAlreadyThere (c);
  33635. }
  33636. void Desktop::removeDesktopComponent (Component* const c)
  33637. {
  33638. desktopComponents.removeValue (c);
  33639. }
  33640. void Desktop::componentBroughtToFront (Component* const c)
  33641. {
  33642. const int index = desktopComponents.indexOf (c);
  33643. jassert (index >= 0);
  33644. if (index >= 0)
  33645. {
  33646. int newIndex = -1;
  33647. if (! c->isAlwaysOnTop())
  33648. {
  33649. newIndex = desktopComponents.size();
  33650. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33651. --newIndex;
  33652. --newIndex;
  33653. }
  33654. desktopComponents.move (index, newIndex);
  33655. }
  33656. }
  33657. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33658. {
  33659. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33660. }
  33661. int Desktop::getMouseButtonClickCounter() throw()
  33662. {
  33663. return getInstance().mouseClickCounter;
  33664. }
  33665. void Desktop::incrementMouseClickCounter() throw()
  33666. {
  33667. ++mouseClickCounter;
  33668. }
  33669. int Desktop::getNumDraggingMouseSources() const throw()
  33670. {
  33671. int num = 0;
  33672. for (int i = mouseSources.size(); --i >= 0;)
  33673. if (mouseSources.getUnchecked(i)->isDragging())
  33674. ++num;
  33675. return num;
  33676. }
  33677. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33678. {
  33679. int num = 0;
  33680. for (int i = mouseSources.size(); --i >= 0;)
  33681. {
  33682. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33683. if (mi->isDragging())
  33684. {
  33685. if (index == num)
  33686. return mi;
  33687. ++num;
  33688. }
  33689. }
  33690. return 0;
  33691. }
  33692. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33693. {
  33694. focusListeners.add (listener);
  33695. }
  33696. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33697. {
  33698. focusListeners.remove (listener);
  33699. }
  33700. void Desktop::triggerFocusCallback()
  33701. {
  33702. triggerAsyncUpdate();
  33703. }
  33704. void Desktop::handleAsyncUpdate()
  33705. {
  33706. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33707. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33708. }
  33709. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33710. {
  33711. mouseListeners.add (listener);
  33712. resetTimer();
  33713. }
  33714. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33715. {
  33716. mouseListeners.remove (listener);
  33717. resetTimer();
  33718. }
  33719. void Desktop::timerCallback()
  33720. {
  33721. if (lastFakeMouseMove != getMousePosition())
  33722. sendMouseMove();
  33723. }
  33724. void Desktop::sendMouseMove()
  33725. {
  33726. if (! mouseListeners.isEmpty())
  33727. {
  33728. startTimer (20);
  33729. lastFakeMouseMove = getMousePosition();
  33730. Component* const target = findComponentAt (lastFakeMouseMove);
  33731. if (target != 0)
  33732. {
  33733. Component::BailOutChecker checker (target);
  33734. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33735. const Time now (Time::getCurrentTime());
  33736. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33737. target, target, now, pos, now, 0, false);
  33738. if (me.mods.isAnyMouseButtonDown())
  33739. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33740. else
  33741. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33742. }
  33743. }
  33744. }
  33745. void Desktop::resetTimer()
  33746. {
  33747. if (mouseListeners.size() == 0)
  33748. stopTimer();
  33749. else
  33750. startTimer (100);
  33751. lastFakeMouseMove = getMousePosition();
  33752. }
  33753. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33754. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33755. {
  33756. if (kioskModeComponent != componentToUse)
  33757. {
  33758. // agh! Don't delete a component without first stopping it being the kiosk comp
  33759. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33760. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33761. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33762. if (kioskModeComponent->isValidComponent())
  33763. {
  33764. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33765. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33766. }
  33767. kioskModeComponent = componentToUse;
  33768. if (kioskModeComponent != 0)
  33769. {
  33770. jassert (kioskModeComponent->isValidComponent());
  33771. // Only components that are already on the desktop can be put into kiosk mode!
  33772. jassert (kioskModeComponent->isOnDesktop());
  33773. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33774. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33775. }
  33776. }
  33777. }
  33778. END_JUCE_NAMESPACE
  33779. /*** End of inlined file: juce_Desktop.cpp ***/
  33780. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  33781. BEGIN_JUCE_NAMESPACE
  33782. class ModalComponentManager::ModalItem : public ComponentListener
  33783. {
  33784. public:
  33785. ModalItem (Component* const comp, Callback* const callback)
  33786. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  33787. {
  33788. if (callback != 0)
  33789. callbacks.add (callback);
  33790. jassert (comp != 0);
  33791. component->addComponentListener (this);
  33792. }
  33793. ~ModalItem()
  33794. {
  33795. if (! isDeleted)
  33796. component->removeComponentListener (this);
  33797. }
  33798. void componentBeingDeleted (Component&)
  33799. {
  33800. isDeleted = true;
  33801. cancel();
  33802. }
  33803. void componentVisibilityChanged (Component&)
  33804. {
  33805. if (! component->isShowing())
  33806. cancel();
  33807. }
  33808. void componentParentHierarchyChanged (Component&)
  33809. {
  33810. if (! component->isShowing())
  33811. cancel();
  33812. }
  33813. void cancel()
  33814. {
  33815. if (isActive)
  33816. {
  33817. isActive = false;
  33818. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  33819. }
  33820. }
  33821. Component* component;
  33822. OwnedArray<Callback> callbacks;
  33823. int returnValue;
  33824. bool isActive, isDeleted;
  33825. private:
  33826. ModalItem (const ModalItem&);
  33827. ModalItem& operator= (const ModalItem&);
  33828. };
  33829. ModalComponentManager::ModalComponentManager()
  33830. {
  33831. }
  33832. ModalComponentManager::~ModalComponentManager()
  33833. {
  33834. clearSingletonInstance();
  33835. }
  33836. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  33837. void ModalComponentManager::startModal (Component* component, Callback* callback)
  33838. {
  33839. if (component != 0)
  33840. stack.add (new ModalItem (component, callback));
  33841. }
  33842. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  33843. {
  33844. if (callback != 0)
  33845. {
  33846. ScopedPointer<Callback> callbackDeleter (callback);
  33847. for (int i = stack.size(); --i >= 0;)
  33848. {
  33849. ModalItem* const item = stack.getUnchecked(i);
  33850. if (item->component == component)
  33851. {
  33852. item->callbacks.add (callback);
  33853. callbackDeleter.release();
  33854. break;
  33855. }
  33856. }
  33857. }
  33858. }
  33859. void ModalComponentManager::endModal (Component* component)
  33860. {
  33861. for (int i = stack.size(); --i >= 0;)
  33862. {
  33863. ModalItem* const item = stack.getUnchecked(i);
  33864. if (item->component == component)
  33865. item->cancel();
  33866. }
  33867. }
  33868. void ModalComponentManager::endModal (Component* component, int returnValue)
  33869. {
  33870. for (int i = stack.size(); --i >= 0;)
  33871. {
  33872. ModalItem* const item = stack.getUnchecked(i);
  33873. if (item->component == component)
  33874. {
  33875. item->returnValue = returnValue;
  33876. item->cancel();
  33877. }
  33878. }
  33879. }
  33880. int ModalComponentManager::getNumModalComponents() const
  33881. {
  33882. int n = 0;
  33883. for (int i = 0; i < stack.size(); ++i)
  33884. if (stack.getUnchecked(i)->isActive)
  33885. ++n;
  33886. return n;
  33887. }
  33888. Component* ModalComponentManager::getModalComponent (const int index) const
  33889. {
  33890. int n = 0;
  33891. for (int i = stack.size(); --i >= 0;)
  33892. {
  33893. const ModalItem* const item = stack.getUnchecked(i);
  33894. if (item->isActive)
  33895. if (n++ == index)
  33896. return item->component;
  33897. }
  33898. return 0;
  33899. }
  33900. bool ModalComponentManager::isModal (Component* const comp) const
  33901. {
  33902. for (int i = stack.size(); --i >= 0;)
  33903. {
  33904. const ModalItem* const item = stack.getUnchecked(i);
  33905. if (item->isActive && item->component == comp)
  33906. return true;
  33907. }
  33908. return false;
  33909. }
  33910. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  33911. {
  33912. return comp == getModalComponent (0);
  33913. }
  33914. void ModalComponentManager::handleAsyncUpdate()
  33915. {
  33916. for (int i = stack.size(); --i >= 0;)
  33917. {
  33918. const ModalItem* const item = stack.getUnchecked(i);
  33919. if (! item->isActive)
  33920. {
  33921. for (int j = item->callbacks.size(); --j >= 0;)
  33922. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  33923. stack.remove (i);
  33924. }
  33925. }
  33926. }
  33927. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  33928. {
  33929. public:
  33930. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  33931. ~ReturnValueRetriever() {}
  33932. void modalStateFinished (int returnValue)
  33933. {
  33934. finished = true;
  33935. value = returnValue;
  33936. }
  33937. private:
  33938. int& value;
  33939. bool& finished;
  33940. ReturnValueRetriever (const ReturnValueRetriever&);
  33941. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  33942. };
  33943. int ModalComponentManager::runEventLoopForCurrentComponent()
  33944. {
  33945. // This can only be run from the message thread!
  33946. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  33947. Component* currentlyModal = getModalComponent (0);
  33948. if (currentlyModal == 0)
  33949. return 0;
  33950. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  33951. int returnValue = 0;
  33952. bool finished = false;
  33953. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  33954. JUCE_TRY
  33955. {
  33956. while (! finished)
  33957. {
  33958. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  33959. break;
  33960. }
  33961. }
  33962. JUCE_CATCH_EXCEPTION
  33963. if (prevFocused != 0)
  33964. prevFocused->grabKeyboardFocus();
  33965. return returnValue;
  33966. }
  33967. END_JUCE_NAMESPACE
  33968. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  33969. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33970. BEGIN_JUCE_NAMESPACE
  33971. ArrowButton::ArrowButton (const String& name,
  33972. float arrowDirectionInRadians,
  33973. const Colour& arrowColour)
  33974. : Button (name),
  33975. colour (arrowColour)
  33976. {
  33977. path.lineTo (0.0f, 1.0f);
  33978. path.lineTo (1.0f, 0.5f);
  33979. path.closeSubPath();
  33980. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33981. 0.5f, 0.5f));
  33982. setComponentEffect (&shadow);
  33983. buttonStateChanged();
  33984. }
  33985. ArrowButton::~ArrowButton()
  33986. {
  33987. }
  33988. void ArrowButton::paintButton (Graphics& g,
  33989. bool /*isMouseOverButton*/,
  33990. bool /*isButtonDown*/)
  33991. {
  33992. g.setColour (colour);
  33993. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33994. (float) offset,
  33995. (float) (getWidth() - 3),
  33996. (float) (getHeight() - 3),
  33997. false));
  33998. }
  33999. void ArrowButton::buttonStateChanged()
  34000. {
  34001. offset = (isDown()) ? 1 : 0;
  34002. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34003. 0.3f, -1, 0);
  34004. }
  34005. END_JUCE_NAMESPACE
  34006. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34007. /*** Start of inlined file: juce_Button.cpp ***/
  34008. BEGIN_JUCE_NAMESPACE
  34009. class Button::RepeatTimer : public Timer
  34010. {
  34011. public:
  34012. RepeatTimer (Button& owner_) : owner (owner_) {}
  34013. void timerCallback() { owner.repeatTimerCallback(); }
  34014. juce_UseDebuggingNewOperator
  34015. private:
  34016. Button& owner;
  34017. RepeatTimer (const RepeatTimer&);
  34018. RepeatTimer& operator= (const RepeatTimer&);
  34019. };
  34020. Button::Button (const String& name)
  34021. : Component (name),
  34022. text (name),
  34023. buttonPressTime (0),
  34024. lastTimeCallbackTime (0),
  34025. commandManagerToUse (0),
  34026. autoRepeatDelay (-1),
  34027. autoRepeatSpeed (0),
  34028. autoRepeatMinimumDelay (-1),
  34029. radioGroupId (0),
  34030. commandID (0),
  34031. connectedEdgeFlags (0),
  34032. buttonState (buttonNormal),
  34033. lastToggleState (false),
  34034. clickTogglesState (false),
  34035. needsToRelease (false),
  34036. needsRepainting (false),
  34037. isKeyDown (false),
  34038. triggerOnMouseDown (false),
  34039. generateTooltip (false)
  34040. {
  34041. setWantsKeyboardFocus (true);
  34042. isOn.addListener (this);
  34043. }
  34044. Button::~Button()
  34045. {
  34046. isOn.removeListener (this);
  34047. if (commandManagerToUse != 0)
  34048. commandManagerToUse->removeListener (this);
  34049. repeatTimer = 0;
  34050. clearShortcuts();
  34051. }
  34052. void Button::setButtonText (const String& newText)
  34053. {
  34054. if (text != newText)
  34055. {
  34056. text = newText;
  34057. repaint();
  34058. }
  34059. }
  34060. void Button::setTooltip (const String& newTooltip)
  34061. {
  34062. SettableTooltipClient::setTooltip (newTooltip);
  34063. generateTooltip = false;
  34064. }
  34065. const String Button::getTooltip()
  34066. {
  34067. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34068. {
  34069. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34070. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34071. for (int i = 0; i < keyPresses.size(); ++i)
  34072. {
  34073. const String key (keyPresses.getReference(i).getTextDescription());
  34074. tt << " [";
  34075. if (key.length() == 1)
  34076. tt << TRANS("shortcut") << ": '" << key << "']";
  34077. else
  34078. tt << key << ']';
  34079. }
  34080. return tt;
  34081. }
  34082. return SettableTooltipClient::getTooltip();
  34083. }
  34084. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34085. {
  34086. if (connectedEdgeFlags != connectedEdgeFlags_)
  34087. {
  34088. connectedEdgeFlags = connectedEdgeFlags_;
  34089. repaint();
  34090. }
  34091. }
  34092. void Button::setToggleState (const bool shouldBeOn,
  34093. const bool sendChangeNotification)
  34094. {
  34095. if (shouldBeOn != lastToggleState)
  34096. {
  34097. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34098. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34099. lastToggleState = shouldBeOn;
  34100. repaint();
  34101. if (sendChangeNotification)
  34102. {
  34103. Component::SafePointer<Component> deletionWatcher (this);
  34104. sendClickMessage (ModifierKeys());
  34105. if (deletionWatcher == 0)
  34106. return;
  34107. }
  34108. if (lastToggleState)
  34109. turnOffOtherButtonsInGroup (sendChangeNotification);
  34110. }
  34111. }
  34112. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34113. {
  34114. clickTogglesState = shouldToggle;
  34115. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34116. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34117. // it is that this button represents, and the button will update its state to reflect this
  34118. // in the applicationCommandListChanged() method.
  34119. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34120. }
  34121. bool Button::getClickingTogglesState() const throw()
  34122. {
  34123. return clickTogglesState;
  34124. }
  34125. void Button::valueChanged (Value& value)
  34126. {
  34127. if (value.refersToSameSourceAs (isOn))
  34128. setToggleState (isOn.getValue(), true);
  34129. }
  34130. void Button::setRadioGroupId (const int newGroupId)
  34131. {
  34132. if (radioGroupId != newGroupId)
  34133. {
  34134. radioGroupId = newGroupId;
  34135. if (lastToggleState)
  34136. turnOffOtherButtonsInGroup (true);
  34137. }
  34138. }
  34139. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34140. {
  34141. Component* const p = getParentComponent();
  34142. if (p != 0 && radioGroupId != 0)
  34143. {
  34144. Component::SafePointer<Component> deletionWatcher (this);
  34145. for (int i = p->getNumChildComponents(); --i >= 0;)
  34146. {
  34147. Component* const c = p->getChildComponent (i);
  34148. if (c != this)
  34149. {
  34150. Button* const b = dynamic_cast <Button*> (c);
  34151. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34152. {
  34153. b->setToggleState (false, sendChangeNotification);
  34154. if (deletionWatcher == 0)
  34155. return;
  34156. }
  34157. }
  34158. }
  34159. }
  34160. }
  34161. void Button::enablementChanged()
  34162. {
  34163. updateState (0);
  34164. repaint();
  34165. }
  34166. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34167. {
  34168. ButtonState state = buttonNormal;
  34169. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34170. {
  34171. Point<int> mousePos;
  34172. if (e == 0)
  34173. mousePos = getMouseXYRelative();
  34174. else
  34175. mousePos = e->getEventRelativeTo (this).getPosition();
  34176. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34177. const bool down = isMouseButtonDown();
  34178. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34179. state = buttonDown;
  34180. else if (over)
  34181. state = buttonOver;
  34182. }
  34183. setState (state);
  34184. return state;
  34185. }
  34186. void Button::setState (const ButtonState newState)
  34187. {
  34188. if (buttonState != newState)
  34189. {
  34190. buttonState = newState;
  34191. repaint();
  34192. if (buttonState == buttonDown)
  34193. {
  34194. buttonPressTime = Time::getApproximateMillisecondCounter();
  34195. lastTimeCallbackTime = buttonPressTime;
  34196. }
  34197. sendStateMessage();
  34198. }
  34199. }
  34200. bool Button::isDown() const throw()
  34201. {
  34202. return buttonState == buttonDown;
  34203. }
  34204. bool Button::isOver() const throw()
  34205. {
  34206. return buttonState != buttonNormal;
  34207. }
  34208. void Button::buttonStateChanged()
  34209. {
  34210. }
  34211. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34212. {
  34213. const uint32 now = Time::getApproximateMillisecondCounter();
  34214. return now > buttonPressTime ? now - buttonPressTime : 0;
  34215. }
  34216. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34217. {
  34218. triggerOnMouseDown = isTriggeredOnMouseDown;
  34219. }
  34220. void Button::clicked()
  34221. {
  34222. }
  34223. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34224. {
  34225. clicked();
  34226. }
  34227. static const int clickMessageId = 0x2f3f4f99;
  34228. void Button::triggerClick()
  34229. {
  34230. postCommandMessage (clickMessageId);
  34231. }
  34232. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34233. {
  34234. if (clickTogglesState)
  34235. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34236. sendClickMessage (modifiers);
  34237. }
  34238. void Button::flashButtonState()
  34239. {
  34240. if (isEnabled())
  34241. {
  34242. needsToRelease = true;
  34243. setState (buttonDown);
  34244. getRepeatTimer().startTimer (100);
  34245. }
  34246. }
  34247. void Button::handleCommandMessage (int commandId)
  34248. {
  34249. if (commandId == clickMessageId)
  34250. {
  34251. if (isEnabled())
  34252. {
  34253. flashButtonState();
  34254. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34255. }
  34256. }
  34257. else
  34258. {
  34259. Component::handleCommandMessage (commandId);
  34260. }
  34261. }
  34262. void Button::addButtonListener (ButtonListener* const newListener)
  34263. {
  34264. buttonListeners.add (newListener);
  34265. }
  34266. void Button::removeButtonListener (ButtonListener* const listener)
  34267. {
  34268. buttonListeners.remove (listener);
  34269. }
  34270. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34271. {
  34272. Component::BailOutChecker checker (this);
  34273. if (commandManagerToUse != 0 && commandID != 0)
  34274. {
  34275. ApplicationCommandTarget::InvocationInfo info (commandID);
  34276. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34277. info.originatingComponent = this;
  34278. commandManagerToUse->invoke (info, true);
  34279. }
  34280. clicked (modifiers);
  34281. if (! checker.shouldBailOut())
  34282. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34283. }
  34284. void Button::sendStateMessage()
  34285. {
  34286. Component::BailOutChecker checker (this);
  34287. buttonStateChanged();
  34288. if (! checker.shouldBailOut())
  34289. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34290. }
  34291. void Button::paint (Graphics& g)
  34292. {
  34293. if (needsToRelease && isEnabled())
  34294. {
  34295. needsToRelease = false;
  34296. needsRepainting = true;
  34297. }
  34298. paintButton (g, isOver(), isDown());
  34299. }
  34300. void Button::mouseEnter (const MouseEvent& e)
  34301. {
  34302. updateState (&e);
  34303. }
  34304. void Button::mouseExit (const MouseEvent& e)
  34305. {
  34306. updateState (&e);
  34307. }
  34308. void Button::mouseDown (const MouseEvent& e)
  34309. {
  34310. updateState (&e);
  34311. if (isDown())
  34312. {
  34313. if (autoRepeatDelay >= 0)
  34314. getRepeatTimer().startTimer (autoRepeatDelay);
  34315. if (triggerOnMouseDown)
  34316. internalClickCallback (e.mods);
  34317. }
  34318. }
  34319. void Button::mouseUp (const MouseEvent& e)
  34320. {
  34321. const bool wasDown = isDown();
  34322. updateState (&e);
  34323. if (wasDown && isOver() && ! triggerOnMouseDown)
  34324. internalClickCallback (e.mods);
  34325. }
  34326. void Button::mouseDrag (const MouseEvent& e)
  34327. {
  34328. const ButtonState oldState = buttonState;
  34329. updateState (&e);
  34330. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34331. getRepeatTimer().startTimer (autoRepeatSpeed);
  34332. }
  34333. void Button::focusGained (FocusChangeType)
  34334. {
  34335. updateState (0);
  34336. repaint();
  34337. }
  34338. void Button::focusLost (FocusChangeType)
  34339. {
  34340. updateState (0);
  34341. repaint();
  34342. }
  34343. void Button::setVisible (bool shouldBeVisible)
  34344. {
  34345. if (shouldBeVisible != isVisible())
  34346. {
  34347. Component::setVisible (shouldBeVisible);
  34348. if (! shouldBeVisible)
  34349. needsToRelease = false;
  34350. updateState (0);
  34351. }
  34352. else
  34353. {
  34354. Component::setVisible (shouldBeVisible);
  34355. }
  34356. }
  34357. void Button::parentHierarchyChanged()
  34358. {
  34359. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34360. if (newKeySource != keySource.getComponent())
  34361. {
  34362. if (keySource != 0)
  34363. keySource->removeKeyListener (this);
  34364. keySource = newKeySource;
  34365. if (keySource != 0)
  34366. keySource->addKeyListener (this);
  34367. }
  34368. }
  34369. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34370. const int commandID_,
  34371. const bool generateTooltip_)
  34372. {
  34373. commandID = commandID_;
  34374. generateTooltip = generateTooltip_;
  34375. if (commandManagerToUse != commandManagerToUse_)
  34376. {
  34377. if (commandManagerToUse != 0)
  34378. commandManagerToUse->removeListener (this);
  34379. commandManagerToUse = commandManagerToUse_;
  34380. if (commandManagerToUse != 0)
  34381. commandManagerToUse->addListener (this);
  34382. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34383. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34384. // it is that this button represents, and the button will update its state to reflect this
  34385. // in the applicationCommandListChanged() method.
  34386. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34387. }
  34388. if (commandManagerToUse != 0)
  34389. applicationCommandListChanged();
  34390. else
  34391. setEnabled (true);
  34392. }
  34393. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34394. {
  34395. if (info.commandID == commandID
  34396. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34397. {
  34398. flashButtonState();
  34399. }
  34400. }
  34401. void Button::applicationCommandListChanged()
  34402. {
  34403. if (commandManagerToUse != 0)
  34404. {
  34405. ApplicationCommandInfo info (0);
  34406. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34407. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34408. if (target != 0)
  34409. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34410. }
  34411. }
  34412. void Button::addShortcut (const KeyPress& key)
  34413. {
  34414. if (key.isValid())
  34415. {
  34416. jassert (! isRegisteredForShortcut (key)); // already registered!
  34417. shortcuts.add (key);
  34418. parentHierarchyChanged();
  34419. }
  34420. }
  34421. void Button::clearShortcuts()
  34422. {
  34423. shortcuts.clear();
  34424. parentHierarchyChanged();
  34425. }
  34426. bool Button::isShortcutPressed() const
  34427. {
  34428. if (! isCurrentlyBlockedByAnotherModalComponent())
  34429. {
  34430. for (int i = shortcuts.size(); --i >= 0;)
  34431. if (shortcuts.getReference(i).isCurrentlyDown())
  34432. return true;
  34433. }
  34434. return false;
  34435. }
  34436. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34437. {
  34438. for (int i = shortcuts.size(); --i >= 0;)
  34439. if (key == shortcuts.getReference(i))
  34440. return true;
  34441. return false;
  34442. }
  34443. bool Button::keyStateChanged (const bool, Component*)
  34444. {
  34445. if (! isEnabled())
  34446. return false;
  34447. const bool wasDown = isKeyDown;
  34448. isKeyDown = isShortcutPressed();
  34449. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34450. getRepeatTimer().startTimer (autoRepeatDelay);
  34451. updateState (0);
  34452. if (isEnabled() && wasDown && ! isKeyDown)
  34453. {
  34454. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34455. // (return immediately - this button may now have been deleted)
  34456. return true;
  34457. }
  34458. return wasDown || isKeyDown;
  34459. }
  34460. bool Button::keyPressed (const KeyPress&, Component*)
  34461. {
  34462. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34463. return isShortcutPressed();
  34464. }
  34465. bool Button::keyPressed (const KeyPress& key)
  34466. {
  34467. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34468. {
  34469. triggerClick();
  34470. return true;
  34471. }
  34472. return false;
  34473. }
  34474. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34475. const int repeatMillisecs,
  34476. const int minimumDelayInMillisecs) throw()
  34477. {
  34478. autoRepeatDelay = initialDelayMillisecs;
  34479. autoRepeatSpeed = repeatMillisecs;
  34480. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34481. }
  34482. void Button::repeatTimerCallback()
  34483. {
  34484. if (needsRepainting)
  34485. {
  34486. getRepeatTimer().stopTimer();
  34487. updateState (0);
  34488. needsRepainting = false;
  34489. }
  34490. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34491. {
  34492. int repeatSpeed = autoRepeatSpeed;
  34493. if (autoRepeatMinimumDelay >= 0)
  34494. {
  34495. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34496. timeHeldDown *= timeHeldDown;
  34497. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34498. }
  34499. repeatSpeed = jmax (1, repeatSpeed);
  34500. getRepeatTimer().startTimer (repeatSpeed);
  34501. const uint32 now = Time::getApproximateMillisecondCounter();
  34502. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34503. lastTimeCallbackTime = now;
  34504. Component::SafePointer<Component> deletionWatcher (this);
  34505. for (int i = numTimesToCallback; --i >= 0;)
  34506. {
  34507. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34508. if (deletionWatcher == 0 || ! isDown())
  34509. return;
  34510. }
  34511. }
  34512. else if (! needsToRelease)
  34513. {
  34514. getRepeatTimer().stopTimer();
  34515. }
  34516. }
  34517. Button::RepeatTimer& Button::getRepeatTimer()
  34518. {
  34519. if (repeatTimer == 0)
  34520. repeatTimer = new RepeatTimer (*this);
  34521. return *repeatTimer;
  34522. }
  34523. END_JUCE_NAMESPACE
  34524. /*** End of inlined file: juce_Button.cpp ***/
  34525. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34526. BEGIN_JUCE_NAMESPACE
  34527. DrawableButton::DrawableButton (const String& name,
  34528. const DrawableButton::ButtonStyle buttonStyle)
  34529. : Button (name),
  34530. style (buttonStyle),
  34531. edgeIndent (3)
  34532. {
  34533. if (buttonStyle == ImageOnButtonBackground)
  34534. {
  34535. backgroundOff = Colour (0xffbbbbff);
  34536. backgroundOn = Colour (0xff3333ff);
  34537. }
  34538. else
  34539. {
  34540. backgroundOff = Colours::transparentBlack;
  34541. backgroundOn = Colour (0xaabbbbff);
  34542. }
  34543. }
  34544. DrawableButton::~DrawableButton()
  34545. {
  34546. deleteImages();
  34547. }
  34548. void DrawableButton::deleteImages()
  34549. {
  34550. }
  34551. void DrawableButton::setImages (const Drawable* normal,
  34552. const Drawable* over,
  34553. const Drawable* down,
  34554. const Drawable* disabled,
  34555. const Drawable* normalOn,
  34556. const Drawable* overOn,
  34557. const Drawable* downOn,
  34558. const Drawable* disabledOn)
  34559. {
  34560. deleteImages();
  34561. jassert (normal != 0); // you really need to give it at least a normal image..
  34562. if (normal != 0)
  34563. normalImage = normal->createCopy();
  34564. if (over != 0)
  34565. overImage = over->createCopy();
  34566. if (down != 0)
  34567. downImage = down->createCopy();
  34568. if (disabled != 0)
  34569. disabledImage = disabled->createCopy();
  34570. if (normalOn != 0)
  34571. normalImageOn = normalOn->createCopy();
  34572. if (overOn != 0)
  34573. overImageOn = overOn->createCopy();
  34574. if (downOn != 0)
  34575. downImageOn = downOn->createCopy();
  34576. if (disabledOn != 0)
  34577. disabledImageOn = disabledOn->createCopy();
  34578. repaint();
  34579. }
  34580. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34581. {
  34582. if (style != newStyle)
  34583. {
  34584. style = newStyle;
  34585. repaint();
  34586. }
  34587. }
  34588. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34589. const Colour& toggledOnColour)
  34590. {
  34591. if (backgroundOff != toggledOffColour
  34592. || backgroundOn != toggledOnColour)
  34593. {
  34594. backgroundOff = toggledOffColour;
  34595. backgroundOn = toggledOnColour;
  34596. repaint();
  34597. }
  34598. }
  34599. const Colour& DrawableButton::getBackgroundColour() const throw()
  34600. {
  34601. return getToggleState() ? backgroundOn
  34602. : backgroundOff;
  34603. }
  34604. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34605. {
  34606. edgeIndent = numPixelsIndent;
  34607. repaint();
  34608. }
  34609. void DrawableButton::paintButton (Graphics& g,
  34610. bool isMouseOverButton,
  34611. bool isButtonDown)
  34612. {
  34613. Rectangle<int> imageSpace;
  34614. if (style == ImageOnButtonBackground)
  34615. {
  34616. const int insetX = getWidth() / 4;
  34617. const int insetY = getHeight() / 4;
  34618. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34619. getLookAndFeel().drawButtonBackground (g, *this,
  34620. getBackgroundColour(),
  34621. isMouseOverButton,
  34622. isButtonDown);
  34623. }
  34624. else
  34625. {
  34626. g.fillAll (getBackgroundColour());
  34627. const int textH = (style == ImageAboveTextLabel)
  34628. ? jmin (16, proportionOfHeight (0.25f))
  34629. : 0;
  34630. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34631. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34632. imageSpace.setBounds (indentX, indentY,
  34633. getWidth() - indentX * 2,
  34634. getHeight() - indentY * 2 - textH);
  34635. if (textH > 0)
  34636. {
  34637. g.setFont ((float) textH);
  34638. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34639. g.drawFittedText (getButtonText(),
  34640. 2, getHeight() - textH - 1,
  34641. getWidth() - 4, textH,
  34642. Justification::centred, 1);
  34643. }
  34644. }
  34645. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34646. g.setOpacity (1.0f);
  34647. const Drawable* imageToDraw = 0;
  34648. if (isEnabled())
  34649. {
  34650. imageToDraw = getCurrentImage();
  34651. }
  34652. else
  34653. {
  34654. imageToDraw = getToggleState() ? disabledImageOn
  34655. : disabledImage;
  34656. if (imageToDraw == 0)
  34657. {
  34658. g.setOpacity (0.4f);
  34659. imageToDraw = getNormalImage();
  34660. }
  34661. }
  34662. if (imageToDraw != 0)
  34663. {
  34664. if (style == ImageRaw)
  34665. {
  34666. imageToDraw->draw (g, 1.0f);
  34667. }
  34668. else
  34669. {
  34670. imageToDraw->drawWithin (g,
  34671. imageSpace.getX(),
  34672. imageSpace.getY(),
  34673. imageSpace.getWidth(),
  34674. imageSpace.getHeight(),
  34675. RectanglePlacement::centred,
  34676. 1.0f);
  34677. }
  34678. }
  34679. }
  34680. const Drawable* DrawableButton::getCurrentImage() const throw()
  34681. {
  34682. if (isDown())
  34683. return getDownImage();
  34684. if (isOver())
  34685. return getOverImage();
  34686. return getNormalImage();
  34687. }
  34688. const Drawable* DrawableButton::getNormalImage() const throw()
  34689. {
  34690. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34691. : normalImage;
  34692. }
  34693. const Drawable* DrawableButton::getOverImage() const throw()
  34694. {
  34695. const Drawable* d = normalImage;
  34696. if (getToggleState())
  34697. {
  34698. if (overImageOn != 0)
  34699. d = overImageOn;
  34700. else if (normalImageOn != 0)
  34701. d = normalImageOn;
  34702. else if (overImage != 0)
  34703. d = overImage;
  34704. }
  34705. else
  34706. {
  34707. if (overImage != 0)
  34708. d = overImage;
  34709. }
  34710. return d;
  34711. }
  34712. const Drawable* DrawableButton::getDownImage() const throw()
  34713. {
  34714. const Drawable* d = normalImage;
  34715. if (getToggleState())
  34716. {
  34717. if (downImageOn != 0)
  34718. d = downImageOn;
  34719. else if (overImageOn != 0)
  34720. d = overImageOn;
  34721. else if (normalImageOn != 0)
  34722. d = normalImageOn;
  34723. else if (downImage != 0)
  34724. d = downImage;
  34725. else
  34726. d = getOverImage();
  34727. }
  34728. else
  34729. {
  34730. if (downImage != 0)
  34731. d = downImage;
  34732. else
  34733. d = getOverImage();
  34734. }
  34735. return d;
  34736. }
  34737. END_JUCE_NAMESPACE
  34738. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34739. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34740. BEGIN_JUCE_NAMESPACE
  34741. HyperlinkButton::HyperlinkButton (const String& linkText,
  34742. const URL& linkURL)
  34743. : Button (linkText),
  34744. url (linkURL),
  34745. font (14.0f, Font::underlined),
  34746. resizeFont (true),
  34747. justification (Justification::centred)
  34748. {
  34749. setMouseCursor (MouseCursor::PointingHandCursor);
  34750. setTooltip (linkURL.toString (false));
  34751. }
  34752. HyperlinkButton::~HyperlinkButton()
  34753. {
  34754. }
  34755. void HyperlinkButton::setFont (const Font& newFont,
  34756. const bool resizeToMatchComponentHeight,
  34757. const Justification& justificationType)
  34758. {
  34759. font = newFont;
  34760. resizeFont = resizeToMatchComponentHeight;
  34761. justification = justificationType;
  34762. repaint();
  34763. }
  34764. void HyperlinkButton::setURL (const URL& newURL) throw()
  34765. {
  34766. url = newURL;
  34767. setTooltip (newURL.toString (false));
  34768. }
  34769. const Font HyperlinkButton::getFontToUse() const
  34770. {
  34771. Font f (font);
  34772. if (resizeFont)
  34773. f.setHeight (getHeight() * 0.7f);
  34774. return f;
  34775. }
  34776. void HyperlinkButton::changeWidthToFitText()
  34777. {
  34778. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34779. }
  34780. void HyperlinkButton::colourChanged()
  34781. {
  34782. repaint();
  34783. }
  34784. void HyperlinkButton::clicked()
  34785. {
  34786. if (url.isWellFormed())
  34787. url.launchInDefaultBrowser();
  34788. }
  34789. void HyperlinkButton::paintButton (Graphics& g,
  34790. bool isMouseOverButton,
  34791. bool isButtonDown)
  34792. {
  34793. const Colour textColour (findColour (textColourId));
  34794. if (isEnabled())
  34795. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34796. : textColour);
  34797. else
  34798. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34799. g.setFont (getFontToUse());
  34800. g.drawText (getButtonText(),
  34801. 2, 0, getWidth() - 2, getHeight(),
  34802. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34803. true);
  34804. }
  34805. END_JUCE_NAMESPACE
  34806. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34807. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34808. BEGIN_JUCE_NAMESPACE
  34809. ImageButton::ImageButton (const String& text_)
  34810. : Button (text_),
  34811. scaleImageToFit (true),
  34812. preserveProportions (true),
  34813. alphaThreshold (0),
  34814. imageX (0),
  34815. imageY (0),
  34816. imageW (0),
  34817. imageH (0),
  34818. normalImage (0),
  34819. overImage (0),
  34820. downImage (0)
  34821. {
  34822. }
  34823. ImageButton::~ImageButton()
  34824. {
  34825. }
  34826. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34827. const bool rescaleImagesWhenButtonSizeChanges,
  34828. const bool preserveImageProportions,
  34829. const Image& normalImage_,
  34830. const float imageOpacityWhenNormal,
  34831. const Colour& overlayColourWhenNormal,
  34832. const Image& overImage_,
  34833. const float imageOpacityWhenOver,
  34834. const Colour& overlayColourWhenOver,
  34835. const Image& downImage_,
  34836. const float imageOpacityWhenDown,
  34837. const Colour& overlayColourWhenDown,
  34838. const float hitTestAlphaThreshold)
  34839. {
  34840. normalImage = normalImage_;
  34841. overImage = overImage_;
  34842. downImage = downImage_;
  34843. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34844. {
  34845. imageW = normalImage.getWidth();
  34846. imageH = normalImage.getHeight();
  34847. setSize (imageW, imageH);
  34848. }
  34849. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34850. preserveProportions = preserveImageProportions;
  34851. normalOpacity = imageOpacityWhenNormal;
  34852. normalOverlay = overlayColourWhenNormal;
  34853. overOpacity = imageOpacityWhenOver;
  34854. overOverlay = overlayColourWhenOver;
  34855. downOpacity = imageOpacityWhenDown;
  34856. downOverlay = overlayColourWhenDown;
  34857. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34858. repaint();
  34859. }
  34860. const Image ImageButton::getCurrentImage() const
  34861. {
  34862. if (isDown() || getToggleState())
  34863. return getDownImage();
  34864. if (isOver())
  34865. return getOverImage();
  34866. return getNormalImage();
  34867. }
  34868. const Image ImageButton::getNormalImage() const
  34869. {
  34870. return normalImage;
  34871. }
  34872. const Image ImageButton::getOverImage() const
  34873. {
  34874. return overImage.isValid() ? overImage
  34875. : normalImage;
  34876. }
  34877. const Image ImageButton::getDownImage() const
  34878. {
  34879. return downImage.isValid() ? downImage
  34880. : getOverImage();
  34881. }
  34882. void ImageButton::paintButton (Graphics& g,
  34883. bool isMouseOverButton,
  34884. bool isButtonDown)
  34885. {
  34886. if (! isEnabled())
  34887. {
  34888. isMouseOverButton = false;
  34889. isButtonDown = false;
  34890. }
  34891. Image im (getCurrentImage());
  34892. if (im.isValid())
  34893. {
  34894. const int iw = im.getWidth();
  34895. const int ih = im.getHeight();
  34896. imageW = getWidth();
  34897. imageH = getHeight();
  34898. imageX = (imageW - iw) >> 1;
  34899. imageY = (imageH - ih) >> 1;
  34900. if (scaleImageToFit)
  34901. {
  34902. if (preserveProportions)
  34903. {
  34904. int newW, newH;
  34905. const float imRatio = ih / (float)iw;
  34906. const float destRatio = imageH / (float)imageW;
  34907. if (imRatio > destRatio)
  34908. {
  34909. newW = roundToInt (imageH / imRatio);
  34910. newH = imageH;
  34911. }
  34912. else
  34913. {
  34914. newW = imageW;
  34915. newH = roundToInt (imageW * imRatio);
  34916. }
  34917. imageX = (imageW - newW) / 2;
  34918. imageY = (imageH - newH) / 2;
  34919. imageW = newW;
  34920. imageH = newH;
  34921. }
  34922. else
  34923. {
  34924. imageX = 0;
  34925. imageY = 0;
  34926. }
  34927. }
  34928. if (! scaleImageToFit)
  34929. {
  34930. imageW = iw;
  34931. imageH = ih;
  34932. }
  34933. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34934. isButtonDown ? downOverlay
  34935. : (isMouseOverButton ? overOverlay
  34936. : normalOverlay),
  34937. isButtonDown ? downOpacity
  34938. : (isMouseOverButton ? overOpacity
  34939. : normalOpacity),
  34940. *this);
  34941. }
  34942. }
  34943. bool ImageButton::hitTest (int x, int y)
  34944. {
  34945. if (alphaThreshold == 0)
  34946. return true;
  34947. Image im (getCurrentImage());
  34948. return im.isNull() || (imageW > 0 && imageH > 0
  34949. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34950. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34951. }
  34952. END_JUCE_NAMESPACE
  34953. /*** End of inlined file: juce_ImageButton.cpp ***/
  34954. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34955. BEGIN_JUCE_NAMESPACE
  34956. ShapeButton::ShapeButton (const String& text_,
  34957. const Colour& normalColour_,
  34958. const Colour& overColour_,
  34959. const Colour& downColour_)
  34960. : Button (text_),
  34961. normalColour (normalColour_),
  34962. overColour (overColour_),
  34963. downColour (downColour_),
  34964. maintainShapeProportions (false),
  34965. outlineWidth (0.0f)
  34966. {
  34967. }
  34968. ShapeButton::~ShapeButton()
  34969. {
  34970. }
  34971. void ShapeButton::setColours (const Colour& newNormalColour,
  34972. const Colour& newOverColour,
  34973. const Colour& newDownColour)
  34974. {
  34975. normalColour = newNormalColour;
  34976. overColour = newOverColour;
  34977. downColour = newDownColour;
  34978. }
  34979. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34980. const float newOutlineWidth)
  34981. {
  34982. outlineColour = newOutlineColour;
  34983. outlineWidth = newOutlineWidth;
  34984. }
  34985. void ShapeButton::setShape (const Path& newShape,
  34986. const bool resizeNowToFitThisShape,
  34987. const bool maintainShapeProportions_,
  34988. const bool hasShadow)
  34989. {
  34990. shape = newShape;
  34991. maintainShapeProportions = maintainShapeProportions_;
  34992. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34993. setComponentEffect ((hasShadow) ? &shadow : 0);
  34994. if (resizeNowToFitThisShape)
  34995. {
  34996. Rectangle<float> bounds (shape.getBounds());
  34997. if (hasShadow)
  34998. bounds.expand (4.0f, 4.0f);
  34999. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35000. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35001. 1 + (int) (bounds.getHeight() + outlineWidth));
  35002. }
  35003. }
  35004. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35005. {
  35006. if (! isEnabled())
  35007. {
  35008. isMouseOverButton = false;
  35009. isButtonDown = false;
  35010. }
  35011. g.setColour ((isButtonDown) ? downColour
  35012. : (isMouseOverButton) ? overColour
  35013. : normalColour);
  35014. int w = getWidth();
  35015. int h = getHeight();
  35016. if (getComponentEffect() != 0)
  35017. {
  35018. w -= 4;
  35019. h -= 4;
  35020. }
  35021. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35022. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35023. w - offset - outlineWidth,
  35024. h - offset - outlineWidth,
  35025. maintainShapeProportions));
  35026. g.fillPath (shape, trans);
  35027. if (outlineWidth > 0.0f)
  35028. {
  35029. g.setColour (outlineColour);
  35030. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35031. }
  35032. }
  35033. END_JUCE_NAMESPACE
  35034. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35035. /*** Start of inlined file: juce_TextButton.cpp ***/
  35036. BEGIN_JUCE_NAMESPACE
  35037. TextButton::TextButton (const String& name,
  35038. const String& toolTip)
  35039. : Button (name)
  35040. {
  35041. setTooltip (toolTip);
  35042. }
  35043. TextButton::~TextButton()
  35044. {
  35045. }
  35046. void TextButton::paintButton (Graphics& g,
  35047. bool isMouseOverButton,
  35048. bool isButtonDown)
  35049. {
  35050. getLookAndFeel().drawButtonBackground (g, *this,
  35051. findColour (getToggleState() ? buttonOnColourId
  35052. : buttonColourId),
  35053. isMouseOverButton,
  35054. isButtonDown);
  35055. getLookAndFeel().drawButtonText (g, *this,
  35056. isMouseOverButton,
  35057. isButtonDown);
  35058. }
  35059. void TextButton::colourChanged()
  35060. {
  35061. repaint();
  35062. }
  35063. const Font TextButton::getFont()
  35064. {
  35065. return Font (jmin (15.0f, getHeight() * 0.6f));
  35066. }
  35067. void TextButton::changeWidthToFitText (const int newHeight)
  35068. {
  35069. if (newHeight >= 0)
  35070. setSize (jmax (1, getWidth()), newHeight);
  35071. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35072. getHeight());
  35073. }
  35074. END_JUCE_NAMESPACE
  35075. /*** End of inlined file: juce_TextButton.cpp ***/
  35076. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35077. BEGIN_JUCE_NAMESPACE
  35078. ToggleButton::ToggleButton (const String& buttonText)
  35079. : Button (buttonText)
  35080. {
  35081. setClickingTogglesState (true);
  35082. }
  35083. ToggleButton::~ToggleButton()
  35084. {
  35085. }
  35086. void ToggleButton::paintButton (Graphics& g,
  35087. bool isMouseOverButton,
  35088. bool isButtonDown)
  35089. {
  35090. getLookAndFeel().drawToggleButton (g, *this,
  35091. isMouseOverButton,
  35092. isButtonDown);
  35093. }
  35094. void ToggleButton::changeWidthToFitText()
  35095. {
  35096. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35097. }
  35098. void ToggleButton::colourChanged()
  35099. {
  35100. repaint();
  35101. }
  35102. END_JUCE_NAMESPACE
  35103. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35104. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35105. BEGIN_JUCE_NAMESPACE
  35106. ToolbarButton::ToolbarButton (const int itemId_,
  35107. const String& buttonText,
  35108. Drawable* const normalImage_,
  35109. Drawable* const toggledOnImage_)
  35110. : ToolbarItemComponent (itemId_, buttonText, true),
  35111. normalImage (normalImage_),
  35112. toggledOnImage (toggledOnImage_)
  35113. {
  35114. jassert (normalImage_ != 0);
  35115. }
  35116. ToolbarButton::~ToolbarButton()
  35117. {
  35118. }
  35119. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35120. bool /*isToolbarVertical*/,
  35121. int& preferredSize,
  35122. int& minSize, int& maxSize)
  35123. {
  35124. preferredSize = minSize = maxSize = toolbarDepth;
  35125. return true;
  35126. }
  35127. void ToolbarButton::paintButtonArea (Graphics& g,
  35128. int width, int height,
  35129. bool /*isMouseOver*/,
  35130. bool /*isMouseDown*/)
  35131. {
  35132. Drawable* d = normalImage;
  35133. if (getToggleState() && toggledOnImage != 0)
  35134. d = toggledOnImage;
  35135. if (! isEnabled())
  35136. {
  35137. Image im (Image::ARGB, width, height, true);
  35138. {
  35139. Graphics g2 (im);
  35140. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35141. }
  35142. im.desaturate();
  35143. g.drawImageAt (im, 0, 0);
  35144. }
  35145. else
  35146. {
  35147. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35148. }
  35149. }
  35150. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35151. {
  35152. }
  35153. END_JUCE_NAMESPACE
  35154. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35155. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35156. BEGIN_JUCE_NAMESPACE
  35157. class CodeDocumentLine
  35158. {
  35159. public:
  35160. CodeDocumentLine (const juce_wchar* const line_,
  35161. const int lineLength_,
  35162. const int numNewLineChars,
  35163. const int lineStartInFile_)
  35164. : line (line_, lineLength_),
  35165. lineStartInFile (lineStartInFile_),
  35166. lineLength (lineLength_),
  35167. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35168. {
  35169. }
  35170. ~CodeDocumentLine()
  35171. {
  35172. }
  35173. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35174. {
  35175. const juce_wchar* const t = text;
  35176. int pos = 0;
  35177. while (t [pos] != 0)
  35178. {
  35179. const int startOfLine = pos;
  35180. int numNewLineChars = 0;
  35181. while (t[pos] != 0)
  35182. {
  35183. if (t[pos] == '\r')
  35184. {
  35185. ++numNewLineChars;
  35186. ++pos;
  35187. if (t[pos] == '\n')
  35188. {
  35189. ++numNewLineChars;
  35190. ++pos;
  35191. }
  35192. break;
  35193. }
  35194. if (t[pos] == '\n')
  35195. {
  35196. ++numNewLineChars;
  35197. ++pos;
  35198. break;
  35199. }
  35200. ++pos;
  35201. }
  35202. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35203. numNewLineChars, startOfLine));
  35204. }
  35205. jassert (pos == text.length());
  35206. }
  35207. bool endsWithLineBreak() const throw()
  35208. {
  35209. return lineLengthWithoutNewLines != lineLength;
  35210. }
  35211. void updateLength() throw()
  35212. {
  35213. lineLengthWithoutNewLines = lineLength = line.length();
  35214. while (lineLengthWithoutNewLines > 0
  35215. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35216. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35217. {
  35218. --lineLengthWithoutNewLines;
  35219. }
  35220. }
  35221. String line;
  35222. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35223. };
  35224. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35225. : document (document_),
  35226. currentLine (document_->lines[0]),
  35227. line (0),
  35228. position (0)
  35229. {
  35230. }
  35231. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35232. : document (other.document),
  35233. currentLine (other.currentLine),
  35234. line (other.line),
  35235. position (other.position)
  35236. {
  35237. }
  35238. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35239. {
  35240. document = other.document;
  35241. currentLine = other.currentLine;
  35242. line = other.line;
  35243. position = other.position;
  35244. return *this;
  35245. }
  35246. CodeDocument::Iterator::~Iterator() throw()
  35247. {
  35248. }
  35249. juce_wchar CodeDocument::Iterator::nextChar()
  35250. {
  35251. if (currentLine == 0)
  35252. return 0;
  35253. jassert (currentLine == document->lines.getUnchecked (line));
  35254. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35255. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35256. {
  35257. ++line;
  35258. currentLine = document->lines [line];
  35259. }
  35260. return result;
  35261. }
  35262. void CodeDocument::Iterator::skip()
  35263. {
  35264. if (currentLine != 0)
  35265. {
  35266. jassert (currentLine == document->lines.getUnchecked (line));
  35267. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35268. {
  35269. ++line;
  35270. currentLine = document->lines [line];
  35271. }
  35272. }
  35273. }
  35274. void CodeDocument::Iterator::skipToEndOfLine()
  35275. {
  35276. if (currentLine != 0)
  35277. {
  35278. jassert (currentLine == document->lines.getUnchecked (line));
  35279. ++line;
  35280. currentLine = document->lines [line];
  35281. if (currentLine != 0)
  35282. position = currentLine->lineStartInFile;
  35283. else
  35284. position = document->getNumCharacters();
  35285. }
  35286. }
  35287. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35288. {
  35289. if (currentLine == 0)
  35290. return 0;
  35291. jassert (currentLine == document->lines.getUnchecked (line));
  35292. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35293. }
  35294. void CodeDocument::Iterator::skipWhitespace()
  35295. {
  35296. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35297. skip();
  35298. }
  35299. bool CodeDocument::Iterator::isEOF() const throw()
  35300. {
  35301. return currentLine == 0;
  35302. }
  35303. CodeDocument::Position::Position() throw()
  35304. : owner (0), characterPos (0), line (0),
  35305. indexInLine (0), positionMaintained (false)
  35306. {
  35307. }
  35308. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35309. const int line_, const int indexInLine_) throw()
  35310. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35311. characterPos (0), line (line_),
  35312. indexInLine (indexInLine_), positionMaintained (false)
  35313. {
  35314. setLineAndIndex (line_, indexInLine_);
  35315. }
  35316. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35317. const int characterPos_) throw()
  35318. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35319. positionMaintained (false)
  35320. {
  35321. setPosition (characterPos_);
  35322. }
  35323. CodeDocument::Position::Position (const Position& other) throw()
  35324. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35325. indexInLine (other.indexInLine), positionMaintained (false)
  35326. {
  35327. jassert (*this == other);
  35328. }
  35329. CodeDocument::Position::~Position() throw()
  35330. {
  35331. setPositionMaintained (false);
  35332. }
  35333. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35334. {
  35335. if (this != &other)
  35336. {
  35337. const bool wasPositionMaintained = positionMaintained;
  35338. if (owner != other.owner)
  35339. setPositionMaintained (false);
  35340. owner = other.owner;
  35341. line = other.line;
  35342. indexInLine = other.indexInLine;
  35343. characterPos = other.characterPos;
  35344. setPositionMaintained (wasPositionMaintained);
  35345. jassert (*this == other);
  35346. }
  35347. return *this;
  35348. }
  35349. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35350. {
  35351. jassert ((characterPos == other.characterPos)
  35352. == (line == other.line && indexInLine == other.indexInLine));
  35353. return characterPos == other.characterPos
  35354. && line == other.line
  35355. && indexInLine == other.indexInLine
  35356. && owner == other.owner;
  35357. }
  35358. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35359. {
  35360. return ! operator== (other);
  35361. }
  35362. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35363. {
  35364. jassert (owner != 0);
  35365. if (owner->lines.size() == 0)
  35366. {
  35367. line = 0;
  35368. indexInLine = 0;
  35369. characterPos = 0;
  35370. }
  35371. else
  35372. {
  35373. if (newLine >= owner->lines.size())
  35374. {
  35375. line = owner->lines.size() - 1;
  35376. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35377. jassert (l != 0);
  35378. indexInLine = l->lineLengthWithoutNewLines;
  35379. characterPos = l->lineStartInFile + indexInLine;
  35380. }
  35381. else
  35382. {
  35383. line = jmax (0, newLine);
  35384. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35385. jassert (l != 0);
  35386. if (l->lineLengthWithoutNewLines > 0)
  35387. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35388. else
  35389. indexInLine = 0;
  35390. characterPos = l->lineStartInFile + indexInLine;
  35391. }
  35392. }
  35393. }
  35394. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35395. {
  35396. jassert (owner != 0);
  35397. line = 0;
  35398. indexInLine = 0;
  35399. characterPos = 0;
  35400. if (newPosition > 0)
  35401. {
  35402. int lineStart = 0;
  35403. int lineEnd = owner->lines.size();
  35404. for (;;)
  35405. {
  35406. if (lineEnd - lineStart < 4)
  35407. {
  35408. for (int i = lineStart; i < lineEnd; ++i)
  35409. {
  35410. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35411. int index = newPosition - l->lineStartInFile;
  35412. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35413. {
  35414. line = i;
  35415. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35416. characterPos = l->lineStartInFile + indexInLine;
  35417. }
  35418. }
  35419. break;
  35420. }
  35421. else
  35422. {
  35423. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35424. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35425. if (newPosition >= mid->lineStartInFile)
  35426. lineStart = midIndex;
  35427. else
  35428. lineEnd = midIndex;
  35429. }
  35430. }
  35431. }
  35432. }
  35433. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35434. {
  35435. jassert (owner != 0);
  35436. if (characterDelta == 1)
  35437. {
  35438. setPosition (getPosition());
  35439. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35440. if (line < owner->lines.size())
  35441. {
  35442. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35443. if (indexInLine + characterDelta < l->lineLength
  35444. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35445. ++characterDelta;
  35446. }
  35447. }
  35448. setPosition (characterPos + characterDelta);
  35449. }
  35450. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35451. {
  35452. CodeDocument::Position p (*this);
  35453. p.moveBy (characterDelta);
  35454. return p;
  35455. }
  35456. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35457. {
  35458. CodeDocument::Position p (*this);
  35459. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35460. return p;
  35461. }
  35462. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35463. {
  35464. const CodeDocumentLine* const l = owner->lines [line];
  35465. return l == 0 ? 0 : l->line [getIndexInLine()];
  35466. }
  35467. const String CodeDocument::Position::getLineText() const throw()
  35468. {
  35469. const CodeDocumentLine* const l = owner->lines [line];
  35470. return l == 0 ? String::empty : l->line;
  35471. }
  35472. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35473. {
  35474. if (isMaintained != positionMaintained)
  35475. {
  35476. positionMaintained = isMaintained;
  35477. if (owner != 0)
  35478. {
  35479. if (isMaintained)
  35480. {
  35481. jassert (! owner->positionsToMaintain.contains (this));
  35482. owner->positionsToMaintain.add (this);
  35483. }
  35484. else
  35485. {
  35486. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35487. jassert (owner->positionsToMaintain.contains (this));
  35488. owner->positionsToMaintain.removeValue (this);
  35489. }
  35490. }
  35491. }
  35492. }
  35493. CodeDocument::CodeDocument()
  35494. : undoManager (std::numeric_limits<int>::max(), 10000),
  35495. currentActionIndex (0),
  35496. indexOfSavedState (-1),
  35497. maximumLineLength (-1),
  35498. newLineChars ("\r\n")
  35499. {
  35500. }
  35501. CodeDocument::~CodeDocument()
  35502. {
  35503. }
  35504. const String CodeDocument::getAllContent() const throw()
  35505. {
  35506. return getTextBetween (Position (this, 0),
  35507. Position (this, lines.size(), 0));
  35508. }
  35509. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35510. {
  35511. if (end.getPosition() <= start.getPosition())
  35512. return String::empty;
  35513. const int startLine = start.getLineNumber();
  35514. const int endLine = end.getLineNumber();
  35515. if (startLine == endLine)
  35516. {
  35517. CodeDocumentLine* const line = lines [startLine];
  35518. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35519. }
  35520. String result;
  35521. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35522. String::Concatenator concatenator (result);
  35523. const int maxLine = jmin (lines.size() - 1, endLine);
  35524. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35525. {
  35526. const CodeDocumentLine* line = lines.getUnchecked(i);
  35527. int len = line->lineLength;
  35528. if (i == startLine)
  35529. {
  35530. const int index = start.getIndexInLine();
  35531. concatenator.append (line->line.substring (index, len));
  35532. }
  35533. else if (i == endLine)
  35534. {
  35535. len = end.getIndexInLine();
  35536. concatenator.append (line->line.substring (0, len));
  35537. }
  35538. else
  35539. {
  35540. concatenator.append (line->line);
  35541. }
  35542. }
  35543. return result;
  35544. }
  35545. int CodeDocument::getNumCharacters() const throw()
  35546. {
  35547. const CodeDocumentLine* const lastLine = lines.getLast();
  35548. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35549. }
  35550. const String CodeDocument::getLine (const int lineIndex) const throw()
  35551. {
  35552. const CodeDocumentLine* const line = lines [lineIndex];
  35553. return (line == 0) ? String::empty : line->line;
  35554. }
  35555. int CodeDocument::getMaximumLineLength() throw()
  35556. {
  35557. if (maximumLineLength < 0)
  35558. {
  35559. maximumLineLength = 0;
  35560. for (int i = lines.size(); --i >= 0;)
  35561. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35562. }
  35563. return maximumLineLength;
  35564. }
  35565. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35566. {
  35567. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35568. }
  35569. void CodeDocument::insertText (const Position& position, const String& text)
  35570. {
  35571. insert (text, position.getPosition(), true);
  35572. }
  35573. void CodeDocument::replaceAllContent (const String& newContent)
  35574. {
  35575. remove (0, getNumCharacters(), true);
  35576. insert (newContent, 0, true);
  35577. }
  35578. bool CodeDocument::loadFromStream (InputStream& stream)
  35579. {
  35580. replaceAllContent (stream.readEntireStreamAsString());
  35581. setSavePoint();
  35582. clearUndoHistory();
  35583. return true;
  35584. }
  35585. bool CodeDocument::writeToStream (OutputStream& stream)
  35586. {
  35587. for (int i = 0; i < lines.size(); ++i)
  35588. {
  35589. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35590. const char* utf8 = temp.toUTF8();
  35591. if (! stream.write (utf8, (int) strlen (utf8)))
  35592. return false;
  35593. }
  35594. return true;
  35595. }
  35596. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35597. {
  35598. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35599. newLineChars = newLine;
  35600. }
  35601. void CodeDocument::newTransaction()
  35602. {
  35603. undoManager.beginNewTransaction (String::empty);
  35604. }
  35605. void CodeDocument::undo()
  35606. {
  35607. newTransaction();
  35608. undoManager.undo();
  35609. }
  35610. void CodeDocument::redo()
  35611. {
  35612. undoManager.redo();
  35613. }
  35614. void CodeDocument::clearUndoHistory()
  35615. {
  35616. undoManager.clearUndoHistory();
  35617. }
  35618. void CodeDocument::setSavePoint() throw()
  35619. {
  35620. indexOfSavedState = currentActionIndex;
  35621. }
  35622. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35623. {
  35624. return currentActionIndex != indexOfSavedState;
  35625. }
  35626. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35627. {
  35628. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35629. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35630. }
  35631. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35632. {
  35633. Position p (position);
  35634. const int maxDistance = 256;
  35635. int i = 0;
  35636. while (i < maxDistance
  35637. && CharacterFunctions::isWhitespace (p.getCharacter())
  35638. && (i == 0 || (p.getCharacter() != '\n'
  35639. && p.getCharacter() != '\r')))
  35640. {
  35641. ++i;
  35642. p.moveBy (1);
  35643. }
  35644. if (i == 0)
  35645. {
  35646. const int type = getCodeCharacterCategory (p.getCharacter());
  35647. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35648. {
  35649. ++i;
  35650. p.moveBy (1);
  35651. }
  35652. while (i < maxDistance
  35653. && CharacterFunctions::isWhitespace (p.getCharacter())
  35654. && (i == 0 || (p.getCharacter() != '\n'
  35655. && p.getCharacter() != '\r')))
  35656. {
  35657. ++i;
  35658. p.moveBy (1);
  35659. }
  35660. }
  35661. return p;
  35662. }
  35663. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35664. {
  35665. Position p (position);
  35666. const int maxDistance = 256;
  35667. int i = 0;
  35668. bool stoppedAtLineStart = false;
  35669. while (i < maxDistance)
  35670. {
  35671. const juce_wchar c = p.movedBy (-1).getCharacter();
  35672. if (c == '\r' || c == '\n')
  35673. {
  35674. stoppedAtLineStart = true;
  35675. if (i > 0)
  35676. break;
  35677. }
  35678. if (! CharacterFunctions::isWhitespace (c))
  35679. break;
  35680. p.moveBy (-1);
  35681. ++i;
  35682. }
  35683. if (i < maxDistance && ! stoppedAtLineStart)
  35684. {
  35685. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35686. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35687. {
  35688. p.moveBy (-1);
  35689. ++i;
  35690. }
  35691. }
  35692. return p;
  35693. }
  35694. void CodeDocument::checkLastLineStatus()
  35695. {
  35696. while (lines.size() > 0
  35697. && lines.getLast()->lineLength == 0
  35698. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35699. {
  35700. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35701. lines.removeLast();
  35702. }
  35703. const CodeDocumentLine* const lastLine = lines.getLast();
  35704. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35705. {
  35706. // check that there's an empty line at the end if the preceding one ends in a newline..
  35707. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35708. }
  35709. }
  35710. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35711. {
  35712. listeners.add (listener);
  35713. }
  35714. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35715. {
  35716. listeners.remove (listener);
  35717. }
  35718. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35719. {
  35720. Position startPos (this, startLine, 0);
  35721. Position endPos (this, endLine, 0);
  35722. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35723. }
  35724. class CodeDocumentInsertAction : public UndoableAction
  35725. {
  35726. CodeDocument& owner;
  35727. const String text;
  35728. int insertPos;
  35729. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35730. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35731. public:
  35732. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35733. : owner (owner_),
  35734. text (text_),
  35735. insertPos (insertPos_)
  35736. {
  35737. }
  35738. ~CodeDocumentInsertAction() {}
  35739. bool perform()
  35740. {
  35741. owner.currentActionIndex++;
  35742. owner.insert (text, insertPos, false);
  35743. return true;
  35744. }
  35745. bool undo()
  35746. {
  35747. owner.currentActionIndex--;
  35748. owner.remove (insertPos, insertPos + text.length(), false);
  35749. return true;
  35750. }
  35751. int getSizeInUnits() { return text.length() + 32; }
  35752. };
  35753. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35754. {
  35755. if (text.isEmpty())
  35756. return;
  35757. if (undoable)
  35758. {
  35759. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35760. }
  35761. else
  35762. {
  35763. Position pos (this, insertPos);
  35764. const int firstAffectedLine = pos.getLineNumber();
  35765. int lastAffectedLine = firstAffectedLine + 1;
  35766. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35767. String textInsideOriginalLine (text);
  35768. if (firstLine != 0)
  35769. {
  35770. const int index = pos.getIndexInLine();
  35771. textInsideOriginalLine = firstLine->line.substring (0, index)
  35772. + textInsideOriginalLine
  35773. + firstLine->line.substring (index);
  35774. }
  35775. maximumLineLength = -1;
  35776. Array <CodeDocumentLine*> newLines;
  35777. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35778. jassert (newLines.size() > 0);
  35779. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35780. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35781. lines.set (firstAffectedLine, newFirstLine);
  35782. if (newLines.size() > 1)
  35783. {
  35784. for (int i = 1; i < newLines.size(); ++i)
  35785. {
  35786. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35787. lines.insert (firstAffectedLine + i, l);
  35788. }
  35789. lastAffectedLine = lines.size();
  35790. }
  35791. int i, lineStart = newFirstLine->lineStartInFile;
  35792. for (i = firstAffectedLine; i < lines.size(); ++i)
  35793. {
  35794. CodeDocumentLine* const l = lines.getUnchecked (i);
  35795. l->lineStartInFile = lineStart;
  35796. lineStart += l->lineLength;
  35797. }
  35798. checkLastLineStatus();
  35799. const int newTextLength = text.length();
  35800. for (i = 0; i < positionsToMaintain.size(); ++i)
  35801. {
  35802. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35803. if (p->getPosition() >= insertPos)
  35804. p->setPosition (p->getPosition() + newTextLength);
  35805. }
  35806. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35807. }
  35808. }
  35809. class CodeDocumentDeleteAction : public UndoableAction
  35810. {
  35811. CodeDocument& owner;
  35812. int startPos, endPos;
  35813. String removedText;
  35814. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35815. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35816. public:
  35817. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35818. : owner (owner_),
  35819. startPos (startPos_),
  35820. endPos (endPos_)
  35821. {
  35822. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35823. CodeDocument::Position (&owner, endPos));
  35824. }
  35825. ~CodeDocumentDeleteAction() {}
  35826. bool perform()
  35827. {
  35828. owner.currentActionIndex++;
  35829. owner.remove (startPos, endPos, false);
  35830. return true;
  35831. }
  35832. bool undo()
  35833. {
  35834. owner.currentActionIndex--;
  35835. owner.insert (removedText, startPos, false);
  35836. return true;
  35837. }
  35838. int getSizeInUnits() { return removedText.length() + 32; }
  35839. };
  35840. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35841. {
  35842. if (endPos <= startPos)
  35843. return;
  35844. if (undoable)
  35845. {
  35846. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35847. }
  35848. else
  35849. {
  35850. Position startPosition (this, startPos);
  35851. Position endPosition (this, endPos);
  35852. maximumLineLength = -1;
  35853. const int firstAffectedLine = startPosition.getLineNumber();
  35854. const int endLine = endPosition.getLineNumber();
  35855. int lastAffectedLine = firstAffectedLine + 1;
  35856. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35857. if (firstAffectedLine == endLine)
  35858. {
  35859. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35860. + firstLine->line.substring (endPosition.getIndexInLine());
  35861. firstLine->updateLength();
  35862. }
  35863. else
  35864. {
  35865. lastAffectedLine = lines.size();
  35866. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35867. jassert (lastLine != 0);
  35868. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35869. + lastLine->line.substring (endPosition.getIndexInLine());
  35870. firstLine->updateLength();
  35871. int numLinesToRemove = endLine - firstAffectedLine;
  35872. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35873. }
  35874. int i;
  35875. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35876. {
  35877. CodeDocumentLine* const l = lines.getUnchecked (i);
  35878. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35879. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35880. }
  35881. checkLastLineStatus();
  35882. const int totalChars = getNumCharacters();
  35883. for (i = 0; i < positionsToMaintain.size(); ++i)
  35884. {
  35885. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35886. if (p->getPosition() > startPosition.getPosition())
  35887. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35888. if (p->getPosition() > totalChars)
  35889. p->setPosition (totalChars);
  35890. }
  35891. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35892. }
  35893. }
  35894. END_JUCE_NAMESPACE
  35895. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35896. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35897. BEGIN_JUCE_NAMESPACE
  35898. class CodeEditorComponent::CaretComponent : public Component,
  35899. public Timer
  35900. {
  35901. public:
  35902. CaretComponent (CodeEditorComponent& owner_)
  35903. : owner (owner_)
  35904. {
  35905. setAlwaysOnTop (true);
  35906. setInterceptsMouseClicks (false, false);
  35907. }
  35908. ~CaretComponent()
  35909. {
  35910. }
  35911. void paint (Graphics& g)
  35912. {
  35913. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35914. }
  35915. void timerCallback()
  35916. {
  35917. setVisible (shouldBeShown() && ! isVisible());
  35918. }
  35919. void updatePosition()
  35920. {
  35921. startTimer (400);
  35922. setVisible (shouldBeShown());
  35923. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35924. }
  35925. private:
  35926. CodeEditorComponent& owner;
  35927. CaretComponent (const CaretComponent&);
  35928. CaretComponent& operator= (const CaretComponent&);
  35929. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35930. };
  35931. class CodeEditorComponent::CodeEditorLine
  35932. {
  35933. public:
  35934. CodeEditorLine() throw()
  35935. : highlightColumnStart (0), highlightColumnEnd (0)
  35936. {
  35937. }
  35938. ~CodeEditorLine() throw()
  35939. {
  35940. }
  35941. bool update (CodeDocument& document, int lineNum,
  35942. CodeDocument::Iterator& source,
  35943. CodeTokeniser* analyser, const int spacesPerTab,
  35944. const CodeDocument::Position& selectionStart,
  35945. const CodeDocument::Position& selectionEnd)
  35946. {
  35947. Array <SyntaxToken> newTokens;
  35948. newTokens.ensureStorageAllocated (8);
  35949. if (analyser == 0)
  35950. {
  35951. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35952. }
  35953. else if (lineNum < document.getNumLines())
  35954. {
  35955. const CodeDocument::Position pos (&document, lineNum, 0);
  35956. createTokens (pos.getPosition(), pos.getLineText(),
  35957. source, analyser, newTokens);
  35958. }
  35959. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35960. int newHighlightStart = 0;
  35961. int newHighlightEnd = 0;
  35962. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35963. {
  35964. const String line (document.getLine (lineNum));
  35965. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35966. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35967. line, spacesPerTab);
  35968. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35969. line, spacesPerTab);
  35970. }
  35971. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35972. {
  35973. highlightColumnStart = newHighlightStart;
  35974. highlightColumnEnd = newHighlightEnd;
  35975. }
  35976. else
  35977. {
  35978. if (tokens.size() == newTokens.size())
  35979. {
  35980. bool allTheSame = true;
  35981. for (int i = newTokens.size(); --i >= 0;)
  35982. {
  35983. if (tokens.getReference(i) != newTokens.getReference(i))
  35984. {
  35985. allTheSame = false;
  35986. break;
  35987. }
  35988. }
  35989. if (allTheSame)
  35990. return false;
  35991. }
  35992. }
  35993. tokens.swapWithArray (newTokens);
  35994. return true;
  35995. }
  35996. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35997. float x, const int y, const int baselineOffset, const int lineHeight,
  35998. const Colour& highlightColour) const throw()
  35999. {
  36000. if (highlightColumnStart < highlightColumnEnd)
  36001. {
  36002. g.setColour (highlightColour);
  36003. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36004. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36005. }
  36006. int lastType = std::numeric_limits<int>::min();
  36007. for (int i = 0; i < tokens.size(); ++i)
  36008. {
  36009. SyntaxToken& token = tokens.getReference(i);
  36010. if (lastType != token.tokenType)
  36011. {
  36012. lastType = token.tokenType;
  36013. g.setColour (owner.getColourForTokenType (lastType));
  36014. }
  36015. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36016. if (i < tokens.size() - 1)
  36017. {
  36018. if (token.width < 0)
  36019. token.width = font.getStringWidthFloat (token.text);
  36020. x += token.width;
  36021. }
  36022. }
  36023. }
  36024. private:
  36025. struct SyntaxToken
  36026. {
  36027. String text;
  36028. int tokenType;
  36029. float width;
  36030. SyntaxToken (const String& text_, const int type) throw()
  36031. : text (text_), tokenType (type), width (-1.0f)
  36032. {
  36033. }
  36034. bool operator!= (const SyntaxToken& other) const throw()
  36035. {
  36036. return text != other.text || tokenType != other.tokenType;
  36037. }
  36038. };
  36039. Array <SyntaxToken> tokens;
  36040. int highlightColumnStart, highlightColumnEnd;
  36041. static void createTokens (int startPosition, const String& lineText,
  36042. CodeDocument::Iterator& source,
  36043. CodeTokeniser* analyser,
  36044. Array <SyntaxToken>& newTokens)
  36045. {
  36046. CodeDocument::Iterator lastIterator (source);
  36047. const int lineLength = lineText.length();
  36048. for (;;)
  36049. {
  36050. int tokenType = analyser->readNextToken (source);
  36051. int tokenStart = lastIterator.getPosition();
  36052. int tokenEnd = source.getPosition();
  36053. if (tokenEnd <= tokenStart)
  36054. break;
  36055. tokenEnd -= startPosition;
  36056. if (tokenEnd > 0)
  36057. {
  36058. tokenStart -= startPosition;
  36059. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36060. tokenType));
  36061. if (tokenEnd >= lineLength)
  36062. break;
  36063. }
  36064. lastIterator = source;
  36065. }
  36066. source = lastIterator;
  36067. }
  36068. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  36069. {
  36070. int x = 0;
  36071. for (int i = 0; i < tokens.size(); ++i)
  36072. {
  36073. SyntaxToken& t = tokens.getReference(i);
  36074. for (;;)
  36075. {
  36076. int tabPos = t.text.indexOfChar ('\t');
  36077. if (tabPos < 0)
  36078. break;
  36079. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36080. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36081. }
  36082. x += t.text.length();
  36083. }
  36084. }
  36085. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36086. {
  36087. jassert (index <= line.length());
  36088. int col = 0;
  36089. for (int i = 0; i < index; ++i)
  36090. {
  36091. if (line[i] != '\t')
  36092. ++col;
  36093. else
  36094. col += spacesPerTab - (col % spacesPerTab);
  36095. }
  36096. return col;
  36097. }
  36098. };
  36099. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36100. CodeTokeniser* const codeTokeniser_)
  36101. : document (document_),
  36102. firstLineOnScreen (0),
  36103. gutter (5),
  36104. spacesPerTab (4),
  36105. lineHeight (0),
  36106. linesOnScreen (0),
  36107. columnsOnScreen (0),
  36108. scrollbarThickness (16),
  36109. columnToTryToMaintain (-1),
  36110. useSpacesForTabs (false),
  36111. xOffset (0),
  36112. codeTokeniser (codeTokeniser_)
  36113. {
  36114. caretPos = CodeDocument::Position (&document_, 0, 0);
  36115. caretPos.setPositionMaintained (true);
  36116. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36117. selectionStart.setPositionMaintained (true);
  36118. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36119. selectionEnd.setPositionMaintained (true);
  36120. setOpaque (true);
  36121. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36122. setWantsKeyboardFocus (true);
  36123. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36124. verticalScrollBar->setSingleStepSize (1.0);
  36125. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36126. horizontalScrollBar->setSingleStepSize (1.0);
  36127. addAndMakeVisible (caret = new CaretComponent (*this));
  36128. Font f (12.0f);
  36129. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36130. setFont (f);
  36131. resetToDefaultColours();
  36132. verticalScrollBar->addListener (this);
  36133. horizontalScrollBar->addListener (this);
  36134. document.addListener (this);
  36135. }
  36136. CodeEditorComponent::~CodeEditorComponent()
  36137. {
  36138. document.removeListener (this);
  36139. deleteAllChildren();
  36140. }
  36141. void CodeEditorComponent::loadContent (const String& newContent)
  36142. {
  36143. clearCachedIterators (0);
  36144. document.replaceAllContent (newContent);
  36145. document.clearUndoHistory();
  36146. document.setSavePoint();
  36147. caretPos.setPosition (0);
  36148. selectionStart.setPosition (0);
  36149. selectionEnd.setPosition (0);
  36150. scrollToLine (0);
  36151. }
  36152. bool CodeEditorComponent::isTextInputActive() const
  36153. {
  36154. return true;
  36155. }
  36156. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36157. const CodeDocument::Position& affectedTextEnd)
  36158. {
  36159. clearCachedIterators (affectedTextStart.getLineNumber());
  36160. triggerAsyncUpdate();
  36161. caret->updatePosition();
  36162. columnToTryToMaintain = -1;
  36163. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36164. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36165. deselectAll();
  36166. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36167. || caretPos.getPosition() < affectedTextStart.getPosition())
  36168. moveCaretTo (affectedTextStart, false);
  36169. updateScrollBars();
  36170. }
  36171. void CodeEditorComponent::resized()
  36172. {
  36173. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36174. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36175. lines.clear();
  36176. rebuildLineTokens();
  36177. caret->updatePosition();
  36178. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36179. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36180. updateScrollBars();
  36181. }
  36182. void CodeEditorComponent::paint (Graphics& g)
  36183. {
  36184. handleUpdateNowIfNeeded();
  36185. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36186. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36187. g.setFont (font);
  36188. const int baselineOffset = (int) font.getAscent();
  36189. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36190. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36191. const Rectangle<int> clip (g.getClipBounds());
  36192. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36193. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36194. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36195. {
  36196. lines.getUnchecked(j)->draw (*this, g, font,
  36197. (float) (gutter - xOffset * charWidth),
  36198. lineHeight * j, baselineOffset, lineHeight,
  36199. highlightColour);
  36200. }
  36201. }
  36202. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36203. {
  36204. if (scrollbarThickness != thickness)
  36205. {
  36206. scrollbarThickness = thickness;
  36207. resized();
  36208. }
  36209. }
  36210. void CodeEditorComponent::handleAsyncUpdate()
  36211. {
  36212. rebuildLineTokens();
  36213. }
  36214. void CodeEditorComponent::rebuildLineTokens()
  36215. {
  36216. cancelPendingUpdate();
  36217. const int numNeeded = linesOnScreen + 1;
  36218. int minLineToRepaint = numNeeded;
  36219. int maxLineToRepaint = 0;
  36220. if (numNeeded != lines.size())
  36221. {
  36222. lines.clear();
  36223. for (int i = numNeeded; --i >= 0;)
  36224. lines.add (new CodeEditorLine());
  36225. minLineToRepaint = 0;
  36226. maxLineToRepaint = numNeeded;
  36227. }
  36228. jassert (numNeeded == lines.size());
  36229. CodeDocument::Iterator source (&document);
  36230. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36231. for (int i = 0; i < numNeeded; ++i)
  36232. {
  36233. CodeEditorLine* const line = lines.getUnchecked(i);
  36234. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36235. selectionStart, selectionEnd))
  36236. {
  36237. minLineToRepaint = jmin (minLineToRepaint, i);
  36238. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36239. }
  36240. }
  36241. if (minLineToRepaint <= maxLineToRepaint)
  36242. {
  36243. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36244. verticalScrollBar->getX() - gutter,
  36245. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36246. }
  36247. }
  36248. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36249. {
  36250. caretPos = newPos;
  36251. columnToTryToMaintain = -1;
  36252. if (highlighting)
  36253. {
  36254. if (dragType == notDragging)
  36255. {
  36256. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36257. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36258. dragType = draggingSelectionStart;
  36259. else
  36260. dragType = draggingSelectionEnd;
  36261. }
  36262. if (dragType == draggingSelectionStart)
  36263. {
  36264. selectionStart = caretPos;
  36265. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36266. {
  36267. const CodeDocument::Position temp (selectionStart);
  36268. selectionStart = selectionEnd;
  36269. selectionEnd = temp;
  36270. dragType = draggingSelectionEnd;
  36271. }
  36272. }
  36273. else
  36274. {
  36275. selectionEnd = caretPos;
  36276. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36277. {
  36278. const CodeDocument::Position temp (selectionStart);
  36279. selectionStart = selectionEnd;
  36280. selectionEnd = temp;
  36281. dragType = draggingSelectionStart;
  36282. }
  36283. }
  36284. triggerAsyncUpdate();
  36285. }
  36286. else
  36287. {
  36288. deselectAll();
  36289. }
  36290. caret->updatePosition();
  36291. scrollToKeepCaretOnScreen();
  36292. updateScrollBars();
  36293. }
  36294. void CodeEditorComponent::deselectAll()
  36295. {
  36296. if (selectionStart != selectionEnd)
  36297. triggerAsyncUpdate();
  36298. selectionStart = caretPos;
  36299. selectionEnd = caretPos;
  36300. }
  36301. void CodeEditorComponent::updateScrollBars()
  36302. {
  36303. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36304. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36305. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36306. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36307. }
  36308. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36309. {
  36310. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36311. newFirstLineOnScreen);
  36312. if (newFirstLineOnScreen != firstLineOnScreen)
  36313. {
  36314. firstLineOnScreen = newFirstLineOnScreen;
  36315. caret->updatePosition();
  36316. updateCachedIterators (firstLineOnScreen);
  36317. triggerAsyncUpdate();
  36318. }
  36319. }
  36320. void CodeEditorComponent::scrollToColumnInternal (double column)
  36321. {
  36322. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36323. if (xOffset != newOffset)
  36324. {
  36325. xOffset = newOffset;
  36326. caret->updatePosition();
  36327. repaint();
  36328. }
  36329. }
  36330. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36331. {
  36332. scrollToLineInternal (newFirstLineOnScreen);
  36333. updateScrollBars();
  36334. }
  36335. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36336. {
  36337. scrollToColumnInternal (newFirstColumnOnScreen);
  36338. updateScrollBars();
  36339. }
  36340. void CodeEditorComponent::scrollBy (int deltaLines)
  36341. {
  36342. scrollToLine (firstLineOnScreen + deltaLines);
  36343. }
  36344. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36345. {
  36346. if (caretPos.getLineNumber() < firstLineOnScreen)
  36347. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36348. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36349. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36350. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36351. if (column >= xOffset + columnsOnScreen - 1)
  36352. scrollToColumn (column + 1 - columnsOnScreen);
  36353. else if (column < xOffset)
  36354. scrollToColumn (column);
  36355. }
  36356. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36357. {
  36358. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36359. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36360. roundToInt (charWidth),
  36361. lineHeight);
  36362. }
  36363. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36364. {
  36365. const int line = y / lineHeight + firstLineOnScreen;
  36366. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36367. const int index = columnToIndex (line, column);
  36368. return CodeDocument::Position (&document, line, index);
  36369. }
  36370. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36371. {
  36372. document.deleteSection (selectionStart, selectionEnd);
  36373. if (newText.isNotEmpty())
  36374. document.insertText (caretPos, newText);
  36375. scrollToKeepCaretOnScreen();
  36376. }
  36377. void CodeEditorComponent::insertTabAtCaret()
  36378. {
  36379. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36380. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36381. {
  36382. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36383. }
  36384. if (useSpacesForTabs)
  36385. {
  36386. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36387. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36388. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36389. }
  36390. else
  36391. {
  36392. insertTextAtCaret ("\t");
  36393. }
  36394. }
  36395. void CodeEditorComponent::cut()
  36396. {
  36397. insertTextAtCaret (String::empty);
  36398. }
  36399. void CodeEditorComponent::copy()
  36400. {
  36401. newTransaction();
  36402. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36403. if (selection.isNotEmpty())
  36404. SystemClipboard::copyTextToClipboard (selection);
  36405. }
  36406. void CodeEditorComponent::copyThenCut()
  36407. {
  36408. copy();
  36409. cut();
  36410. newTransaction();
  36411. }
  36412. void CodeEditorComponent::paste()
  36413. {
  36414. newTransaction();
  36415. const String clip (SystemClipboard::getTextFromClipboard());
  36416. if (clip.isNotEmpty())
  36417. insertTextAtCaret (clip);
  36418. newTransaction();
  36419. }
  36420. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36421. {
  36422. newTransaction();
  36423. if (moveInWholeWordSteps)
  36424. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36425. else
  36426. moveCaretTo (caretPos.movedBy (-1), selecting);
  36427. }
  36428. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36429. {
  36430. newTransaction();
  36431. if (moveInWholeWordSteps)
  36432. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36433. else
  36434. moveCaretTo (caretPos.movedBy (1), selecting);
  36435. }
  36436. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36437. {
  36438. CodeDocument::Position pos (caretPos);
  36439. const int newLineNum = pos.getLineNumber() + delta;
  36440. if (columnToTryToMaintain < 0)
  36441. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36442. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36443. const int colToMaintain = columnToTryToMaintain;
  36444. moveCaretTo (pos, selecting);
  36445. columnToTryToMaintain = colToMaintain;
  36446. }
  36447. void CodeEditorComponent::cursorDown (const bool selecting)
  36448. {
  36449. newTransaction();
  36450. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36451. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36452. else
  36453. moveLineDelta (1, selecting);
  36454. }
  36455. void CodeEditorComponent::cursorUp (const bool selecting)
  36456. {
  36457. newTransaction();
  36458. if (caretPos.getLineNumber() == 0)
  36459. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36460. else
  36461. moveLineDelta (-1, selecting);
  36462. }
  36463. void CodeEditorComponent::pageDown (const bool selecting)
  36464. {
  36465. newTransaction();
  36466. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36467. moveLineDelta (linesOnScreen, selecting);
  36468. }
  36469. void CodeEditorComponent::pageUp (const bool selecting)
  36470. {
  36471. newTransaction();
  36472. scrollBy (-linesOnScreen);
  36473. moveLineDelta (-linesOnScreen, selecting);
  36474. }
  36475. void CodeEditorComponent::scrollUp()
  36476. {
  36477. newTransaction();
  36478. scrollBy (1);
  36479. if (caretPos.getLineNumber() < firstLineOnScreen)
  36480. moveLineDelta (1, false);
  36481. }
  36482. void CodeEditorComponent::scrollDown()
  36483. {
  36484. newTransaction();
  36485. scrollBy (-1);
  36486. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36487. moveLineDelta (-1, false);
  36488. }
  36489. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36490. {
  36491. newTransaction();
  36492. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36493. }
  36494. static int findFirstNonWhitespaceChar (const String& line) throw()
  36495. {
  36496. const int len = line.length();
  36497. for (int i = 0; i < len; ++i)
  36498. if (! CharacterFunctions::isWhitespace (line [i]))
  36499. return i;
  36500. return 0;
  36501. }
  36502. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36503. {
  36504. newTransaction();
  36505. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36506. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36507. index = 0;
  36508. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36509. }
  36510. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36511. {
  36512. newTransaction();
  36513. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36514. }
  36515. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36516. {
  36517. newTransaction();
  36518. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36519. }
  36520. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36521. {
  36522. if (moveInWholeWordSteps)
  36523. {
  36524. cut(); // in case something is already highlighted
  36525. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36526. }
  36527. else
  36528. {
  36529. if (selectionStart == selectionEnd)
  36530. selectionStart.moveBy (-1);
  36531. }
  36532. cut();
  36533. }
  36534. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36535. {
  36536. if (moveInWholeWordSteps)
  36537. {
  36538. cut(); // in case something is already highlighted
  36539. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36540. }
  36541. else
  36542. {
  36543. if (selectionStart == selectionEnd)
  36544. selectionEnd.moveBy (1);
  36545. else
  36546. newTransaction();
  36547. }
  36548. cut();
  36549. }
  36550. void CodeEditorComponent::selectAll()
  36551. {
  36552. newTransaction();
  36553. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36554. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36555. }
  36556. void CodeEditorComponent::undo()
  36557. {
  36558. document.undo();
  36559. scrollToKeepCaretOnScreen();
  36560. }
  36561. void CodeEditorComponent::redo()
  36562. {
  36563. document.redo();
  36564. scrollToKeepCaretOnScreen();
  36565. }
  36566. void CodeEditorComponent::newTransaction()
  36567. {
  36568. document.newTransaction();
  36569. startTimer (600);
  36570. }
  36571. void CodeEditorComponent::timerCallback()
  36572. {
  36573. newTransaction();
  36574. }
  36575. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36576. {
  36577. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36578. }
  36579. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36580. {
  36581. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36582. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36583. }
  36584. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36585. {
  36586. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36587. CodeDocument::Position (&document, range.getEnd()));
  36588. }
  36589. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36590. {
  36591. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36592. const bool shiftDown = key.getModifiers().isShiftDown();
  36593. if (key.isKeyCode (KeyPress::leftKey))
  36594. {
  36595. cursorLeft (moveInWholeWordSteps, shiftDown);
  36596. }
  36597. else if (key.isKeyCode (KeyPress::rightKey))
  36598. {
  36599. cursorRight (moveInWholeWordSteps, shiftDown);
  36600. }
  36601. else if (key.isKeyCode (KeyPress::upKey))
  36602. {
  36603. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36604. scrollDown();
  36605. #if JUCE_MAC
  36606. else if (key.getModifiers().isCommandDown())
  36607. goToStartOfDocument (shiftDown);
  36608. #endif
  36609. else
  36610. cursorUp (shiftDown);
  36611. }
  36612. else if (key.isKeyCode (KeyPress::downKey))
  36613. {
  36614. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36615. scrollUp();
  36616. #if JUCE_MAC
  36617. else if (key.getModifiers().isCommandDown())
  36618. goToEndOfDocument (shiftDown);
  36619. #endif
  36620. else
  36621. cursorDown (shiftDown);
  36622. }
  36623. else if (key.isKeyCode (KeyPress::pageDownKey))
  36624. {
  36625. pageDown (shiftDown);
  36626. }
  36627. else if (key.isKeyCode (KeyPress::pageUpKey))
  36628. {
  36629. pageUp (shiftDown);
  36630. }
  36631. else if (key.isKeyCode (KeyPress::homeKey))
  36632. {
  36633. if (moveInWholeWordSteps)
  36634. goToStartOfDocument (shiftDown);
  36635. else
  36636. goToStartOfLine (shiftDown);
  36637. }
  36638. else if (key.isKeyCode (KeyPress::endKey))
  36639. {
  36640. if (moveInWholeWordSteps)
  36641. goToEndOfDocument (shiftDown);
  36642. else
  36643. goToEndOfLine (shiftDown);
  36644. }
  36645. else if (key.isKeyCode (KeyPress::backspaceKey))
  36646. {
  36647. backspace (moveInWholeWordSteps);
  36648. }
  36649. else if (key.isKeyCode (KeyPress::deleteKey))
  36650. {
  36651. deleteForward (moveInWholeWordSteps);
  36652. }
  36653. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36654. {
  36655. copy();
  36656. }
  36657. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36658. {
  36659. copyThenCut();
  36660. }
  36661. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36662. {
  36663. paste();
  36664. }
  36665. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36666. {
  36667. undo();
  36668. }
  36669. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36670. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36671. {
  36672. redo();
  36673. }
  36674. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36675. {
  36676. selectAll();
  36677. }
  36678. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36679. {
  36680. insertTabAtCaret();
  36681. }
  36682. else if (key == KeyPress::returnKey)
  36683. {
  36684. newTransaction();
  36685. insertTextAtCaret (document.getNewLineCharacters());
  36686. }
  36687. else if (key.isKeyCode (KeyPress::escapeKey))
  36688. {
  36689. newTransaction();
  36690. }
  36691. else if (key.getTextCharacter() >= ' ')
  36692. {
  36693. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36694. }
  36695. else
  36696. {
  36697. return false;
  36698. }
  36699. return true;
  36700. }
  36701. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36702. {
  36703. newTransaction();
  36704. dragType = notDragging;
  36705. if (! e.mods.isPopupMenu())
  36706. {
  36707. beginDragAutoRepeat (100);
  36708. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36709. }
  36710. else
  36711. {
  36712. /*PopupMenu m;
  36713. addPopupMenuItems (m, &e);
  36714. const int result = m.show();
  36715. if (result != 0)
  36716. performPopupMenuAction (result);
  36717. */
  36718. }
  36719. }
  36720. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36721. {
  36722. if (! e.mods.isPopupMenu())
  36723. moveCaretTo (getPositionAt (e.x, e.y), true);
  36724. }
  36725. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36726. {
  36727. newTransaction();
  36728. beginDragAutoRepeat (0);
  36729. dragType = notDragging;
  36730. }
  36731. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36732. {
  36733. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36734. CodeDocument::Position tokenEnd (tokenStart);
  36735. if (e.getNumberOfClicks() > 2)
  36736. {
  36737. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36738. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36739. }
  36740. else
  36741. {
  36742. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36743. tokenEnd.moveBy (1);
  36744. tokenStart = tokenEnd;
  36745. while (tokenStart.getIndexInLine() > 0
  36746. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36747. tokenStart.moveBy (-1);
  36748. }
  36749. moveCaretTo (tokenEnd, false);
  36750. moveCaretTo (tokenStart, true);
  36751. }
  36752. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36753. {
  36754. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36755. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36756. {
  36757. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36758. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36759. }
  36760. else
  36761. {
  36762. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36763. }
  36764. }
  36765. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36766. {
  36767. if (scrollBarThatHasMoved == verticalScrollBar)
  36768. scrollToLineInternal ((int) newRangeStart);
  36769. else
  36770. scrollToColumnInternal (newRangeStart);
  36771. }
  36772. void CodeEditorComponent::focusGained (FocusChangeType)
  36773. {
  36774. caret->updatePosition();
  36775. }
  36776. void CodeEditorComponent::focusLost (FocusChangeType)
  36777. {
  36778. caret->updatePosition();
  36779. }
  36780. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36781. {
  36782. useSpacesForTabs = insertSpaces;
  36783. if (spacesPerTab != numSpaces)
  36784. {
  36785. spacesPerTab = numSpaces;
  36786. triggerAsyncUpdate();
  36787. }
  36788. }
  36789. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36790. {
  36791. const String line (document.getLine (lineNum));
  36792. jassert (index <= line.length());
  36793. int col = 0;
  36794. for (int i = 0; i < index; ++i)
  36795. {
  36796. if (line[i] != '\t')
  36797. ++col;
  36798. else
  36799. col += getTabSize() - (col % getTabSize());
  36800. }
  36801. return col;
  36802. }
  36803. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36804. {
  36805. const String line (document.getLine (lineNum));
  36806. const int lineLength = line.length();
  36807. int i, col = 0;
  36808. for (i = 0; i < lineLength; ++i)
  36809. {
  36810. if (line[i] != '\t')
  36811. ++col;
  36812. else
  36813. col += getTabSize() - (col % getTabSize());
  36814. if (col > column)
  36815. break;
  36816. }
  36817. return i;
  36818. }
  36819. void CodeEditorComponent::setFont (const Font& newFont)
  36820. {
  36821. font = newFont;
  36822. charWidth = font.getStringWidthFloat ("0");
  36823. lineHeight = roundToInt (font.getHeight());
  36824. resized();
  36825. }
  36826. void CodeEditorComponent::resetToDefaultColours()
  36827. {
  36828. coloursForTokenCategories.clear();
  36829. if (codeTokeniser != 0)
  36830. {
  36831. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36832. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36833. }
  36834. }
  36835. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36836. {
  36837. jassert (tokenType < 256);
  36838. while (coloursForTokenCategories.size() < tokenType)
  36839. coloursForTokenCategories.add (Colours::black);
  36840. coloursForTokenCategories.set (tokenType, colour);
  36841. repaint();
  36842. }
  36843. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36844. {
  36845. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36846. return findColour (CodeEditorComponent::defaultTextColourId);
  36847. return coloursForTokenCategories.getReference (tokenType);
  36848. }
  36849. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36850. {
  36851. int i;
  36852. for (i = cachedIterators.size(); --i >= 0;)
  36853. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36854. break;
  36855. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36856. }
  36857. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36858. {
  36859. const int maxNumCachedPositions = 5000;
  36860. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36861. if (cachedIterators.size() == 0)
  36862. cachedIterators.add (new CodeDocument::Iterator (&document));
  36863. if (codeTokeniser == 0)
  36864. return;
  36865. for (;;)
  36866. {
  36867. CodeDocument::Iterator* last = cachedIterators.getLast();
  36868. if (last->getLine() >= maxLineNum)
  36869. break;
  36870. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36871. cachedIterators.add (t);
  36872. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36873. for (;;)
  36874. {
  36875. codeTokeniser->readNextToken (*t);
  36876. if (t->getLine() >= targetLine)
  36877. break;
  36878. if (t->isEOF())
  36879. return;
  36880. }
  36881. }
  36882. }
  36883. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36884. {
  36885. if (codeTokeniser == 0)
  36886. return;
  36887. for (int i = cachedIterators.size(); --i >= 0;)
  36888. {
  36889. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36890. if (t->getPosition() <= position)
  36891. {
  36892. source = *t;
  36893. break;
  36894. }
  36895. }
  36896. while (source.getPosition() < position)
  36897. {
  36898. const CodeDocument::Iterator original (source);
  36899. codeTokeniser->readNextToken (source);
  36900. if (source.getPosition() > position || source.isEOF())
  36901. {
  36902. source = original;
  36903. break;
  36904. }
  36905. }
  36906. }
  36907. END_JUCE_NAMESPACE
  36908. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36909. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36910. BEGIN_JUCE_NAMESPACE
  36911. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36912. {
  36913. }
  36914. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36915. {
  36916. }
  36917. namespace CppTokeniser
  36918. {
  36919. static bool isIdentifierStart (const juce_wchar c) throw()
  36920. {
  36921. return CharacterFunctions::isLetter (c)
  36922. || c == '_' || c == '@';
  36923. }
  36924. static bool isIdentifierBody (const juce_wchar c) throw()
  36925. {
  36926. return CharacterFunctions::isLetterOrDigit (c)
  36927. || c == '_' || c == '@';
  36928. }
  36929. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36930. {
  36931. static const juce_wchar* const keywords2Char[] =
  36932. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36933. static const juce_wchar* const keywords3Char[] =
  36934. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  36935. static const juce_wchar* const keywords4Char[] =
  36936. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36937. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36938. static const juce_wchar* const keywords5Char[] =
  36939. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36940. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36941. static const juce_wchar* const keywords6Char[] =
  36942. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36943. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36944. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36945. static const juce_wchar* const keywordsOther[] =
  36946. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36947. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36948. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36949. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36950. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36951. const juce_wchar* const* k;
  36952. switch (tokenLength)
  36953. {
  36954. case 2: k = keywords2Char; break;
  36955. case 3: k = keywords3Char; break;
  36956. case 4: k = keywords4Char; break;
  36957. case 5: k = keywords5Char; break;
  36958. case 6: k = keywords6Char; break;
  36959. default:
  36960. if (tokenLength < 2 || tokenLength > 16)
  36961. return false;
  36962. k = keywordsOther;
  36963. break;
  36964. }
  36965. int i = 0;
  36966. while (k[i] != 0)
  36967. {
  36968. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36969. return true;
  36970. ++i;
  36971. }
  36972. return false;
  36973. }
  36974. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36975. {
  36976. int tokenLength = 0;
  36977. juce_wchar possibleIdentifier [19];
  36978. while (isIdentifierBody (source.peekNextChar()))
  36979. {
  36980. const juce_wchar c = source.nextChar();
  36981. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36982. possibleIdentifier [tokenLength] = c;
  36983. ++tokenLength;
  36984. }
  36985. if (tokenLength > 1 && tokenLength <= 16)
  36986. {
  36987. possibleIdentifier [tokenLength] = 0;
  36988. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36989. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36990. }
  36991. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36992. }
  36993. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36994. {
  36995. const juce_wchar c = source.peekNextChar();
  36996. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36997. source.skip();
  36998. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36999. return false;
  37000. return true;
  37001. }
  37002. static bool isHexDigit (const juce_wchar c) throw()
  37003. {
  37004. return (c >= '0' && c <= '9')
  37005. || (c >= 'a' && c <= 'f')
  37006. || (c >= 'A' && c <= 'F');
  37007. }
  37008. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37009. {
  37010. if (source.nextChar() != '0')
  37011. return false;
  37012. juce_wchar c = source.nextChar();
  37013. if (c != 'x' && c != 'X')
  37014. return false;
  37015. int numDigits = 0;
  37016. while (isHexDigit (source.peekNextChar()))
  37017. {
  37018. ++numDigits;
  37019. source.skip();
  37020. }
  37021. if (numDigits == 0)
  37022. return false;
  37023. return skipNumberSuffix (source);
  37024. }
  37025. static bool isOctalDigit (const juce_wchar c) throw()
  37026. {
  37027. return c >= '0' && c <= '7';
  37028. }
  37029. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37030. {
  37031. if (source.nextChar() != '0')
  37032. return false;
  37033. if (! isOctalDigit (source.nextChar()))
  37034. return false;
  37035. while (isOctalDigit (source.peekNextChar()))
  37036. source.skip();
  37037. return skipNumberSuffix (source);
  37038. }
  37039. static bool isDecimalDigit (const juce_wchar c) throw()
  37040. {
  37041. return c >= '0' && c <= '9';
  37042. }
  37043. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37044. {
  37045. int numChars = 0;
  37046. while (isDecimalDigit (source.peekNextChar()))
  37047. {
  37048. ++numChars;
  37049. source.skip();
  37050. }
  37051. if (numChars == 0)
  37052. return false;
  37053. return skipNumberSuffix (source);
  37054. }
  37055. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37056. {
  37057. int numDigits = 0;
  37058. while (isDecimalDigit (source.peekNextChar()))
  37059. {
  37060. source.skip();
  37061. ++numDigits;
  37062. }
  37063. const bool hasPoint = (source.peekNextChar() == '.');
  37064. if (hasPoint)
  37065. {
  37066. source.skip();
  37067. while (isDecimalDigit (source.peekNextChar()))
  37068. {
  37069. source.skip();
  37070. ++numDigits;
  37071. }
  37072. }
  37073. if (numDigits == 0)
  37074. return false;
  37075. juce_wchar c = source.peekNextChar();
  37076. const bool hasExponent = (c == 'e' || c == 'E');
  37077. if (hasExponent)
  37078. {
  37079. source.skip();
  37080. c = source.peekNextChar();
  37081. if (c == '+' || c == '-')
  37082. source.skip();
  37083. int numExpDigits = 0;
  37084. while (isDecimalDigit (source.peekNextChar()))
  37085. {
  37086. source.skip();
  37087. ++numExpDigits;
  37088. }
  37089. if (numExpDigits == 0)
  37090. return false;
  37091. }
  37092. c = source.peekNextChar();
  37093. if (c == 'f' || c == 'F')
  37094. source.skip();
  37095. else if (! (hasExponent || hasPoint))
  37096. return false;
  37097. return true;
  37098. }
  37099. static int parseNumber (CodeDocument::Iterator& source)
  37100. {
  37101. const CodeDocument::Iterator original (source);
  37102. if (parseFloatLiteral (source))
  37103. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37104. source = original;
  37105. if (parseHexLiteral (source))
  37106. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37107. source = original;
  37108. if (parseOctalLiteral (source))
  37109. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37110. source = original;
  37111. if (parseDecimalLiteral (source))
  37112. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37113. source = original;
  37114. source.skip();
  37115. return CPlusPlusCodeTokeniser::tokenType_error;
  37116. }
  37117. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37118. {
  37119. const juce_wchar quote = source.nextChar();
  37120. for (;;)
  37121. {
  37122. const juce_wchar c = source.nextChar();
  37123. if (c == quote || c == 0)
  37124. break;
  37125. if (c == '\\')
  37126. source.skip();
  37127. }
  37128. }
  37129. static void skipComment (CodeDocument::Iterator& source) throw()
  37130. {
  37131. bool lastWasStar = false;
  37132. for (;;)
  37133. {
  37134. const juce_wchar c = source.nextChar();
  37135. if (c == 0 || (c == '/' && lastWasStar))
  37136. break;
  37137. lastWasStar = (c == '*');
  37138. }
  37139. }
  37140. }
  37141. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37142. {
  37143. int result = tokenType_error;
  37144. source.skipWhitespace();
  37145. juce_wchar firstChar = source.peekNextChar();
  37146. switch (firstChar)
  37147. {
  37148. case 0:
  37149. source.skip();
  37150. break;
  37151. case '0':
  37152. case '1':
  37153. case '2':
  37154. case '3':
  37155. case '4':
  37156. case '5':
  37157. case '6':
  37158. case '7':
  37159. case '8':
  37160. case '9':
  37161. result = CppTokeniser::parseNumber (source);
  37162. break;
  37163. case '.':
  37164. result = CppTokeniser::parseNumber (source);
  37165. if (result == tokenType_error)
  37166. result = tokenType_punctuation;
  37167. break;
  37168. case ',':
  37169. case ';':
  37170. case ':':
  37171. source.skip();
  37172. result = tokenType_punctuation;
  37173. break;
  37174. case '(':
  37175. case ')':
  37176. case '{':
  37177. case '}':
  37178. case '[':
  37179. case ']':
  37180. source.skip();
  37181. result = tokenType_bracket;
  37182. break;
  37183. case '"':
  37184. case '\'':
  37185. CppTokeniser::skipQuotedString (source);
  37186. result = tokenType_stringLiteral;
  37187. break;
  37188. case '+':
  37189. result = tokenType_operator;
  37190. source.skip();
  37191. if (source.peekNextChar() == '+')
  37192. source.skip();
  37193. else if (source.peekNextChar() == '=')
  37194. source.skip();
  37195. break;
  37196. case '-':
  37197. source.skip();
  37198. result = CppTokeniser::parseNumber (source);
  37199. if (result == tokenType_error)
  37200. {
  37201. result = tokenType_operator;
  37202. if (source.peekNextChar() == '-')
  37203. source.skip();
  37204. else if (source.peekNextChar() == '=')
  37205. source.skip();
  37206. }
  37207. break;
  37208. case '*':
  37209. case '%':
  37210. case '=':
  37211. case '!':
  37212. result = tokenType_operator;
  37213. source.skip();
  37214. if (source.peekNextChar() == '=')
  37215. source.skip();
  37216. break;
  37217. case '/':
  37218. result = tokenType_operator;
  37219. source.skip();
  37220. if (source.peekNextChar() == '=')
  37221. {
  37222. source.skip();
  37223. }
  37224. else if (source.peekNextChar() == '/')
  37225. {
  37226. result = tokenType_comment;
  37227. source.skipToEndOfLine();
  37228. }
  37229. else if (source.peekNextChar() == '*')
  37230. {
  37231. source.skip();
  37232. result = tokenType_comment;
  37233. CppTokeniser::skipComment (source);
  37234. }
  37235. break;
  37236. case '?':
  37237. case '~':
  37238. source.skip();
  37239. result = tokenType_operator;
  37240. break;
  37241. case '<':
  37242. source.skip();
  37243. result = tokenType_operator;
  37244. if (source.peekNextChar() == '=')
  37245. {
  37246. source.skip();
  37247. }
  37248. else if (source.peekNextChar() == '<')
  37249. {
  37250. source.skip();
  37251. if (source.peekNextChar() == '=')
  37252. source.skip();
  37253. }
  37254. break;
  37255. case '>':
  37256. source.skip();
  37257. result = tokenType_operator;
  37258. if (source.peekNextChar() == '=')
  37259. {
  37260. source.skip();
  37261. }
  37262. else if (source.peekNextChar() == '<')
  37263. {
  37264. source.skip();
  37265. if (source.peekNextChar() == '=')
  37266. source.skip();
  37267. }
  37268. break;
  37269. case '|':
  37270. source.skip();
  37271. result = tokenType_operator;
  37272. if (source.peekNextChar() == '=')
  37273. {
  37274. source.skip();
  37275. }
  37276. else if (source.peekNextChar() == '|')
  37277. {
  37278. source.skip();
  37279. if (source.peekNextChar() == '=')
  37280. source.skip();
  37281. }
  37282. break;
  37283. case '&':
  37284. source.skip();
  37285. result = tokenType_operator;
  37286. if (source.peekNextChar() == '=')
  37287. {
  37288. source.skip();
  37289. }
  37290. else if (source.peekNextChar() == '&')
  37291. {
  37292. source.skip();
  37293. if (source.peekNextChar() == '=')
  37294. source.skip();
  37295. }
  37296. break;
  37297. case '^':
  37298. source.skip();
  37299. result = tokenType_operator;
  37300. if (source.peekNextChar() == '=')
  37301. {
  37302. source.skip();
  37303. }
  37304. else if (source.peekNextChar() == '^')
  37305. {
  37306. source.skip();
  37307. if (source.peekNextChar() == '=')
  37308. source.skip();
  37309. }
  37310. break;
  37311. case '#':
  37312. result = tokenType_preprocessor;
  37313. source.skipToEndOfLine();
  37314. break;
  37315. default:
  37316. if (CppTokeniser::isIdentifierStart (firstChar))
  37317. result = CppTokeniser::parseIdentifier (source);
  37318. else
  37319. source.skip();
  37320. break;
  37321. }
  37322. return result;
  37323. }
  37324. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37325. {
  37326. const char* const types[] =
  37327. {
  37328. "Error",
  37329. "Comment",
  37330. "C++ keyword",
  37331. "Identifier",
  37332. "Integer literal",
  37333. "Float literal",
  37334. "String literal",
  37335. "Operator",
  37336. "Bracket",
  37337. "Punctuation",
  37338. "Preprocessor line",
  37339. 0
  37340. };
  37341. return StringArray (types);
  37342. }
  37343. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37344. {
  37345. const uint32 colours[] =
  37346. {
  37347. 0xffcc0000, // error
  37348. 0xff00aa00, // comment
  37349. 0xff0000cc, // keyword
  37350. 0xff000000, // identifier
  37351. 0xff880000, // int literal
  37352. 0xff885500, // float literal
  37353. 0xff990099, // string literal
  37354. 0xff225500, // operator
  37355. 0xff000055, // bracket
  37356. 0xff004400, // punctuation
  37357. 0xff660000 // preprocessor
  37358. };
  37359. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37360. return Colour (colours [tokenType]);
  37361. return Colours::black;
  37362. }
  37363. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37364. {
  37365. return CppTokeniser::isReservedKeyword (token, token.length());
  37366. }
  37367. END_JUCE_NAMESPACE
  37368. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37369. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37370. BEGIN_JUCE_NAMESPACE
  37371. ComboBox::ComboBox (const String& name)
  37372. : Component (name),
  37373. lastCurrentId (0),
  37374. isButtonDown (false),
  37375. separatorPending (false),
  37376. menuActive (false),
  37377. label (0)
  37378. {
  37379. noChoicesMessage = TRANS("(no choices)");
  37380. setRepaintsOnMouseActivity (true);
  37381. lookAndFeelChanged();
  37382. currentId.addListener (this);
  37383. }
  37384. ComboBox::~ComboBox()
  37385. {
  37386. currentId.removeListener (this);
  37387. if (menuActive)
  37388. PopupMenu::dismissAllActiveMenus();
  37389. label = 0;
  37390. deleteAllChildren();
  37391. }
  37392. void ComboBox::setEditableText (const bool isEditable)
  37393. {
  37394. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37395. {
  37396. label->setEditable (isEditable, isEditable, false);
  37397. setWantsKeyboardFocus (! isEditable);
  37398. resized();
  37399. }
  37400. }
  37401. bool ComboBox::isTextEditable() const throw()
  37402. {
  37403. return label->isEditable();
  37404. }
  37405. void ComboBox::setJustificationType (const Justification& justification) throw()
  37406. {
  37407. label->setJustificationType (justification);
  37408. }
  37409. const Justification ComboBox::getJustificationType() const throw()
  37410. {
  37411. return label->getJustificationType();
  37412. }
  37413. void ComboBox::setTooltip (const String& newTooltip)
  37414. {
  37415. SettableTooltipClient::setTooltip (newTooltip);
  37416. label->setTooltip (newTooltip);
  37417. }
  37418. void ComboBox::addItem (const String& newItemText,
  37419. const int newItemId) throw()
  37420. {
  37421. // you can't add empty strings to the list..
  37422. jassert (newItemText.isNotEmpty());
  37423. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37424. jassert (newItemId != 0);
  37425. // you shouldn't use duplicate item IDs!
  37426. jassert (getItemForId (newItemId) == 0);
  37427. if (newItemText.isNotEmpty() && newItemId != 0)
  37428. {
  37429. if (separatorPending)
  37430. {
  37431. separatorPending = false;
  37432. ItemInfo* const item = new ItemInfo();
  37433. item->itemId = 0;
  37434. item->isEnabled = false;
  37435. item->isHeading = false;
  37436. items.add (item);
  37437. }
  37438. ItemInfo* const item = new ItemInfo();
  37439. item->name = newItemText;
  37440. item->itemId = newItemId;
  37441. item->isEnabled = true;
  37442. item->isHeading = false;
  37443. items.add (item);
  37444. }
  37445. }
  37446. void ComboBox::addSeparator() throw()
  37447. {
  37448. separatorPending = (items.size() > 0);
  37449. }
  37450. void ComboBox::addSectionHeading (const String& headingName) throw()
  37451. {
  37452. // you can't add empty strings to the list..
  37453. jassert (headingName.isNotEmpty());
  37454. if (headingName.isNotEmpty())
  37455. {
  37456. if (separatorPending)
  37457. {
  37458. separatorPending = false;
  37459. ItemInfo* const item = new ItemInfo();
  37460. item->itemId = 0;
  37461. item->isEnabled = false;
  37462. item->isHeading = false;
  37463. items.add (item);
  37464. }
  37465. ItemInfo* const item = new ItemInfo();
  37466. item->name = headingName;
  37467. item->itemId = 0;
  37468. item->isEnabled = true;
  37469. item->isHeading = true;
  37470. items.add (item);
  37471. }
  37472. }
  37473. void ComboBox::setItemEnabled (const int itemId,
  37474. const bool shouldBeEnabled) throw()
  37475. {
  37476. ItemInfo* const item = getItemForId (itemId);
  37477. if (item != 0)
  37478. item->isEnabled = shouldBeEnabled;
  37479. }
  37480. void ComboBox::changeItemText (const int itemId,
  37481. const String& newText) throw()
  37482. {
  37483. ItemInfo* const item = getItemForId (itemId);
  37484. jassert (item != 0);
  37485. if (item != 0)
  37486. item->name = newText;
  37487. }
  37488. void ComboBox::clear (const bool dontSendChangeMessage)
  37489. {
  37490. items.clear();
  37491. separatorPending = false;
  37492. if (! label->isEditable())
  37493. setSelectedItemIndex (-1, dontSendChangeMessage);
  37494. }
  37495. bool ComboBox::ItemInfo::isSeparator() const throw()
  37496. {
  37497. return name.isEmpty();
  37498. }
  37499. bool ComboBox::ItemInfo::isRealItem() const throw()
  37500. {
  37501. return ! (isHeading || name.isEmpty());
  37502. }
  37503. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37504. {
  37505. if (itemId != 0)
  37506. {
  37507. for (int i = items.size(); --i >= 0;)
  37508. if (items.getUnchecked(i)->itemId == itemId)
  37509. return items.getUnchecked(i);
  37510. }
  37511. return 0;
  37512. }
  37513. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37514. {
  37515. int n = 0;
  37516. for (int i = 0; i < items.size(); ++i)
  37517. {
  37518. ItemInfo* const item = items.getUnchecked(i);
  37519. if (item->isRealItem())
  37520. if (n++ == index)
  37521. return item;
  37522. }
  37523. return 0;
  37524. }
  37525. int ComboBox::getNumItems() const throw()
  37526. {
  37527. int n = 0;
  37528. for (int i = items.size(); --i >= 0;)
  37529. if (items.getUnchecked(i)->isRealItem())
  37530. ++n;
  37531. return n;
  37532. }
  37533. const String ComboBox::getItemText (const int index) const throw()
  37534. {
  37535. const ItemInfo* const item = getItemForIndex (index);
  37536. if (item != 0)
  37537. return item->name;
  37538. return String::empty;
  37539. }
  37540. int ComboBox::getItemId (const int index) const throw()
  37541. {
  37542. const ItemInfo* const item = getItemForIndex (index);
  37543. return (item != 0) ? item->itemId : 0;
  37544. }
  37545. int ComboBox::indexOfItemId (const int itemId) const throw()
  37546. {
  37547. int n = 0;
  37548. for (int i = 0; i < items.size(); ++i)
  37549. {
  37550. const ItemInfo* const item = items.getUnchecked(i);
  37551. if (item->isRealItem())
  37552. {
  37553. if (item->itemId == itemId)
  37554. return n;
  37555. ++n;
  37556. }
  37557. }
  37558. return -1;
  37559. }
  37560. int ComboBox::getSelectedItemIndex() const throw()
  37561. {
  37562. int index = indexOfItemId (currentId.getValue());
  37563. if (getText() != getItemText (index))
  37564. index = -1;
  37565. return index;
  37566. }
  37567. void ComboBox::setSelectedItemIndex (const int index,
  37568. const bool dontSendChangeMessage) throw()
  37569. {
  37570. setSelectedId (getItemId (index), dontSendChangeMessage);
  37571. }
  37572. int ComboBox::getSelectedId() const throw()
  37573. {
  37574. const ItemInfo* const item = getItemForId (currentId.getValue());
  37575. return (item != 0 && getText() == item->name)
  37576. ? item->itemId
  37577. : 0;
  37578. }
  37579. void ComboBox::setSelectedId (const int newItemId,
  37580. const bool dontSendChangeMessage) throw()
  37581. {
  37582. const ItemInfo* const item = getItemForId (newItemId);
  37583. const String newItemText (item != 0 ? item->name : String::empty);
  37584. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37585. {
  37586. if (! dontSendChangeMessage)
  37587. triggerAsyncUpdate();
  37588. label->setText (newItemText, false);
  37589. lastCurrentId = newItemId;
  37590. currentId = newItemId;
  37591. repaint(); // for the benefit of the 'none selected' text
  37592. }
  37593. }
  37594. void ComboBox::valueChanged (Value&)
  37595. {
  37596. if (lastCurrentId != (int) currentId.getValue())
  37597. setSelectedId (currentId.getValue(), false);
  37598. }
  37599. const String ComboBox::getText() const throw()
  37600. {
  37601. return label->getText();
  37602. }
  37603. void ComboBox::setText (const String& newText,
  37604. const bool dontSendChangeMessage) throw()
  37605. {
  37606. for (int i = items.size(); --i >= 0;)
  37607. {
  37608. const ItemInfo* const item = items.getUnchecked(i);
  37609. if (item->isRealItem()
  37610. && item->name == newText)
  37611. {
  37612. setSelectedId (item->itemId, dontSendChangeMessage);
  37613. return;
  37614. }
  37615. }
  37616. lastCurrentId = 0;
  37617. currentId = 0;
  37618. if (label->getText() != newText)
  37619. {
  37620. label->setText (newText, false);
  37621. if (! dontSendChangeMessage)
  37622. triggerAsyncUpdate();
  37623. }
  37624. repaint();
  37625. }
  37626. void ComboBox::showEditor()
  37627. {
  37628. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37629. label->showEditor();
  37630. }
  37631. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37632. {
  37633. if (textWhenNothingSelected != newMessage)
  37634. {
  37635. textWhenNothingSelected = newMessage;
  37636. repaint();
  37637. }
  37638. }
  37639. const String ComboBox::getTextWhenNothingSelected() const throw()
  37640. {
  37641. return textWhenNothingSelected;
  37642. }
  37643. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37644. {
  37645. noChoicesMessage = newMessage;
  37646. }
  37647. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37648. {
  37649. return noChoicesMessage;
  37650. }
  37651. void ComboBox::paint (Graphics& g)
  37652. {
  37653. getLookAndFeel().drawComboBox (g,
  37654. getWidth(),
  37655. getHeight(),
  37656. isButtonDown,
  37657. label->getRight(),
  37658. 0,
  37659. getWidth() - label->getRight(),
  37660. getHeight(),
  37661. *this);
  37662. if (textWhenNothingSelected.isNotEmpty()
  37663. && label->getText().isEmpty()
  37664. && ! label->isBeingEdited())
  37665. {
  37666. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37667. g.setFont (label->getFont());
  37668. g.drawFittedText (textWhenNothingSelected,
  37669. label->getX() + 2, label->getY() + 1,
  37670. label->getWidth() - 4, label->getHeight() - 2,
  37671. label->getJustificationType(),
  37672. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37673. }
  37674. }
  37675. void ComboBox::resized()
  37676. {
  37677. if (getHeight() > 0 && getWidth() > 0)
  37678. getLookAndFeel().positionComboBoxText (*this, *label);
  37679. }
  37680. void ComboBox::enablementChanged()
  37681. {
  37682. repaint();
  37683. }
  37684. void ComboBox::lookAndFeelChanged()
  37685. {
  37686. repaint();
  37687. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37688. if (label != 0)
  37689. {
  37690. newLabel->setEditable (label->isEditable());
  37691. newLabel->setJustificationType (label->getJustificationType());
  37692. newLabel->setTooltip (label->getTooltip());
  37693. newLabel->setText (label->getText(), false);
  37694. }
  37695. label = newLabel;
  37696. addAndMakeVisible (newLabel);
  37697. newLabel->addListener (this);
  37698. newLabel->addMouseListener (this, false);
  37699. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37700. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37701. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37702. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37703. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37704. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37705. resized();
  37706. }
  37707. void ComboBox::colourChanged()
  37708. {
  37709. lookAndFeelChanged();
  37710. }
  37711. bool ComboBox::keyPressed (const KeyPress& key)
  37712. {
  37713. bool used = false;
  37714. if (key.isKeyCode (KeyPress::upKey)
  37715. || key.isKeyCode (KeyPress::leftKey))
  37716. {
  37717. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37718. used = true;
  37719. }
  37720. else if (key.isKeyCode (KeyPress::downKey)
  37721. || key.isKeyCode (KeyPress::rightKey))
  37722. {
  37723. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37724. used = true;
  37725. }
  37726. else if (key.isKeyCode (KeyPress::returnKey))
  37727. {
  37728. showPopup();
  37729. used = true;
  37730. }
  37731. return used;
  37732. }
  37733. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37734. {
  37735. // only forward key events that aren't used by this component
  37736. return isKeyDown
  37737. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37738. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37739. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37740. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37741. }
  37742. void ComboBox::focusGained (FocusChangeType)
  37743. {
  37744. repaint();
  37745. }
  37746. void ComboBox::focusLost (FocusChangeType)
  37747. {
  37748. repaint();
  37749. }
  37750. void ComboBox::labelTextChanged (Label*)
  37751. {
  37752. triggerAsyncUpdate();
  37753. }
  37754. class ComboBox::Callback : public ModalComponentManager::Callback
  37755. {
  37756. public:
  37757. Callback (ComboBox* const box_)
  37758. : box (box_)
  37759. {
  37760. }
  37761. void modalStateFinished (int returnValue)
  37762. {
  37763. if (box != 0)
  37764. {
  37765. box->menuActive = false;
  37766. if (returnValue != 0)
  37767. box->setSelectedId (returnValue);
  37768. }
  37769. }
  37770. private:
  37771. Component::SafePointer<ComboBox> box;
  37772. Callback (const Callback&);
  37773. Callback& operator= (const Callback&);
  37774. };
  37775. void ComboBox::showPopup()
  37776. {
  37777. if (! menuActive)
  37778. {
  37779. const int selectedId = getSelectedId();
  37780. PopupMenu menu;
  37781. menu.setLookAndFeel (&getLookAndFeel());
  37782. for (int i = 0; i < items.size(); ++i)
  37783. {
  37784. const ItemInfo* const item = items.getUnchecked(i);
  37785. if (item->isSeparator())
  37786. menu.addSeparator();
  37787. else if (item->isHeading)
  37788. menu.addSectionHeader (item->name);
  37789. else
  37790. menu.addItem (item->itemId, item->name,
  37791. item->isEnabled, item->itemId == selectedId);
  37792. }
  37793. if (items.size() == 0)
  37794. menu.addItem (1, noChoicesMessage, false);
  37795. menuActive = true;
  37796. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  37797. new Callback (this));
  37798. }
  37799. }
  37800. void ComboBox::mouseDown (const MouseEvent& e)
  37801. {
  37802. beginDragAutoRepeat (300);
  37803. isButtonDown = isEnabled();
  37804. if (isButtonDown
  37805. && (e.eventComponent == this || ! label->isEditable()))
  37806. {
  37807. showPopup();
  37808. }
  37809. }
  37810. void ComboBox::mouseDrag (const MouseEvent& e)
  37811. {
  37812. beginDragAutoRepeat (50);
  37813. if (isButtonDown && ! e.mouseWasClicked())
  37814. showPopup();
  37815. }
  37816. void ComboBox::mouseUp (const MouseEvent& e2)
  37817. {
  37818. if (isButtonDown)
  37819. {
  37820. isButtonDown = false;
  37821. repaint();
  37822. const MouseEvent e (e2.getEventRelativeTo (this));
  37823. if (reallyContains (e.x, e.y, true)
  37824. && (e2.eventComponent == this || ! label->isEditable()))
  37825. {
  37826. showPopup();
  37827. }
  37828. }
  37829. }
  37830. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37831. {
  37832. listeners.add (listener);
  37833. }
  37834. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37835. {
  37836. listeners.remove (listener);
  37837. }
  37838. void ComboBox::handleAsyncUpdate()
  37839. {
  37840. Component::BailOutChecker checker (this);
  37841. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37842. }
  37843. END_JUCE_NAMESPACE
  37844. /*** End of inlined file: juce_ComboBox.cpp ***/
  37845. /*** Start of inlined file: juce_Label.cpp ***/
  37846. BEGIN_JUCE_NAMESPACE
  37847. Label::Label (const String& componentName,
  37848. const String& labelText)
  37849. : Component (componentName),
  37850. textValue (labelText),
  37851. lastTextValue (labelText),
  37852. font (15.0f),
  37853. justification (Justification::centredLeft),
  37854. ownerComponent (0),
  37855. horizontalBorderSize (5),
  37856. verticalBorderSize (1),
  37857. minimumHorizontalScale (0.7f),
  37858. editSingleClick (false),
  37859. editDoubleClick (false),
  37860. lossOfFocusDiscardsChanges (false)
  37861. {
  37862. setColour (TextEditor::textColourId, Colours::black);
  37863. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37864. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37865. textValue.addListener (this);
  37866. }
  37867. Label::~Label()
  37868. {
  37869. textValue.removeListener (this);
  37870. if (ownerComponent != 0)
  37871. ownerComponent->removeComponentListener (this);
  37872. editor = 0;
  37873. }
  37874. void Label::setText (const String& newText,
  37875. const bool broadcastChangeMessage)
  37876. {
  37877. hideEditor (true);
  37878. if (lastTextValue != newText)
  37879. {
  37880. lastTextValue = newText;
  37881. textValue = newText;
  37882. repaint();
  37883. textWasChanged();
  37884. if (ownerComponent != 0)
  37885. componentMovedOrResized (*ownerComponent, true, true);
  37886. if (broadcastChangeMessage)
  37887. callChangeListeners();
  37888. }
  37889. }
  37890. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37891. {
  37892. return (returnActiveEditorContents && isBeingEdited())
  37893. ? editor->getText()
  37894. : textValue.toString();
  37895. }
  37896. void Label::valueChanged (Value&)
  37897. {
  37898. if (lastTextValue != textValue.toString())
  37899. setText (textValue.toString(), true);
  37900. }
  37901. void Label::setFont (const Font& newFont) throw()
  37902. {
  37903. if (font != newFont)
  37904. {
  37905. font = newFont;
  37906. repaint();
  37907. }
  37908. }
  37909. const Font& Label::getFont() const throw()
  37910. {
  37911. return font;
  37912. }
  37913. void Label::setEditable (const bool editOnSingleClick,
  37914. const bool editOnDoubleClick,
  37915. const bool lossOfFocusDiscardsChanges_) throw()
  37916. {
  37917. editSingleClick = editOnSingleClick;
  37918. editDoubleClick = editOnDoubleClick;
  37919. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37920. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37921. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37922. }
  37923. void Label::setJustificationType (const Justification& newJustification) throw()
  37924. {
  37925. if (justification != newJustification)
  37926. {
  37927. justification = newJustification;
  37928. repaint();
  37929. }
  37930. }
  37931. void Label::setBorderSize (int h, int v)
  37932. {
  37933. if (horizontalBorderSize != h || verticalBorderSize != v)
  37934. {
  37935. horizontalBorderSize = h;
  37936. verticalBorderSize = v;
  37937. repaint();
  37938. }
  37939. }
  37940. Component* Label::getAttachedComponent() const
  37941. {
  37942. return static_cast<Component*> (ownerComponent);
  37943. }
  37944. void Label::attachToComponent (Component* owner,
  37945. const bool onLeft)
  37946. {
  37947. if (ownerComponent != 0)
  37948. ownerComponent->removeComponentListener (this);
  37949. ownerComponent = owner;
  37950. leftOfOwnerComp = onLeft;
  37951. if (ownerComponent != 0)
  37952. {
  37953. setVisible (owner->isVisible());
  37954. ownerComponent->addComponentListener (this);
  37955. componentParentHierarchyChanged (*ownerComponent);
  37956. componentMovedOrResized (*ownerComponent, true, true);
  37957. }
  37958. }
  37959. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37960. {
  37961. if (leftOfOwnerComp)
  37962. {
  37963. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37964. component.getHeight());
  37965. setTopRightPosition (component.getX(), component.getY());
  37966. }
  37967. else
  37968. {
  37969. setSize (component.getWidth(),
  37970. 8 + roundToInt (getFont().getHeight()));
  37971. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37972. }
  37973. }
  37974. void Label::componentParentHierarchyChanged (Component& component)
  37975. {
  37976. if (component.getParentComponent() != 0)
  37977. component.getParentComponent()->addChildComponent (this);
  37978. }
  37979. void Label::componentVisibilityChanged (Component& component)
  37980. {
  37981. setVisible (component.isVisible());
  37982. }
  37983. void Label::textWasEdited()
  37984. {
  37985. }
  37986. void Label::textWasChanged()
  37987. {
  37988. }
  37989. void Label::showEditor()
  37990. {
  37991. if (editor == 0)
  37992. {
  37993. addAndMakeVisible (editor = createEditorComponent());
  37994. editor->setText (getText(), false);
  37995. editor->addListener (this);
  37996. editor->grabKeyboardFocus();
  37997. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37998. editor->addListener (this);
  37999. resized();
  38000. repaint();
  38001. editorShown (editor);
  38002. enterModalState (false);
  38003. editor->grabKeyboardFocus();
  38004. }
  38005. }
  38006. void Label::editorShown (TextEditor* /*editorComponent*/)
  38007. {
  38008. }
  38009. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38010. {
  38011. }
  38012. bool Label::updateFromTextEditorContents()
  38013. {
  38014. jassert (editor != 0);
  38015. const String newText (editor->getText());
  38016. if (textValue.toString() != newText)
  38017. {
  38018. lastTextValue = newText;
  38019. textValue = newText;
  38020. repaint();
  38021. textWasChanged();
  38022. if (ownerComponent != 0)
  38023. componentMovedOrResized (*ownerComponent, true, true);
  38024. return true;
  38025. }
  38026. return false;
  38027. }
  38028. void Label::hideEditor (const bool discardCurrentEditorContents)
  38029. {
  38030. if (editor != 0)
  38031. {
  38032. Component::SafePointer<Component> deletionChecker (this);
  38033. editorAboutToBeHidden (editor);
  38034. const bool changed = (! discardCurrentEditorContents)
  38035. && updateFromTextEditorContents();
  38036. editor = 0;
  38037. repaint();
  38038. if (changed)
  38039. textWasEdited();
  38040. if (deletionChecker != 0)
  38041. exitModalState (0);
  38042. if (changed && deletionChecker != 0)
  38043. callChangeListeners();
  38044. }
  38045. }
  38046. void Label::inputAttemptWhenModal()
  38047. {
  38048. if (editor != 0)
  38049. {
  38050. if (lossOfFocusDiscardsChanges)
  38051. textEditorEscapeKeyPressed (*editor);
  38052. else
  38053. textEditorReturnKeyPressed (*editor);
  38054. }
  38055. }
  38056. bool Label::isBeingEdited() const throw()
  38057. {
  38058. return editor != 0;
  38059. }
  38060. TextEditor* Label::createEditorComponent()
  38061. {
  38062. TextEditor* const ed = new TextEditor (getName());
  38063. ed->setFont (font);
  38064. // copy these colours from our own settings..
  38065. const int cols[] = { TextEditor::backgroundColourId,
  38066. TextEditor::textColourId,
  38067. TextEditor::highlightColourId,
  38068. TextEditor::highlightedTextColourId,
  38069. TextEditor::caretColourId,
  38070. TextEditor::outlineColourId,
  38071. TextEditor::focusedOutlineColourId,
  38072. TextEditor::shadowColourId };
  38073. for (int i = 0; i < numElementsInArray (cols); ++i)
  38074. ed->setColour (cols[i], findColour (cols[i]));
  38075. return ed;
  38076. }
  38077. void Label::paint (Graphics& g)
  38078. {
  38079. getLookAndFeel().drawLabel (g, *this);
  38080. }
  38081. void Label::mouseUp (const MouseEvent& e)
  38082. {
  38083. if (editSingleClick
  38084. && e.mouseWasClicked()
  38085. && contains (e.x, e.y)
  38086. && ! e.mods.isPopupMenu())
  38087. {
  38088. showEditor();
  38089. }
  38090. }
  38091. void Label::mouseDoubleClick (const MouseEvent& e)
  38092. {
  38093. if (editDoubleClick && ! e.mods.isPopupMenu())
  38094. showEditor();
  38095. }
  38096. void Label::resized()
  38097. {
  38098. if (editor != 0)
  38099. editor->setBoundsInset (BorderSize (0));
  38100. }
  38101. void Label::focusGained (FocusChangeType cause)
  38102. {
  38103. if (editSingleClick && cause == focusChangedByTabKey)
  38104. showEditor();
  38105. }
  38106. void Label::enablementChanged()
  38107. {
  38108. repaint();
  38109. }
  38110. void Label::colourChanged()
  38111. {
  38112. repaint();
  38113. }
  38114. void Label::setMinimumHorizontalScale (const float newScale)
  38115. {
  38116. if (minimumHorizontalScale != newScale)
  38117. {
  38118. minimumHorizontalScale = newScale;
  38119. repaint();
  38120. }
  38121. }
  38122. // We'll use a custom focus traverser here to make sure focus goes from the
  38123. // text editor to another component rather than back to the label itself.
  38124. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38125. {
  38126. public:
  38127. LabelKeyboardFocusTraverser() {}
  38128. Component* getNextComponent (Component* current)
  38129. {
  38130. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38131. ? current->getParentComponent() : current);
  38132. }
  38133. Component* getPreviousComponent (Component* current)
  38134. {
  38135. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38136. ? current->getParentComponent() : current);
  38137. }
  38138. };
  38139. KeyboardFocusTraverser* Label::createFocusTraverser()
  38140. {
  38141. return new LabelKeyboardFocusTraverser();
  38142. }
  38143. void Label::addListener (LabelListener* const listener) throw()
  38144. {
  38145. listeners.add (listener);
  38146. }
  38147. void Label::removeListener (LabelListener* const listener) throw()
  38148. {
  38149. listeners.remove (listener);
  38150. }
  38151. void Label::callChangeListeners()
  38152. {
  38153. Component::BailOutChecker checker (this);
  38154. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  38155. }
  38156. void Label::textEditorTextChanged (TextEditor& ed)
  38157. {
  38158. if (editor != 0)
  38159. {
  38160. jassert (&ed == editor);
  38161. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38162. {
  38163. if (lossOfFocusDiscardsChanges)
  38164. textEditorEscapeKeyPressed (ed);
  38165. else
  38166. textEditorReturnKeyPressed (ed);
  38167. }
  38168. }
  38169. }
  38170. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38171. {
  38172. if (editor != 0)
  38173. {
  38174. jassert (&ed == editor);
  38175. (void) ed;
  38176. const bool changed = updateFromTextEditorContents();
  38177. hideEditor (true);
  38178. if (changed)
  38179. {
  38180. Component::SafePointer<Component> deletionChecker (this);
  38181. textWasEdited();
  38182. if (deletionChecker != 0)
  38183. callChangeListeners();
  38184. }
  38185. }
  38186. }
  38187. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38188. {
  38189. if (editor != 0)
  38190. {
  38191. jassert (&ed == editor);
  38192. (void) ed;
  38193. editor->setText (textValue.toString(), false);
  38194. hideEditor (true);
  38195. }
  38196. }
  38197. void Label::textEditorFocusLost (TextEditor& ed)
  38198. {
  38199. textEditorTextChanged (ed);
  38200. }
  38201. END_JUCE_NAMESPACE
  38202. /*** End of inlined file: juce_Label.cpp ***/
  38203. /*** Start of inlined file: juce_ListBox.cpp ***/
  38204. BEGIN_JUCE_NAMESPACE
  38205. class ListBoxRowComponent : public Component,
  38206. public TooltipClient
  38207. {
  38208. public:
  38209. ListBoxRowComponent (ListBox& owner_)
  38210. : owner (owner_),
  38211. row (-1),
  38212. selected (false),
  38213. isDragging (false)
  38214. {
  38215. }
  38216. ~ListBoxRowComponent()
  38217. {
  38218. deleteAllChildren();
  38219. }
  38220. void paint (Graphics& g)
  38221. {
  38222. if (owner.getModel() != 0)
  38223. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38224. }
  38225. void update (const int row_, const bool selected_)
  38226. {
  38227. if (row != row_ || selected != selected_)
  38228. {
  38229. repaint();
  38230. row = row_;
  38231. selected = selected_;
  38232. }
  38233. if (owner.getModel() != 0)
  38234. {
  38235. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38236. if (customComp != 0)
  38237. {
  38238. addAndMakeVisible (customComp);
  38239. customComp->setBounds (getLocalBounds());
  38240. for (int i = getNumChildComponents(); --i >= 0;)
  38241. if (getChildComponent (i) != customComp)
  38242. delete getChildComponent (i);
  38243. }
  38244. else
  38245. {
  38246. deleteAllChildren();
  38247. }
  38248. }
  38249. }
  38250. void mouseDown (const MouseEvent& e)
  38251. {
  38252. isDragging = false;
  38253. selectRowOnMouseUp = false;
  38254. if (isEnabled())
  38255. {
  38256. if (! selected)
  38257. {
  38258. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38259. if (owner.getModel() != 0)
  38260. owner.getModel()->listBoxItemClicked (row, e);
  38261. }
  38262. else
  38263. {
  38264. selectRowOnMouseUp = true;
  38265. }
  38266. }
  38267. }
  38268. void mouseUp (const MouseEvent& e)
  38269. {
  38270. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38271. {
  38272. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38273. if (owner.getModel() != 0)
  38274. owner.getModel()->listBoxItemClicked (row, e);
  38275. }
  38276. }
  38277. void mouseDoubleClick (const MouseEvent& e)
  38278. {
  38279. if (owner.getModel() != 0 && isEnabled())
  38280. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38281. }
  38282. void mouseDrag (const MouseEvent& e)
  38283. {
  38284. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38285. {
  38286. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38287. if (selectedRows.size() > 0)
  38288. {
  38289. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38290. if (dragDescription.isNotEmpty())
  38291. {
  38292. isDragging = true;
  38293. owner.startDragAndDrop (e, dragDescription);
  38294. }
  38295. }
  38296. }
  38297. }
  38298. void resized()
  38299. {
  38300. if (getNumChildComponents() > 0)
  38301. getChildComponent(0)->setBounds (getLocalBounds());
  38302. }
  38303. const String getTooltip()
  38304. {
  38305. if (owner.getModel() != 0)
  38306. return owner.getModel()->getTooltipForRow (row);
  38307. return String::empty;
  38308. }
  38309. juce_UseDebuggingNewOperator
  38310. bool neededFlag;
  38311. private:
  38312. ListBox& owner;
  38313. int row;
  38314. bool selected, isDragging, selectRowOnMouseUp;
  38315. ListBoxRowComponent (const ListBoxRowComponent&);
  38316. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38317. };
  38318. class ListViewport : public Viewport
  38319. {
  38320. public:
  38321. int firstIndex, firstWholeIndex, lastWholeIndex;
  38322. bool hasUpdated;
  38323. ListViewport (ListBox& owner_)
  38324. : owner (owner_)
  38325. {
  38326. setWantsKeyboardFocus (false);
  38327. setViewedComponent (new Component());
  38328. getViewedComponent()->addMouseListener (this, false);
  38329. getViewedComponent()->setWantsKeyboardFocus (false);
  38330. }
  38331. ~ListViewport()
  38332. {
  38333. getViewedComponent()->removeMouseListener (this);
  38334. getViewedComponent()->deleteAllChildren();
  38335. }
  38336. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38337. {
  38338. return static_cast <ListBoxRowComponent*>
  38339. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38340. }
  38341. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38342. {
  38343. const int index = getIndexOfChildComponent (rowComponent);
  38344. const int num = getViewedComponent()->getNumChildComponents();
  38345. for (int i = num; --i >= 0;)
  38346. if (((firstIndex + i) % jmax (1, num)) == index)
  38347. return firstIndex + i;
  38348. return -1;
  38349. }
  38350. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38351. {
  38352. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38353. ? getComponentForRow (row) : 0;
  38354. }
  38355. void visibleAreaChanged (int, int, int, int)
  38356. {
  38357. updateVisibleArea (true);
  38358. if (owner.getModel() != 0)
  38359. owner.getModel()->listWasScrolled();
  38360. }
  38361. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38362. {
  38363. hasUpdated = false;
  38364. const int newX = getViewedComponent()->getX();
  38365. int newY = getViewedComponent()->getY();
  38366. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38367. const int newH = owner.totalItems * owner.getRowHeight();
  38368. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38369. newY = getMaximumVisibleHeight() - newH;
  38370. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38371. if (makeSureItUpdatesContent && ! hasUpdated)
  38372. updateContents();
  38373. }
  38374. void updateContents()
  38375. {
  38376. hasUpdated = true;
  38377. const int rowHeight = owner.getRowHeight();
  38378. if (rowHeight > 0)
  38379. {
  38380. const int y = getViewPositionY();
  38381. const int w = getViewedComponent()->getWidth();
  38382. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38383. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38384. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38385. jassert (numNeeded >= 0);
  38386. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38387. {
  38388. Component* const rowToRemove
  38389. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38390. delete rowToRemove;
  38391. }
  38392. firstIndex = y / rowHeight;
  38393. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38394. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38395. for (int i = 0; i < numNeeded; ++i)
  38396. {
  38397. const int row = i + firstIndex;
  38398. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38399. if (rowComp != 0)
  38400. {
  38401. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38402. rowComp->update (row, owner.isRowSelected (row));
  38403. }
  38404. }
  38405. }
  38406. if (owner.headerComponent != 0)
  38407. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38408. owner.outlineThickness,
  38409. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38410. getViewedComponent()->getWidth()),
  38411. owner.headerComponent->getHeight());
  38412. }
  38413. void paint (Graphics& g)
  38414. {
  38415. if (isOpaque())
  38416. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38417. }
  38418. bool keyPressed (const KeyPress& key)
  38419. {
  38420. if (key.isKeyCode (KeyPress::upKey)
  38421. || key.isKeyCode (KeyPress::downKey)
  38422. || key.isKeyCode (KeyPress::pageUpKey)
  38423. || key.isKeyCode (KeyPress::pageDownKey)
  38424. || key.isKeyCode (KeyPress::homeKey)
  38425. || key.isKeyCode (KeyPress::endKey))
  38426. {
  38427. // we want to avoid these keypresses going to the viewport, and instead allow
  38428. // them to pass up to our listbox..
  38429. return false;
  38430. }
  38431. return Viewport::keyPressed (key);
  38432. }
  38433. juce_UseDebuggingNewOperator
  38434. private:
  38435. ListBox& owner;
  38436. ListViewport (const ListViewport&);
  38437. ListViewport& operator= (const ListViewport&);
  38438. };
  38439. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38440. : Component (name),
  38441. model (model_),
  38442. totalItems (0),
  38443. rowHeight (22),
  38444. minimumRowWidth (0),
  38445. outlineThickness (0),
  38446. lastRowSelected (-1),
  38447. mouseMoveSelects (false),
  38448. multipleSelection (false),
  38449. hasDoneInitialUpdate (false)
  38450. {
  38451. addAndMakeVisible (viewport = new ListViewport (*this));
  38452. setWantsKeyboardFocus (true);
  38453. colourChanged();
  38454. }
  38455. ListBox::~ListBox()
  38456. {
  38457. headerComponent = 0;
  38458. viewport = 0;
  38459. }
  38460. void ListBox::setModel (ListBoxModel* const newModel)
  38461. {
  38462. if (model != newModel)
  38463. {
  38464. model = newModel;
  38465. updateContent();
  38466. }
  38467. }
  38468. void ListBox::setMultipleSelectionEnabled (bool b)
  38469. {
  38470. multipleSelection = b;
  38471. }
  38472. void ListBox::setMouseMoveSelectsRows (bool b)
  38473. {
  38474. mouseMoveSelects = b;
  38475. if (b)
  38476. addMouseListener (this, true);
  38477. }
  38478. void ListBox::paint (Graphics& g)
  38479. {
  38480. if (! hasDoneInitialUpdate)
  38481. updateContent();
  38482. g.fillAll (findColour (backgroundColourId));
  38483. }
  38484. void ListBox::paintOverChildren (Graphics& g)
  38485. {
  38486. if (outlineThickness > 0)
  38487. {
  38488. g.setColour (findColour (outlineColourId));
  38489. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38490. }
  38491. }
  38492. void ListBox::resized()
  38493. {
  38494. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38495. outlineThickness,
  38496. outlineThickness,
  38497. outlineThickness));
  38498. viewport->setSingleStepSizes (20, getRowHeight());
  38499. viewport->updateVisibleArea (false);
  38500. }
  38501. void ListBox::visibilityChanged()
  38502. {
  38503. viewport->updateVisibleArea (true);
  38504. }
  38505. Viewport* ListBox::getViewport() const throw()
  38506. {
  38507. return viewport;
  38508. }
  38509. void ListBox::updateContent()
  38510. {
  38511. hasDoneInitialUpdate = true;
  38512. totalItems = (model != 0) ? model->getNumRows() : 0;
  38513. bool selectionChanged = false;
  38514. if (selected [selected.size() - 1] >= totalItems)
  38515. {
  38516. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38517. lastRowSelected = getSelectedRow (0);
  38518. selectionChanged = true;
  38519. }
  38520. viewport->updateVisibleArea (isVisible());
  38521. viewport->resized();
  38522. if (selectionChanged && model != 0)
  38523. model->selectedRowsChanged (lastRowSelected);
  38524. }
  38525. void ListBox::selectRow (const int row,
  38526. bool dontScroll,
  38527. bool deselectOthersFirst)
  38528. {
  38529. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38530. }
  38531. void ListBox::selectRowInternal (const int row,
  38532. bool dontScroll,
  38533. bool deselectOthersFirst,
  38534. bool isMouseClick)
  38535. {
  38536. if (! multipleSelection)
  38537. deselectOthersFirst = true;
  38538. if ((! isRowSelected (row))
  38539. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38540. {
  38541. if (((unsigned int) row) < (unsigned int) totalItems)
  38542. {
  38543. if (deselectOthersFirst)
  38544. selected.clear();
  38545. selected.addRange (Range<int> (row, row + 1));
  38546. if (getHeight() == 0 || getWidth() == 0)
  38547. dontScroll = true;
  38548. viewport->hasUpdated = false;
  38549. if (row < viewport->firstWholeIndex && ! dontScroll)
  38550. {
  38551. viewport->setViewPosition (viewport->getViewPositionX(),
  38552. row * getRowHeight());
  38553. }
  38554. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38555. {
  38556. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38557. if (row >= lastRowSelected + rowsOnScreen
  38558. && rowsOnScreen < totalItems - 1
  38559. && ! isMouseClick)
  38560. {
  38561. viewport->setViewPosition (viewport->getViewPositionX(),
  38562. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38563. * getRowHeight());
  38564. }
  38565. else
  38566. {
  38567. viewport->setViewPosition (viewport->getViewPositionX(),
  38568. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38569. }
  38570. }
  38571. if (! viewport->hasUpdated)
  38572. viewport->updateContents();
  38573. lastRowSelected = row;
  38574. model->selectedRowsChanged (row);
  38575. }
  38576. else
  38577. {
  38578. if (deselectOthersFirst)
  38579. deselectAllRows();
  38580. }
  38581. }
  38582. }
  38583. void ListBox::deselectRow (const int row)
  38584. {
  38585. if (selected.contains (row))
  38586. {
  38587. selected.removeRange (Range <int> (row, row + 1));
  38588. if (row == lastRowSelected)
  38589. lastRowSelected = getSelectedRow (0);
  38590. viewport->updateContents();
  38591. model->selectedRowsChanged (lastRowSelected);
  38592. }
  38593. }
  38594. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38595. const bool sendNotificationEventToModel)
  38596. {
  38597. selected = setOfRowsToBeSelected;
  38598. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38599. if (! isRowSelected (lastRowSelected))
  38600. lastRowSelected = getSelectedRow (0);
  38601. viewport->updateContents();
  38602. if ((model != 0) && sendNotificationEventToModel)
  38603. model->selectedRowsChanged (lastRowSelected);
  38604. }
  38605. const SparseSet<int> ListBox::getSelectedRows() const
  38606. {
  38607. return selected;
  38608. }
  38609. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38610. {
  38611. if (multipleSelection && (firstRow != lastRow))
  38612. {
  38613. const int numRows = totalItems - 1;
  38614. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38615. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38616. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38617. jmax (firstRow, lastRow) + 1));
  38618. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38619. }
  38620. selectRowInternal (lastRow, false, false, true);
  38621. }
  38622. void ListBox::flipRowSelection (const int row)
  38623. {
  38624. if (isRowSelected (row))
  38625. deselectRow (row);
  38626. else
  38627. selectRowInternal (row, false, false, true);
  38628. }
  38629. void ListBox::deselectAllRows()
  38630. {
  38631. if (! selected.isEmpty())
  38632. {
  38633. selected.clear();
  38634. lastRowSelected = -1;
  38635. viewport->updateContents();
  38636. if (model != 0)
  38637. model->selectedRowsChanged (lastRowSelected);
  38638. }
  38639. }
  38640. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38641. const ModifierKeys& mods)
  38642. {
  38643. if (multipleSelection && mods.isCommandDown())
  38644. {
  38645. flipRowSelection (row);
  38646. }
  38647. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38648. {
  38649. selectRangeOfRows (lastRowSelected, row);
  38650. }
  38651. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38652. {
  38653. selectRowInternal (row, false, true, true);
  38654. }
  38655. }
  38656. int ListBox::getNumSelectedRows() const
  38657. {
  38658. return selected.size();
  38659. }
  38660. int ListBox::getSelectedRow (const int index) const
  38661. {
  38662. return (((unsigned int) index) < (unsigned int) selected.size())
  38663. ? selected [index] : -1;
  38664. }
  38665. bool ListBox::isRowSelected (const int row) const
  38666. {
  38667. return selected.contains (row);
  38668. }
  38669. int ListBox::getLastRowSelected() const
  38670. {
  38671. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38672. }
  38673. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38674. {
  38675. if (((unsigned int) x) < (unsigned int) getWidth())
  38676. {
  38677. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38678. if (((unsigned int) row) < (unsigned int) totalItems)
  38679. return row;
  38680. }
  38681. return -1;
  38682. }
  38683. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38684. {
  38685. if (((unsigned int) x) < (unsigned int) getWidth())
  38686. {
  38687. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38688. return jlimit (0, totalItems, row);
  38689. }
  38690. return -1;
  38691. }
  38692. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38693. {
  38694. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38695. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38696. }
  38697. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38698. {
  38699. return viewport->getRowNumberOfComponent (rowComponent);
  38700. }
  38701. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38702. const bool relativeToComponentTopLeft) const throw()
  38703. {
  38704. int y = viewport->getY() + rowHeight * rowNumber;
  38705. if (relativeToComponentTopLeft)
  38706. y -= viewport->getViewPositionY();
  38707. return Rectangle<int> (viewport->getX(), y,
  38708. viewport->getViewedComponent()->getWidth(), rowHeight);
  38709. }
  38710. void ListBox::setVerticalPosition (const double proportion)
  38711. {
  38712. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38713. viewport->setViewPosition (viewport->getViewPositionX(),
  38714. jmax (0, roundToInt (proportion * offscreen)));
  38715. }
  38716. double ListBox::getVerticalPosition() const
  38717. {
  38718. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38719. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38720. : 0;
  38721. }
  38722. int ListBox::getVisibleRowWidth() const throw()
  38723. {
  38724. return viewport->getViewWidth();
  38725. }
  38726. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38727. {
  38728. if (row < viewport->firstWholeIndex)
  38729. {
  38730. viewport->setViewPosition (viewport->getViewPositionX(),
  38731. row * getRowHeight());
  38732. }
  38733. else if (row >= viewport->lastWholeIndex)
  38734. {
  38735. viewport->setViewPosition (viewport->getViewPositionX(),
  38736. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38737. }
  38738. }
  38739. bool ListBox::keyPressed (const KeyPress& key)
  38740. {
  38741. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38742. const bool multiple = multipleSelection
  38743. && (lastRowSelected >= 0)
  38744. && (key.getModifiers().isShiftDown()
  38745. || key.getModifiers().isCtrlDown()
  38746. || key.getModifiers().isCommandDown());
  38747. if (key.isKeyCode (KeyPress::upKey))
  38748. {
  38749. if (multiple)
  38750. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38751. else
  38752. selectRow (jmax (0, lastRowSelected - 1));
  38753. }
  38754. else if (key.isKeyCode (KeyPress::returnKey)
  38755. && isRowSelected (lastRowSelected))
  38756. {
  38757. if (model != 0)
  38758. model->returnKeyPressed (lastRowSelected);
  38759. }
  38760. else if (key.isKeyCode (KeyPress::pageUpKey))
  38761. {
  38762. if (multiple)
  38763. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38764. else
  38765. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38766. }
  38767. else if (key.isKeyCode (KeyPress::pageDownKey))
  38768. {
  38769. if (multiple)
  38770. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38771. else
  38772. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38773. }
  38774. else if (key.isKeyCode (KeyPress::homeKey))
  38775. {
  38776. if (multiple && key.getModifiers().isShiftDown())
  38777. selectRangeOfRows (lastRowSelected, 0);
  38778. else
  38779. selectRow (0);
  38780. }
  38781. else if (key.isKeyCode (KeyPress::endKey))
  38782. {
  38783. if (multiple && key.getModifiers().isShiftDown())
  38784. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38785. else
  38786. selectRow (totalItems - 1);
  38787. }
  38788. else if (key.isKeyCode (KeyPress::downKey))
  38789. {
  38790. if (multiple)
  38791. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38792. else
  38793. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38794. }
  38795. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38796. && isRowSelected (lastRowSelected))
  38797. {
  38798. if (model != 0)
  38799. model->deleteKeyPressed (lastRowSelected);
  38800. }
  38801. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38802. {
  38803. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38804. }
  38805. else
  38806. {
  38807. return false;
  38808. }
  38809. return true;
  38810. }
  38811. bool ListBox::keyStateChanged (const bool isKeyDown)
  38812. {
  38813. return isKeyDown
  38814. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38815. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38816. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38817. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38818. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38819. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38820. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38821. }
  38822. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38823. {
  38824. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38825. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38826. }
  38827. void ListBox::mouseMove (const MouseEvent& e)
  38828. {
  38829. if (mouseMoveSelects)
  38830. {
  38831. const MouseEvent e2 (e.getEventRelativeTo (this));
  38832. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38833. }
  38834. }
  38835. void ListBox::mouseExit (const MouseEvent& e)
  38836. {
  38837. mouseMove (e);
  38838. }
  38839. void ListBox::mouseUp (const MouseEvent& e)
  38840. {
  38841. if (e.mouseWasClicked() && model != 0)
  38842. model->backgroundClicked();
  38843. }
  38844. void ListBox::setRowHeight (const int newHeight)
  38845. {
  38846. rowHeight = jmax (1, newHeight);
  38847. viewport->setSingleStepSizes (20, rowHeight);
  38848. updateContent();
  38849. }
  38850. int ListBox::getNumRowsOnScreen() const throw()
  38851. {
  38852. return viewport->getMaximumVisibleHeight() / rowHeight;
  38853. }
  38854. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38855. {
  38856. minimumRowWidth = newMinimumWidth;
  38857. updateContent();
  38858. }
  38859. int ListBox::getVisibleContentWidth() const throw()
  38860. {
  38861. return viewport->getMaximumVisibleWidth();
  38862. }
  38863. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38864. {
  38865. return viewport->getVerticalScrollBar();
  38866. }
  38867. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38868. {
  38869. return viewport->getHorizontalScrollBar();
  38870. }
  38871. void ListBox::colourChanged()
  38872. {
  38873. setOpaque (findColour (backgroundColourId).isOpaque());
  38874. viewport->setOpaque (isOpaque());
  38875. repaint();
  38876. }
  38877. void ListBox::setOutlineThickness (const int outlineThickness_)
  38878. {
  38879. outlineThickness = outlineThickness_;
  38880. resized();
  38881. }
  38882. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38883. {
  38884. if (newHeaderComponent != headerComponent)
  38885. {
  38886. headerComponent = newHeaderComponent;
  38887. addAndMakeVisible (newHeaderComponent);
  38888. ListBox::resized();
  38889. }
  38890. }
  38891. void ListBox::repaintRow (const int rowNumber) throw()
  38892. {
  38893. repaint (getRowPosition (rowNumber, true));
  38894. }
  38895. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38896. {
  38897. Rectangle<int> imageArea;
  38898. const int firstRow = getRowContainingPosition (0, 0);
  38899. int i;
  38900. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38901. {
  38902. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38903. if (rowComp != 0 && isRowSelected (firstRow + i))
  38904. {
  38905. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38906. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38907. imageArea = imageArea.getUnion (rowRect);
  38908. }
  38909. }
  38910. imageArea = imageArea.getIntersection (getLocalBounds());
  38911. imageX = imageArea.getX();
  38912. imageY = imageArea.getY();
  38913. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38914. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38915. {
  38916. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38917. if (rowComp != 0 && isRowSelected (firstRow + i))
  38918. {
  38919. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38920. Graphics g (snapshot);
  38921. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38922. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38923. rowComp->paintEntireComponent (g);
  38924. }
  38925. }
  38926. return snapshot;
  38927. }
  38928. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38929. {
  38930. DragAndDropContainer* const dragContainer
  38931. = DragAndDropContainer::findParentDragContainerFor (this);
  38932. if (dragContainer != 0)
  38933. {
  38934. int x, y;
  38935. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38936. dragImage.multiplyAllAlphas (0.6f);
  38937. MouseEvent e2 (e.getEventRelativeTo (this));
  38938. const Point<int> p (x - e2.x, y - e2.y);
  38939. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38940. }
  38941. else
  38942. {
  38943. // to be able to do a drag-and-drop operation, the listbox needs to
  38944. // be inside a component which is also a DragAndDropContainer.
  38945. jassertfalse;
  38946. }
  38947. }
  38948. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38949. {
  38950. (void) existingComponentToUpdate;
  38951. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38952. return 0;
  38953. }
  38954. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38955. {
  38956. }
  38957. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38958. {
  38959. }
  38960. void ListBoxModel::backgroundClicked()
  38961. {
  38962. }
  38963. void ListBoxModel::selectedRowsChanged (int)
  38964. {
  38965. }
  38966. void ListBoxModel::deleteKeyPressed (int)
  38967. {
  38968. }
  38969. void ListBoxModel::returnKeyPressed (int)
  38970. {
  38971. }
  38972. void ListBoxModel::listWasScrolled()
  38973. {
  38974. }
  38975. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38976. {
  38977. return String::empty;
  38978. }
  38979. const String ListBoxModel::getTooltipForRow (int)
  38980. {
  38981. return String::empty;
  38982. }
  38983. END_JUCE_NAMESPACE
  38984. /*** End of inlined file: juce_ListBox.cpp ***/
  38985. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38986. BEGIN_JUCE_NAMESPACE
  38987. ProgressBar::ProgressBar (double& progress_)
  38988. : progress (progress_),
  38989. displayPercentage (true),
  38990. lastCallbackTime (0)
  38991. {
  38992. currentValue = jlimit (0.0, 1.0, progress);
  38993. }
  38994. ProgressBar::~ProgressBar()
  38995. {
  38996. }
  38997. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38998. {
  38999. displayPercentage = shouldDisplayPercentage;
  39000. repaint();
  39001. }
  39002. void ProgressBar::setTextToDisplay (const String& text)
  39003. {
  39004. displayPercentage = false;
  39005. displayedMessage = text;
  39006. }
  39007. void ProgressBar::lookAndFeelChanged()
  39008. {
  39009. setOpaque (findColour (backgroundColourId).isOpaque());
  39010. }
  39011. void ProgressBar::colourChanged()
  39012. {
  39013. lookAndFeelChanged();
  39014. }
  39015. void ProgressBar::paint (Graphics& g)
  39016. {
  39017. String text;
  39018. if (displayPercentage)
  39019. {
  39020. if (currentValue >= 0 && currentValue <= 1.0)
  39021. text << roundToInt (currentValue * 100.0) << '%';
  39022. }
  39023. else
  39024. {
  39025. text = displayedMessage;
  39026. }
  39027. getLookAndFeel().drawProgressBar (g, *this,
  39028. getWidth(), getHeight(),
  39029. currentValue, text);
  39030. }
  39031. void ProgressBar::visibilityChanged()
  39032. {
  39033. if (isVisible())
  39034. startTimer (30);
  39035. else
  39036. stopTimer();
  39037. }
  39038. void ProgressBar::timerCallback()
  39039. {
  39040. double newProgress = progress;
  39041. const uint32 now = Time::getMillisecondCounter();
  39042. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39043. lastCallbackTime = now;
  39044. if (currentValue != newProgress
  39045. || newProgress < 0 || newProgress >= 1.0
  39046. || currentMessage != displayedMessage)
  39047. {
  39048. if (currentValue < newProgress
  39049. && newProgress >= 0 && newProgress < 1.0
  39050. && currentValue >= 0 && currentValue < 1.0)
  39051. {
  39052. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39053. newProgress);
  39054. }
  39055. currentValue = newProgress;
  39056. currentMessage = displayedMessage;
  39057. repaint();
  39058. }
  39059. }
  39060. END_JUCE_NAMESPACE
  39061. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39062. /*** Start of inlined file: juce_Slider.cpp ***/
  39063. BEGIN_JUCE_NAMESPACE
  39064. class SliderPopupDisplayComponent : public BubbleComponent
  39065. {
  39066. public:
  39067. SliderPopupDisplayComponent (Slider* const owner_)
  39068. : owner (owner_),
  39069. font (15.0f, Font::bold)
  39070. {
  39071. setAlwaysOnTop (true);
  39072. }
  39073. ~SliderPopupDisplayComponent()
  39074. {
  39075. }
  39076. void paintContent (Graphics& g, int w, int h)
  39077. {
  39078. g.setFont (font);
  39079. g.setColour (Colours::black);
  39080. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39081. }
  39082. void getContentSize (int& w, int& h)
  39083. {
  39084. w = font.getStringWidth (text) + 18;
  39085. h = (int) (font.getHeight() * 1.6f);
  39086. }
  39087. void updatePosition (const String& newText)
  39088. {
  39089. if (text != newText)
  39090. {
  39091. text = newText;
  39092. repaint();
  39093. }
  39094. BubbleComponent::setPosition (owner);
  39095. }
  39096. juce_UseDebuggingNewOperator
  39097. private:
  39098. Slider* owner;
  39099. Font font;
  39100. String text;
  39101. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39102. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39103. };
  39104. Slider::Slider (const String& name)
  39105. : Component (name),
  39106. lastCurrentValue (0),
  39107. lastValueMin (0),
  39108. lastValueMax (0),
  39109. minimum (0),
  39110. maximum (10),
  39111. interval (0),
  39112. skewFactor (1.0),
  39113. velocityModeSensitivity (1.0),
  39114. velocityModeOffset (0.0),
  39115. velocityModeThreshold (1),
  39116. rotaryStart (float_Pi * 1.2f),
  39117. rotaryEnd (float_Pi * 2.8f),
  39118. numDecimalPlaces (7),
  39119. sliderRegionStart (0),
  39120. sliderRegionSize (1),
  39121. sliderBeingDragged (-1),
  39122. pixelsForFullDragExtent (250),
  39123. style (LinearHorizontal),
  39124. textBoxPos (TextBoxLeft),
  39125. textBoxWidth (80),
  39126. textBoxHeight (20),
  39127. incDecButtonMode (incDecButtonsNotDraggable),
  39128. editableText (true),
  39129. doubleClickToValue (false),
  39130. isVelocityBased (false),
  39131. userKeyOverridesVelocity (true),
  39132. rotaryStop (true),
  39133. incDecButtonsSideBySide (false),
  39134. sendChangeOnlyOnRelease (false),
  39135. popupDisplayEnabled (false),
  39136. menuEnabled (false),
  39137. menuShown (false),
  39138. scrollWheelEnabled (true),
  39139. snapsToMousePos (true),
  39140. valueBox (0),
  39141. incButton (0),
  39142. decButton (0),
  39143. popupDisplay (0),
  39144. parentForPopupDisplay (0)
  39145. {
  39146. setWantsKeyboardFocus (false);
  39147. setRepaintsOnMouseActivity (true);
  39148. lookAndFeelChanged();
  39149. updateText();
  39150. currentValue.addListener (this);
  39151. valueMin.addListener (this);
  39152. valueMax.addListener (this);
  39153. }
  39154. Slider::~Slider()
  39155. {
  39156. currentValue.removeListener (this);
  39157. valueMin.removeListener (this);
  39158. valueMax.removeListener (this);
  39159. popupDisplay = 0;
  39160. deleteAllChildren();
  39161. }
  39162. void Slider::handleAsyncUpdate()
  39163. {
  39164. cancelPendingUpdate();
  39165. Component::BailOutChecker checker (this);
  39166. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  39167. }
  39168. void Slider::sendDragStart()
  39169. {
  39170. startedDragging();
  39171. Component::BailOutChecker checker (this);
  39172. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39173. }
  39174. void Slider::sendDragEnd()
  39175. {
  39176. stoppedDragging();
  39177. sliderBeingDragged = -1;
  39178. Component::BailOutChecker checker (this);
  39179. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39180. }
  39181. void Slider::addListener (SliderListener* const listener)
  39182. {
  39183. listeners.add (listener);
  39184. }
  39185. void Slider::removeListener (SliderListener* const listener)
  39186. {
  39187. listeners.remove (listener);
  39188. }
  39189. void Slider::setSliderStyle (const SliderStyle newStyle)
  39190. {
  39191. if (style != newStyle)
  39192. {
  39193. style = newStyle;
  39194. repaint();
  39195. lookAndFeelChanged();
  39196. }
  39197. }
  39198. void Slider::setRotaryParameters (const float startAngleRadians,
  39199. const float endAngleRadians,
  39200. const bool stopAtEnd)
  39201. {
  39202. // make sure the values are sensible..
  39203. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39204. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39205. jassert (rotaryStart < rotaryEnd);
  39206. rotaryStart = startAngleRadians;
  39207. rotaryEnd = endAngleRadians;
  39208. rotaryStop = stopAtEnd;
  39209. }
  39210. void Slider::setVelocityBasedMode (const bool velBased)
  39211. {
  39212. isVelocityBased = velBased;
  39213. }
  39214. void Slider::setVelocityModeParameters (const double sensitivity,
  39215. const int threshold,
  39216. const double offset,
  39217. const bool userCanPressKeyToSwapMode)
  39218. {
  39219. jassert (threshold >= 0);
  39220. jassert (sensitivity > 0);
  39221. jassert (offset >= 0);
  39222. velocityModeSensitivity = sensitivity;
  39223. velocityModeOffset = offset;
  39224. velocityModeThreshold = threshold;
  39225. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39226. }
  39227. void Slider::setSkewFactor (const double factor)
  39228. {
  39229. skewFactor = factor;
  39230. }
  39231. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39232. {
  39233. if (maximum > minimum)
  39234. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39235. / (maximum - minimum));
  39236. }
  39237. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39238. {
  39239. jassert (distanceForFullScaleDrag > 0);
  39240. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39241. }
  39242. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39243. {
  39244. if (incDecButtonMode != mode)
  39245. {
  39246. incDecButtonMode = mode;
  39247. lookAndFeelChanged();
  39248. }
  39249. }
  39250. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39251. const bool isReadOnly,
  39252. const int textEntryBoxWidth,
  39253. const int textEntryBoxHeight)
  39254. {
  39255. if (textBoxPos != newPosition
  39256. || editableText != (! isReadOnly)
  39257. || textBoxWidth != textEntryBoxWidth
  39258. || textBoxHeight != textEntryBoxHeight)
  39259. {
  39260. textBoxPos = newPosition;
  39261. editableText = ! isReadOnly;
  39262. textBoxWidth = textEntryBoxWidth;
  39263. textBoxHeight = textEntryBoxHeight;
  39264. repaint();
  39265. lookAndFeelChanged();
  39266. }
  39267. }
  39268. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39269. {
  39270. editableText = shouldBeEditable;
  39271. if (valueBox != 0)
  39272. valueBox->setEditable (shouldBeEditable && isEnabled());
  39273. }
  39274. void Slider::showTextBox()
  39275. {
  39276. jassert (editableText); // this should probably be avoided in read-only sliders.
  39277. if (valueBox != 0)
  39278. valueBox->showEditor();
  39279. }
  39280. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39281. {
  39282. if (valueBox != 0)
  39283. {
  39284. valueBox->hideEditor (discardCurrentEditorContents);
  39285. if (discardCurrentEditorContents)
  39286. updateText();
  39287. }
  39288. }
  39289. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39290. {
  39291. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39292. }
  39293. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39294. {
  39295. snapsToMousePos = shouldSnapToMouse;
  39296. }
  39297. void Slider::setPopupDisplayEnabled (const bool enabled,
  39298. Component* const parentComponentToUse)
  39299. {
  39300. popupDisplayEnabled = enabled;
  39301. parentForPopupDisplay = parentComponentToUse;
  39302. }
  39303. void Slider::colourChanged()
  39304. {
  39305. lookAndFeelChanged();
  39306. }
  39307. void Slider::lookAndFeelChanged()
  39308. {
  39309. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39310. : getTextFromValue (currentValue.getValue()));
  39311. deleteAllChildren();
  39312. valueBox = 0;
  39313. LookAndFeel& lf = getLookAndFeel();
  39314. if (textBoxPos != NoTextBox)
  39315. {
  39316. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39317. valueBox->setWantsKeyboardFocus (false);
  39318. valueBox->setText (previousTextBoxContent, false);
  39319. valueBox->setEditable (editableText && isEnabled());
  39320. valueBox->addListener (this);
  39321. if (style == LinearBar)
  39322. valueBox->addMouseListener (this, false);
  39323. valueBox->setTooltip (getTooltip());
  39324. }
  39325. if (style == IncDecButtons)
  39326. {
  39327. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39328. incButton->addButtonListener (this);
  39329. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39330. decButton->addButtonListener (this);
  39331. if (incDecButtonMode != incDecButtonsNotDraggable)
  39332. {
  39333. incButton->addMouseListener (this, false);
  39334. decButton->addMouseListener (this, false);
  39335. }
  39336. else
  39337. {
  39338. incButton->setRepeatSpeed (300, 100, 20);
  39339. incButton->addMouseListener (decButton, false);
  39340. decButton->setRepeatSpeed (300, 100, 20);
  39341. decButton->addMouseListener (incButton, false);
  39342. }
  39343. incButton->setTooltip (getTooltip());
  39344. decButton->setTooltip (getTooltip());
  39345. }
  39346. setComponentEffect (lf.getSliderEffect());
  39347. resized();
  39348. repaint();
  39349. }
  39350. void Slider::setRange (const double newMin,
  39351. const double newMax,
  39352. const double newInt)
  39353. {
  39354. if (minimum != newMin
  39355. || maximum != newMax
  39356. || interval != newInt)
  39357. {
  39358. minimum = newMin;
  39359. maximum = newMax;
  39360. interval = newInt;
  39361. // figure out the number of DPs needed to display all values at this
  39362. // interval setting.
  39363. numDecimalPlaces = 7;
  39364. if (newInt != 0)
  39365. {
  39366. int v = abs ((int) (newInt * 10000000));
  39367. while ((v % 10) == 0)
  39368. {
  39369. --numDecimalPlaces;
  39370. v /= 10;
  39371. }
  39372. }
  39373. // keep the current values inside the new range..
  39374. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39375. {
  39376. setValue (getValue(), false, false);
  39377. }
  39378. else
  39379. {
  39380. setMinValue (getMinValue(), false, false);
  39381. setMaxValue (getMaxValue(), false, false);
  39382. }
  39383. updateText();
  39384. }
  39385. }
  39386. void Slider::triggerChangeMessage (const bool synchronous)
  39387. {
  39388. if (synchronous)
  39389. handleAsyncUpdate();
  39390. else
  39391. triggerAsyncUpdate();
  39392. valueChanged();
  39393. }
  39394. void Slider::valueChanged (Value& value)
  39395. {
  39396. if (value.refersToSameSourceAs (currentValue))
  39397. {
  39398. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39399. setValue (currentValue.getValue(), false, false);
  39400. }
  39401. else if (value.refersToSameSourceAs (valueMin))
  39402. setMinValue (valueMin.getValue(), false, false, true);
  39403. else if (value.refersToSameSourceAs (valueMax))
  39404. setMaxValue (valueMax.getValue(), false, false, true);
  39405. }
  39406. double Slider::getValue() const
  39407. {
  39408. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39409. // methods to get the two values.
  39410. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39411. return currentValue.getValue();
  39412. }
  39413. void Slider::setValue (double newValue,
  39414. const bool sendUpdateMessage,
  39415. const bool sendMessageSynchronously)
  39416. {
  39417. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39418. // methods to set the two values.
  39419. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39420. newValue = constrainedValue (newValue);
  39421. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39422. {
  39423. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39424. newValue = jlimit ((double) valueMin.getValue(),
  39425. (double) valueMax.getValue(),
  39426. newValue);
  39427. }
  39428. if (newValue != lastCurrentValue)
  39429. {
  39430. if (valueBox != 0)
  39431. valueBox->hideEditor (true);
  39432. lastCurrentValue = newValue;
  39433. currentValue = newValue;
  39434. updateText();
  39435. repaint();
  39436. if (popupDisplay != 0)
  39437. {
  39438. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39439. ->updatePosition (getTextFromValue (newValue));
  39440. popupDisplay->repaint();
  39441. }
  39442. if (sendUpdateMessage)
  39443. triggerChangeMessage (sendMessageSynchronously);
  39444. }
  39445. }
  39446. double Slider::getMinValue() const
  39447. {
  39448. // The minimum value only applies to sliders that are in two- or three-value mode.
  39449. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39450. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39451. return valueMin.getValue();
  39452. }
  39453. double Slider::getMaxValue() const
  39454. {
  39455. // The maximum value only applies to sliders that are in two- or three-value mode.
  39456. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39457. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39458. return valueMax.getValue();
  39459. }
  39460. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39461. {
  39462. // The minimum value only applies to sliders that are in two- or three-value mode.
  39463. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39464. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39465. newValue = constrainedValue (newValue);
  39466. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39467. {
  39468. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39469. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39470. newValue = jmin ((double) valueMax.getValue(), newValue);
  39471. }
  39472. else
  39473. {
  39474. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39475. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39476. newValue = jmin (lastCurrentValue, newValue);
  39477. }
  39478. if (lastValueMin != newValue)
  39479. {
  39480. lastValueMin = newValue;
  39481. valueMin = newValue;
  39482. repaint();
  39483. if (popupDisplay != 0)
  39484. {
  39485. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39486. ->updatePosition (getTextFromValue (newValue));
  39487. popupDisplay->repaint();
  39488. }
  39489. if (sendUpdateMessage)
  39490. triggerChangeMessage (sendMessageSynchronously);
  39491. }
  39492. }
  39493. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39494. {
  39495. // The maximum value only applies to sliders that are in two- or three-value mode.
  39496. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39497. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39498. newValue = constrainedValue (newValue);
  39499. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39500. {
  39501. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39502. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39503. newValue = jmax ((double) valueMin.getValue(), newValue);
  39504. }
  39505. else
  39506. {
  39507. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39508. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39509. newValue = jmax (lastCurrentValue, newValue);
  39510. }
  39511. if (lastValueMax != newValue)
  39512. {
  39513. lastValueMax = newValue;
  39514. valueMax = newValue;
  39515. repaint();
  39516. if (popupDisplay != 0)
  39517. {
  39518. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39519. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39520. popupDisplay->repaint();
  39521. }
  39522. if (sendUpdateMessage)
  39523. triggerChangeMessage (sendMessageSynchronously);
  39524. }
  39525. }
  39526. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39527. const double valueToSetOnDoubleClick)
  39528. {
  39529. doubleClickToValue = isDoubleClickEnabled;
  39530. doubleClickReturnValue = valueToSetOnDoubleClick;
  39531. }
  39532. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39533. {
  39534. isEnabled_ = doubleClickToValue;
  39535. return doubleClickReturnValue;
  39536. }
  39537. void Slider::updateText()
  39538. {
  39539. if (valueBox != 0)
  39540. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39541. }
  39542. void Slider::setTextValueSuffix (const String& suffix)
  39543. {
  39544. if (textSuffix != suffix)
  39545. {
  39546. textSuffix = suffix;
  39547. updateText();
  39548. }
  39549. }
  39550. const String Slider::getTextValueSuffix() const
  39551. {
  39552. return textSuffix;
  39553. }
  39554. const String Slider::getTextFromValue (double v)
  39555. {
  39556. if (getNumDecimalPlacesToDisplay() > 0)
  39557. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39558. else
  39559. return String (roundToInt (v)) + getTextValueSuffix();
  39560. }
  39561. double Slider::getValueFromText (const String& text)
  39562. {
  39563. String t (text.trimStart());
  39564. if (t.endsWith (textSuffix))
  39565. t = t.substring (0, t.length() - textSuffix.length());
  39566. while (t.startsWithChar ('+'))
  39567. t = t.substring (1).trimStart();
  39568. return t.initialSectionContainingOnly ("0123456789.,-")
  39569. .getDoubleValue();
  39570. }
  39571. double Slider::proportionOfLengthToValue (double proportion)
  39572. {
  39573. if (skewFactor != 1.0 && proportion > 0.0)
  39574. proportion = exp (log (proportion) / skewFactor);
  39575. return minimum + (maximum - minimum) * proportion;
  39576. }
  39577. double Slider::valueToProportionOfLength (double value)
  39578. {
  39579. const double n = (value - minimum) / (maximum - minimum);
  39580. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39581. }
  39582. double Slider::snapValue (double attemptedValue, const bool)
  39583. {
  39584. return attemptedValue;
  39585. }
  39586. void Slider::startedDragging()
  39587. {
  39588. }
  39589. void Slider::stoppedDragging()
  39590. {
  39591. }
  39592. void Slider::valueChanged()
  39593. {
  39594. }
  39595. void Slider::enablementChanged()
  39596. {
  39597. repaint();
  39598. }
  39599. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39600. {
  39601. menuEnabled = menuEnabled_;
  39602. }
  39603. void Slider::setScrollWheelEnabled (const bool enabled)
  39604. {
  39605. scrollWheelEnabled = enabled;
  39606. }
  39607. void Slider::labelTextChanged (Label* label)
  39608. {
  39609. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39610. if (newValue != (double) currentValue.getValue())
  39611. {
  39612. sendDragStart();
  39613. setValue (newValue, true, true);
  39614. sendDragEnd();
  39615. }
  39616. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39617. }
  39618. void Slider::buttonClicked (Button* button)
  39619. {
  39620. if (style == IncDecButtons)
  39621. {
  39622. sendDragStart();
  39623. if (button == incButton)
  39624. setValue (snapValue (getValue() + interval, false), true, true);
  39625. else if (button == decButton)
  39626. setValue (snapValue (getValue() - interval, false), true, true);
  39627. sendDragEnd();
  39628. }
  39629. }
  39630. double Slider::constrainedValue (double value) const
  39631. {
  39632. if (interval > 0)
  39633. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39634. if (value <= minimum || maximum <= minimum)
  39635. value = minimum;
  39636. else if (value >= maximum)
  39637. value = maximum;
  39638. return value;
  39639. }
  39640. float Slider::getLinearSliderPos (const double value)
  39641. {
  39642. double sliderPosProportional;
  39643. if (maximum > minimum)
  39644. {
  39645. if (value < minimum)
  39646. {
  39647. sliderPosProportional = 0.0;
  39648. }
  39649. else if (value > maximum)
  39650. {
  39651. sliderPosProportional = 1.0;
  39652. }
  39653. else
  39654. {
  39655. sliderPosProportional = valueToProportionOfLength (value);
  39656. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39657. }
  39658. }
  39659. else
  39660. {
  39661. sliderPosProportional = 0.5;
  39662. }
  39663. if (isVertical() || style == IncDecButtons)
  39664. sliderPosProportional = 1.0 - sliderPosProportional;
  39665. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39666. }
  39667. bool Slider::isHorizontal() const
  39668. {
  39669. return style == LinearHorizontal
  39670. || style == LinearBar
  39671. || style == TwoValueHorizontal
  39672. || style == ThreeValueHorizontal;
  39673. }
  39674. bool Slider::isVertical() const
  39675. {
  39676. return style == LinearVertical
  39677. || style == TwoValueVertical
  39678. || style == ThreeValueVertical;
  39679. }
  39680. bool Slider::incDecDragDirectionIsHorizontal() const
  39681. {
  39682. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39683. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39684. }
  39685. float Slider::getPositionOfValue (const double value)
  39686. {
  39687. if (isHorizontal() || isVertical())
  39688. {
  39689. return getLinearSliderPos (value);
  39690. }
  39691. else
  39692. {
  39693. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39694. return 0.0f;
  39695. }
  39696. }
  39697. void Slider::paint (Graphics& g)
  39698. {
  39699. if (style != IncDecButtons)
  39700. {
  39701. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39702. {
  39703. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39704. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39705. getLookAndFeel().drawRotarySlider (g,
  39706. sliderRect.getX(),
  39707. sliderRect.getY(),
  39708. sliderRect.getWidth(),
  39709. sliderRect.getHeight(),
  39710. sliderPos,
  39711. rotaryStart, rotaryEnd,
  39712. *this);
  39713. }
  39714. else
  39715. {
  39716. getLookAndFeel().drawLinearSlider (g,
  39717. sliderRect.getX(),
  39718. sliderRect.getY(),
  39719. sliderRect.getWidth(),
  39720. sliderRect.getHeight(),
  39721. getLinearSliderPos (lastCurrentValue),
  39722. getLinearSliderPos (lastValueMin),
  39723. getLinearSliderPos (lastValueMax),
  39724. style,
  39725. *this);
  39726. }
  39727. if (style == LinearBar && valueBox == 0)
  39728. {
  39729. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39730. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39731. }
  39732. }
  39733. }
  39734. void Slider::resized()
  39735. {
  39736. int minXSpace = 0;
  39737. int minYSpace = 0;
  39738. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39739. minXSpace = 30;
  39740. else
  39741. minYSpace = 15;
  39742. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39743. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39744. if (style == LinearBar)
  39745. {
  39746. if (valueBox != 0)
  39747. valueBox->setBounds (getLocalBounds());
  39748. }
  39749. else
  39750. {
  39751. if (textBoxPos == NoTextBox)
  39752. {
  39753. sliderRect = getLocalBounds();
  39754. }
  39755. else if (textBoxPos == TextBoxLeft)
  39756. {
  39757. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39758. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39759. }
  39760. else if (textBoxPos == TextBoxRight)
  39761. {
  39762. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39763. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39764. }
  39765. else if (textBoxPos == TextBoxAbove)
  39766. {
  39767. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39768. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39769. }
  39770. else if (textBoxPos == TextBoxBelow)
  39771. {
  39772. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39773. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39774. }
  39775. }
  39776. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39777. if (style == LinearBar)
  39778. {
  39779. const int barIndent = 1;
  39780. sliderRegionStart = barIndent;
  39781. sliderRegionSize = getWidth() - barIndent * 2;
  39782. sliderRect.setBounds (sliderRegionStart, barIndent,
  39783. sliderRegionSize, getHeight() - barIndent * 2);
  39784. }
  39785. else if (isHorizontal())
  39786. {
  39787. sliderRegionStart = sliderRect.getX() + indent;
  39788. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39789. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39790. sliderRegionSize, sliderRect.getHeight());
  39791. }
  39792. else if (isVertical())
  39793. {
  39794. sliderRegionStart = sliderRect.getY() + indent;
  39795. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39796. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39797. sliderRect.getWidth(), sliderRegionSize);
  39798. }
  39799. else
  39800. {
  39801. sliderRegionStart = 0;
  39802. sliderRegionSize = 100;
  39803. }
  39804. if (style == IncDecButtons)
  39805. {
  39806. Rectangle<int> buttonRect (sliderRect);
  39807. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39808. buttonRect.expand (-2, 0);
  39809. else
  39810. buttonRect.expand (0, -2);
  39811. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39812. if (incDecButtonsSideBySide)
  39813. {
  39814. decButton->setBounds (buttonRect.getX(),
  39815. buttonRect.getY(),
  39816. buttonRect.getWidth() / 2,
  39817. buttonRect.getHeight());
  39818. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39819. incButton->setBounds (buttonRect.getCentreX(),
  39820. buttonRect.getY(),
  39821. buttonRect.getWidth() / 2,
  39822. buttonRect.getHeight());
  39823. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39824. }
  39825. else
  39826. {
  39827. incButton->setBounds (buttonRect.getX(),
  39828. buttonRect.getY(),
  39829. buttonRect.getWidth(),
  39830. buttonRect.getHeight() / 2);
  39831. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39832. decButton->setBounds (buttonRect.getX(),
  39833. buttonRect.getCentreY(),
  39834. buttonRect.getWidth(),
  39835. buttonRect.getHeight() / 2);
  39836. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39837. }
  39838. }
  39839. }
  39840. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39841. {
  39842. repaint();
  39843. }
  39844. void Slider::mouseDown (const MouseEvent& e)
  39845. {
  39846. mouseWasHidden = false;
  39847. incDecDragged = false;
  39848. mouseXWhenLastDragged = e.x;
  39849. mouseYWhenLastDragged = e.y;
  39850. mouseDragStartX = e.getMouseDownX();
  39851. mouseDragStartY = e.getMouseDownY();
  39852. if (isEnabled())
  39853. {
  39854. if (e.mods.isPopupMenu() && menuEnabled)
  39855. {
  39856. menuShown = true;
  39857. PopupMenu m;
  39858. m.setLookAndFeel (&getLookAndFeel());
  39859. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39860. m.addSeparator();
  39861. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39862. {
  39863. PopupMenu rotaryMenu;
  39864. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39865. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39866. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39867. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39868. }
  39869. const int r = m.show();
  39870. if (r == 1)
  39871. {
  39872. setVelocityBasedMode (! isVelocityBased);
  39873. }
  39874. else if (r == 2)
  39875. {
  39876. setSliderStyle (Rotary);
  39877. }
  39878. else if (r == 3)
  39879. {
  39880. setSliderStyle (RotaryHorizontalDrag);
  39881. }
  39882. else if (r == 4)
  39883. {
  39884. setSliderStyle (RotaryVerticalDrag);
  39885. }
  39886. }
  39887. else if (maximum > minimum)
  39888. {
  39889. menuShown = false;
  39890. if (valueBox != 0)
  39891. valueBox->hideEditor (true);
  39892. sliderBeingDragged = 0;
  39893. if (style == TwoValueHorizontal
  39894. || style == TwoValueVertical
  39895. || style == ThreeValueHorizontal
  39896. || style == ThreeValueVertical)
  39897. {
  39898. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39899. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39900. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39901. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39902. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39903. {
  39904. if (maxPosDistance <= minPosDistance)
  39905. sliderBeingDragged = 2;
  39906. else
  39907. sliderBeingDragged = 1;
  39908. }
  39909. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39910. {
  39911. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39912. sliderBeingDragged = 1;
  39913. else if (normalPosDistance >= maxPosDistance)
  39914. sliderBeingDragged = 2;
  39915. }
  39916. }
  39917. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39918. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39919. * valueToProportionOfLength (currentValue.getValue());
  39920. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39921. : ((sliderBeingDragged == 1) ? valueMin
  39922. : currentValue)).getValue();
  39923. valueOnMouseDown = valueWhenLastDragged;
  39924. if (popupDisplayEnabled)
  39925. {
  39926. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39927. popupDisplay = popup;
  39928. if (parentForPopupDisplay != 0)
  39929. {
  39930. parentForPopupDisplay->addChildComponent (popup);
  39931. }
  39932. else
  39933. {
  39934. popup->addToDesktop (0);
  39935. }
  39936. popup->setVisible (true);
  39937. }
  39938. sendDragStart();
  39939. mouseDrag (e);
  39940. }
  39941. }
  39942. }
  39943. void Slider::mouseUp (const MouseEvent&)
  39944. {
  39945. if (isEnabled()
  39946. && (! menuShown)
  39947. && (maximum > minimum)
  39948. && (style != IncDecButtons || incDecDragged))
  39949. {
  39950. restoreMouseIfHidden();
  39951. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39952. triggerChangeMessage (false);
  39953. sendDragEnd();
  39954. popupDisplay = 0;
  39955. if (style == IncDecButtons)
  39956. {
  39957. incButton->setState (Button::buttonNormal);
  39958. decButton->setState (Button::buttonNormal);
  39959. }
  39960. }
  39961. }
  39962. void Slider::restoreMouseIfHidden()
  39963. {
  39964. if (mouseWasHidden)
  39965. {
  39966. mouseWasHidden = false;
  39967. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39968. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39969. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39970. : ((sliderBeingDragged == 1) ? getMinValue()
  39971. : (double) currentValue.getValue());
  39972. Point<int> mousePos;
  39973. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39974. {
  39975. mousePos = Desktop::getLastMouseDownPosition();
  39976. if (style == RotaryHorizontalDrag)
  39977. {
  39978. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39979. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39980. }
  39981. else
  39982. {
  39983. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39984. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39985. }
  39986. }
  39987. else
  39988. {
  39989. const int pixelPos = (int) getLinearSliderPos (pos);
  39990. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39991. isVertical() ? pixelPos : (getHeight() / 2)));
  39992. }
  39993. Desktop::setMousePosition (mousePos);
  39994. }
  39995. }
  39996. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39997. {
  39998. if (isEnabled()
  39999. && style != IncDecButtons
  40000. && style != Rotary
  40001. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40002. {
  40003. restoreMouseIfHidden();
  40004. }
  40005. }
  40006. static double smallestAngleBetween (double a1, double a2)
  40007. {
  40008. return jmin (std::abs (a1 - a2),
  40009. std::abs (a1 + double_Pi * 2.0 - a2),
  40010. std::abs (a2 + double_Pi * 2.0 - a1));
  40011. }
  40012. void Slider::mouseDrag (const MouseEvent& e)
  40013. {
  40014. if (isEnabled()
  40015. && (! menuShown)
  40016. && (maximum > minimum))
  40017. {
  40018. if (style == Rotary)
  40019. {
  40020. int dx = e.x - sliderRect.getCentreX();
  40021. int dy = e.y - sliderRect.getCentreY();
  40022. if (dx * dx + dy * dy > 25)
  40023. {
  40024. double angle = std::atan2 ((double) dx, (double) -dy);
  40025. while (angle < 0.0)
  40026. angle += double_Pi * 2.0;
  40027. if (rotaryStop && ! e.mouseWasClicked())
  40028. {
  40029. if (std::abs (angle - lastAngle) > double_Pi)
  40030. {
  40031. if (angle >= lastAngle)
  40032. angle -= double_Pi * 2.0;
  40033. else
  40034. angle += double_Pi * 2.0;
  40035. }
  40036. if (angle >= lastAngle)
  40037. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40038. else
  40039. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40040. }
  40041. else
  40042. {
  40043. while (angle < rotaryStart)
  40044. angle += double_Pi * 2.0;
  40045. if (angle > rotaryEnd)
  40046. {
  40047. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40048. angle = rotaryStart;
  40049. else
  40050. angle = rotaryEnd;
  40051. }
  40052. }
  40053. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40054. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40055. lastAngle = angle;
  40056. }
  40057. }
  40058. else
  40059. {
  40060. if (style == LinearBar && e.mouseWasClicked()
  40061. && valueBox != 0 && valueBox->isEditable())
  40062. return;
  40063. if (style == IncDecButtons && ! incDecDragged)
  40064. {
  40065. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40066. return;
  40067. incDecDragged = true;
  40068. mouseDragStartX = e.x;
  40069. mouseDragStartY = e.y;
  40070. }
  40071. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40072. : false))
  40073. || ((maximum - minimum) / sliderRegionSize < interval))
  40074. {
  40075. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40076. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40077. if (style == RotaryHorizontalDrag
  40078. || style == RotaryVerticalDrag
  40079. || style == IncDecButtons
  40080. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40081. && ! snapsToMousePos))
  40082. {
  40083. const int mouseDiff = (style == RotaryHorizontalDrag
  40084. || style == LinearHorizontal
  40085. || style == LinearBar
  40086. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40087. ? e.x - mouseDragStartX
  40088. : mouseDragStartY - e.y;
  40089. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40090. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40091. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40092. if (style == IncDecButtons)
  40093. {
  40094. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40095. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40096. }
  40097. }
  40098. else
  40099. {
  40100. if (isVertical())
  40101. scaledMousePos = 1.0 - scaledMousePos;
  40102. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40103. }
  40104. }
  40105. else
  40106. {
  40107. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40108. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40109. ? e.x - mouseXWhenLastDragged
  40110. : e.y - mouseYWhenLastDragged;
  40111. const double maxSpeed = jmax (200, sliderRegionSize);
  40112. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40113. if (speed != 0)
  40114. {
  40115. speed = 0.2 * velocityModeSensitivity
  40116. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40117. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40118. / maxSpeed))));
  40119. if (mouseDiff < 0)
  40120. speed = -speed;
  40121. if (isVertical() || style == RotaryVerticalDrag
  40122. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40123. speed = -speed;
  40124. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40125. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40126. e.source.enableUnboundedMouseMovement (true, false);
  40127. mouseWasHidden = true;
  40128. }
  40129. }
  40130. }
  40131. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40132. if (sliderBeingDragged == 0)
  40133. {
  40134. setValue (snapValue (valueWhenLastDragged, true),
  40135. ! sendChangeOnlyOnRelease, true);
  40136. }
  40137. else if (sliderBeingDragged == 1)
  40138. {
  40139. setMinValue (snapValue (valueWhenLastDragged, true),
  40140. ! sendChangeOnlyOnRelease, false, true);
  40141. if (e.mods.isShiftDown())
  40142. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40143. else
  40144. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40145. }
  40146. else
  40147. {
  40148. jassert (sliderBeingDragged == 2);
  40149. setMaxValue (snapValue (valueWhenLastDragged, true),
  40150. ! sendChangeOnlyOnRelease, false, true);
  40151. if (e.mods.isShiftDown())
  40152. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40153. else
  40154. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40155. }
  40156. mouseXWhenLastDragged = e.x;
  40157. mouseYWhenLastDragged = e.y;
  40158. }
  40159. }
  40160. void Slider::mouseDoubleClick (const MouseEvent&)
  40161. {
  40162. if (doubleClickToValue
  40163. && isEnabled()
  40164. && style != IncDecButtons
  40165. && minimum <= doubleClickReturnValue
  40166. && maximum >= doubleClickReturnValue)
  40167. {
  40168. sendDragStart();
  40169. setValue (doubleClickReturnValue, true, true);
  40170. sendDragEnd();
  40171. }
  40172. }
  40173. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40174. {
  40175. if (scrollWheelEnabled && isEnabled()
  40176. && style != TwoValueHorizontal
  40177. && style != TwoValueVertical)
  40178. {
  40179. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40180. {
  40181. if (valueBox != 0)
  40182. valueBox->hideEditor (false);
  40183. const double value = (double) currentValue.getValue();
  40184. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40185. const double currentPos = valueToProportionOfLength (value);
  40186. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40187. double delta = (newValue != value)
  40188. ? jmax (std::abs (newValue - value), interval) : 0;
  40189. if (value > newValue)
  40190. delta = -delta;
  40191. sendDragStart();
  40192. setValue (snapValue (value + delta, false), true, true);
  40193. sendDragEnd();
  40194. }
  40195. }
  40196. else
  40197. {
  40198. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40199. }
  40200. }
  40201. void SliderListener::sliderDragStarted (Slider*)
  40202. {
  40203. }
  40204. void SliderListener::sliderDragEnded (Slider*)
  40205. {
  40206. }
  40207. END_JUCE_NAMESPACE
  40208. /*** End of inlined file: juce_Slider.cpp ***/
  40209. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40210. BEGIN_JUCE_NAMESPACE
  40211. class DragOverlayComp : public Component
  40212. {
  40213. public:
  40214. DragOverlayComp (const Image& image_)
  40215. : image (image_)
  40216. {
  40217. image.duplicateIfShared();
  40218. image.multiplyAllAlphas (0.8f);
  40219. setAlwaysOnTop (true);
  40220. }
  40221. ~DragOverlayComp()
  40222. {
  40223. }
  40224. void paint (Graphics& g)
  40225. {
  40226. g.drawImageAt (image, 0, 0);
  40227. }
  40228. private:
  40229. Image image;
  40230. DragOverlayComp (const DragOverlayComp&);
  40231. DragOverlayComp& operator= (const DragOverlayComp&);
  40232. };
  40233. TableHeaderComponent::TableHeaderComponent()
  40234. : columnsChanged (false),
  40235. columnsResized (false),
  40236. sortChanged (false),
  40237. menuActive (true),
  40238. stretchToFit (false),
  40239. columnIdBeingResized (0),
  40240. columnIdBeingDragged (0),
  40241. columnIdUnderMouse (0),
  40242. lastDeliberateWidth (0)
  40243. {
  40244. }
  40245. TableHeaderComponent::~TableHeaderComponent()
  40246. {
  40247. dragOverlayComp = 0;
  40248. }
  40249. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40250. {
  40251. menuActive = hasMenu;
  40252. }
  40253. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40254. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40255. {
  40256. if (onlyCountVisibleColumns)
  40257. {
  40258. int num = 0;
  40259. for (int i = columns.size(); --i >= 0;)
  40260. if (columns.getUnchecked(i)->isVisible())
  40261. ++num;
  40262. return num;
  40263. }
  40264. else
  40265. {
  40266. return columns.size();
  40267. }
  40268. }
  40269. const String TableHeaderComponent::getColumnName (const int columnId) const
  40270. {
  40271. const ColumnInfo* const ci = getInfoForId (columnId);
  40272. return ci != 0 ? ci->name : String::empty;
  40273. }
  40274. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40275. {
  40276. ColumnInfo* const ci = getInfoForId (columnId);
  40277. if (ci != 0 && ci->name != newName)
  40278. {
  40279. ci->name = newName;
  40280. sendColumnsChanged();
  40281. }
  40282. }
  40283. void TableHeaderComponent::addColumn (const String& columnName,
  40284. const int columnId,
  40285. const int width,
  40286. const int minimumWidth,
  40287. const int maximumWidth,
  40288. const int propertyFlags,
  40289. const int insertIndex)
  40290. {
  40291. // can't have a duplicate or null ID!
  40292. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40293. jassert (width > 0);
  40294. ColumnInfo* const ci = new ColumnInfo();
  40295. ci->name = columnName;
  40296. ci->id = columnId;
  40297. ci->width = width;
  40298. ci->lastDeliberateWidth = width;
  40299. ci->minimumWidth = minimumWidth;
  40300. ci->maximumWidth = maximumWidth;
  40301. if (ci->maximumWidth < 0)
  40302. ci->maximumWidth = std::numeric_limits<int>::max();
  40303. jassert (ci->maximumWidth >= ci->minimumWidth);
  40304. ci->propertyFlags = propertyFlags;
  40305. columns.insert (insertIndex, ci);
  40306. sendColumnsChanged();
  40307. }
  40308. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40309. {
  40310. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40311. if (index >= 0)
  40312. {
  40313. columns.remove (index);
  40314. sortChanged = true;
  40315. sendColumnsChanged();
  40316. }
  40317. }
  40318. void TableHeaderComponent::removeAllColumns()
  40319. {
  40320. if (columns.size() > 0)
  40321. {
  40322. columns.clear();
  40323. sendColumnsChanged();
  40324. }
  40325. }
  40326. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40327. {
  40328. const int currentIndex = getIndexOfColumnId (columnId, false);
  40329. newIndex = visibleIndexToTotalIndex (newIndex);
  40330. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40331. {
  40332. columns.move (currentIndex, newIndex);
  40333. sendColumnsChanged();
  40334. }
  40335. }
  40336. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40337. {
  40338. const ColumnInfo* const ci = getInfoForId (columnId);
  40339. return ci != 0 ? ci->width : 0;
  40340. }
  40341. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40342. {
  40343. ColumnInfo* const ci = getInfoForId (columnId);
  40344. if (ci != 0 && ci->width != newWidth)
  40345. {
  40346. const int numColumns = getNumColumns (true);
  40347. ci->lastDeliberateWidth = ci->width
  40348. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40349. if (stretchToFit)
  40350. {
  40351. const int index = getIndexOfColumnId (columnId, true) + 1;
  40352. if (((unsigned int) index) < (unsigned int) numColumns)
  40353. {
  40354. const int x = getColumnPosition (index).getX();
  40355. if (lastDeliberateWidth == 0)
  40356. lastDeliberateWidth = getTotalWidth();
  40357. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40358. }
  40359. }
  40360. repaint();
  40361. columnsResized = true;
  40362. triggerAsyncUpdate();
  40363. }
  40364. }
  40365. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40366. {
  40367. int n = 0;
  40368. for (int i = 0; i < columns.size(); ++i)
  40369. {
  40370. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40371. {
  40372. if (columns.getUnchecked(i)->id == columnId)
  40373. return n;
  40374. ++n;
  40375. }
  40376. }
  40377. return -1;
  40378. }
  40379. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40380. {
  40381. if (onlyCountVisibleColumns)
  40382. index = visibleIndexToTotalIndex (index);
  40383. const ColumnInfo* const ci = columns [index];
  40384. return (ci != 0) ? ci->id : 0;
  40385. }
  40386. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40387. {
  40388. int x = 0, width = 0, n = 0;
  40389. for (int i = 0; i < columns.size(); ++i)
  40390. {
  40391. x += width;
  40392. if (columns.getUnchecked(i)->isVisible())
  40393. {
  40394. width = columns.getUnchecked(i)->width;
  40395. if (n++ == index)
  40396. break;
  40397. }
  40398. else
  40399. {
  40400. width = 0;
  40401. }
  40402. }
  40403. return Rectangle<int> (x, 0, width, getHeight());
  40404. }
  40405. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40406. {
  40407. if (xToFind >= 0)
  40408. {
  40409. int x = 0;
  40410. for (int i = 0; i < columns.size(); ++i)
  40411. {
  40412. const ColumnInfo* const ci = columns.getUnchecked(i);
  40413. if (ci->isVisible())
  40414. {
  40415. x += ci->width;
  40416. if (xToFind < x)
  40417. return ci->id;
  40418. }
  40419. }
  40420. }
  40421. return 0;
  40422. }
  40423. int TableHeaderComponent::getTotalWidth() const
  40424. {
  40425. int w = 0;
  40426. for (int i = columns.size(); --i >= 0;)
  40427. if (columns.getUnchecked(i)->isVisible())
  40428. w += columns.getUnchecked(i)->width;
  40429. return w;
  40430. }
  40431. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40432. {
  40433. stretchToFit = shouldStretchToFit;
  40434. lastDeliberateWidth = getTotalWidth();
  40435. resized();
  40436. }
  40437. bool TableHeaderComponent::isStretchToFitActive() const
  40438. {
  40439. return stretchToFit;
  40440. }
  40441. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40442. {
  40443. if (stretchToFit && getWidth() > 0
  40444. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40445. {
  40446. lastDeliberateWidth = targetTotalWidth;
  40447. resizeColumnsToFit (0, targetTotalWidth);
  40448. }
  40449. }
  40450. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40451. {
  40452. targetTotalWidth = jmax (targetTotalWidth, 0);
  40453. StretchableObjectResizer sor;
  40454. int i;
  40455. for (i = firstColumnIndex; i < columns.size(); ++i)
  40456. {
  40457. ColumnInfo* const ci = columns.getUnchecked(i);
  40458. if (ci->isVisible())
  40459. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40460. }
  40461. sor.resizeToFit (targetTotalWidth);
  40462. int visIndex = 0;
  40463. for (i = firstColumnIndex; i < columns.size(); ++i)
  40464. {
  40465. ColumnInfo* const ci = columns.getUnchecked(i);
  40466. if (ci->isVisible())
  40467. {
  40468. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40469. (int) std::floor (sor.getItemSize (visIndex++)));
  40470. if (newWidth != ci->width)
  40471. {
  40472. ci->width = newWidth;
  40473. repaint();
  40474. columnsResized = true;
  40475. triggerAsyncUpdate();
  40476. }
  40477. }
  40478. }
  40479. }
  40480. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40481. {
  40482. ColumnInfo* const ci = getInfoForId (columnId);
  40483. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40484. {
  40485. if (shouldBeVisible)
  40486. ci->propertyFlags |= visible;
  40487. else
  40488. ci->propertyFlags &= ~visible;
  40489. sendColumnsChanged();
  40490. resized();
  40491. }
  40492. }
  40493. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40494. {
  40495. const ColumnInfo* const ci = getInfoForId (columnId);
  40496. return ci != 0 && ci->isVisible();
  40497. }
  40498. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40499. {
  40500. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40501. {
  40502. for (int i = columns.size(); --i >= 0;)
  40503. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40504. ColumnInfo* const ci = getInfoForId (columnId);
  40505. if (ci != 0)
  40506. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40507. reSortTable();
  40508. }
  40509. }
  40510. int TableHeaderComponent::getSortColumnId() const
  40511. {
  40512. for (int i = columns.size(); --i >= 0;)
  40513. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40514. return columns.getUnchecked(i)->id;
  40515. return 0;
  40516. }
  40517. bool TableHeaderComponent::isSortedForwards() const
  40518. {
  40519. for (int i = columns.size(); --i >= 0;)
  40520. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40521. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40522. return true;
  40523. }
  40524. void TableHeaderComponent::reSortTable()
  40525. {
  40526. sortChanged = true;
  40527. repaint();
  40528. triggerAsyncUpdate();
  40529. }
  40530. const String TableHeaderComponent::toString() const
  40531. {
  40532. String s;
  40533. XmlElement doc ("TABLELAYOUT");
  40534. doc.setAttribute ("sortedCol", getSortColumnId());
  40535. doc.setAttribute ("sortForwards", isSortedForwards());
  40536. for (int i = 0; i < columns.size(); ++i)
  40537. {
  40538. const ColumnInfo* const ci = columns.getUnchecked (i);
  40539. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40540. e->setAttribute ("id", ci->id);
  40541. e->setAttribute ("visible", ci->isVisible());
  40542. e->setAttribute ("width", ci->width);
  40543. }
  40544. return doc.createDocument (String::empty, true, false);
  40545. }
  40546. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40547. {
  40548. XmlDocument doc (storedVersion);
  40549. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40550. int index = 0;
  40551. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40552. {
  40553. forEachXmlChildElement (*storedXml, col)
  40554. {
  40555. const int tabId = col->getIntAttribute ("id");
  40556. ColumnInfo* const ci = getInfoForId (tabId);
  40557. if (ci != 0)
  40558. {
  40559. columns.move (columns.indexOf (ci), index);
  40560. ci->width = col->getIntAttribute ("width");
  40561. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40562. }
  40563. ++index;
  40564. }
  40565. columnsResized = true;
  40566. sendColumnsChanged();
  40567. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40568. storedXml->getBoolAttribute ("sortForwards", true));
  40569. }
  40570. }
  40571. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40572. {
  40573. listeners.addIfNotAlreadyThere (newListener);
  40574. }
  40575. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40576. {
  40577. listeners.removeValue (listenerToRemove);
  40578. }
  40579. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40580. {
  40581. const ColumnInfo* const ci = getInfoForId (columnId);
  40582. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40583. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40584. }
  40585. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40586. {
  40587. for (int i = 0; i < columns.size(); ++i)
  40588. {
  40589. const ColumnInfo* const ci = columns.getUnchecked(i);
  40590. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40591. menu.addItem (ci->id, ci->name,
  40592. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40593. isColumnVisible (ci->id));
  40594. }
  40595. }
  40596. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40597. {
  40598. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40599. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40600. }
  40601. void TableHeaderComponent::paint (Graphics& g)
  40602. {
  40603. LookAndFeel& lf = getLookAndFeel();
  40604. lf.drawTableHeaderBackground (g, *this);
  40605. const Rectangle<int> clip (g.getClipBounds());
  40606. int x = 0;
  40607. for (int i = 0; i < columns.size(); ++i)
  40608. {
  40609. const ColumnInfo* const ci = columns.getUnchecked(i);
  40610. if (ci->isVisible())
  40611. {
  40612. if (x + ci->width > clip.getX()
  40613. && (ci->id != columnIdBeingDragged
  40614. || dragOverlayComp == 0
  40615. || ! dragOverlayComp->isVisible()))
  40616. {
  40617. g.saveState();
  40618. g.setOrigin (x, 0);
  40619. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40620. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40621. ci->id == columnIdUnderMouse,
  40622. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40623. ci->propertyFlags);
  40624. g.restoreState();
  40625. }
  40626. x += ci->width;
  40627. if (x >= clip.getRight())
  40628. break;
  40629. }
  40630. }
  40631. }
  40632. void TableHeaderComponent::resized()
  40633. {
  40634. }
  40635. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40636. {
  40637. updateColumnUnderMouse (e.x, e.y);
  40638. }
  40639. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40640. {
  40641. updateColumnUnderMouse (e.x, e.y);
  40642. }
  40643. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40644. {
  40645. updateColumnUnderMouse (e.x, e.y);
  40646. }
  40647. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40648. {
  40649. repaint();
  40650. columnIdBeingResized = 0;
  40651. columnIdBeingDragged = 0;
  40652. if (columnIdUnderMouse != 0)
  40653. {
  40654. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40655. if (e.mods.isPopupMenu())
  40656. columnClicked (columnIdUnderMouse, e.mods);
  40657. }
  40658. if (menuActive && e.mods.isPopupMenu())
  40659. showColumnChooserMenu (columnIdUnderMouse);
  40660. }
  40661. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40662. {
  40663. if (columnIdBeingResized == 0
  40664. && columnIdBeingDragged == 0
  40665. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40666. {
  40667. dragOverlayComp = 0;
  40668. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40669. if (columnIdBeingResized != 0)
  40670. {
  40671. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40672. initialColumnWidth = ci->width;
  40673. }
  40674. else
  40675. {
  40676. beginDrag (e);
  40677. }
  40678. }
  40679. if (columnIdBeingResized != 0)
  40680. {
  40681. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40682. if (ci != 0)
  40683. {
  40684. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40685. initialColumnWidth + e.getDistanceFromDragStartX());
  40686. if (stretchToFit)
  40687. {
  40688. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40689. int minWidthOnRight = 0;
  40690. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40691. if (columns.getUnchecked (i)->isVisible())
  40692. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40693. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40694. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40695. }
  40696. setColumnWidth (columnIdBeingResized, w);
  40697. }
  40698. }
  40699. else if (columnIdBeingDragged != 0)
  40700. {
  40701. if (e.y >= -50 && e.y < getHeight() + 50)
  40702. {
  40703. if (dragOverlayComp != 0)
  40704. {
  40705. dragOverlayComp->setVisible (true);
  40706. dragOverlayComp->setBounds (jlimit (0,
  40707. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40708. e.x - draggingColumnOffset),
  40709. 0,
  40710. dragOverlayComp->getWidth(),
  40711. getHeight());
  40712. for (int i = columns.size(); --i >= 0;)
  40713. {
  40714. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40715. int newIndex = currentIndex;
  40716. if (newIndex > 0)
  40717. {
  40718. // if the previous column isn't draggable, we can't move our column
  40719. // past it, because that'd change the undraggable column's position..
  40720. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40721. if ((previous->propertyFlags & draggable) != 0)
  40722. {
  40723. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40724. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40725. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40726. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40727. {
  40728. --newIndex;
  40729. }
  40730. }
  40731. }
  40732. if (newIndex < columns.size() - 1)
  40733. {
  40734. // if the next column isn't draggable, we can't move our column
  40735. // past it, because that'd change the undraggable column's position..
  40736. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40737. if ((nextCol->propertyFlags & draggable) != 0)
  40738. {
  40739. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40740. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40741. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40742. > abs (dragOverlayComp->getRight() - rightOfNext))
  40743. {
  40744. ++newIndex;
  40745. }
  40746. }
  40747. }
  40748. if (newIndex != currentIndex)
  40749. moveColumn (columnIdBeingDragged, newIndex);
  40750. else
  40751. break;
  40752. }
  40753. }
  40754. }
  40755. else
  40756. {
  40757. endDrag (draggingColumnOriginalIndex);
  40758. }
  40759. }
  40760. }
  40761. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40762. {
  40763. if (columnIdBeingDragged == 0)
  40764. {
  40765. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40766. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40767. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40768. {
  40769. columnIdBeingDragged = 0;
  40770. }
  40771. else
  40772. {
  40773. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40774. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40775. const int temp = columnIdBeingDragged;
  40776. columnIdBeingDragged = 0;
  40777. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40778. columnIdBeingDragged = temp;
  40779. dragOverlayComp->setBounds (columnRect);
  40780. for (int i = listeners.size(); --i >= 0;)
  40781. {
  40782. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40783. i = jmin (i, listeners.size() - 1);
  40784. }
  40785. }
  40786. }
  40787. }
  40788. void TableHeaderComponent::endDrag (const int finalIndex)
  40789. {
  40790. if (columnIdBeingDragged != 0)
  40791. {
  40792. moveColumn (columnIdBeingDragged, finalIndex);
  40793. columnIdBeingDragged = 0;
  40794. repaint();
  40795. for (int i = listeners.size(); --i >= 0;)
  40796. {
  40797. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40798. i = jmin (i, listeners.size() - 1);
  40799. }
  40800. }
  40801. }
  40802. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40803. {
  40804. mouseDrag (e);
  40805. for (int i = columns.size(); --i >= 0;)
  40806. if (columns.getUnchecked (i)->isVisible())
  40807. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40808. columnIdBeingResized = 0;
  40809. repaint();
  40810. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40811. updateColumnUnderMouse (e.x, e.y);
  40812. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40813. columnClicked (columnIdUnderMouse, e.mods);
  40814. dragOverlayComp = 0;
  40815. }
  40816. const MouseCursor TableHeaderComponent::getMouseCursor()
  40817. {
  40818. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40819. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40820. return Component::getMouseCursor();
  40821. }
  40822. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40823. {
  40824. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40825. }
  40826. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40827. {
  40828. for (int i = columns.size(); --i >= 0;)
  40829. if (columns.getUnchecked(i)->id == id)
  40830. return columns.getUnchecked(i);
  40831. return 0;
  40832. }
  40833. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40834. {
  40835. int n = 0;
  40836. for (int i = 0; i < columns.size(); ++i)
  40837. {
  40838. if (columns.getUnchecked(i)->isVisible())
  40839. {
  40840. if (n == visibleIndex)
  40841. return i;
  40842. ++n;
  40843. }
  40844. }
  40845. return -1;
  40846. }
  40847. void TableHeaderComponent::sendColumnsChanged()
  40848. {
  40849. if (stretchToFit && lastDeliberateWidth > 0)
  40850. resizeAllColumnsToFit (lastDeliberateWidth);
  40851. repaint();
  40852. columnsChanged = true;
  40853. triggerAsyncUpdate();
  40854. }
  40855. void TableHeaderComponent::handleAsyncUpdate()
  40856. {
  40857. const bool changed = columnsChanged || sortChanged;
  40858. const bool sized = columnsResized || changed;
  40859. const bool sorted = sortChanged;
  40860. columnsChanged = false;
  40861. columnsResized = false;
  40862. sortChanged = false;
  40863. if (sorted)
  40864. {
  40865. for (int i = listeners.size(); --i >= 0;)
  40866. {
  40867. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40868. i = jmin (i, listeners.size() - 1);
  40869. }
  40870. }
  40871. if (changed)
  40872. {
  40873. for (int i = listeners.size(); --i >= 0;)
  40874. {
  40875. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40876. i = jmin (i, listeners.size() - 1);
  40877. }
  40878. }
  40879. if (sized)
  40880. {
  40881. for (int i = listeners.size(); --i >= 0;)
  40882. {
  40883. listeners.getUnchecked(i)->tableColumnsResized (this);
  40884. i = jmin (i, listeners.size() - 1);
  40885. }
  40886. }
  40887. }
  40888. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40889. {
  40890. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40891. {
  40892. const int draggableDistance = 3;
  40893. int x = 0;
  40894. for (int i = 0; i < columns.size(); ++i)
  40895. {
  40896. const ColumnInfo* const ci = columns.getUnchecked(i);
  40897. if (ci->isVisible())
  40898. {
  40899. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40900. && (ci->propertyFlags & resizable) != 0)
  40901. return ci->id;
  40902. x += ci->width;
  40903. }
  40904. }
  40905. }
  40906. return 0;
  40907. }
  40908. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40909. {
  40910. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40911. ? getColumnIdAtX (x) : 0;
  40912. if (newCol != columnIdUnderMouse)
  40913. {
  40914. columnIdUnderMouse = newCol;
  40915. repaint();
  40916. }
  40917. }
  40918. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40919. {
  40920. PopupMenu m;
  40921. addMenuItems (m, columnIdClicked);
  40922. if (m.getNumItems() > 0)
  40923. {
  40924. m.setLookAndFeel (&getLookAndFeel());
  40925. const int result = m.show();
  40926. if (result != 0)
  40927. reactToMenuItem (result, columnIdClicked);
  40928. }
  40929. }
  40930. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40931. {
  40932. }
  40933. END_JUCE_NAMESPACE
  40934. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40935. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40936. BEGIN_JUCE_NAMESPACE
  40937. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40938. class TableListRowComp : public Component,
  40939. public TooltipClient
  40940. {
  40941. public:
  40942. TableListRowComp (TableListBox& owner_)
  40943. : owner (owner_),
  40944. row (-1),
  40945. isSelected (false)
  40946. {
  40947. }
  40948. ~TableListRowComp()
  40949. {
  40950. deleteAllChildren();
  40951. }
  40952. void paint (Graphics& g)
  40953. {
  40954. TableListBoxModel* const model = owner.getModel();
  40955. if (model != 0)
  40956. {
  40957. const TableHeaderComponent* const header = owner.getHeader();
  40958. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40959. const int numColumns = header->getNumColumns (true);
  40960. for (int i = 0; i < numColumns; ++i)
  40961. {
  40962. if (! columnsWithComponents [i])
  40963. {
  40964. const int columnId = header->getColumnIdOfIndex (i, true);
  40965. Rectangle<int> columnRect (header->getColumnPosition (i));
  40966. columnRect.setSize (columnRect.getWidth(), getHeight());
  40967. g.saveState();
  40968. g.reduceClipRegion (columnRect);
  40969. g.setOrigin (columnRect.getX(), 0);
  40970. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40971. g.restoreState();
  40972. }
  40973. }
  40974. }
  40975. }
  40976. void update (const int newRow, const bool isNowSelected)
  40977. {
  40978. if (newRow != row || isNowSelected != isSelected)
  40979. {
  40980. row = newRow;
  40981. isSelected = isNowSelected;
  40982. repaint();
  40983. }
  40984. if (row < owner.getNumRows())
  40985. {
  40986. jassert (row >= 0);
  40987. const Identifier tagPropertyName ("_tableLastUseNum");
  40988. const int newTag = Random::getSystemRandom().nextInt();
  40989. const TableHeaderComponent* const header = owner.getHeader();
  40990. const int numColumns = header->getNumColumns (true);
  40991. int i;
  40992. columnsWithComponents.clear();
  40993. if (owner.getModel() != 0)
  40994. {
  40995. for (i = 0; i < numColumns; ++i)
  40996. {
  40997. const int columnId = header->getColumnIdOfIndex (i, true);
  40998. Component* const newComp
  40999. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41000. findChildComponentForColumn (columnId));
  41001. if (newComp != 0)
  41002. {
  41003. addAndMakeVisible (newComp);
  41004. newComp->getProperties().set (tagPropertyName, newTag);
  41005. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41006. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41007. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41008. columnsWithComponents.setBit (i);
  41009. }
  41010. }
  41011. }
  41012. for (i = getNumChildComponents(); --i >= 0;)
  41013. {
  41014. Component* const c = getChildComponent (i);
  41015. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41016. delete c;
  41017. }
  41018. }
  41019. else
  41020. {
  41021. columnsWithComponents.clear();
  41022. deleteAllChildren();
  41023. }
  41024. }
  41025. void resized()
  41026. {
  41027. for (int i = getNumChildComponents(); --i >= 0;)
  41028. {
  41029. Component* const c = getChildComponent (i);
  41030. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41031. if (columnId != 0)
  41032. {
  41033. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41034. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41035. }
  41036. }
  41037. }
  41038. void mouseDown (const MouseEvent& e)
  41039. {
  41040. isDragging = false;
  41041. selectRowOnMouseUp = false;
  41042. if (isEnabled())
  41043. {
  41044. if (! isSelected)
  41045. {
  41046. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41047. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41048. if (columnId != 0 && owner.getModel() != 0)
  41049. owner.getModel()->cellClicked (row, columnId, e);
  41050. }
  41051. else
  41052. {
  41053. selectRowOnMouseUp = true;
  41054. }
  41055. }
  41056. }
  41057. void mouseDrag (const MouseEvent& e)
  41058. {
  41059. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41060. {
  41061. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41062. if (selectedRows.size() > 0)
  41063. {
  41064. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41065. if (dragDescription.isNotEmpty())
  41066. {
  41067. isDragging = true;
  41068. owner.startDragAndDrop (e, dragDescription);
  41069. }
  41070. }
  41071. }
  41072. }
  41073. void mouseUp (const MouseEvent& e)
  41074. {
  41075. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41076. {
  41077. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41078. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41079. if (columnId != 0 && owner.getModel() != 0)
  41080. owner.getModel()->cellClicked (row, columnId, e);
  41081. }
  41082. }
  41083. void mouseDoubleClick (const MouseEvent& e)
  41084. {
  41085. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41086. if (columnId != 0 && owner.getModel() != 0)
  41087. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41088. }
  41089. const String getTooltip()
  41090. {
  41091. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41092. if (columnId != 0 && owner.getModel() != 0)
  41093. return owner.getModel()->getCellTooltip (row, columnId);
  41094. return String::empty;
  41095. }
  41096. juce_UseDebuggingNewOperator
  41097. private:
  41098. TableListBox& owner;
  41099. int row;
  41100. bool isSelected, isDragging, selectRowOnMouseUp;
  41101. BigInteger columnsWithComponents;
  41102. Component* findChildComponentForColumn (const int columnId) const
  41103. {
  41104. for (int i = getNumChildComponents(); --i >= 0;)
  41105. {
  41106. Component* const c = getChildComponent (i);
  41107. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41108. return c;
  41109. }
  41110. return 0;
  41111. }
  41112. TableListRowComp (const TableListRowComp&);
  41113. TableListRowComp& operator= (const TableListRowComp&);
  41114. };
  41115. class TableListBoxHeader : public TableHeaderComponent
  41116. {
  41117. public:
  41118. TableListBoxHeader (TableListBox& owner_)
  41119. : owner (owner_)
  41120. {
  41121. }
  41122. ~TableListBoxHeader()
  41123. {
  41124. }
  41125. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41126. {
  41127. if (owner.isAutoSizeMenuOptionShown())
  41128. {
  41129. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41130. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41131. menu.addSeparator();
  41132. }
  41133. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41134. }
  41135. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41136. {
  41137. if (menuReturnId == 0xf836743)
  41138. {
  41139. owner.autoSizeColumn (columnIdClicked);
  41140. }
  41141. else if (menuReturnId == 0xf836744)
  41142. {
  41143. owner.autoSizeAllColumns();
  41144. }
  41145. else
  41146. {
  41147. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41148. }
  41149. }
  41150. juce_UseDebuggingNewOperator
  41151. private:
  41152. TableListBox& owner;
  41153. TableListBoxHeader (const TableListBoxHeader&);
  41154. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41155. };
  41156. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41157. : ListBox (name, 0),
  41158. model (model_),
  41159. autoSizeOptionsShown (true)
  41160. {
  41161. ListBox::model = this;
  41162. header = new TableListBoxHeader (*this);
  41163. header->setSize (100, 28);
  41164. header->addListener (this);
  41165. setHeaderComponent (header);
  41166. }
  41167. TableListBox::~TableListBox()
  41168. {
  41169. header = 0;
  41170. }
  41171. void TableListBox::setModel (TableListBoxModel* const newModel)
  41172. {
  41173. if (model != newModel)
  41174. {
  41175. model = newModel;
  41176. updateContent();
  41177. }
  41178. }
  41179. int TableListBox::getHeaderHeight() const
  41180. {
  41181. return header->getHeight();
  41182. }
  41183. void TableListBox::setHeaderHeight (const int newHeight)
  41184. {
  41185. header->setSize (header->getWidth(), newHeight);
  41186. resized();
  41187. }
  41188. void TableListBox::autoSizeColumn (const int columnId)
  41189. {
  41190. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41191. if (width > 0)
  41192. header->setColumnWidth (columnId, width);
  41193. }
  41194. void TableListBox::autoSizeAllColumns()
  41195. {
  41196. for (int i = 0; i < header->getNumColumns (true); ++i)
  41197. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41198. }
  41199. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41200. {
  41201. autoSizeOptionsShown = shouldBeShown;
  41202. }
  41203. bool TableListBox::isAutoSizeMenuOptionShown() const
  41204. {
  41205. return autoSizeOptionsShown;
  41206. }
  41207. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41208. const int rowNumber,
  41209. const bool relativeToComponentTopLeft) const
  41210. {
  41211. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41212. if (relativeToComponentTopLeft)
  41213. headerCell.translate (header->getX(), 0);
  41214. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41215. return Rectangle<int> (headerCell.getX(), row.getY(),
  41216. headerCell.getWidth(), row.getHeight());
  41217. }
  41218. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41219. {
  41220. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41221. if (scrollbar != 0)
  41222. {
  41223. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41224. double x = scrollbar->getCurrentRangeStart();
  41225. const double w = scrollbar->getCurrentRangeSize();
  41226. if (pos.getX() < x)
  41227. x = pos.getX();
  41228. else if (pos.getRight() > x + w)
  41229. x += jmax (0.0, pos.getRight() - (x + w));
  41230. scrollbar->setCurrentRangeStart (x);
  41231. }
  41232. }
  41233. int TableListBox::getNumRows()
  41234. {
  41235. return model != 0 ? model->getNumRows() : 0;
  41236. }
  41237. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41238. {
  41239. }
  41240. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41241. {
  41242. if (existingComponentToUpdate == 0)
  41243. existingComponentToUpdate = new TableListRowComp (*this);
  41244. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41245. return existingComponentToUpdate;
  41246. }
  41247. void TableListBox::selectedRowsChanged (int row)
  41248. {
  41249. if (model != 0)
  41250. model->selectedRowsChanged (row);
  41251. }
  41252. void TableListBox::deleteKeyPressed (int row)
  41253. {
  41254. if (model != 0)
  41255. model->deleteKeyPressed (row);
  41256. }
  41257. void TableListBox::returnKeyPressed (int row)
  41258. {
  41259. if (model != 0)
  41260. model->returnKeyPressed (row);
  41261. }
  41262. void TableListBox::backgroundClicked()
  41263. {
  41264. if (model != 0)
  41265. model->backgroundClicked();
  41266. }
  41267. void TableListBox::listWasScrolled()
  41268. {
  41269. if (model != 0)
  41270. model->listWasScrolled();
  41271. }
  41272. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41273. {
  41274. setMinimumContentWidth (header->getTotalWidth());
  41275. repaint();
  41276. updateColumnComponents();
  41277. }
  41278. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41279. {
  41280. setMinimumContentWidth (header->getTotalWidth());
  41281. repaint();
  41282. updateColumnComponents();
  41283. }
  41284. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41285. {
  41286. if (model != 0)
  41287. model->sortOrderChanged (header->getSortColumnId(),
  41288. header->isSortedForwards());
  41289. }
  41290. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41291. {
  41292. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41293. repaint();
  41294. }
  41295. void TableListBox::resized()
  41296. {
  41297. ListBox::resized();
  41298. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41299. setMinimumContentWidth (header->getTotalWidth());
  41300. }
  41301. void TableListBox::updateColumnComponents() const
  41302. {
  41303. const int firstRow = getRowContainingPosition (0, 0);
  41304. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41305. {
  41306. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41307. if (rowComp != 0)
  41308. rowComp->resized();
  41309. }
  41310. }
  41311. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41312. {
  41313. }
  41314. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41315. {
  41316. }
  41317. void TableListBoxModel::backgroundClicked()
  41318. {
  41319. }
  41320. void TableListBoxModel::sortOrderChanged (int, const bool)
  41321. {
  41322. }
  41323. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41324. {
  41325. return 0;
  41326. }
  41327. void TableListBoxModel::selectedRowsChanged (int)
  41328. {
  41329. }
  41330. void TableListBoxModel::deleteKeyPressed (int)
  41331. {
  41332. }
  41333. void TableListBoxModel::returnKeyPressed (int)
  41334. {
  41335. }
  41336. void TableListBoxModel::listWasScrolled()
  41337. {
  41338. }
  41339. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41340. {
  41341. return String::empty;
  41342. }
  41343. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41344. {
  41345. return String::empty;
  41346. }
  41347. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41348. {
  41349. (void) existingComponentToUpdate;
  41350. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41351. return 0;
  41352. }
  41353. END_JUCE_NAMESPACE
  41354. /*** End of inlined file: juce_TableListBox.cpp ***/
  41355. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41356. BEGIN_JUCE_NAMESPACE
  41357. // a word or space that can't be broken down any further
  41358. struct TextAtom
  41359. {
  41360. String atomText;
  41361. float width;
  41362. uint16 numChars;
  41363. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41364. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41365. const String getText (const juce_wchar passwordCharacter) const
  41366. {
  41367. if (passwordCharacter == 0)
  41368. return atomText;
  41369. else
  41370. return String::repeatedString (String::charToString (passwordCharacter),
  41371. atomText.length());
  41372. }
  41373. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41374. {
  41375. if (passwordCharacter == 0)
  41376. return atomText.substring (0, numChars);
  41377. else if (isNewLine())
  41378. return String::empty;
  41379. else
  41380. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41381. }
  41382. };
  41383. // a run of text with a single font and colour
  41384. class TextEditor::UniformTextSection
  41385. {
  41386. public:
  41387. UniformTextSection (const String& text,
  41388. const Font& font_,
  41389. const Colour& colour_,
  41390. const juce_wchar passwordCharacter)
  41391. : font (font_),
  41392. colour (colour_)
  41393. {
  41394. initialiseAtoms (text, passwordCharacter);
  41395. }
  41396. UniformTextSection (const UniformTextSection& other)
  41397. : font (other.font),
  41398. colour (other.colour)
  41399. {
  41400. atoms.ensureStorageAllocated (other.atoms.size());
  41401. for (int i = 0; i < other.atoms.size(); ++i)
  41402. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41403. }
  41404. ~UniformTextSection()
  41405. {
  41406. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41407. }
  41408. void clear()
  41409. {
  41410. for (int i = atoms.size(); --i >= 0;)
  41411. delete getAtom(i);
  41412. atoms.clear();
  41413. }
  41414. int getNumAtoms() const
  41415. {
  41416. return atoms.size();
  41417. }
  41418. TextAtom* getAtom (const int index) const throw()
  41419. {
  41420. return atoms.getUnchecked (index);
  41421. }
  41422. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41423. {
  41424. if (other.atoms.size() > 0)
  41425. {
  41426. TextAtom* const lastAtom = atoms.getLast();
  41427. int i = 0;
  41428. if (lastAtom != 0)
  41429. {
  41430. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41431. {
  41432. TextAtom* const first = other.getAtom(0);
  41433. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41434. {
  41435. lastAtom->atomText += first->atomText;
  41436. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41437. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41438. delete first;
  41439. ++i;
  41440. }
  41441. }
  41442. }
  41443. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41444. while (i < other.atoms.size())
  41445. {
  41446. atoms.add (other.getAtom(i));
  41447. ++i;
  41448. }
  41449. }
  41450. }
  41451. UniformTextSection* split (const int indexToBreakAt,
  41452. const juce_wchar passwordCharacter)
  41453. {
  41454. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41455. font, colour,
  41456. passwordCharacter);
  41457. int index = 0;
  41458. for (int i = 0; i < atoms.size(); ++i)
  41459. {
  41460. TextAtom* const atom = getAtom(i);
  41461. const int nextIndex = index + atom->numChars;
  41462. if (index == indexToBreakAt)
  41463. {
  41464. int j;
  41465. for (j = i; j < atoms.size(); ++j)
  41466. section2->atoms.add (getAtom (j));
  41467. for (j = atoms.size(); --j >= i;)
  41468. atoms.remove (j);
  41469. break;
  41470. }
  41471. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41472. {
  41473. TextAtom* const secondAtom = new TextAtom();
  41474. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41475. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41476. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41477. section2->atoms.add (secondAtom);
  41478. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41479. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41480. atom->numChars = (uint16) (indexToBreakAt - index);
  41481. int j;
  41482. for (j = i + 1; j < atoms.size(); ++j)
  41483. section2->atoms.add (getAtom (j));
  41484. for (j = atoms.size(); --j > i;)
  41485. atoms.remove (j);
  41486. break;
  41487. }
  41488. index = nextIndex;
  41489. }
  41490. return section2;
  41491. }
  41492. void appendAllText (String::Concatenator& concatenator) const
  41493. {
  41494. for (int i = 0; i < atoms.size(); ++i)
  41495. concatenator.append (getAtom(i)->atomText);
  41496. }
  41497. void appendSubstring (String::Concatenator& concatenator,
  41498. const Range<int>& range) const
  41499. {
  41500. int index = 0;
  41501. for (int i = 0; i < atoms.size(); ++i)
  41502. {
  41503. const TextAtom* const atom = getAtom (i);
  41504. const int nextIndex = index + atom->numChars;
  41505. if (range.getStart() < nextIndex)
  41506. {
  41507. if (range.getEnd() <= index)
  41508. break;
  41509. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41510. if (! r.isEmpty())
  41511. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41512. }
  41513. index = nextIndex;
  41514. }
  41515. }
  41516. int getTotalLength() const
  41517. {
  41518. int total = 0;
  41519. for (int i = atoms.size(); --i >= 0;)
  41520. total += getAtom(i)->numChars;
  41521. return total;
  41522. }
  41523. void setFont (const Font& newFont,
  41524. const juce_wchar passwordCharacter)
  41525. {
  41526. if (font != newFont)
  41527. {
  41528. font = newFont;
  41529. for (int i = atoms.size(); --i >= 0;)
  41530. {
  41531. TextAtom* const atom = atoms.getUnchecked(i);
  41532. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41533. }
  41534. }
  41535. }
  41536. juce_UseDebuggingNewOperator
  41537. Font font;
  41538. Colour colour;
  41539. private:
  41540. Array <TextAtom*> atoms;
  41541. void initialiseAtoms (const String& textToParse,
  41542. const juce_wchar passwordCharacter)
  41543. {
  41544. int i = 0;
  41545. const int len = textToParse.length();
  41546. const juce_wchar* const text = textToParse;
  41547. while (i < len)
  41548. {
  41549. int start = i;
  41550. // create a whitespace atom unless it starts with non-ws
  41551. if (CharacterFunctions::isWhitespace (text[i])
  41552. && text[i] != '\r'
  41553. && text[i] != '\n')
  41554. {
  41555. while (i < len
  41556. && CharacterFunctions::isWhitespace (text[i])
  41557. && text[i] != '\r'
  41558. && text[i] != '\n')
  41559. {
  41560. ++i;
  41561. }
  41562. }
  41563. else
  41564. {
  41565. if (text[i] == '\r')
  41566. {
  41567. ++i;
  41568. if ((i < len) && (text[i] == '\n'))
  41569. {
  41570. ++start;
  41571. ++i;
  41572. }
  41573. }
  41574. else if (text[i] == '\n')
  41575. {
  41576. ++i;
  41577. }
  41578. else
  41579. {
  41580. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41581. ++i;
  41582. }
  41583. }
  41584. TextAtom* const atom = new TextAtom();
  41585. atom->atomText = String (text + start, i - start);
  41586. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41587. atom->numChars = (uint16) (i - start);
  41588. atoms.add (atom);
  41589. }
  41590. }
  41591. UniformTextSection& operator= (const UniformTextSection& other);
  41592. };
  41593. class TextEditor::Iterator
  41594. {
  41595. public:
  41596. Iterator (const Array <UniformTextSection*>& sections_,
  41597. const float wordWrapWidth_,
  41598. const juce_wchar passwordCharacter_)
  41599. : indexInText (0),
  41600. lineY (0),
  41601. lineHeight (0),
  41602. maxDescent (0),
  41603. atomX (0),
  41604. atomRight (0),
  41605. atom (0),
  41606. currentSection (0),
  41607. sections (sections_),
  41608. sectionIndex (0),
  41609. atomIndex (0),
  41610. wordWrapWidth (wordWrapWidth_),
  41611. passwordCharacter (passwordCharacter_)
  41612. {
  41613. jassert (wordWrapWidth_ > 0);
  41614. if (sections.size() > 0)
  41615. {
  41616. currentSection = sections.getUnchecked (sectionIndex);
  41617. if (currentSection != 0)
  41618. beginNewLine();
  41619. }
  41620. }
  41621. Iterator (const Iterator& other)
  41622. : indexInText (other.indexInText),
  41623. lineY (other.lineY),
  41624. lineHeight (other.lineHeight),
  41625. maxDescent (other.maxDescent),
  41626. atomX (other.atomX),
  41627. atomRight (other.atomRight),
  41628. atom (other.atom),
  41629. currentSection (other.currentSection),
  41630. sections (other.sections),
  41631. sectionIndex (other.sectionIndex),
  41632. atomIndex (other.atomIndex),
  41633. wordWrapWidth (other.wordWrapWidth),
  41634. passwordCharacter (other.passwordCharacter),
  41635. tempAtom (other.tempAtom)
  41636. {
  41637. }
  41638. ~Iterator()
  41639. {
  41640. }
  41641. bool next()
  41642. {
  41643. if (atom == &tempAtom)
  41644. {
  41645. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41646. if (numRemaining > 0)
  41647. {
  41648. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41649. atomX = 0;
  41650. if (tempAtom.numChars > 0)
  41651. lineY += lineHeight;
  41652. indexInText += tempAtom.numChars;
  41653. GlyphArrangement g;
  41654. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41655. int split;
  41656. for (split = 0; split < g.getNumGlyphs(); ++split)
  41657. if (shouldWrap (g.getGlyph (split).getRight()))
  41658. break;
  41659. if (split > 0 && split <= numRemaining)
  41660. {
  41661. tempAtom.numChars = (uint16) split;
  41662. tempAtom.width = g.getGlyph (split - 1).getRight();
  41663. atomRight = atomX + tempAtom.width;
  41664. return true;
  41665. }
  41666. }
  41667. }
  41668. bool forceNewLine = false;
  41669. if (sectionIndex >= sections.size())
  41670. {
  41671. moveToEndOfLastAtom();
  41672. return false;
  41673. }
  41674. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41675. {
  41676. if (atomIndex >= currentSection->getNumAtoms())
  41677. {
  41678. if (++sectionIndex >= sections.size())
  41679. {
  41680. moveToEndOfLastAtom();
  41681. return false;
  41682. }
  41683. atomIndex = 0;
  41684. currentSection = sections.getUnchecked (sectionIndex);
  41685. }
  41686. else
  41687. {
  41688. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41689. if (! lastAtom->isWhitespace())
  41690. {
  41691. // handle the case where the last atom in a section is actually part of the same
  41692. // word as the first atom of the next section...
  41693. float right = atomRight + lastAtom->width;
  41694. float lineHeight2 = lineHeight;
  41695. float maxDescent2 = maxDescent;
  41696. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41697. {
  41698. const UniformTextSection* const s = sections.getUnchecked (section);
  41699. if (s->getNumAtoms() == 0)
  41700. break;
  41701. const TextAtom* const nextAtom = s->getAtom (0);
  41702. if (nextAtom->isWhitespace())
  41703. break;
  41704. right += nextAtom->width;
  41705. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41706. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41707. if (shouldWrap (right))
  41708. {
  41709. lineHeight = lineHeight2;
  41710. maxDescent = maxDescent2;
  41711. forceNewLine = true;
  41712. break;
  41713. }
  41714. if (s->getNumAtoms() > 1)
  41715. break;
  41716. }
  41717. }
  41718. }
  41719. }
  41720. if (atom != 0)
  41721. {
  41722. atomX = atomRight;
  41723. indexInText += atom->numChars;
  41724. if (atom->isNewLine())
  41725. beginNewLine();
  41726. }
  41727. atom = currentSection->getAtom (atomIndex);
  41728. atomRight = atomX + atom->width;
  41729. ++atomIndex;
  41730. if (shouldWrap (atomRight) || forceNewLine)
  41731. {
  41732. if (atom->isWhitespace())
  41733. {
  41734. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41735. atomRight = jmin (atomRight, wordWrapWidth);
  41736. }
  41737. else
  41738. {
  41739. atomRight = atom->width;
  41740. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41741. {
  41742. tempAtom = *atom;
  41743. tempAtom.width = 0;
  41744. tempAtom.numChars = 0;
  41745. atom = &tempAtom;
  41746. if (atomX > 0)
  41747. beginNewLine();
  41748. return next();
  41749. }
  41750. beginNewLine();
  41751. return true;
  41752. }
  41753. }
  41754. return true;
  41755. }
  41756. void beginNewLine()
  41757. {
  41758. atomX = 0;
  41759. lineY += lineHeight;
  41760. int tempSectionIndex = sectionIndex;
  41761. int tempAtomIndex = atomIndex;
  41762. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41763. lineHeight = section->font.getHeight();
  41764. maxDescent = section->font.getDescent();
  41765. float x = (atom != 0) ? atom->width : 0;
  41766. while (! shouldWrap (x))
  41767. {
  41768. if (tempSectionIndex >= sections.size())
  41769. break;
  41770. bool checkSize = false;
  41771. if (tempAtomIndex >= section->getNumAtoms())
  41772. {
  41773. if (++tempSectionIndex >= sections.size())
  41774. break;
  41775. tempAtomIndex = 0;
  41776. section = sections.getUnchecked (tempSectionIndex);
  41777. checkSize = true;
  41778. }
  41779. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41780. if (nextAtom == 0)
  41781. break;
  41782. x += nextAtom->width;
  41783. if (shouldWrap (x) || nextAtom->isNewLine())
  41784. break;
  41785. if (checkSize)
  41786. {
  41787. lineHeight = jmax (lineHeight, section->font.getHeight());
  41788. maxDescent = jmax (maxDescent, section->font.getDescent());
  41789. }
  41790. ++tempAtomIndex;
  41791. }
  41792. }
  41793. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41794. {
  41795. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41796. {
  41797. if (lastSection != currentSection)
  41798. {
  41799. lastSection = currentSection;
  41800. g.setColour (currentSection->colour);
  41801. g.setFont (currentSection->font);
  41802. }
  41803. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41804. GlyphArrangement ga;
  41805. ga.addLineOfText (currentSection->font,
  41806. atom->getTrimmedText (passwordCharacter),
  41807. atomX,
  41808. (float) roundToInt (lineY + lineHeight - maxDescent));
  41809. ga.draw (g);
  41810. }
  41811. }
  41812. void drawSelection (Graphics& g,
  41813. const Range<int>& selection) const
  41814. {
  41815. const int startX = roundToInt (indexToX (selection.getStart()));
  41816. const int endX = roundToInt (indexToX (selection.getEnd()));
  41817. const int y = roundToInt (lineY);
  41818. const int nextY = roundToInt (lineY + lineHeight);
  41819. g.fillRect (startX, y, endX - startX, nextY - y);
  41820. }
  41821. void drawSelectedText (Graphics& g,
  41822. const Range<int>& selection,
  41823. const Colour& selectedTextColour) const
  41824. {
  41825. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41826. {
  41827. GlyphArrangement ga;
  41828. ga.addLineOfText (currentSection->font,
  41829. atom->getTrimmedText (passwordCharacter),
  41830. atomX,
  41831. (float) roundToInt (lineY + lineHeight - maxDescent));
  41832. if (selection.getEnd() < indexInText + atom->numChars)
  41833. {
  41834. GlyphArrangement ga2 (ga);
  41835. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41836. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41837. g.setColour (currentSection->colour);
  41838. ga2.draw (g);
  41839. }
  41840. if (selection.getStart() > indexInText)
  41841. {
  41842. GlyphArrangement ga2 (ga);
  41843. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41844. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41845. g.setColour (currentSection->colour);
  41846. ga2.draw (g);
  41847. }
  41848. g.setColour (selectedTextColour);
  41849. ga.draw (g);
  41850. }
  41851. }
  41852. float indexToX (const int indexToFind) const
  41853. {
  41854. if (indexToFind <= indexInText)
  41855. return atomX;
  41856. if (indexToFind >= indexInText + atom->numChars)
  41857. return atomRight;
  41858. GlyphArrangement g;
  41859. g.addLineOfText (currentSection->font,
  41860. atom->getText (passwordCharacter),
  41861. atomX, 0.0f);
  41862. if (indexToFind - indexInText >= g.getNumGlyphs())
  41863. return atomRight;
  41864. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41865. }
  41866. int xToIndex (const float xToFind) const
  41867. {
  41868. if (xToFind <= atomX || atom->isNewLine())
  41869. return indexInText;
  41870. if (xToFind >= atomRight)
  41871. return indexInText + atom->numChars;
  41872. GlyphArrangement g;
  41873. g.addLineOfText (currentSection->font,
  41874. atom->getText (passwordCharacter),
  41875. atomX, 0.0f);
  41876. int j;
  41877. for (j = 0; j < g.getNumGlyphs(); ++j)
  41878. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41879. break;
  41880. return indexInText + j;
  41881. }
  41882. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41883. {
  41884. while (next())
  41885. {
  41886. if (indexInText + atom->numChars > index)
  41887. {
  41888. cx = indexToX (index);
  41889. cy = lineY;
  41890. lineHeight_ = lineHeight;
  41891. return true;
  41892. }
  41893. }
  41894. cx = atomX;
  41895. cy = lineY;
  41896. lineHeight_ = lineHeight;
  41897. return false;
  41898. }
  41899. juce_UseDebuggingNewOperator
  41900. int indexInText;
  41901. float lineY, lineHeight, maxDescent;
  41902. float atomX, atomRight;
  41903. const TextAtom* atom;
  41904. const UniformTextSection* currentSection;
  41905. private:
  41906. const Array <UniformTextSection*>& sections;
  41907. int sectionIndex, atomIndex;
  41908. const float wordWrapWidth;
  41909. const juce_wchar passwordCharacter;
  41910. TextAtom tempAtom;
  41911. Iterator& operator= (const Iterator&);
  41912. void moveToEndOfLastAtom()
  41913. {
  41914. if (atom != 0)
  41915. {
  41916. atomX = atomRight;
  41917. if (atom->isNewLine())
  41918. {
  41919. atomX = 0.0f;
  41920. lineY += lineHeight;
  41921. }
  41922. }
  41923. }
  41924. bool shouldWrap (const float x) const
  41925. {
  41926. return (x - 0.0001f) >= wordWrapWidth;
  41927. }
  41928. };
  41929. class TextEditor::InsertAction : public UndoableAction
  41930. {
  41931. TextEditor& owner;
  41932. const String text;
  41933. const int insertIndex, oldCaretPos, newCaretPos;
  41934. const Font font;
  41935. const Colour colour;
  41936. InsertAction (const InsertAction&);
  41937. InsertAction& operator= (const InsertAction&);
  41938. public:
  41939. InsertAction (TextEditor& owner_,
  41940. const String& text_,
  41941. const int insertIndex_,
  41942. const Font& font_,
  41943. const Colour& colour_,
  41944. const int oldCaretPos_,
  41945. const int newCaretPos_)
  41946. : owner (owner_),
  41947. text (text_),
  41948. insertIndex (insertIndex_),
  41949. oldCaretPos (oldCaretPos_),
  41950. newCaretPos (newCaretPos_),
  41951. font (font_),
  41952. colour (colour_)
  41953. {
  41954. }
  41955. ~InsertAction()
  41956. {
  41957. }
  41958. bool perform()
  41959. {
  41960. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41961. return true;
  41962. }
  41963. bool undo()
  41964. {
  41965. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41966. return true;
  41967. }
  41968. int getSizeInUnits()
  41969. {
  41970. return text.length() + 16;
  41971. }
  41972. };
  41973. class TextEditor::RemoveAction : public UndoableAction
  41974. {
  41975. TextEditor& owner;
  41976. const Range<int> range;
  41977. const int oldCaretPos, newCaretPos;
  41978. Array <UniformTextSection*> removedSections;
  41979. RemoveAction (const RemoveAction&);
  41980. RemoveAction& operator= (const RemoveAction&);
  41981. public:
  41982. RemoveAction (TextEditor& owner_,
  41983. const Range<int> range_,
  41984. const int oldCaretPos_,
  41985. const int newCaretPos_,
  41986. const Array <UniformTextSection*>& removedSections_)
  41987. : owner (owner_),
  41988. range (range_),
  41989. oldCaretPos (oldCaretPos_),
  41990. newCaretPos (newCaretPos_),
  41991. removedSections (removedSections_)
  41992. {
  41993. }
  41994. ~RemoveAction()
  41995. {
  41996. for (int i = removedSections.size(); --i >= 0;)
  41997. {
  41998. UniformTextSection* const section = removedSections.getUnchecked (i);
  41999. section->clear();
  42000. delete section;
  42001. }
  42002. }
  42003. bool perform()
  42004. {
  42005. owner.remove (range, 0, newCaretPos);
  42006. return true;
  42007. }
  42008. bool undo()
  42009. {
  42010. owner.reinsert (range.getStart(), removedSections);
  42011. owner.moveCursorTo (oldCaretPos, false);
  42012. return true;
  42013. }
  42014. int getSizeInUnits()
  42015. {
  42016. int n = 0;
  42017. for (int i = removedSections.size(); --i >= 0;)
  42018. n += removedSections.getUnchecked (i)->getTotalLength();
  42019. return n + 16;
  42020. }
  42021. };
  42022. class TextEditor::TextHolderComponent : public Component,
  42023. public Timer,
  42024. public Value::Listener
  42025. {
  42026. public:
  42027. TextHolderComponent (TextEditor& owner_)
  42028. : owner (owner_)
  42029. {
  42030. setWantsKeyboardFocus (false);
  42031. setInterceptsMouseClicks (false, true);
  42032. owner.getTextValue().addListener (this);
  42033. }
  42034. ~TextHolderComponent()
  42035. {
  42036. owner.getTextValue().removeListener (this);
  42037. }
  42038. void paint (Graphics& g)
  42039. {
  42040. owner.drawContent (g);
  42041. }
  42042. void timerCallback()
  42043. {
  42044. owner.timerCallbackInt();
  42045. }
  42046. const MouseCursor getMouseCursor()
  42047. {
  42048. return owner.getMouseCursor();
  42049. }
  42050. void valueChanged (Value&)
  42051. {
  42052. owner.textWasChangedByValue();
  42053. }
  42054. private:
  42055. TextEditor& owner;
  42056. TextHolderComponent (const TextHolderComponent&);
  42057. TextHolderComponent& operator= (const TextHolderComponent&);
  42058. };
  42059. class TextEditorViewport : public Viewport
  42060. {
  42061. public:
  42062. TextEditorViewport (TextEditor* const owner_)
  42063. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42064. {
  42065. }
  42066. ~TextEditorViewport()
  42067. {
  42068. }
  42069. void visibleAreaChanged (int, int, int, int)
  42070. {
  42071. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42072. // appear and disappear, causing the wrap width to change.
  42073. {
  42074. const float wordWrapWidth = owner->getWordWrapWidth();
  42075. if (wordWrapWidth != lastWordWrapWidth)
  42076. {
  42077. lastWordWrapWidth = wordWrapWidth;
  42078. rentrant = true;
  42079. owner->updateTextHolderSize();
  42080. rentrant = false;
  42081. }
  42082. }
  42083. }
  42084. private:
  42085. TextEditor* const owner;
  42086. float lastWordWrapWidth;
  42087. bool rentrant;
  42088. TextEditorViewport (const TextEditorViewport&);
  42089. TextEditorViewport& operator= (const TextEditorViewport&);
  42090. };
  42091. namespace TextEditorDefs
  42092. {
  42093. const int flashSpeedIntervalMs = 380;
  42094. const int textChangeMessageId = 0x10003001;
  42095. const int returnKeyMessageId = 0x10003002;
  42096. const int escapeKeyMessageId = 0x10003003;
  42097. const int focusLossMessageId = 0x10003004;
  42098. const int maxActionsPerTransaction = 100;
  42099. }
  42100. TextEditor::TextEditor (const String& name,
  42101. const juce_wchar passwordCharacter_)
  42102. : Component (name),
  42103. borderSize (1, 1, 1, 3),
  42104. readOnly (false),
  42105. multiline (false),
  42106. wordWrap (false),
  42107. returnKeyStartsNewLine (false),
  42108. caretVisible (true),
  42109. popupMenuEnabled (true),
  42110. selectAllTextWhenFocused (false),
  42111. scrollbarVisible (true),
  42112. wasFocused (false),
  42113. caretFlashState (true),
  42114. keepCursorOnScreen (true),
  42115. tabKeyUsed (false),
  42116. menuActive (false),
  42117. valueTextNeedsUpdating (false),
  42118. cursorX (0),
  42119. cursorY (0),
  42120. cursorHeight (0),
  42121. maxTextLength (0),
  42122. leftIndent (4),
  42123. topIndent (4),
  42124. lastTransactionTime (0),
  42125. currentFont (14.0f),
  42126. totalNumChars (0),
  42127. caretPosition (0),
  42128. passwordCharacter (passwordCharacter_),
  42129. dragType (notDragging)
  42130. {
  42131. setOpaque (true);
  42132. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42133. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42134. viewport->setWantsKeyboardFocus (false);
  42135. viewport->setScrollBarsShown (false, false);
  42136. setMouseCursor (MouseCursor::IBeamCursor);
  42137. setWantsKeyboardFocus (true);
  42138. }
  42139. TextEditor::~TextEditor()
  42140. {
  42141. textValue.referTo (Value());
  42142. clearInternal (0);
  42143. viewport = 0;
  42144. textHolder = 0;
  42145. }
  42146. void TextEditor::newTransaction()
  42147. {
  42148. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42149. undoManager.beginNewTransaction();
  42150. }
  42151. void TextEditor::doUndoRedo (const bool isRedo)
  42152. {
  42153. if (! isReadOnly())
  42154. {
  42155. if (isRedo ? undoManager.redo()
  42156. : undoManager.undo())
  42157. {
  42158. scrollToMakeSureCursorIsVisible();
  42159. repaint();
  42160. textChanged();
  42161. }
  42162. }
  42163. }
  42164. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42165. const bool shouldWordWrap)
  42166. {
  42167. if (multiline != shouldBeMultiLine
  42168. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42169. {
  42170. multiline = shouldBeMultiLine;
  42171. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42172. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42173. scrollbarVisible && multiline);
  42174. viewport->setViewPosition (0, 0);
  42175. resized();
  42176. scrollToMakeSureCursorIsVisible();
  42177. }
  42178. }
  42179. bool TextEditor::isMultiLine() const
  42180. {
  42181. return multiline;
  42182. }
  42183. void TextEditor::setScrollbarsShown (bool shown)
  42184. {
  42185. if (scrollbarVisible != shown)
  42186. {
  42187. scrollbarVisible = shown;
  42188. shown = shown && isMultiLine();
  42189. viewport->setScrollBarsShown (shown, shown);
  42190. }
  42191. }
  42192. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42193. {
  42194. if (readOnly != shouldBeReadOnly)
  42195. {
  42196. readOnly = shouldBeReadOnly;
  42197. enablementChanged();
  42198. }
  42199. }
  42200. bool TextEditor::isReadOnly() const
  42201. {
  42202. return readOnly || ! isEnabled();
  42203. }
  42204. bool TextEditor::isTextInputActive() const
  42205. {
  42206. return ! isReadOnly();
  42207. }
  42208. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42209. {
  42210. returnKeyStartsNewLine = shouldStartNewLine;
  42211. }
  42212. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42213. {
  42214. tabKeyUsed = shouldTabKeyBeUsed;
  42215. }
  42216. void TextEditor::setPopupMenuEnabled (const bool b)
  42217. {
  42218. popupMenuEnabled = b;
  42219. }
  42220. void TextEditor::setSelectAllWhenFocused (const bool b)
  42221. {
  42222. selectAllTextWhenFocused = b;
  42223. }
  42224. const Font TextEditor::getFont() const
  42225. {
  42226. return currentFont;
  42227. }
  42228. void TextEditor::setFont (const Font& newFont)
  42229. {
  42230. currentFont = newFont;
  42231. scrollToMakeSureCursorIsVisible();
  42232. }
  42233. void TextEditor::applyFontToAllText (const Font& newFont)
  42234. {
  42235. currentFont = newFont;
  42236. const Colour overallColour (findColour (textColourId));
  42237. for (int i = sections.size(); --i >= 0;)
  42238. {
  42239. UniformTextSection* const uts = sections.getUnchecked (i);
  42240. uts->setFont (newFont, passwordCharacter);
  42241. uts->colour = overallColour;
  42242. }
  42243. coalesceSimilarSections();
  42244. updateTextHolderSize();
  42245. scrollToMakeSureCursorIsVisible();
  42246. repaint();
  42247. }
  42248. void TextEditor::colourChanged()
  42249. {
  42250. setOpaque (findColour (backgroundColourId).isOpaque());
  42251. repaint();
  42252. }
  42253. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42254. {
  42255. caretVisible = shouldCaretBeVisible;
  42256. if (shouldCaretBeVisible)
  42257. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42258. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42259. : MouseCursor::NormalCursor);
  42260. }
  42261. void TextEditor::setInputRestrictions (const int maxLen,
  42262. const String& chars)
  42263. {
  42264. maxTextLength = jmax (0, maxLen);
  42265. allowedCharacters = chars;
  42266. }
  42267. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42268. {
  42269. textToShowWhenEmpty = text;
  42270. colourForTextWhenEmpty = colourToUse;
  42271. }
  42272. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42273. {
  42274. if (passwordCharacter != newPasswordCharacter)
  42275. {
  42276. passwordCharacter = newPasswordCharacter;
  42277. resized();
  42278. repaint();
  42279. }
  42280. }
  42281. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42282. {
  42283. viewport->setScrollBarThickness (newThicknessPixels);
  42284. }
  42285. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42286. {
  42287. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42288. }
  42289. void TextEditor::clear()
  42290. {
  42291. clearInternal (0);
  42292. updateTextHolderSize();
  42293. undoManager.clearUndoHistory();
  42294. }
  42295. void TextEditor::setText (const String& newText,
  42296. const bool sendTextChangeMessage)
  42297. {
  42298. const int newLength = newText.length();
  42299. if (newLength != getTotalNumChars() || getText() != newText)
  42300. {
  42301. const int oldCursorPos = caretPosition;
  42302. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42303. clearInternal (0);
  42304. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42305. // if you're adding text with line-feeds to a single-line text editor, it
  42306. // ain't gonna look right!
  42307. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42308. if (cursorWasAtEnd && ! isMultiLine())
  42309. moveCursorTo (getTotalNumChars(), false);
  42310. else
  42311. moveCursorTo (oldCursorPos, false);
  42312. if (sendTextChangeMessage)
  42313. textChanged();
  42314. updateTextHolderSize();
  42315. scrollToMakeSureCursorIsVisible();
  42316. undoManager.clearUndoHistory();
  42317. repaint();
  42318. }
  42319. }
  42320. Value& TextEditor::getTextValue()
  42321. {
  42322. if (valueTextNeedsUpdating)
  42323. {
  42324. valueTextNeedsUpdating = false;
  42325. textValue = getText();
  42326. }
  42327. return textValue;
  42328. }
  42329. void TextEditor::textWasChangedByValue()
  42330. {
  42331. if (textValue.getValueSource().getReferenceCount() > 1)
  42332. setText (textValue.getValue());
  42333. }
  42334. void TextEditor::textChanged()
  42335. {
  42336. updateTextHolderSize();
  42337. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42338. if (textValue.getValueSource().getReferenceCount() > 1)
  42339. {
  42340. valueTextNeedsUpdating = false;
  42341. textValue = getText();
  42342. }
  42343. }
  42344. void TextEditor::returnPressed()
  42345. {
  42346. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42347. }
  42348. void TextEditor::escapePressed()
  42349. {
  42350. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42351. }
  42352. void TextEditor::addListener (TextEditorListener* const newListener)
  42353. {
  42354. listeners.add (newListener);
  42355. }
  42356. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42357. {
  42358. listeners.remove (listenerToRemove);
  42359. }
  42360. void TextEditor::timerCallbackInt()
  42361. {
  42362. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42363. if (caretFlashState != newState)
  42364. {
  42365. caretFlashState = newState;
  42366. if (caretFlashState)
  42367. wasFocused = true;
  42368. if (caretVisible
  42369. && hasKeyboardFocus (false)
  42370. && ! isReadOnly())
  42371. {
  42372. repaintCaret();
  42373. }
  42374. }
  42375. const unsigned int now = Time::getApproximateMillisecondCounter();
  42376. if (now > lastTransactionTime + 200)
  42377. newTransaction();
  42378. }
  42379. void TextEditor::repaintCaret()
  42380. {
  42381. if (! findColour (caretColourId).isTransparent())
  42382. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42383. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42384. 4,
  42385. roundToInt (cursorHeight) + 2);
  42386. }
  42387. void TextEditor::repaintText (const Range<int>& range)
  42388. {
  42389. if (! range.isEmpty())
  42390. {
  42391. float x = 0, y = 0, lh = currentFont.getHeight();
  42392. const float wordWrapWidth = getWordWrapWidth();
  42393. if (wordWrapWidth > 0)
  42394. {
  42395. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42396. i.getCharPosition (range.getStart(), x, y, lh);
  42397. const int y1 = (int) y;
  42398. int y2;
  42399. if (range.getEnd() >= getTotalNumChars())
  42400. {
  42401. y2 = textHolder->getHeight();
  42402. }
  42403. else
  42404. {
  42405. i.getCharPosition (range.getEnd(), x, y, lh);
  42406. y2 = (int) (y + lh * 2.0f);
  42407. }
  42408. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42409. }
  42410. }
  42411. }
  42412. void TextEditor::moveCaret (int newCaretPos)
  42413. {
  42414. if (newCaretPos < 0)
  42415. newCaretPos = 0;
  42416. else if (newCaretPos > getTotalNumChars())
  42417. newCaretPos = getTotalNumChars();
  42418. if (newCaretPos != getCaretPosition())
  42419. {
  42420. repaintCaret();
  42421. caretFlashState = true;
  42422. caretPosition = newCaretPos;
  42423. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42424. scrollToMakeSureCursorIsVisible();
  42425. repaintCaret();
  42426. }
  42427. }
  42428. void TextEditor::setCaretPosition (const int newIndex)
  42429. {
  42430. moveCursorTo (newIndex, false);
  42431. }
  42432. int TextEditor::getCaretPosition() const
  42433. {
  42434. return caretPosition;
  42435. }
  42436. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42437. const int desiredCaretY)
  42438. {
  42439. updateCaretPosition();
  42440. int vx = roundToInt (cursorX) - desiredCaretX;
  42441. int vy = roundToInt (cursorY) - desiredCaretY;
  42442. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42443. {
  42444. vx += desiredCaretX - proportionOfWidth (0.2f);
  42445. }
  42446. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42447. {
  42448. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42449. }
  42450. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42451. if (! isMultiLine())
  42452. {
  42453. vy = viewport->getViewPositionY();
  42454. }
  42455. else
  42456. {
  42457. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42458. const int curH = roundToInt (cursorHeight);
  42459. if (desiredCaretY < 0)
  42460. {
  42461. vy = jmax (0, desiredCaretY + vy);
  42462. }
  42463. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42464. {
  42465. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42466. }
  42467. }
  42468. viewport->setViewPosition (vx, vy);
  42469. }
  42470. const Rectangle<int> TextEditor::getCaretRectangle()
  42471. {
  42472. updateCaretPosition();
  42473. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42474. roundToInt (cursorY) - viewport->getY(),
  42475. 1, roundToInt (cursorHeight));
  42476. }
  42477. float TextEditor::getWordWrapWidth() const
  42478. {
  42479. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42480. : 1.0e10f;
  42481. }
  42482. void TextEditor::updateTextHolderSize()
  42483. {
  42484. const float wordWrapWidth = getWordWrapWidth();
  42485. if (wordWrapWidth > 0)
  42486. {
  42487. float maxWidth = 0.0f;
  42488. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42489. while (i.next())
  42490. maxWidth = jmax (maxWidth, i.atomRight);
  42491. const int w = leftIndent + roundToInt (maxWidth);
  42492. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42493. currentFont.getHeight()));
  42494. textHolder->setSize (w + 1, h + 1);
  42495. }
  42496. }
  42497. int TextEditor::getTextWidth() const
  42498. {
  42499. return textHolder->getWidth();
  42500. }
  42501. int TextEditor::getTextHeight() const
  42502. {
  42503. return textHolder->getHeight();
  42504. }
  42505. void TextEditor::setIndents (const int newLeftIndent,
  42506. const int newTopIndent)
  42507. {
  42508. leftIndent = newLeftIndent;
  42509. topIndent = newTopIndent;
  42510. }
  42511. void TextEditor::setBorder (const BorderSize& border)
  42512. {
  42513. borderSize = border;
  42514. resized();
  42515. }
  42516. const BorderSize TextEditor::getBorder() const
  42517. {
  42518. return borderSize;
  42519. }
  42520. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42521. {
  42522. keepCursorOnScreen = shouldScrollToShowCursor;
  42523. }
  42524. void TextEditor::updateCaretPosition()
  42525. {
  42526. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42527. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42528. }
  42529. void TextEditor::scrollToMakeSureCursorIsVisible()
  42530. {
  42531. updateCaretPosition();
  42532. if (keepCursorOnScreen)
  42533. {
  42534. int x = viewport->getViewPositionX();
  42535. int y = viewport->getViewPositionY();
  42536. const int relativeCursorX = roundToInt (cursorX) - x;
  42537. const int relativeCursorY = roundToInt (cursorY) - y;
  42538. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42539. {
  42540. x += relativeCursorX - proportionOfWidth (0.2f);
  42541. }
  42542. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42543. {
  42544. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42545. }
  42546. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42547. if (! isMultiLine())
  42548. {
  42549. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42550. }
  42551. else
  42552. {
  42553. const int curH = roundToInt (cursorHeight);
  42554. if (relativeCursorY < 0)
  42555. {
  42556. y = jmax (0, relativeCursorY + y);
  42557. }
  42558. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42559. {
  42560. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42561. }
  42562. }
  42563. viewport->setViewPosition (x, y);
  42564. }
  42565. }
  42566. void TextEditor::moveCursorTo (const int newPosition,
  42567. const bool isSelecting)
  42568. {
  42569. if (isSelecting)
  42570. {
  42571. moveCaret (newPosition);
  42572. const Range<int> oldSelection (selection);
  42573. if (dragType == notDragging)
  42574. {
  42575. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42576. dragType = draggingSelectionStart;
  42577. else
  42578. dragType = draggingSelectionEnd;
  42579. }
  42580. if (dragType == draggingSelectionStart)
  42581. {
  42582. if (getCaretPosition() >= selection.getEnd())
  42583. dragType = draggingSelectionEnd;
  42584. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42585. }
  42586. else
  42587. {
  42588. if (getCaretPosition() < selection.getStart())
  42589. dragType = draggingSelectionStart;
  42590. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42591. }
  42592. repaintText (selection.getUnionWith (oldSelection));
  42593. }
  42594. else
  42595. {
  42596. dragType = notDragging;
  42597. repaintText (selection);
  42598. moveCaret (newPosition);
  42599. selection = Range<int>::emptyRange (getCaretPosition());
  42600. }
  42601. }
  42602. int TextEditor::getTextIndexAt (const int x,
  42603. const int y)
  42604. {
  42605. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42606. (float) (y + viewport->getViewPositionY() - topIndent));
  42607. }
  42608. void TextEditor::insertTextAtCaret (const String& newText_)
  42609. {
  42610. String newText (newText_);
  42611. if (allowedCharacters.isNotEmpty())
  42612. newText = newText.retainCharacters (allowedCharacters);
  42613. if ((! returnKeyStartsNewLine) && newText == "\n")
  42614. {
  42615. returnPressed();
  42616. return;
  42617. }
  42618. if (! isMultiLine())
  42619. newText = newText.replaceCharacters ("\r\n", " ");
  42620. else
  42621. newText = newText.replace ("\r\n", "\n");
  42622. const int newCaretPos = selection.getStart() + newText.length();
  42623. const int insertIndex = selection.getStart();
  42624. remove (selection, getUndoManager(),
  42625. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42626. if (maxTextLength > 0)
  42627. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42628. if (newText.isNotEmpty())
  42629. insert (newText,
  42630. insertIndex,
  42631. currentFont,
  42632. findColour (textColourId),
  42633. getUndoManager(),
  42634. newCaretPos);
  42635. textChanged();
  42636. }
  42637. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42638. {
  42639. moveCursorTo (newSelection.getStart(), false);
  42640. moveCursorTo (newSelection.getEnd(), true);
  42641. }
  42642. void TextEditor::copy()
  42643. {
  42644. if (passwordCharacter == 0)
  42645. {
  42646. const String selectedText (getHighlightedText());
  42647. if (selectedText.isNotEmpty())
  42648. SystemClipboard::copyTextToClipboard (selectedText);
  42649. }
  42650. }
  42651. void TextEditor::paste()
  42652. {
  42653. if (! isReadOnly())
  42654. {
  42655. const String clip (SystemClipboard::getTextFromClipboard());
  42656. if (clip.isNotEmpty())
  42657. insertTextAtCaret (clip);
  42658. }
  42659. }
  42660. void TextEditor::cut()
  42661. {
  42662. if (! isReadOnly())
  42663. {
  42664. moveCaret (selection.getEnd());
  42665. insertTextAtCaret (String::empty);
  42666. }
  42667. }
  42668. void TextEditor::drawContent (Graphics& g)
  42669. {
  42670. const float wordWrapWidth = getWordWrapWidth();
  42671. if (wordWrapWidth > 0)
  42672. {
  42673. g.setOrigin (leftIndent, topIndent);
  42674. const Rectangle<int> clip (g.getClipBounds());
  42675. Colour selectedTextColour;
  42676. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42677. while (i.lineY + 200.0 < clip.getY() && i.next())
  42678. {}
  42679. if (! selection.isEmpty())
  42680. {
  42681. g.setColour (findColour (highlightColourId)
  42682. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42683. selectedTextColour = findColour (highlightedTextColourId);
  42684. Iterator i2 (i);
  42685. while (i2.next() && i2.lineY < clip.getBottom())
  42686. {
  42687. if (i2.lineY + i2.lineHeight >= clip.getY()
  42688. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42689. {
  42690. i2.drawSelection (g, selection);
  42691. }
  42692. }
  42693. }
  42694. const UniformTextSection* lastSection = 0;
  42695. while (i.next() && i.lineY < clip.getBottom())
  42696. {
  42697. if (i.lineY + i.lineHeight >= clip.getY())
  42698. {
  42699. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42700. {
  42701. i.drawSelectedText (g, selection, selectedTextColour);
  42702. lastSection = 0;
  42703. }
  42704. else
  42705. {
  42706. i.draw (g, lastSection);
  42707. }
  42708. }
  42709. }
  42710. }
  42711. }
  42712. void TextEditor::paint (Graphics& g)
  42713. {
  42714. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42715. }
  42716. void TextEditor::paintOverChildren (Graphics& g)
  42717. {
  42718. if (caretFlashState
  42719. && hasKeyboardFocus (false)
  42720. && caretVisible
  42721. && ! isReadOnly())
  42722. {
  42723. g.setColour (findColour (caretColourId));
  42724. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42725. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42726. 2.0f, cursorHeight);
  42727. }
  42728. if (textToShowWhenEmpty.isNotEmpty()
  42729. && (! hasKeyboardFocus (false))
  42730. && getTotalNumChars() == 0)
  42731. {
  42732. g.setColour (colourForTextWhenEmpty);
  42733. g.setFont (getFont());
  42734. if (isMultiLine())
  42735. {
  42736. g.drawText (textToShowWhenEmpty,
  42737. 0, 0, getWidth(), getHeight(),
  42738. Justification::centred, true);
  42739. }
  42740. else
  42741. {
  42742. g.drawText (textToShowWhenEmpty,
  42743. leftIndent, topIndent,
  42744. viewport->getWidth() - leftIndent,
  42745. viewport->getHeight() - topIndent,
  42746. Justification::centredLeft, true);
  42747. }
  42748. }
  42749. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42750. }
  42751. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  42752. {
  42753. public:
  42754. TextEditorMenuPerformer (TextEditor* const editor_)
  42755. : editor (editor_)
  42756. {
  42757. }
  42758. void modalStateFinished (int returnValue)
  42759. {
  42760. if (editor != 0 && returnValue != 0)
  42761. editor->performPopupMenuAction (returnValue);
  42762. }
  42763. private:
  42764. Component::SafePointer<TextEditor> editor;
  42765. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  42766. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  42767. };
  42768. void TextEditor::mouseDown (const MouseEvent& e)
  42769. {
  42770. beginDragAutoRepeat (100);
  42771. newTransaction();
  42772. if (wasFocused || ! selectAllTextWhenFocused)
  42773. {
  42774. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42775. {
  42776. moveCursorTo (getTextIndexAt (e.x, e.y),
  42777. e.mods.isShiftDown());
  42778. }
  42779. else
  42780. {
  42781. PopupMenu m;
  42782. m.setLookAndFeel (&getLookAndFeel());
  42783. addPopupMenuItems (m, &e);
  42784. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  42785. }
  42786. }
  42787. }
  42788. void TextEditor::mouseDrag (const MouseEvent& e)
  42789. {
  42790. if (wasFocused || ! selectAllTextWhenFocused)
  42791. {
  42792. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42793. {
  42794. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42795. }
  42796. }
  42797. }
  42798. void TextEditor::mouseUp (const MouseEvent& e)
  42799. {
  42800. newTransaction();
  42801. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42802. if (wasFocused || ! selectAllTextWhenFocused)
  42803. {
  42804. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42805. {
  42806. moveCaret (getTextIndexAt (e.x, e.y));
  42807. }
  42808. }
  42809. wasFocused = true;
  42810. }
  42811. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42812. {
  42813. int tokenEnd = getTextIndexAt (e.x, e.y);
  42814. int tokenStart = tokenEnd;
  42815. if (e.getNumberOfClicks() > 3)
  42816. {
  42817. tokenStart = 0;
  42818. tokenEnd = getTotalNumChars();
  42819. }
  42820. else
  42821. {
  42822. const String t (getText());
  42823. const int totalLength = getTotalNumChars();
  42824. while (tokenEnd < totalLength)
  42825. {
  42826. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42827. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42828. ++tokenEnd;
  42829. else
  42830. break;
  42831. }
  42832. tokenStart = tokenEnd;
  42833. while (tokenStart > 0)
  42834. {
  42835. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42836. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42837. --tokenStart;
  42838. else
  42839. break;
  42840. }
  42841. if (e.getNumberOfClicks() > 2)
  42842. {
  42843. while (tokenEnd < totalLength)
  42844. {
  42845. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42846. ++tokenEnd;
  42847. else
  42848. break;
  42849. }
  42850. while (tokenStart > 0)
  42851. {
  42852. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42853. --tokenStart;
  42854. else
  42855. break;
  42856. }
  42857. }
  42858. }
  42859. moveCursorTo (tokenEnd, false);
  42860. moveCursorTo (tokenStart, true);
  42861. }
  42862. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42863. {
  42864. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42865. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42866. }
  42867. bool TextEditor::keyPressed (const KeyPress& key)
  42868. {
  42869. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42870. return false;
  42871. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42872. if (key.isKeyCode (KeyPress::leftKey)
  42873. || key.isKeyCode (KeyPress::upKey))
  42874. {
  42875. newTransaction();
  42876. int newPos;
  42877. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42878. newPos = indexAtPosition (cursorX, cursorY - 1);
  42879. else if (moveInWholeWordSteps)
  42880. newPos = findWordBreakBefore (getCaretPosition());
  42881. else
  42882. newPos = getCaretPosition() - 1;
  42883. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42884. }
  42885. else if (key.isKeyCode (KeyPress::rightKey)
  42886. || key.isKeyCode (KeyPress::downKey))
  42887. {
  42888. newTransaction();
  42889. int newPos;
  42890. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42891. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42892. else if (moveInWholeWordSteps)
  42893. newPos = findWordBreakAfter (getCaretPosition());
  42894. else
  42895. newPos = getCaretPosition() + 1;
  42896. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42897. }
  42898. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42899. {
  42900. newTransaction();
  42901. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42902. key.getModifiers().isShiftDown());
  42903. }
  42904. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42905. {
  42906. newTransaction();
  42907. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42908. key.getModifiers().isShiftDown());
  42909. }
  42910. else if (key.isKeyCode (KeyPress::homeKey))
  42911. {
  42912. newTransaction();
  42913. if (isMultiLine() && ! moveInWholeWordSteps)
  42914. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42915. key.getModifiers().isShiftDown());
  42916. else
  42917. moveCursorTo (0, key.getModifiers().isShiftDown());
  42918. }
  42919. else if (key.isKeyCode (KeyPress::endKey))
  42920. {
  42921. newTransaction();
  42922. if (isMultiLine() && ! moveInWholeWordSteps)
  42923. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42924. key.getModifiers().isShiftDown());
  42925. else
  42926. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42927. }
  42928. else if (key.isKeyCode (KeyPress::backspaceKey))
  42929. {
  42930. if (moveInWholeWordSteps)
  42931. {
  42932. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42933. }
  42934. else
  42935. {
  42936. if (selection.isEmpty() && selection.getStart() > 0)
  42937. selection.setStart (selection.getEnd() - 1);
  42938. }
  42939. cut();
  42940. }
  42941. else if (key.isKeyCode (KeyPress::deleteKey))
  42942. {
  42943. if (key.getModifiers().isShiftDown())
  42944. copy();
  42945. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42946. selection.setEnd (selection.getStart() + 1);
  42947. cut();
  42948. }
  42949. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42950. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42951. {
  42952. newTransaction();
  42953. copy();
  42954. }
  42955. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42956. {
  42957. newTransaction();
  42958. copy();
  42959. cut();
  42960. }
  42961. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42962. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42963. {
  42964. newTransaction();
  42965. paste();
  42966. }
  42967. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42968. {
  42969. newTransaction();
  42970. doUndoRedo (false);
  42971. }
  42972. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42973. {
  42974. newTransaction();
  42975. doUndoRedo (true);
  42976. }
  42977. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42978. {
  42979. newTransaction();
  42980. moveCursorTo (getTotalNumChars(), false);
  42981. moveCursorTo (0, true);
  42982. }
  42983. else if (key == KeyPress::returnKey)
  42984. {
  42985. newTransaction();
  42986. insertTextAtCaret ("\n");
  42987. }
  42988. else if (key.isKeyCode (KeyPress::escapeKey))
  42989. {
  42990. newTransaction();
  42991. moveCursorTo (getCaretPosition(), false);
  42992. escapePressed();
  42993. }
  42994. else if (key.getTextCharacter() >= ' '
  42995. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42996. {
  42997. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42998. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42999. }
  43000. else
  43001. {
  43002. return false;
  43003. }
  43004. return true;
  43005. }
  43006. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43007. {
  43008. if (! isKeyDown)
  43009. return false;
  43010. #if JUCE_WINDOWS
  43011. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43012. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43013. #endif
  43014. // (overridden to avoid forwarding key events to the parent)
  43015. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43016. }
  43017. const int baseMenuItemID = 0x7fff0000;
  43018. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43019. {
  43020. const bool writable = ! isReadOnly();
  43021. if (passwordCharacter == 0)
  43022. {
  43023. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43024. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43025. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43026. }
  43027. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43028. m.addSeparator();
  43029. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43030. m.addSeparator();
  43031. if (getUndoManager() != 0)
  43032. {
  43033. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43034. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43035. }
  43036. }
  43037. void TextEditor::performPopupMenuAction (const int menuItemID)
  43038. {
  43039. switch (menuItemID)
  43040. {
  43041. case baseMenuItemID + 1:
  43042. copy();
  43043. cut();
  43044. break;
  43045. case baseMenuItemID + 2:
  43046. copy();
  43047. break;
  43048. case baseMenuItemID + 3:
  43049. paste();
  43050. break;
  43051. case baseMenuItemID + 4:
  43052. cut();
  43053. break;
  43054. case baseMenuItemID + 5:
  43055. moveCursorTo (getTotalNumChars(), false);
  43056. moveCursorTo (0, true);
  43057. break;
  43058. case baseMenuItemID + 6:
  43059. doUndoRedo (false);
  43060. break;
  43061. case baseMenuItemID + 7:
  43062. doUndoRedo (true);
  43063. break;
  43064. default:
  43065. break;
  43066. }
  43067. }
  43068. void TextEditor::focusGained (FocusChangeType)
  43069. {
  43070. newTransaction();
  43071. caretFlashState = true;
  43072. if (selectAllTextWhenFocused)
  43073. {
  43074. moveCursorTo (0, false);
  43075. moveCursorTo (getTotalNumChars(), true);
  43076. }
  43077. repaint();
  43078. if (caretVisible)
  43079. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43080. ComponentPeer* const peer = getPeer();
  43081. if (peer != 0 && ! isReadOnly())
  43082. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43083. }
  43084. void TextEditor::focusLost (FocusChangeType)
  43085. {
  43086. newTransaction();
  43087. wasFocused = false;
  43088. textHolder->stopTimer();
  43089. caretFlashState = false;
  43090. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43091. repaint();
  43092. }
  43093. void TextEditor::resized()
  43094. {
  43095. viewport->setBoundsInset (borderSize);
  43096. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43097. updateTextHolderSize();
  43098. if (! isMultiLine())
  43099. {
  43100. scrollToMakeSureCursorIsVisible();
  43101. }
  43102. else
  43103. {
  43104. updateCaretPosition();
  43105. }
  43106. }
  43107. void TextEditor::handleCommandMessage (const int commandId)
  43108. {
  43109. Component::BailOutChecker checker (this);
  43110. switch (commandId)
  43111. {
  43112. case TextEditorDefs::textChangeMessageId:
  43113. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43114. break;
  43115. case TextEditorDefs::returnKeyMessageId:
  43116. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43117. break;
  43118. case TextEditorDefs::escapeKeyMessageId:
  43119. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43120. break;
  43121. case TextEditorDefs::focusLossMessageId:
  43122. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43123. break;
  43124. default:
  43125. jassertfalse;
  43126. break;
  43127. }
  43128. }
  43129. void TextEditor::enablementChanged()
  43130. {
  43131. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43132. : MouseCursor::IBeamCursor);
  43133. repaint();
  43134. }
  43135. UndoManager* TextEditor::getUndoManager() throw()
  43136. {
  43137. return isReadOnly() ? 0 : &undoManager;
  43138. }
  43139. void TextEditor::clearInternal (UndoManager* const um)
  43140. {
  43141. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43142. }
  43143. void TextEditor::insert (const String& text,
  43144. const int insertIndex,
  43145. const Font& font,
  43146. const Colour& colour,
  43147. UndoManager* const um,
  43148. const int caretPositionToMoveTo)
  43149. {
  43150. if (text.isNotEmpty())
  43151. {
  43152. if (um != 0)
  43153. {
  43154. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43155. newTransaction();
  43156. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43157. caretPosition, caretPositionToMoveTo));
  43158. }
  43159. else
  43160. {
  43161. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43162. // a line gets moved due to word wrap
  43163. int index = 0;
  43164. int nextIndex = 0;
  43165. for (int i = 0; i < sections.size(); ++i)
  43166. {
  43167. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43168. if (insertIndex == index)
  43169. {
  43170. sections.insert (i, new UniformTextSection (text,
  43171. font, colour,
  43172. passwordCharacter));
  43173. break;
  43174. }
  43175. else if (insertIndex > index && insertIndex < nextIndex)
  43176. {
  43177. splitSection (i, insertIndex - index);
  43178. sections.insert (i + 1, new UniformTextSection (text,
  43179. font, colour,
  43180. passwordCharacter));
  43181. break;
  43182. }
  43183. index = nextIndex;
  43184. }
  43185. if (nextIndex == insertIndex)
  43186. sections.add (new UniformTextSection (text,
  43187. font, colour,
  43188. passwordCharacter));
  43189. coalesceSimilarSections();
  43190. totalNumChars = -1;
  43191. valueTextNeedsUpdating = true;
  43192. moveCursorTo (caretPositionToMoveTo, false);
  43193. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43194. }
  43195. }
  43196. }
  43197. void TextEditor::reinsert (const int insertIndex,
  43198. const Array <UniformTextSection*>& sectionsToInsert)
  43199. {
  43200. int index = 0;
  43201. int nextIndex = 0;
  43202. for (int i = 0; i < sections.size(); ++i)
  43203. {
  43204. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43205. if (insertIndex == index)
  43206. {
  43207. for (int j = sectionsToInsert.size(); --j >= 0;)
  43208. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43209. break;
  43210. }
  43211. else if (insertIndex > index && insertIndex < nextIndex)
  43212. {
  43213. splitSection (i, insertIndex - index);
  43214. for (int j = sectionsToInsert.size(); --j >= 0;)
  43215. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43216. break;
  43217. }
  43218. index = nextIndex;
  43219. }
  43220. if (nextIndex == insertIndex)
  43221. {
  43222. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43223. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43224. }
  43225. coalesceSimilarSections();
  43226. totalNumChars = -1;
  43227. valueTextNeedsUpdating = true;
  43228. }
  43229. void TextEditor::remove (const Range<int>& range,
  43230. UndoManager* const um,
  43231. const int caretPositionToMoveTo)
  43232. {
  43233. if (! range.isEmpty())
  43234. {
  43235. int index = 0;
  43236. for (int i = 0; i < sections.size(); ++i)
  43237. {
  43238. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43239. if (range.getStart() > index && range.getStart() < nextIndex)
  43240. {
  43241. splitSection (i, range.getStart() - index);
  43242. --i;
  43243. }
  43244. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43245. {
  43246. splitSection (i, range.getEnd() - index);
  43247. --i;
  43248. }
  43249. else
  43250. {
  43251. index = nextIndex;
  43252. if (index > range.getEnd())
  43253. break;
  43254. }
  43255. }
  43256. index = 0;
  43257. if (um != 0)
  43258. {
  43259. Array <UniformTextSection*> removedSections;
  43260. for (int i = 0; i < sections.size(); ++i)
  43261. {
  43262. if (range.getEnd() <= range.getStart())
  43263. break;
  43264. UniformTextSection* const section = sections.getUnchecked (i);
  43265. const int nextIndex = index + section->getTotalLength();
  43266. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43267. removedSections.add (new UniformTextSection (*section));
  43268. index = nextIndex;
  43269. }
  43270. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43271. newTransaction();
  43272. um->perform (new RemoveAction (*this, range, caretPosition,
  43273. caretPositionToMoveTo, removedSections));
  43274. }
  43275. else
  43276. {
  43277. Range<int> remainingRange (range);
  43278. for (int i = 0; i < sections.size(); ++i)
  43279. {
  43280. UniformTextSection* const section = sections.getUnchecked (i);
  43281. const int nextIndex = index + section->getTotalLength();
  43282. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43283. {
  43284. sections.remove(i);
  43285. section->clear();
  43286. delete section;
  43287. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43288. if (remainingRange.isEmpty())
  43289. break;
  43290. --i;
  43291. }
  43292. else
  43293. {
  43294. index = nextIndex;
  43295. }
  43296. }
  43297. coalesceSimilarSections();
  43298. totalNumChars = -1;
  43299. valueTextNeedsUpdating = true;
  43300. moveCursorTo (caretPositionToMoveTo, false);
  43301. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43302. }
  43303. }
  43304. }
  43305. const String TextEditor::getText() const
  43306. {
  43307. String t;
  43308. t.preallocateStorage (getTotalNumChars());
  43309. String::Concatenator concatenator (t);
  43310. for (int i = 0; i < sections.size(); ++i)
  43311. sections.getUnchecked (i)->appendAllText (concatenator);
  43312. return t;
  43313. }
  43314. const String TextEditor::getTextInRange (const Range<int>& range) const
  43315. {
  43316. String t;
  43317. if (! range.isEmpty())
  43318. {
  43319. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43320. String::Concatenator concatenator (t);
  43321. int index = 0;
  43322. for (int i = 0; i < sections.size(); ++i)
  43323. {
  43324. const UniformTextSection* const s = sections.getUnchecked (i);
  43325. const int nextIndex = index + s->getTotalLength();
  43326. if (range.getStart() < nextIndex)
  43327. {
  43328. if (range.getEnd() <= index)
  43329. break;
  43330. s->appendSubstring (concatenator, range - index);
  43331. }
  43332. index = nextIndex;
  43333. }
  43334. }
  43335. return t;
  43336. }
  43337. const String TextEditor::getHighlightedText() const
  43338. {
  43339. return getTextInRange (selection);
  43340. }
  43341. int TextEditor::getTotalNumChars() const
  43342. {
  43343. if (totalNumChars < 0)
  43344. {
  43345. totalNumChars = 0;
  43346. for (int i = sections.size(); --i >= 0;)
  43347. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43348. }
  43349. return totalNumChars;
  43350. }
  43351. bool TextEditor::isEmpty() const
  43352. {
  43353. return getTotalNumChars() == 0;
  43354. }
  43355. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43356. {
  43357. const float wordWrapWidth = getWordWrapWidth();
  43358. if (wordWrapWidth > 0 && sections.size() > 0)
  43359. {
  43360. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43361. i.getCharPosition (index, cx, cy, lineHeight);
  43362. }
  43363. else
  43364. {
  43365. cx = cy = 0;
  43366. lineHeight = currentFont.getHeight();
  43367. }
  43368. }
  43369. int TextEditor::indexAtPosition (const float x, const float y)
  43370. {
  43371. const float wordWrapWidth = getWordWrapWidth();
  43372. if (wordWrapWidth > 0)
  43373. {
  43374. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43375. while (i.next())
  43376. {
  43377. if (i.lineY + i.lineHeight > y)
  43378. {
  43379. if (i.lineY > y)
  43380. return jmax (0, i.indexInText - 1);
  43381. if (i.atomX >= x)
  43382. return i.indexInText;
  43383. if (x < i.atomRight)
  43384. return i.xToIndex (x);
  43385. }
  43386. }
  43387. }
  43388. return getTotalNumChars();
  43389. }
  43390. static int getCharacterCategory (const juce_wchar character)
  43391. {
  43392. return CharacterFunctions::isLetterOrDigit (character)
  43393. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43394. }
  43395. int TextEditor::findWordBreakAfter (const int position) const
  43396. {
  43397. const String t (getTextInRange (Range<int> (position, position + 512)));
  43398. const int totalLength = t.length();
  43399. int i = 0;
  43400. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43401. ++i;
  43402. const int type = getCharacterCategory (t[i]);
  43403. while (i < totalLength && type == getCharacterCategory (t[i]))
  43404. ++i;
  43405. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43406. ++i;
  43407. return position + i;
  43408. }
  43409. int TextEditor::findWordBreakBefore (const int position) const
  43410. {
  43411. if (position <= 0)
  43412. return 0;
  43413. const int startOfBuffer = jmax (0, position - 512);
  43414. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43415. int i = position - startOfBuffer;
  43416. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43417. --i;
  43418. if (i > 0)
  43419. {
  43420. const int type = getCharacterCategory (t [i - 1]);
  43421. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43422. --i;
  43423. }
  43424. jassert (startOfBuffer + i >= 0);
  43425. return startOfBuffer + i;
  43426. }
  43427. void TextEditor::splitSection (const int sectionIndex,
  43428. const int charToSplitAt)
  43429. {
  43430. jassert (sections[sectionIndex] != 0);
  43431. sections.insert (sectionIndex + 1,
  43432. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43433. }
  43434. void TextEditor::coalesceSimilarSections()
  43435. {
  43436. for (int i = 0; i < sections.size() - 1; ++i)
  43437. {
  43438. UniformTextSection* const s1 = sections.getUnchecked (i);
  43439. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43440. if (s1->font == s2->font
  43441. && s1->colour == s2->colour)
  43442. {
  43443. s1->append (*s2, passwordCharacter);
  43444. sections.remove (i + 1);
  43445. delete s2;
  43446. --i;
  43447. }
  43448. }
  43449. }
  43450. END_JUCE_NAMESPACE
  43451. /*** End of inlined file: juce_TextEditor.cpp ***/
  43452. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43453. BEGIN_JUCE_NAMESPACE
  43454. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43455. class ToolbarSpacerComp : public ToolbarItemComponent
  43456. {
  43457. public:
  43458. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43459. : ToolbarItemComponent (itemId_, String::empty, false),
  43460. fixedSize (fixedSize_),
  43461. drawBar (drawBar_)
  43462. {
  43463. }
  43464. ~ToolbarSpacerComp()
  43465. {
  43466. }
  43467. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43468. int& preferredSize, int& minSize, int& maxSize)
  43469. {
  43470. if (fixedSize <= 0)
  43471. {
  43472. preferredSize = toolbarThickness * 2;
  43473. minSize = 4;
  43474. maxSize = 32768;
  43475. }
  43476. else
  43477. {
  43478. maxSize = roundToInt (toolbarThickness * fixedSize);
  43479. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43480. preferredSize = maxSize;
  43481. if (getEditingMode() == editableOnPalette)
  43482. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43483. }
  43484. return true;
  43485. }
  43486. void paintButtonArea (Graphics&, int, int, bool, bool)
  43487. {
  43488. }
  43489. void contentAreaChanged (const Rectangle<int>&)
  43490. {
  43491. }
  43492. int getResizeOrder() const throw()
  43493. {
  43494. return fixedSize <= 0 ? 0 : 1;
  43495. }
  43496. void paint (Graphics& g)
  43497. {
  43498. const int w = getWidth();
  43499. const int h = getHeight();
  43500. if (drawBar)
  43501. {
  43502. g.setColour (findColour (Toolbar::separatorColourId, true));
  43503. const float thickness = 0.2f;
  43504. if (isToolbarVertical())
  43505. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43506. else
  43507. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43508. }
  43509. if (getEditingMode() != normalMode && ! drawBar)
  43510. {
  43511. g.setColour (findColour (Toolbar::separatorColourId, true));
  43512. const int indentX = jmin (2, (w - 3) / 2);
  43513. const int indentY = jmin (2, (h - 3) / 2);
  43514. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43515. if (fixedSize <= 0)
  43516. {
  43517. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43518. if (isToolbarVertical())
  43519. {
  43520. x1 = w * 0.5f;
  43521. y1 = h * 0.4f;
  43522. x2 = x1;
  43523. y2 = indentX * 2.0f;
  43524. x3 = x1;
  43525. y3 = h * 0.6f;
  43526. x4 = x1;
  43527. y4 = h - y2;
  43528. hw = w * 0.15f;
  43529. hl = w * 0.2f;
  43530. }
  43531. else
  43532. {
  43533. x1 = w * 0.4f;
  43534. y1 = h * 0.5f;
  43535. x2 = indentX * 2.0f;
  43536. y2 = y1;
  43537. x3 = w * 0.6f;
  43538. y3 = y1;
  43539. x4 = w - x2;
  43540. y4 = y1;
  43541. hw = h * 0.15f;
  43542. hl = h * 0.2f;
  43543. }
  43544. Path p;
  43545. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43546. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43547. g.fillPath (p);
  43548. }
  43549. }
  43550. }
  43551. juce_UseDebuggingNewOperator
  43552. private:
  43553. const float fixedSize;
  43554. const bool drawBar;
  43555. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43556. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43557. };
  43558. class MissingItemsComponent : public PopupMenuCustomComponent
  43559. {
  43560. public:
  43561. MissingItemsComponent (Toolbar& owner_, const int height_)
  43562. : PopupMenuCustomComponent (true),
  43563. owner (owner_),
  43564. height (height_)
  43565. {
  43566. for (int i = owner_.items.size(); --i >= 0;)
  43567. {
  43568. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43569. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43570. {
  43571. oldIndexes.insert (0, i);
  43572. addAndMakeVisible (tc, 0);
  43573. }
  43574. }
  43575. layout (400);
  43576. }
  43577. ~MissingItemsComponent()
  43578. {
  43579. // deleting the toolbar while its menu it open??
  43580. jassert (owner.isValidComponent());
  43581. for (int i = 0; i < getNumChildComponents(); ++i)
  43582. {
  43583. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43584. if (tc != 0)
  43585. {
  43586. tc->setVisible (false);
  43587. const int index = oldIndexes.remove (i);
  43588. owner.addChildComponent (tc, index);
  43589. --i;
  43590. }
  43591. }
  43592. owner.resized();
  43593. }
  43594. void layout (const int preferredWidth)
  43595. {
  43596. const int indent = 8;
  43597. int x = indent;
  43598. int y = indent;
  43599. int maxX = 0;
  43600. for (int i = 0; i < getNumChildComponents(); ++i)
  43601. {
  43602. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43603. if (tc != 0)
  43604. {
  43605. int preferredSize = 1, minSize = 1, maxSize = 1;
  43606. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43607. {
  43608. if (x + preferredSize > preferredWidth && x > indent)
  43609. {
  43610. x = indent;
  43611. y += height;
  43612. }
  43613. tc->setBounds (x, y, preferredSize, height);
  43614. x += preferredSize;
  43615. maxX = jmax (maxX, x);
  43616. }
  43617. }
  43618. }
  43619. setSize (maxX + 8, y + height + 8);
  43620. }
  43621. void getIdealSize (int& idealWidth, int& idealHeight)
  43622. {
  43623. idealWidth = getWidth();
  43624. idealHeight = getHeight();
  43625. }
  43626. juce_UseDebuggingNewOperator
  43627. private:
  43628. Toolbar& owner;
  43629. const int height;
  43630. Array <int> oldIndexes;
  43631. MissingItemsComponent (const MissingItemsComponent&);
  43632. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43633. };
  43634. Toolbar::Toolbar()
  43635. : vertical (false),
  43636. isEditingActive (false),
  43637. toolbarStyle (Toolbar::iconsOnly)
  43638. {
  43639. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43640. missingItemsButton->setAlwaysOnTop (true);
  43641. missingItemsButton->addButtonListener (this);
  43642. }
  43643. Toolbar::~Toolbar()
  43644. {
  43645. animator.cancelAllAnimations (true);
  43646. deleteAllChildren();
  43647. }
  43648. void Toolbar::setVertical (const bool shouldBeVertical)
  43649. {
  43650. if (vertical != shouldBeVertical)
  43651. {
  43652. vertical = shouldBeVertical;
  43653. resized();
  43654. }
  43655. }
  43656. void Toolbar::clear()
  43657. {
  43658. for (int i = items.size(); --i >= 0;)
  43659. {
  43660. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43661. items.remove (i);
  43662. delete tc;
  43663. }
  43664. resized();
  43665. }
  43666. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43667. {
  43668. if (itemId == ToolbarItemFactory::separatorBarId)
  43669. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43670. else if (itemId == ToolbarItemFactory::spacerId)
  43671. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43672. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43673. return new ToolbarSpacerComp (itemId, 0, false);
  43674. return factory.createItem (itemId);
  43675. }
  43676. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43677. const int itemId,
  43678. const int insertIndex)
  43679. {
  43680. // An ID can't be zero - this might indicate a mistake somewhere?
  43681. jassert (itemId != 0);
  43682. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43683. if (tc != 0)
  43684. {
  43685. #if JUCE_DEBUG
  43686. Array <int> allowedIds;
  43687. factory.getAllToolbarItemIds (allowedIds);
  43688. // If your factory can create an item for a given ID, it must also return
  43689. // that ID from its getAllToolbarItemIds() method!
  43690. jassert (allowedIds.contains (itemId));
  43691. #endif
  43692. items.insert (insertIndex, tc);
  43693. addAndMakeVisible (tc, insertIndex);
  43694. }
  43695. }
  43696. void Toolbar::addItem (ToolbarItemFactory& factory,
  43697. const int itemId,
  43698. const int insertIndex)
  43699. {
  43700. addItemInternal (factory, itemId, insertIndex);
  43701. resized();
  43702. }
  43703. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43704. {
  43705. Array <int> ids;
  43706. factoryToUse.getDefaultItemSet (ids);
  43707. clear();
  43708. for (int i = 0; i < ids.size(); ++i)
  43709. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43710. resized();
  43711. }
  43712. void Toolbar::removeToolbarItem (const int itemIndex)
  43713. {
  43714. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43715. if (tc != 0)
  43716. {
  43717. items.removeValue (tc);
  43718. delete tc;
  43719. resized();
  43720. }
  43721. }
  43722. int Toolbar::getNumItems() const throw()
  43723. {
  43724. return items.size();
  43725. }
  43726. int Toolbar::getItemId (const int itemIndex) const throw()
  43727. {
  43728. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43729. return tc != 0 ? tc->getItemId() : 0;
  43730. }
  43731. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43732. {
  43733. return items [itemIndex];
  43734. }
  43735. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43736. {
  43737. for (;;)
  43738. {
  43739. index += delta;
  43740. ToolbarItemComponent* const tc = getItemComponent (index);
  43741. if (tc == 0)
  43742. break;
  43743. if (tc->isActive)
  43744. return tc;
  43745. }
  43746. return 0;
  43747. }
  43748. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43749. {
  43750. if (toolbarStyle != newStyle)
  43751. {
  43752. toolbarStyle = newStyle;
  43753. updateAllItemPositions (false);
  43754. }
  43755. }
  43756. const String Toolbar::toString() const
  43757. {
  43758. String s ("TB:");
  43759. for (int i = 0; i < getNumItems(); ++i)
  43760. s << getItemId(i) << ' ';
  43761. return s.trimEnd();
  43762. }
  43763. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43764. const String& savedVersion)
  43765. {
  43766. if (! savedVersion.startsWith ("TB:"))
  43767. return false;
  43768. StringArray tokens;
  43769. tokens.addTokens (savedVersion.substring (3), false);
  43770. clear();
  43771. for (int i = 0; i < tokens.size(); ++i)
  43772. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43773. resized();
  43774. return true;
  43775. }
  43776. void Toolbar::paint (Graphics& g)
  43777. {
  43778. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43779. }
  43780. int Toolbar::getThickness() const throw()
  43781. {
  43782. return vertical ? getWidth() : getHeight();
  43783. }
  43784. int Toolbar::getLength() const throw()
  43785. {
  43786. return vertical ? getHeight() : getWidth();
  43787. }
  43788. void Toolbar::setEditingActive (const bool active)
  43789. {
  43790. if (isEditingActive != active)
  43791. {
  43792. isEditingActive = active;
  43793. updateAllItemPositions (false);
  43794. }
  43795. }
  43796. void Toolbar::resized()
  43797. {
  43798. updateAllItemPositions (false);
  43799. }
  43800. void Toolbar::updateAllItemPositions (const bool animate)
  43801. {
  43802. if (getWidth() > 0 && getHeight() > 0)
  43803. {
  43804. StretchableObjectResizer resizer;
  43805. int i;
  43806. for (i = 0; i < items.size(); ++i)
  43807. {
  43808. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43809. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43810. : ToolbarItemComponent::normalMode);
  43811. tc->setStyle (toolbarStyle);
  43812. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43813. int preferredSize = 1, minSize = 1, maxSize = 1;
  43814. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43815. preferredSize, minSize, maxSize))
  43816. {
  43817. tc->isActive = true;
  43818. resizer.addItem (preferredSize, minSize, maxSize,
  43819. spacer != 0 ? spacer->getResizeOrder() : 2);
  43820. }
  43821. else
  43822. {
  43823. tc->isActive = false;
  43824. tc->setVisible (false);
  43825. }
  43826. }
  43827. resizer.resizeToFit (getLength());
  43828. int totalLength = 0;
  43829. for (i = 0; i < resizer.getNumItems(); ++i)
  43830. totalLength += (int) resizer.getItemSize (i);
  43831. const bool itemsOffTheEnd = totalLength > getLength();
  43832. const int extrasButtonSize = getThickness() / 2;
  43833. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43834. missingItemsButton->setVisible (itemsOffTheEnd);
  43835. missingItemsButton->setEnabled (! isEditingActive);
  43836. if (vertical)
  43837. missingItemsButton->setCentrePosition (getWidth() / 2,
  43838. getHeight() - 4 - extrasButtonSize / 2);
  43839. else
  43840. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43841. getHeight() / 2);
  43842. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43843. : missingItemsButton->getX()) - 4
  43844. : getLength();
  43845. int pos = 0, activeIndex = 0;
  43846. for (i = 0; i < items.size(); ++i)
  43847. {
  43848. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43849. if (tc->isActive)
  43850. {
  43851. const int size = (int) resizer.getItemSize (activeIndex++);
  43852. Rectangle<int> newBounds;
  43853. if (vertical)
  43854. newBounds.setBounds (0, pos, getWidth(), size);
  43855. else
  43856. newBounds.setBounds (pos, 0, size, getHeight());
  43857. if (animate)
  43858. {
  43859. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43860. }
  43861. else
  43862. {
  43863. animator.cancelAnimation (tc, false);
  43864. tc->setBounds (newBounds);
  43865. }
  43866. pos += size;
  43867. tc->setVisible (pos <= maxLength
  43868. && ((! tc->isBeingDragged)
  43869. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43870. }
  43871. }
  43872. }
  43873. }
  43874. void Toolbar::buttonClicked (Button*)
  43875. {
  43876. jassert (missingItemsButton->isShowing());
  43877. if (missingItemsButton->isShowing())
  43878. {
  43879. PopupMenu m;
  43880. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43881. m.showAt (missingItemsButton);
  43882. }
  43883. }
  43884. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43885. Component* /*sourceComponent*/)
  43886. {
  43887. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43888. }
  43889. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43890. {
  43891. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43892. if (tc != 0)
  43893. {
  43894. if (getNumItems() == 0)
  43895. {
  43896. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43897. {
  43898. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43899. if (palette != 0)
  43900. palette->replaceComponent (tc);
  43901. }
  43902. else
  43903. {
  43904. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43905. }
  43906. items.add (tc);
  43907. addChildComponent (tc);
  43908. updateAllItemPositions (false);
  43909. }
  43910. else
  43911. {
  43912. for (int i = getNumItems(); --i >= 0;)
  43913. {
  43914. int currentIndex = getIndexOfChildComponent (tc);
  43915. if (currentIndex < 0)
  43916. {
  43917. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43918. {
  43919. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43920. if (palette != 0)
  43921. palette->replaceComponent (tc);
  43922. }
  43923. else
  43924. {
  43925. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43926. }
  43927. items.add (tc);
  43928. addChildComponent (tc);
  43929. currentIndex = getIndexOfChildComponent (tc);
  43930. updateAllItemPositions (true);
  43931. }
  43932. int newIndex = currentIndex;
  43933. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43934. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43935. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43936. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43937. if (prev != 0)
  43938. {
  43939. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43940. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43941. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43942. {
  43943. newIndex = getIndexOfChildComponent (prev);
  43944. }
  43945. }
  43946. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43947. if (next != 0)
  43948. {
  43949. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43950. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43951. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43952. {
  43953. newIndex = getIndexOfChildComponent (next) + 1;
  43954. }
  43955. }
  43956. if (newIndex != currentIndex)
  43957. {
  43958. items.removeValue (tc);
  43959. removeChildComponent (tc);
  43960. addChildComponent (tc, newIndex);
  43961. items.insert (newIndex, tc);
  43962. updateAllItemPositions (true);
  43963. }
  43964. else
  43965. {
  43966. break;
  43967. }
  43968. }
  43969. }
  43970. }
  43971. }
  43972. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43973. {
  43974. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43975. if (tc != 0)
  43976. {
  43977. if (isParentOf (tc))
  43978. {
  43979. items.removeValue (tc);
  43980. removeChildComponent (tc);
  43981. updateAllItemPositions (true);
  43982. }
  43983. }
  43984. }
  43985. void Toolbar::itemDropped (const String&, Component*, int, int)
  43986. {
  43987. }
  43988. void Toolbar::mouseDown (const MouseEvent& e)
  43989. {
  43990. if (e.mods.isPopupMenu())
  43991. {
  43992. }
  43993. }
  43994. class ToolbarCustomisationDialog : public DialogWindow
  43995. {
  43996. public:
  43997. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43998. Toolbar* const toolbar_,
  43999. const int optionFlags)
  44000. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44001. toolbar (toolbar_)
  44002. {
  44003. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44004. setResizable (true, true);
  44005. setResizeLimits (400, 300, 1500, 1000);
  44006. positionNearBar();
  44007. }
  44008. ~ToolbarCustomisationDialog()
  44009. {
  44010. setContentComponent (0, true);
  44011. }
  44012. void closeButtonPressed()
  44013. {
  44014. setVisible (false);
  44015. }
  44016. bool canModalEventBeSentToComponent (const Component* comp)
  44017. {
  44018. return toolbar->isParentOf (comp);
  44019. }
  44020. void positionNearBar()
  44021. {
  44022. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44023. const int tbx = toolbar->getScreenX();
  44024. const int tby = toolbar->getScreenY();
  44025. const int gap = 8;
  44026. int x, y;
  44027. if (toolbar->isVertical())
  44028. {
  44029. y = tby;
  44030. if (tbx > screenSize.getCentreX())
  44031. x = tbx - getWidth() - gap;
  44032. else
  44033. x = tbx + toolbar->getWidth() + gap;
  44034. }
  44035. else
  44036. {
  44037. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44038. if (tby > screenSize.getCentreY())
  44039. y = tby - getHeight() - gap;
  44040. else
  44041. y = tby + toolbar->getHeight() + gap;
  44042. }
  44043. setTopLeftPosition (x, y);
  44044. }
  44045. private:
  44046. Toolbar* const toolbar;
  44047. class CustomiserPanel : public Component,
  44048. private ComboBoxListener,
  44049. private ButtonListener
  44050. {
  44051. public:
  44052. CustomiserPanel (ToolbarItemFactory& factory_,
  44053. Toolbar* const toolbar_,
  44054. const int optionFlags)
  44055. : factory (factory_),
  44056. toolbar (toolbar_),
  44057. styleBox (0),
  44058. defaultButton (0)
  44059. {
  44060. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44061. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44062. | Toolbar::allowIconsWithTextChoice
  44063. | Toolbar::allowTextOnlyChoice)) != 0)
  44064. {
  44065. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44066. styleBox->setEditableText (false);
  44067. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44068. styleBox->addItem (TRANS("Show icons only"), 1);
  44069. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44070. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44071. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44072. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44073. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44074. styleBox->setSelectedId (1);
  44075. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44076. styleBox->setSelectedId (2);
  44077. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44078. styleBox->setSelectedId (3);
  44079. styleBox->addListener (this);
  44080. }
  44081. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44082. {
  44083. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44084. defaultButton->addButtonListener (this);
  44085. }
  44086. addAndMakeVisible (instructions = new Label (String::empty,
  44087. 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.")));
  44088. instructions->setFont (Font (13.0f));
  44089. setSize (500, 300);
  44090. }
  44091. ~CustomiserPanel()
  44092. {
  44093. deleteAllChildren();
  44094. }
  44095. void comboBoxChanged (ComboBox*)
  44096. {
  44097. if (styleBox->getSelectedId() == 1)
  44098. toolbar->setStyle (Toolbar::iconsOnly);
  44099. else if (styleBox->getSelectedId() == 2)
  44100. toolbar->setStyle (Toolbar::iconsWithText);
  44101. else if (styleBox->getSelectedId() == 3)
  44102. toolbar->setStyle (Toolbar::textOnly);
  44103. palette->resized(); // to make it update the styles
  44104. }
  44105. void buttonClicked (Button*)
  44106. {
  44107. toolbar->addDefaultItems (factory);
  44108. }
  44109. void paint (Graphics& g)
  44110. {
  44111. Colour background;
  44112. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44113. if (dw != 0)
  44114. background = dw->getBackgroundColour();
  44115. g.setColour (background.contrasting().withAlpha (0.3f));
  44116. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44117. }
  44118. void resized()
  44119. {
  44120. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44121. if (styleBox != 0)
  44122. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44123. if (defaultButton != 0)
  44124. {
  44125. defaultButton->changeWidthToFitText (22);
  44126. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44127. }
  44128. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44129. }
  44130. private:
  44131. ToolbarItemFactory& factory;
  44132. Toolbar* const toolbar;
  44133. Label* instructions;
  44134. ToolbarItemPalette* palette;
  44135. ComboBox* styleBox;
  44136. TextButton* defaultButton;
  44137. };
  44138. };
  44139. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44140. {
  44141. setEditingActive (true);
  44142. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44143. dw.runModalLoop();
  44144. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44145. setEditingActive (false);
  44146. }
  44147. END_JUCE_NAMESPACE
  44148. /*** End of inlined file: juce_Toolbar.cpp ***/
  44149. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44150. BEGIN_JUCE_NAMESPACE
  44151. ToolbarItemFactory::ToolbarItemFactory()
  44152. {
  44153. }
  44154. ToolbarItemFactory::~ToolbarItemFactory()
  44155. {
  44156. }
  44157. class ItemDragAndDropOverlayComponent : public Component
  44158. {
  44159. public:
  44160. ItemDragAndDropOverlayComponent()
  44161. : isDragging (false)
  44162. {
  44163. setAlwaysOnTop (true);
  44164. setRepaintsOnMouseActivity (true);
  44165. setMouseCursor (MouseCursor::DraggingHandCursor);
  44166. }
  44167. ~ItemDragAndDropOverlayComponent()
  44168. {
  44169. }
  44170. void paint (Graphics& g)
  44171. {
  44172. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44173. if (isMouseOverOrDragging()
  44174. && tc != 0
  44175. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44176. {
  44177. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44178. g.drawRect (0, 0, getWidth(), getHeight(),
  44179. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44180. }
  44181. }
  44182. void mouseDown (const MouseEvent& e)
  44183. {
  44184. isDragging = false;
  44185. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44186. if (tc != 0)
  44187. {
  44188. tc->dragOffsetX = e.x;
  44189. tc->dragOffsetY = e.y;
  44190. }
  44191. }
  44192. void mouseDrag (const MouseEvent& e)
  44193. {
  44194. if (! (isDragging || e.mouseWasClicked()))
  44195. {
  44196. isDragging = true;
  44197. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44198. if (dnd != 0)
  44199. {
  44200. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image(), true);
  44201. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44202. if (tc != 0)
  44203. {
  44204. tc->isBeingDragged = true;
  44205. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44206. tc->setVisible (false);
  44207. }
  44208. }
  44209. }
  44210. }
  44211. void mouseUp (const MouseEvent&)
  44212. {
  44213. isDragging = false;
  44214. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44215. if (tc != 0)
  44216. {
  44217. tc->isBeingDragged = false;
  44218. Toolbar* const tb = tc->getToolbar();
  44219. if (tb != 0)
  44220. tb->updateAllItemPositions (true);
  44221. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44222. delete tc;
  44223. }
  44224. }
  44225. void parentSizeChanged()
  44226. {
  44227. setBounds (0, 0, getParentWidth(), getParentHeight());
  44228. }
  44229. juce_UseDebuggingNewOperator
  44230. private:
  44231. bool isDragging;
  44232. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44233. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44234. };
  44235. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44236. const String& labelText,
  44237. const bool isBeingUsedAsAButton_)
  44238. : Button (labelText),
  44239. itemId (itemId_),
  44240. mode (normalMode),
  44241. toolbarStyle (Toolbar::iconsOnly),
  44242. dragOffsetX (0),
  44243. dragOffsetY (0),
  44244. isActive (true),
  44245. isBeingDragged (false),
  44246. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44247. {
  44248. // Your item ID can't be 0!
  44249. jassert (itemId_ != 0);
  44250. }
  44251. ToolbarItemComponent::~ToolbarItemComponent()
  44252. {
  44253. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44254. overlayComp = 0;
  44255. }
  44256. Toolbar* ToolbarItemComponent::getToolbar() const
  44257. {
  44258. return dynamic_cast <Toolbar*> (getParentComponent());
  44259. }
  44260. bool ToolbarItemComponent::isToolbarVertical() const
  44261. {
  44262. const Toolbar* const t = getToolbar();
  44263. return t != 0 && t->isVertical();
  44264. }
  44265. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44266. {
  44267. if (toolbarStyle != newStyle)
  44268. {
  44269. toolbarStyle = newStyle;
  44270. repaint();
  44271. resized();
  44272. }
  44273. }
  44274. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44275. {
  44276. if (isBeingUsedAsAButton)
  44277. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44278. over, down, *this);
  44279. if (toolbarStyle != Toolbar::iconsOnly)
  44280. {
  44281. const int indent = contentArea.getX();
  44282. int y = indent;
  44283. int h = getHeight() - indent * 2;
  44284. if (toolbarStyle == Toolbar::iconsWithText)
  44285. {
  44286. y = contentArea.getBottom() + indent / 2;
  44287. h -= contentArea.getHeight();
  44288. }
  44289. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44290. getButtonText(), *this);
  44291. }
  44292. if (! contentArea.isEmpty())
  44293. {
  44294. g.saveState();
  44295. g.setOrigin (contentArea.getX(), contentArea.getY());
  44296. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44297. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44298. g.restoreState();
  44299. }
  44300. }
  44301. void ToolbarItemComponent::resized()
  44302. {
  44303. if (toolbarStyle != Toolbar::textOnly)
  44304. {
  44305. const int indent = jmin (proportionOfWidth (0.08f),
  44306. proportionOfHeight (0.08f));
  44307. contentArea = Rectangle<int> (indent, indent,
  44308. getWidth() - indent * 2,
  44309. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44310. : (getHeight() - indent * 2));
  44311. }
  44312. else
  44313. {
  44314. contentArea = Rectangle<int>();
  44315. }
  44316. contentAreaChanged (contentArea);
  44317. }
  44318. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44319. {
  44320. if (mode != newMode)
  44321. {
  44322. mode = newMode;
  44323. repaint();
  44324. if (mode == normalMode)
  44325. {
  44326. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44327. overlayComp = 0;
  44328. }
  44329. else if (overlayComp == 0)
  44330. {
  44331. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44332. overlayComp->parentSizeChanged();
  44333. }
  44334. resized();
  44335. }
  44336. }
  44337. END_JUCE_NAMESPACE
  44338. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44339. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44340. BEGIN_JUCE_NAMESPACE
  44341. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44342. Toolbar* const toolbar_)
  44343. : factory (factory_),
  44344. toolbar (toolbar_)
  44345. {
  44346. Component* const itemHolder = new Component();
  44347. Array <int> allIds;
  44348. factory_.getAllToolbarItemIds (allIds);
  44349. for (int i = 0; i < allIds.size(); ++i)
  44350. {
  44351. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44352. jassert (tc != 0);
  44353. if (tc != 0)
  44354. {
  44355. itemHolder->addAndMakeVisible (tc);
  44356. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44357. }
  44358. }
  44359. viewport = new Viewport();
  44360. viewport->setViewedComponent (itemHolder);
  44361. addAndMakeVisible (viewport);
  44362. }
  44363. ToolbarItemPalette::~ToolbarItemPalette()
  44364. {
  44365. viewport->getViewedComponent()->deleteAllChildren();
  44366. deleteAllChildren();
  44367. }
  44368. void ToolbarItemPalette::resized()
  44369. {
  44370. viewport->setBoundsInset (BorderSize (1));
  44371. Component* const itemHolder = viewport->getViewedComponent();
  44372. const int indent = 8;
  44373. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44374. const int height = toolbar->getThickness();
  44375. int x = indent;
  44376. int y = indent;
  44377. int maxX = 0;
  44378. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44379. {
  44380. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44381. if (tc != 0)
  44382. {
  44383. tc->setStyle (toolbar->getStyle());
  44384. int preferredSize = 1, minSize = 1, maxSize = 1;
  44385. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44386. {
  44387. if (x + preferredSize > preferredWidth && x > indent)
  44388. {
  44389. x = indent;
  44390. y += height;
  44391. }
  44392. tc->setBounds (x, y, preferredSize, height);
  44393. x += preferredSize + 8;
  44394. maxX = jmax (maxX, x);
  44395. }
  44396. }
  44397. }
  44398. itemHolder->setSize (maxX, y + height + 8);
  44399. }
  44400. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44401. {
  44402. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44403. jassert (tc != 0);
  44404. if (tc != 0)
  44405. {
  44406. tc->setBounds (comp->getBounds());
  44407. tc->setStyle (toolbar->getStyle());
  44408. tc->setEditingMode (comp->getEditingMode());
  44409. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44410. }
  44411. }
  44412. END_JUCE_NAMESPACE
  44413. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44414. /*** Start of inlined file: juce_TreeView.cpp ***/
  44415. BEGIN_JUCE_NAMESPACE
  44416. class TreeViewContentComponent : public Component,
  44417. public TooltipClient
  44418. {
  44419. public:
  44420. TreeViewContentComponent (TreeView& owner_)
  44421. : owner (owner_),
  44422. buttonUnderMouse (0),
  44423. isDragging (false)
  44424. {
  44425. }
  44426. ~TreeViewContentComponent()
  44427. {
  44428. deleteAllChildren();
  44429. }
  44430. void mouseDown (const MouseEvent& e)
  44431. {
  44432. updateButtonUnderMouse (e);
  44433. isDragging = false;
  44434. needSelectionOnMouseUp = false;
  44435. Rectangle<int> pos;
  44436. TreeViewItem* const item = findItemAt (e.y, pos);
  44437. if (item == 0)
  44438. return;
  44439. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44440. // as selection clicks)
  44441. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44442. {
  44443. if (e.x >= pos.getX() - owner.getIndentSize())
  44444. item->setOpen (! item->isOpen());
  44445. // (clicks to the left of an open/close button are ignored)
  44446. }
  44447. else
  44448. {
  44449. // mouse-down inside the body of the item..
  44450. if (! owner.isMultiSelectEnabled())
  44451. item->setSelected (true, true);
  44452. else if (item->isSelected())
  44453. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44454. else
  44455. selectBasedOnModifiers (item, e.mods);
  44456. if (e.x >= pos.getX())
  44457. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44458. }
  44459. }
  44460. void mouseUp (const MouseEvent& e)
  44461. {
  44462. updateButtonUnderMouse (e);
  44463. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44464. {
  44465. Rectangle<int> pos;
  44466. TreeViewItem* const item = findItemAt (e.y, pos);
  44467. if (item != 0)
  44468. selectBasedOnModifiers (item, e.mods);
  44469. }
  44470. }
  44471. void mouseDoubleClick (const MouseEvent& e)
  44472. {
  44473. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44474. {
  44475. Rectangle<int> pos;
  44476. TreeViewItem* const item = findItemAt (e.y, pos);
  44477. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44478. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44479. }
  44480. }
  44481. void mouseDrag (const MouseEvent& e)
  44482. {
  44483. if (isEnabled()
  44484. && ! (isDragging || e.mouseWasClicked()
  44485. || e.getDistanceFromDragStart() < 5
  44486. || e.mods.isPopupMenu()))
  44487. {
  44488. isDragging = true;
  44489. Rectangle<int> pos;
  44490. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44491. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44492. {
  44493. const String dragDescription (item->getDragSourceDescription());
  44494. if (dragDescription.isNotEmpty())
  44495. {
  44496. DragAndDropContainer* const dragContainer
  44497. = DragAndDropContainer::findParentDragContainerFor (this);
  44498. if (dragContainer != 0)
  44499. {
  44500. pos.setSize (pos.getWidth(), item->itemHeight);
  44501. Image dragImage (Component::createComponentSnapshot (pos, true));
  44502. dragImage.multiplyAllAlphas (0.6f);
  44503. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44504. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44505. }
  44506. else
  44507. {
  44508. // to be able to do a drag-and-drop operation, the treeview needs to
  44509. // be inside a component which is also a DragAndDropContainer.
  44510. jassertfalse;
  44511. }
  44512. }
  44513. }
  44514. }
  44515. }
  44516. void mouseMove (const MouseEvent& e)
  44517. {
  44518. updateButtonUnderMouse (e);
  44519. }
  44520. void mouseExit (const MouseEvent& e)
  44521. {
  44522. updateButtonUnderMouse (e);
  44523. }
  44524. void paint (Graphics& g)
  44525. {
  44526. if (owner.rootItem != 0)
  44527. {
  44528. owner.handleAsyncUpdate();
  44529. if (! owner.rootItemVisible)
  44530. g.setOrigin (0, -owner.rootItem->itemHeight);
  44531. owner.rootItem->paintRecursively (g, getWidth());
  44532. }
  44533. }
  44534. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44535. {
  44536. if (owner.rootItem != 0)
  44537. {
  44538. owner.handleAsyncUpdate();
  44539. if (! owner.rootItemVisible)
  44540. y += owner.rootItem->itemHeight;
  44541. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44542. if (ti != 0)
  44543. itemPosition = ti->getItemPosition (false);
  44544. return ti;
  44545. }
  44546. return 0;
  44547. }
  44548. void updateComponents()
  44549. {
  44550. const int visibleTop = -getY();
  44551. const int visibleBottom = visibleTop + getParentHeight();
  44552. BigInteger itemsToKeep;
  44553. {
  44554. TreeViewItem* item = owner.rootItem;
  44555. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44556. while (item != 0 && y < visibleBottom)
  44557. {
  44558. y += item->itemHeight;
  44559. if (y >= visibleTop)
  44560. {
  44561. const int index = rowComponentIds.indexOf (item->uid);
  44562. if (index < 0)
  44563. {
  44564. Component* const comp = item->createItemComponent();
  44565. if (comp != 0)
  44566. {
  44567. addAndMakeVisible (comp);
  44568. itemsToKeep.setBit (rowComponentItems.size());
  44569. rowComponentItems.add (item);
  44570. rowComponentIds.add (item->uid);
  44571. rowComponents.add (comp);
  44572. }
  44573. }
  44574. else
  44575. {
  44576. itemsToKeep.setBit (index);
  44577. }
  44578. }
  44579. item = item->getNextVisibleItem (true);
  44580. }
  44581. }
  44582. for (int i = rowComponentItems.size(); --i >= 0;)
  44583. {
  44584. Component* const comp = rowComponents.getUnchecked(i);
  44585. bool keep = false;
  44586. if (isParentOf (comp))
  44587. {
  44588. if (itemsToKeep[i])
  44589. {
  44590. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44591. Rectangle<int> pos (item->getItemPosition (false));
  44592. pos.setSize (pos.getWidth(), item->itemHeight);
  44593. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44594. {
  44595. keep = true;
  44596. comp->setBounds (pos);
  44597. }
  44598. }
  44599. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44600. {
  44601. keep = true;
  44602. comp->setSize (0, 0);
  44603. }
  44604. }
  44605. if (! keep)
  44606. {
  44607. delete comp;
  44608. rowComponents.remove (i);
  44609. rowComponentIds.remove (i);
  44610. rowComponentItems.remove (i);
  44611. }
  44612. }
  44613. }
  44614. void updateButtonUnderMouse (const MouseEvent& e)
  44615. {
  44616. TreeViewItem* newItem = 0;
  44617. if (owner.openCloseButtonsVisible)
  44618. {
  44619. Rectangle<int> pos;
  44620. TreeViewItem* item = findItemAt (e.y, pos);
  44621. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44622. {
  44623. newItem = item;
  44624. if (! newItem->mightContainSubItems())
  44625. newItem = 0;
  44626. }
  44627. }
  44628. if (buttonUnderMouse != newItem)
  44629. {
  44630. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44631. {
  44632. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44633. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44634. }
  44635. buttonUnderMouse = newItem;
  44636. if (buttonUnderMouse != 0)
  44637. {
  44638. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44639. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44640. }
  44641. }
  44642. }
  44643. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44644. {
  44645. return item == buttonUnderMouse;
  44646. }
  44647. void resized()
  44648. {
  44649. owner.itemsChanged();
  44650. }
  44651. const String getTooltip()
  44652. {
  44653. Rectangle<int> pos;
  44654. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44655. if (item != 0)
  44656. return item->getTooltip();
  44657. return owner.getTooltip();
  44658. }
  44659. juce_UseDebuggingNewOperator
  44660. private:
  44661. TreeView& owner;
  44662. Array <TreeViewItem*> rowComponentItems;
  44663. Array <int> rowComponentIds;
  44664. Array <Component*> rowComponents;
  44665. TreeViewItem* buttonUnderMouse;
  44666. bool isDragging, needSelectionOnMouseUp;
  44667. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44668. {
  44669. TreeViewItem* firstSelected = 0;
  44670. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44671. {
  44672. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44673. jassert (lastSelected != 0);
  44674. int rowStart = firstSelected->getRowNumberInTree();
  44675. int rowEnd = lastSelected->getRowNumberInTree();
  44676. if (rowStart > rowEnd)
  44677. swapVariables (rowStart, rowEnd);
  44678. int ourRow = item->getRowNumberInTree();
  44679. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44680. if (ourRow > otherEnd)
  44681. swapVariables (ourRow, otherEnd);
  44682. for (int i = ourRow; i <= otherEnd; ++i)
  44683. owner.getItemOnRow (i)->setSelected (true, false);
  44684. }
  44685. else
  44686. {
  44687. const bool cmd = modifiers.isCommandDown();
  44688. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44689. }
  44690. }
  44691. bool containsItem (TreeViewItem* const item) const
  44692. {
  44693. for (int i = rowComponentItems.size(); --i >= 0;)
  44694. if (rowComponentItems.getUnchecked(i) == item)
  44695. return true;
  44696. return false;
  44697. }
  44698. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44699. {
  44700. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44701. {
  44702. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44703. if (source->isDragging())
  44704. {
  44705. Component* const underMouse = source->getComponentUnderMouse();
  44706. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44707. return true;
  44708. }
  44709. }
  44710. return false;
  44711. }
  44712. TreeViewContentComponent (const TreeViewContentComponent&);
  44713. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44714. };
  44715. class TreeView::TreeViewport : public Viewport
  44716. {
  44717. public:
  44718. TreeViewport() throw() : lastX (-1) {}
  44719. ~TreeViewport() throw() {}
  44720. void updateComponents (const bool triggerResize = false)
  44721. {
  44722. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44723. if (tvc != 0)
  44724. {
  44725. if (triggerResize)
  44726. tvc->resized();
  44727. else
  44728. tvc->updateComponents();
  44729. }
  44730. repaint();
  44731. }
  44732. void visibleAreaChanged (int x, int, int, int)
  44733. {
  44734. const bool hasScrolledSideways = (x != lastX);
  44735. lastX = x;
  44736. updateComponents (hasScrolledSideways);
  44737. }
  44738. juce_UseDebuggingNewOperator
  44739. private:
  44740. int lastX;
  44741. TreeViewport (const TreeViewport&);
  44742. TreeViewport& operator= (const TreeViewport&);
  44743. };
  44744. TreeView::TreeView (const String& componentName)
  44745. : Component (componentName),
  44746. rootItem (0),
  44747. indentSize (24),
  44748. defaultOpenness (false),
  44749. needsRecalculating (true),
  44750. rootItemVisible (true),
  44751. multiSelectEnabled (false),
  44752. openCloseButtonsVisible (true)
  44753. {
  44754. addAndMakeVisible (viewport = new TreeViewport());
  44755. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44756. viewport->setWantsKeyboardFocus (false);
  44757. setWantsKeyboardFocus (true);
  44758. }
  44759. TreeView::~TreeView()
  44760. {
  44761. if (rootItem != 0)
  44762. rootItem->setOwnerView (0);
  44763. }
  44764. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44765. {
  44766. if (rootItem != newRootItem)
  44767. {
  44768. if (newRootItem != 0)
  44769. {
  44770. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44771. if (newRootItem->ownerView != 0)
  44772. newRootItem->ownerView->setRootItem (0);
  44773. }
  44774. if (rootItem != 0)
  44775. rootItem->setOwnerView (0);
  44776. rootItem = newRootItem;
  44777. if (newRootItem != 0)
  44778. newRootItem->setOwnerView (this);
  44779. needsRecalculating = true;
  44780. handleAsyncUpdate();
  44781. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44782. {
  44783. rootItem->setOpen (false); // force a re-open
  44784. rootItem->setOpen (true);
  44785. }
  44786. }
  44787. }
  44788. void TreeView::deleteRootItem()
  44789. {
  44790. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44791. setRootItem (0);
  44792. }
  44793. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44794. {
  44795. rootItemVisible = shouldBeVisible;
  44796. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44797. {
  44798. rootItem->setOpen (false); // force a re-open
  44799. rootItem->setOpen (true);
  44800. }
  44801. itemsChanged();
  44802. }
  44803. void TreeView::colourChanged()
  44804. {
  44805. setOpaque (findColour (backgroundColourId).isOpaque());
  44806. repaint();
  44807. }
  44808. void TreeView::setIndentSize (const int newIndentSize)
  44809. {
  44810. if (indentSize != newIndentSize)
  44811. {
  44812. indentSize = newIndentSize;
  44813. resized();
  44814. }
  44815. }
  44816. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44817. {
  44818. if (defaultOpenness != isOpenByDefault)
  44819. {
  44820. defaultOpenness = isOpenByDefault;
  44821. itemsChanged();
  44822. }
  44823. }
  44824. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44825. {
  44826. multiSelectEnabled = canMultiSelect;
  44827. }
  44828. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44829. {
  44830. if (openCloseButtonsVisible != shouldBeVisible)
  44831. {
  44832. openCloseButtonsVisible = shouldBeVisible;
  44833. itemsChanged();
  44834. }
  44835. }
  44836. Viewport* TreeView::getViewport() const throw()
  44837. {
  44838. return viewport;
  44839. }
  44840. void TreeView::clearSelectedItems()
  44841. {
  44842. if (rootItem != 0)
  44843. rootItem->deselectAllRecursively();
  44844. }
  44845. int TreeView::getNumSelectedItems() const throw()
  44846. {
  44847. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44848. }
  44849. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44850. {
  44851. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44852. }
  44853. int TreeView::getNumRowsInTree() const
  44854. {
  44855. if (rootItem != 0)
  44856. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44857. return 0;
  44858. }
  44859. TreeViewItem* TreeView::getItemOnRow (int index) const
  44860. {
  44861. if (! rootItemVisible)
  44862. ++index;
  44863. if (rootItem != 0 && index >= 0)
  44864. return rootItem->getItemOnRow (index);
  44865. return 0;
  44866. }
  44867. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44868. {
  44869. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44870. Rectangle<int> pos;
  44871. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44872. }
  44873. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44874. {
  44875. if (rootItem == 0)
  44876. return 0;
  44877. return rootItem->findItemFromIdentifierString (identifierString);
  44878. }
  44879. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44880. {
  44881. XmlElement* e = 0;
  44882. if (rootItem != 0)
  44883. {
  44884. e = rootItem->getOpennessState();
  44885. if (e != 0 && alsoIncludeScrollPosition)
  44886. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44887. }
  44888. return e;
  44889. }
  44890. void TreeView::restoreOpennessState (const XmlElement& newState)
  44891. {
  44892. if (rootItem != 0)
  44893. {
  44894. rootItem->restoreOpennessState (newState);
  44895. if (newState.hasAttribute ("scrollPos"))
  44896. viewport->setViewPosition (viewport->getViewPositionX(),
  44897. newState.getIntAttribute ("scrollPos"));
  44898. }
  44899. }
  44900. void TreeView::paint (Graphics& g)
  44901. {
  44902. g.fillAll (findColour (backgroundColourId));
  44903. }
  44904. void TreeView::resized()
  44905. {
  44906. viewport->setBounds (getLocalBounds());
  44907. itemsChanged();
  44908. handleAsyncUpdate();
  44909. }
  44910. void TreeView::enablementChanged()
  44911. {
  44912. repaint();
  44913. }
  44914. void TreeView::moveSelectedRow (int delta)
  44915. {
  44916. if (delta == 0)
  44917. return;
  44918. int rowSelected = 0;
  44919. TreeViewItem* const firstSelected = getSelectedItem (0);
  44920. if (firstSelected != 0)
  44921. rowSelected = firstSelected->getRowNumberInTree();
  44922. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44923. for (;;)
  44924. {
  44925. TreeViewItem* item = getItemOnRow (rowSelected);
  44926. if (item != 0)
  44927. {
  44928. if (! item->canBeSelected())
  44929. {
  44930. // if the row we want to highlight doesn't allow it, try skipping
  44931. // to the next item..
  44932. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44933. rowSelected + (delta < 0 ? -1 : 1));
  44934. if (rowSelected != nextRowToTry)
  44935. {
  44936. rowSelected = nextRowToTry;
  44937. continue;
  44938. }
  44939. else
  44940. {
  44941. break;
  44942. }
  44943. }
  44944. item->setSelected (true, true);
  44945. scrollToKeepItemVisible (item);
  44946. }
  44947. break;
  44948. }
  44949. }
  44950. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44951. {
  44952. if (item != 0 && item->ownerView == this)
  44953. {
  44954. handleAsyncUpdate();
  44955. item = item->getDeepestOpenParentItem();
  44956. int y = item->y;
  44957. int viewTop = viewport->getViewPositionY();
  44958. if (y < viewTop)
  44959. {
  44960. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44961. }
  44962. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44963. {
  44964. viewport->setViewPosition (viewport->getViewPositionX(),
  44965. (y + item->itemHeight) - viewport->getViewHeight());
  44966. }
  44967. }
  44968. }
  44969. bool TreeView::keyPressed (const KeyPress& key)
  44970. {
  44971. if (key.isKeyCode (KeyPress::upKey))
  44972. {
  44973. moveSelectedRow (-1);
  44974. }
  44975. else if (key.isKeyCode (KeyPress::downKey))
  44976. {
  44977. moveSelectedRow (1);
  44978. }
  44979. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44980. {
  44981. if (rootItem != 0)
  44982. {
  44983. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44984. if (key.isKeyCode (KeyPress::pageUpKey))
  44985. rowsOnScreen = -rowsOnScreen;
  44986. moveSelectedRow (rowsOnScreen);
  44987. }
  44988. }
  44989. else if (key.isKeyCode (KeyPress::homeKey))
  44990. {
  44991. moveSelectedRow (-0x3fffffff);
  44992. }
  44993. else if (key.isKeyCode (KeyPress::endKey))
  44994. {
  44995. moveSelectedRow (0x3fffffff);
  44996. }
  44997. else if (key.isKeyCode (KeyPress::returnKey))
  44998. {
  44999. TreeViewItem* const firstSelected = getSelectedItem (0);
  45000. if (firstSelected != 0)
  45001. firstSelected->setOpen (! firstSelected->isOpen());
  45002. }
  45003. else if (key.isKeyCode (KeyPress::leftKey))
  45004. {
  45005. TreeViewItem* const firstSelected = getSelectedItem (0);
  45006. if (firstSelected != 0)
  45007. {
  45008. if (firstSelected->isOpen())
  45009. {
  45010. firstSelected->setOpen (false);
  45011. }
  45012. else
  45013. {
  45014. TreeViewItem* parent = firstSelected->parentItem;
  45015. if ((! rootItemVisible) && parent == rootItem)
  45016. parent = 0;
  45017. if (parent != 0)
  45018. {
  45019. parent->setSelected (true, true);
  45020. scrollToKeepItemVisible (parent);
  45021. }
  45022. }
  45023. }
  45024. }
  45025. else if (key.isKeyCode (KeyPress::rightKey))
  45026. {
  45027. TreeViewItem* const firstSelected = getSelectedItem (0);
  45028. if (firstSelected != 0)
  45029. {
  45030. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45031. moveSelectedRow (1);
  45032. else
  45033. firstSelected->setOpen (true);
  45034. }
  45035. }
  45036. else
  45037. {
  45038. return false;
  45039. }
  45040. return true;
  45041. }
  45042. void TreeView::itemsChanged() throw()
  45043. {
  45044. needsRecalculating = true;
  45045. repaint();
  45046. triggerAsyncUpdate();
  45047. }
  45048. void TreeView::handleAsyncUpdate()
  45049. {
  45050. if (needsRecalculating)
  45051. {
  45052. needsRecalculating = false;
  45053. const ScopedLock sl (nodeAlterationLock);
  45054. if (rootItem != 0)
  45055. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45056. viewport->updateComponents();
  45057. if (rootItem != 0)
  45058. {
  45059. viewport->getViewedComponent()
  45060. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45061. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45062. }
  45063. else
  45064. {
  45065. viewport->getViewedComponent()->setSize (0, 0);
  45066. }
  45067. }
  45068. }
  45069. class TreeView::InsertPointHighlight : public Component
  45070. {
  45071. public:
  45072. InsertPointHighlight()
  45073. : lastItem (0)
  45074. {
  45075. setSize (100, 12);
  45076. setAlwaysOnTop (true);
  45077. setInterceptsMouseClicks (false, false);
  45078. }
  45079. ~InsertPointHighlight() {}
  45080. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45081. {
  45082. lastItem = item;
  45083. lastIndex = insertIndex;
  45084. const int offset = getHeight() / 2;
  45085. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45086. }
  45087. void paint (Graphics& g)
  45088. {
  45089. Path p;
  45090. const float h = (float) getHeight();
  45091. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45092. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45093. p.lineTo ((float) getWidth(), h / 2.0f);
  45094. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45095. g.strokePath (p, PathStrokeType (2.0f));
  45096. }
  45097. TreeViewItem* lastItem;
  45098. int lastIndex;
  45099. private:
  45100. InsertPointHighlight (const InsertPointHighlight&);
  45101. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45102. };
  45103. class TreeView::TargetGroupHighlight : public Component
  45104. {
  45105. public:
  45106. TargetGroupHighlight()
  45107. {
  45108. setAlwaysOnTop (true);
  45109. setInterceptsMouseClicks (false, false);
  45110. }
  45111. ~TargetGroupHighlight() {}
  45112. void setTargetPosition (TreeViewItem* const item) throw()
  45113. {
  45114. Rectangle<int> r (item->getItemPosition (true));
  45115. r.setHeight (item->getItemHeight());
  45116. setBounds (r);
  45117. }
  45118. void paint (Graphics& g)
  45119. {
  45120. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45121. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45122. }
  45123. private:
  45124. TargetGroupHighlight (const TargetGroupHighlight&);
  45125. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45126. };
  45127. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45128. {
  45129. beginDragAutoRepeat (1000 / 30);
  45130. if (dragInsertPointHighlight == 0)
  45131. {
  45132. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45133. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45134. }
  45135. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45136. dragTargetGroupHighlight->setTargetPosition (item);
  45137. }
  45138. void TreeView::hideDragHighlight() throw()
  45139. {
  45140. dragInsertPointHighlight = 0;
  45141. dragTargetGroupHighlight = 0;
  45142. }
  45143. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45144. const StringArray& files, const String& sourceDescription,
  45145. Component* sourceComponent) const throw()
  45146. {
  45147. insertIndex = 0;
  45148. TreeViewItem* item = getItemAt (y);
  45149. if (item == 0)
  45150. return 0;
  45151. Rectangle<int> itemPos (item->getItemPosition (true));
  45152. insertIndex = item->getIndexInParent();
  45153. const int oldY = y;
  45154. y = itemPos.getY();
  45155. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45156. {
  45157. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45158. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45159. {
  45160. // Check if we're trying to drag into an empty group item..
  45161. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45162. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45163. {
  45164. insertIndex = 0;
  45165. x = itemPos.getX() + getIndentSize();
  45166. y = itemPos.getBottom();
  45167. return item;
  45168. }
  45169. }
  45170. }
  45171. if (oldY > itemPos.getCentreY())
  45172. {
  45173. y += item->getItemHeight();
  45174. while (item->isLastOfSiblings() && item->parentItem != 0
  45175. && item->parentItem->parentItem != 0)
  45176. {
  45177. if (x > itemPos.getX())
  45178. break;
  45179. item = item->parentItem;
  45180. itemPos = item->getItemPosition (true);
  45181. insertIndex = item->getIndexInParent();
  45182. }
  45183. ++insertIndex;
  45184. }
  45185. x = itemPos.getX();
  45186. return item->parentItem;
  45187. }
  45188. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45189. {
  45190. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45191. int insertIndex;
  45192. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45193. if (item != 0)
  45194. {
  45195. if (scrolled || dragInsertPointHighlight == 0
  45196. || dragInsertPointHighlight->lastItem != item
  45197. || dragInsertPointHighlight->lastIndex != insertIndex)
  45198. {
  45199. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45200. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45201. showDragHighlight (item, insertIndex, x, y);
  45202. else
  45203. hideDragHighlight();
  45204. }
  45205. }
  45206. else
  45207. {
  45208. hideDragHighlight();
  45209. }
  45210. }
  45211. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45212. {
  45213. hideDragHighlight();
  45214. int insertIndex;
  45215. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45216. if (item != 0)
  45217. {
  45218. if (files.size() > 0)
  45219. {
  45220. if (item->isInterestedInFileDrag (files))
  45221. item->filesDropped (files, insertIndex);
  45222. }
  45223. else
  45224. {
  45225. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45226. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45227. }
  45228. }
  45229. }
  45230. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45231. {
  45232. return true;
  45233. }
  45234. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45235. {
  45236. fileDragMove (files, x, y);
  45237. }
  45238. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45239. {
  45240. handleDrag (files, String::empty, 0, x, y);
  45241. }
  45242. void TreeView::fileDragExit (const StringArray&)
  45243. {
  45244. hideDragHighlight();
  45245. }
  45246. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45247. {
  45248. handleDrop (files, String::empty, 0, x, y);
  45249. }
  45250. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45251. {
  45252. return true;
  45253. }
  45254. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45255. {
  45256. itemDragMove (sourceDescription, sourceComponent, x, y);
  45257. }
  45258. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45259. {
  45260. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45261. }
  45262. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45263. {
  45264. hideDragHighlight();
  45265. }
  45266. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45267. {
  45268. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45269. }
  45270. enum TreeViewOpenness
  45271. {
  45272. opennessDefault = 0,
  45273. opennessClosed = 1,
  45274. opennessOpen = 2
  45275. };
  45276. TreeViewItem::TreeViewItem()
  45277. : ownerView (0),
  45278. parentItem (0),
  45279. y (0),
  45280. itemHeight (0),
  45281. totalHeight (0),
  45282. selected (false),
  45283. redrawNeeded (true),
  45284. drawLinesInside (true),
  45285. drawsInLeftMargin (false),
  45286. openness (opennessDefault)
  45287. {
  45288. static int nextUID = 0;
  45289. uid = nextUID++;
  45290. }
  45291. TreeViewItem::~TreeViewItem()
  45292. {
  45293. }
  45294. const String TreeViewItem::getUniqueName() const
  45295. {
  45296. return String::empty;
  45297. }
  45298. void TreeViewItem::itemOpennessChanged (bool)
  45299. {
  45300. }
  45301. int TreeViewItem::getNumSubItems() const throw()
  45302. {
  45303. return subItems.size();
  45304. }
  45305. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45306. {
  45307. return subItems [index];
  45308. }
  45309. void TreeViewItem::clearSubItems()
  45310. {
  45311. if (subItems.size() > 0)
  45312. {
  45313. if (ownerView != 0)
  45314. {
  45315. const ScopedLock sl (ownerView->nodeAlterationLock);
  45316. subItems.clear();
  45317. treeHasChanged();
  45318. }
  45319. else
  45320. {
  45321. subItems.clear();
  45322. }
  45323. }
  45324. }
  45325. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45326. {
  45327. if (newItem != 0)
  45328. {
  45329. newItem->parentItem = this;
  45330. newItem->setOwnerView (ownerView);
  45331. newItem->y = 0;
  45332. newItem->itemHeight = newItem->getItemHeight();
  45333. newItem->totalHeight = 0;
  45334. newItem->itemWidth = newItem->getItemWidth();
  45335. newItem->totalWidth = 0;
  45336. if (ownerView != 0)
  45337. {
  45338. const ScopedLock sl (ownerView->nodeAlterationLock);
  45339. subItems.insert (insertPosition, newItem);
  45340. treeHasChanged();
  45341. if (newItem->isOpen())
  45342. newItem->itemOpennessChanged (true);
  45343. }
  45344. else
  45345. {
  45346. subItems.insert (insertPosition, newItem);
  45347. if (newItem->isOpen())
  45348. newItem->itemOpennessChanged (true);
  45349. }
  45350. }
  45351. }
  45352. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45353. {
  45354. if (ownerView != 0)
  45355. {
  45356. const ScopedLock sl (ownerView->nodeAlterationLock);
  45357. if (((unsigned int) index) < (unsigned int) subItems.size())
  45358. {
  45359. subItems.remove (index, deleteItem);
  45360. treeHasChanged();
  45361. }
  45362. }
  45363. else
  45364. {
  45365. subItems.remove (index, deleteItem);
  45366. }
  45367. }
  45368. bool TreeViewItem::isOpen() const throw()
  45369. {
  45370. if (openness == opennessDefault)
  45371. return ownerView != 0 && ownerView->defaultOpenness;
  45372. else
  45373. return openness == opennessOpen;
  45374. }
  45375. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45376. {
  45377. if (isOpen() != shouldBeOpen)
  45378. {
  45379. openness = shouldBeOpen ? opennessOpen
  45380. : opennessClosed;
  45381. treeHasChanged();
  45382. itemOpennessChanged (isOpen());
  45383. }
  45384. }
  45385. bool TreeViewItem::isSelected() const throw()
  45386. {
  45387. return selected;
  45388. }
  45389. void TreeViewItem::deselectAllRecursively()
  45390. {
  45391. setSelected (false, false);
  45392. for (int i = 0; i < subItems.size(); ++i)
  45393. subItems.getUnchecked(i)->deselectAllRecursively();
  45394. }
  45395. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45396. const bool deselectOtherItemsFirst)
  45397. {
  45398. if (shouldBeSelected && ! canBeSelected())
  45399. return;
  45400. if (deselectOtherItemsFirst)
  45401. getTopLevelItem()->deselectAllRecursively();
  45402. if (shouldBeSelected != selected)
  45403. {
  45404. selected = shouldBeSelected;
  45405. if (ownerView != 0)
  45406. ownerView->repaint();
  45407. itemSelectionChanged (shouldBeSelected);
  45408. }
  45409. }
  45410. void TreeViewItem::paintItem (Graphics&, int, int)
  45411. {
  45412. }
  45413. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45414. {
  45415. ownerView->getLookAndFeel()
  45416. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45417. }
  45418. void TreeViewItem::itemClicked (const MouseEvent&)
  45419. {
  45420. }
  45421. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45422. {
  45423. if (mightContainSubItems())
  45424. setOpen (! isOpen());
  45425. }
  45426. void TreeViewItem::itemSelectionChanged (bool)
  45427. {
  45428. }
  45429. const String TreeViewItem::getTooltip()
  45430. {
  45431. return String::empty;
  45432. }
  45433. const String TreeViewItem::getDragSourceDescription()
  45434. {
  45435. return String::empty;
  45436. }
  45437. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45438. {
  45439. return false;
  45440. }
  45441. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45442. {
  45443. }
  45444. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45445. {
  45446. return false;
  45447. }
  45448. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45449. {
  45450. }
  45451. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45452. {
  45453. const int indentX = getIndentX();
  45454. int width = itemWidth;
  45455. if (ownerView != 0 && width < 0)
  45456. width = ownerView->viewport->getViewWidth() - indentX;
  45457. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45458. if (relativeToTreeViewTopLeft)
  45459. r -= ownerView->viewport->getViewPosition();
  45460. return r;
  45461. }
  45462. void TreeViewItem::treeHasChanged() const throw()
  45463. {
  45464. if (ownerView != 0)
  45465. ownerView->itemsChanged();
  45466. }
  45467. void TreeViewItem::repaintItem() const
  45468. {
  45469. if (ownerView != 0 && areAllParentsOpen())
  45470. {
  45471. Rectangle<int> r (getItemPosition (true));
  45472. r.setLeft (0);
  45473. ownerView->viewport->repaint (r);
  45474. }
  45475. }
  45476. bool TreeViewItem::areAllParentsOpen() const throw()
  45477. {
  45478. return parentItem == 0
  45479. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45480. }
  45481. void TreeViewItem::updatePositions (int newY)
  45482. {
  45483. y = newY;
  45484. itemHeight = getItemHeight();
  45485. totalHeight = itemHeight;
  45486. itemWidth = getItemWidth();
  45487. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45488. if (isOpen())
  45489. {
  45490. newY += totalHeight;
  45491. for (int i = 0; i < subItems.size(); ++i)
  45492. {
  45493. TreeViewItem* const ti = subItems.getUnchecked(i);
  45494. ti->updatePositions (newY);
  45495. newY += ti->totalHeight;
  45496. totalHeight += ti->totalHeight;
  45497. totalWidth = jmax (totalWidth, ti->totalWidth);
  45498. }
  45499. }
  45500. }
  45501. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45502. {
  45503. TreeViewItem* result = this;
  45504. TreeViewItem* item = this;
  45505. while (item->parentItem != 0)
  45506. {
  45507. item = item->parentItem;
  45508. if (! item->isOpen())
  45509. result = item;
  45510. }
  45511. return result;
  45512. }
  45513. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45514. {
  45515. ownerView = newOwner;
  45516. for (int i = subItems.size(); --i >= 0;)
  45517. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45518. }
  45519. int TreeViewItem::getIndentX() const throw()
  45520. {
  45521. const int indentWidth = ownerView->getIndentSize();
  45522. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45523. if (! ownerView->openCloseButtonsVisible)
  45524. x -= indentWidth;
  45525. TreeViewItem* p = parentItem;
  45526. while (p != 0)
  45527. {
  45528. x += indentWidth;
  45529. p = p->parentItem;
  45530. }
  45531. return x;
  45532. }
  45533. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45534. {
  45535. drawsInLeftMargin = canDrawInLeftMargin;
  45536. }
  45537. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45538. {
  45539. jassert (ownerView != 0);
  45540. if (ownerView == 0)
  45541. return;
  45542. const int indent = getIndentX();
  45543. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45544. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45545. const float halfH = itemHeight * 0.5f;
  45546. int depth = 0;
  45547. TreeViewItem* p = parentItem;
  45548. while (p != 0)
  45549. {
  45550. ++depth;
  45551. p = p->parentItem;
  45552. }
  45553. if (! ownerView->rootItemVisible)
  45554. --depth;
  45555. const int indentWidth = ownerView->getIndentSize();
  45556. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45557. {
  45558. float x = (depth + 0.5f) * indentWidth;
  45559. if (depth >= 0)
  45560. {
  45561. if (parentItem != 0 && parentItem->drawLinesInside)
  45562. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45563. if ((parentItem != 0 && parentItem->drawLinesInside)
  45564. || (parentItem == 0 && drawLinesInside))
  45565. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45566. }
  45567. p = parentItem;
  45568. int d = depth;
  45569. while (p != 0 && --d >= 0)
  45570. {
  45571. x -= (float) indentWidth;
  45572. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45573. && ! p->isLastOfSiblings())
  45574. {
  45575. g.drawLine (x, 0, x, (float) itemHeight);
  45576. }
  45577. p = p->parentItem;
  45578. }
  45579. if (mightContainSubItems())
  45580. {
  45581. g.saveState();
  45582. g.setOrigin (depth * indentWidth, 0);
  45583. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45584. paintOpenCloseButton (g, indentWidth, itemHeight,
  45585. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45586. ->isMouseOverButton (this));
  45587. g.restoreState();
  45588. }
  45589. }
  45590. {
  45591. g.saveState();
  45592. g.setOrigin (indent, 0);
  45593. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45594. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45595. paintItem (g, itemW, itemHeight);
  45596. g.restoreState();
  45597. }
  45598. if (isOpen())
  45599. {
  45600. const Rectangle<int> clip (g.getClipBounds());
  45601. for (int i = 0; i < subItems.size(); ++i)
  45602. {
  45603. TreeViewItem* const ti = subItems.getUnchecked(i);
  45604. const int relY = ti->y - y;
  45605. if (relY >= clip.getBottom())
  45606. break;
  45607. if (relY + ti->totalHeight >= clip.getY())
  45608. {
  45609. g.saveState();
  45610. g.setOrigin (0, relY);
  45611. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45612. ti->paintRecursively (g, width);
  45613. g.restoreState();
  45614. }
  45615. }
  45616. }
  45617. }
  45618. bool TreeViewItem::isLastOfSiblings() const throw()
  45619. {
  45620. return parentItem == 0
  45621. || parentItem->subItems.getLast() == this;
  45622. }
  45623. int TreeViewItem::getIndexInParent() const throw()
  45624. {
  45625. if (parentItem == 0)
  45626. return 0;
  45627. return parentItem->subItems.indexOf (this);
  45628. }
  45629. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45630. {
  45631. return (parentItem == 0) ? this
  45632. : parentItem->getTopLevelItem();
  45633. }
  45634. int TreeViewItem::getNumRows() const throw()
  45635. {
  45636. int num = 1;
  45637. if (isOpen())
  45638. {
  45639. for (int i = subItems.size(); --i >= 0;)
  45640. num += subItems.getUnchecked(i)->getNumRows();
  45641. }
  45642. return num;
  45643. }
  45644. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45645. {
  45646. if (index == 0)
  45647. return this;
  45648. if (index > 0 && isOpen())
  45649. {
  45650. --index;
  45651. for (int i = 0; i < subItems.size(); ++i)
  45652. {
  45653. TreeViewItem* const item = subItems.getUnchecked(i);
  45654. if (index == 0)
  45655. return item;
  45656. const int numRows = item->getNumRows();
  45657. if (numRows > index)
  45658. return item->getItemOnRow (index);
  45659. index -= numRows;
  45660. }
  45661. }
  45662. return 0;
  45663. }
  45664. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45665. {
  45666. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45667. {
  45668. const int h = itemHeight;
  45669. if (targetY < h)
  45670. return this;
  45671. if (isOpen())
  45672. {
  45673. targetY -= h;
  45674. for (int i = 0; i < subItems.size(); ++i)
  45675. {
  45676. TreeViewItem* const ti = subItems.getUnchecked(i);
  45677. if (targetY < ti->totalHeight)
  45678. return ti->findItemRecursively (targetY);
  45679. targetY -= ti->totalHeight;
  45680. }
  45681. }
  45682. }
  45683. return 0;
  45684. }
  45685. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45686. {
  45687. int total = 0;
  45688. if (isSelected())
  45689. ++total;
  45690. for (int i = subItems.size(); --i >= 0;)
  45691. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45692. return total;
  45693. }
  45694. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45695. {
  45696. if (isSelected())
  45697. {
  45698. if (index == 0)
  45699. return this;
  45700. --index;
  45701. }
  45702. if (index >= 0)
  45703. {
  45704. for (int i = 0; i < subItems.size(); ++i)
  45705. {
  45706. TreeViewItem* const item = subItems.getUnchecked(i);
  45707. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45708. if (found != 0)
  45709. return found;
  45710. index -= item->countSelectedItemsRecursively();
  45711. }
  45712. }
  45713. return 0;
  45714. }
  45715. int TreeViewItem::getRowNumberInTree() const throw()
  45716. {
  45717. if (parentItem != 0 && ownerView != 0)
  45718. {
  45719. int n = 1 + parentItem->getRowNumberInTree();
  45720. int ourIndex = parentItem->subItems.indexOf (this);
  45721. jassert (ourIndex >= 0);
  45722. while (--ourIndex >= 0)
  45723. n += parentItem->subItems [ourIndex]->getNumRows();
  45724. if (parentItem->parentItem == 0
  45725. && ! ownerView->rootItemVisible)
  45726. --n;
  45727. return n;
  45728. }
  45729. else
  45730. {
  45731. return 0;
  45732. }
  45733. }
  45734. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45735. {
  45736. drawLinesInside = drawLines;
  45737. }
  45738. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45739. {
  45740. if (recurse && isOpen() && subItems.size() > 0)
  45741. return subItems [0];
  45742. if (parentItem != 0)
  45743. {
  45744. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45745. if (nextIndex >= parentItem->subItems.size())
  45746. return parentItem->getNextVisibleItem (false);
  45747. return parentItem->subItems [nextIndex];
  45748. }
  45749. return 0;
  45750. }
  45751. const String TreeViewItem::getItemIdentifierString() const
  45752. {
  45753. String s;
  45754. if (parentItem != 0)
  45755. s = parentItem->getItemIdentifierString();
  45756. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45757. }
  45758. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45759. {
  45760. const String thisId (getUniqueName());
  45761. if (thisId == identifierString)
  45762. return this;
  45763. if (identifierString.startsWith (thisId + "/"))
  45764. {
  45765. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45766. bool wasOpen = isOpen();
  45767. setOpen (true);
  45768. for (int i = subItems.size(); --i >= 0;)
  45769. {
  45770. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45771. if (item != 0)
  45772. return item;
  45773. }
  45774. setOpen (wasOpen);
  45775. }
  45776. return 0;
  45777. }
  45778. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45779. {
  45780. if (e.hasTagName ("CLOSED"))
  45781. {
  45782. setOpen (false);
  45783. }
  45784. else if (e.hasTagName ("OPEN"))
  45785. {
  45786. setOpen (true);
  45787. forEachXmlChildElement (e, n)
  45788. {
  45789. const String id (n->getStringAttribute ("id"));
  45790. for (int i = 0; i < subItems.size(); ++i)
  45791. {
  45792. TreeViewItem* const ti = subItems.getUnchecked(i);
  45793. if (ti->getUniqueName() == id)
  45794. {
  45795. ti->restoreOpennessState (*n);
  45796. break;
  45797. }
  45798. }
  45799. }
  45800. }
  45801. }
  45802. XmlElement* TreeViewItem::getOpennessState() const throw()
  45803. {
  45804. const String name (getUniqueName());
  45805. if (name.isNotEmpty())
  45806. {
  45807. XmlElement* e;
  45808. if (isOpen())
  45809. {
  45810. e = new XmlElement ("OPEN");
  45811. for (int i = 0; i < subItems.size(); ++i)
  45812. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45813. }
  45814. else
  45815. {
  45816. e = new XmlElement ("CLOSED");
  45817. }
  45818. e->setAttribute ("id", name);
  45819. return e;
  45820. }
  45821. else
  45822. {
  45823. // trying to save the openness for an element that has no name - this won't
  45824. // work because it needs the names to identify what to open.
  45825. jassertfalse;
  45826. }
  45827. return 0;
  45828. }
  45829. END_JUCE_NAMESPACE
  45830. /*** End of inlined file: juce_TreeView.cpp ***/
  45831. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45832. BEGIN_JUCE_NAMESPACE
  45833. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45834. : fileList (listToShow)
  45835. {
  45836. }
  45837. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45838. {
  45839. }
  45840. FileBrowserListener::~FileBrowserListener()
  45841. {
  45842. }
  45843. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45844. {
  45845. listeners.add (listener);
  45846. }
  45847. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45848. {
  45849. listeners.remove (listener);
  45850. }
  45851. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45852. {
  45853. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45854. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45855. }
  45856. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45857. {
  45858. if (fileList.getDirectory().exists())
  45859. {
  45860. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45861. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45862. }
  45863. }
  45864. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45865. {
  45866. if (fileList.getDirectory().exists())
  45867. {
  45868. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45869. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45870. }
  45871. }
  45872. END_JUCE_NAMESPACE
  45873. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45874. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45875. BEGIN_JUCE_NAMESPACE
  45876. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45877. TimeSliceThread& thread_)
  45878. : fileFilter (fileFilter_),
  45879. thread (thread_),
  45880. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45881. fileFindHandle (0),
  45882. shouldStop (true)
  45883. {
  45884. }
  45885. DirectoryContentsList::~DirectoryContentsList()
  45886. {
  45887. clear();
  45888. }
  45889. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45890. {
  45891. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45892. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45893. }
  45894. bool DirectoryContentsList::ignoresHiddenFiles() const
  45895. {
  45896. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45897. }
  45898. const File& DirectoryContentsList::getDirectory() const
  45899. {
  45900. return root;
  45901. }
  45902. void DirectoryContentsList::setDirectory (const File& directory,
  45903. const bool includeDirectories,
  45904. const bool includeFiles)
  45905. {
  45906. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45907. if (directory != root)
  45908. {
  45909. clear();
  45910. root = directory;
  45911. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45912. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45913. }
  45914. int newFlags = fileTypeFlags;
  45915. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45916. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45917. setTypeFlags (newFlags);
  45918. }
  45919. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45920. {
  45921. if (fileTypeFlags != newFlags)
  45922. {
  45923. fileTypeFlags = newFlags;
  45924. refresh();
  45925. }
  45926. }
  45927. void DirectoryContentsList::clear()
  45928. {
  45929. shouldStop = true;
  45930. thread.removeTimeSliceClient (this);
  45931. fileFindHandle = 0;
  45932. if (files.size() > 0)
  45933. {
  45934. files.clear();
  45935. changed();
  45936. }
  45937. }
  45938. void DirectoryContentsList::refresh()
  45939. {
  45940. clear();
  45941. if (root.isDirectory())
  45942. {
  45943. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45944. shouldStop = false;
  45945. thread.addTimeSliceClient (this);
  45946. }
  45947. }
  45948. int DirectoryContentsList::getNumFiles() const
  45949. {
  45950. return files.size();
  45951. }
  45952. bool DirectoryContentsList::getFileInfo (const int index,
  45953. FileInfo& result) const
  45954. {
  45955. const ScopedLock sl (fileListLock);
  45956. const FileInfo* const info = files [index];
  45957. if (info != 0)
  45958. {
  45959. result = *info;
  45960. return true;
  45961. }
  45962. return false;
  45963. }
  45964. const File DirectoryContentsList::getFile (const int index) const
  45965. {
  45966. const ScopedLock sl (fileListLock);
  45967. const FileInfo* const info = files [index];
  45968. if (info != 0)
  45969. return root.getChildFile (info->filename);
  45970. return File::nonexistent;
  45971. }
  45972. bool DirectoryContentsList::isStillLoading() const
  45973. {
  45974. return fileFindHandle != 0;
  45975. }
  45976. void DirectoryContentsList::changed()
  45977. {
  45978. sendChangeMessage (this);
  45979. }
  45980. bool DirectoryContentsList::useTimeSlice()
  45981. {
  45982. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45983. bool hasChanged = false;
  45984. for (int i = 100; --i >= 0;)
  45985. {
  45986. if (! checkNextFile (hasChanged))
  45987. {
  45988. if (hasChanged)
  45989. changed();
  45990. return false;
  45991. }
  45992. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45993. break;
  45994. }
  45995. if (hasChanged)
  45996. changed();
  45997. return true;
  45998. }
  45999. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46000. {
  46001. if (fileFindHandle != 0)
  46002. {
  46003. bool fileFoundIsDir, isHidden, isReadOnly;
  46004. int64 fileSize;
  46005. Time modTime, creationTime;
  46006. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46007. &modTime, &creationTime, &isReadOnly))
  46008. {
  46009. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46010. fileSize, modTime, creationTime, isReadOnly))
  46011. {
  46012. hasChanged = true;
  46013. }
  46014. return true;
  46015. }
  46016. else
  46017. {
  46018. fileFindHandle = 0;
  46019. }
  46020. }
  46021. return false;
  46022. }
  46023. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46024. const DirectoryContentsList::FileInfo* const second)
  46025. {
  46026. #if JUCE_WINDOWS
  46027. if (first->isDirectory != second->isDirectory)
  46028. return first->isDirectory ? -1 : 1;
  46029. #endif
  46030. return first->filename.compareIgnoreCase (second->filename);
  46031. }
  46032. bool DirectoryContentsList::addFile (const File& file,
  46033. const bool isDir,
  46034. const int64 fileSize,
  46035. const Time& modTime,
  46036. const Time& creationTime,
  46037. const bool isReadOnly)
  46038. {
  46039. if (fileFilter == 0
  46040. || ((! isDir) && fileFilter->isFileSuitable (file))
  46041. || (isDir && fileFilter->isDirectorySuitable (file)))
  46042. {
  46043. ScopedPointer <FileInfo> info (new FileInfo());
  46044. info->filename = file.getFileName();
  46045. info->fileSize = fileSize;
  46046. info->modificationTime = modTime;
  46047. info->creationTime = creationTime;
  46048. info->isDirectory = isDir;
  46049. info->isReadOnly = isReadOnly;
  46050. const ScopedLock sl (fileListLock);
  46051. for (int i = files.size(); --i >= 0;)
  46052. if (files.getUnchecked(i)->filename == info->filename)
  46053. return false;
  46054. files.addSorted (*this, info.release());
  46055. return true;
  46056. }
  46057. return false;
  46058. }
  46059. END_JUCE_NAMESPACE
  46060. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46061. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46062. BEGIN_JUCE_NAMESPACE
  46063. FileBrowserComponent::FileBrowserComponent (int flags_,
  46064. const File& initialFileOrDirectory,
  46065. const FileFilter* fileFilter_,
  46066. FilePreviewComponent* previewComp_)
  46067. : FileFilter (String::empty),
  46068. fileFilter (fileFilter_),
  46069. flags (flags_),
  46070. previewComp (previewComp_),
  46071. thread ("Juce FileBrowser")
  46072. {
  46073. // You need to specify one or other of the open/save flags..
  46074. jassert ((flags & (saveMode | openMode)) != 0);
  46075. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46076. // You need to specify at least one of these flags..
  46077. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46078. String filename;
  46079. if (initialFileOrDirectory == File::nonexistent)
  46080. {
  46081. currentRoot = File::getCurrentWorkingDirectory();
  46082. }
  46083. else if (initialFileOrDirectory.isDirectory())
  46084. {
  46085. currentRoot = initialFileOrDirectory;
  46086. }
  46087. else
  46088. {
  46089. chosenFiles.add (initialFileOrDirectory);
  46090. currentRoot = initialFileOrDirectory.getParentDirectory();
  46091. filename = initialFileOrDirectory.getFileName();
  46092. }
  46093. fileList = new DirectoryContentsList (this, thread);
  46094. if ((flags & useTreeView) != 0)
  46095. {
  46096. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46097. if ((flags & canSelectMultipleItems) != 0)
  46098. tree->setMultiSelectEnabled (true);
  46099. addAndMakeVisible (tree);
  46100. fileListComponent = tree;
  46101. }
  46102. else
  46103. {
  46104. FileListComponent* const list = new FileListComponent (*fileList);
  46105. list->setOutlineThickness (1);
  46106. if ((flags & canSelectMultipleItems) != 0)
  46107. list->setMultipleSelectionEnabled (true);
  46108. addAndMakeVisible (list);
  46109. fileListComponent = list;
  46110. }
  46111. fileListComponent->addListener (this);
  46112. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46113. currentPathBox->setEditableText (true);
  46114. StringArray rootNames, rootPaths;
  46115. const BigInteger separators (getRoots (rootNames, rootPaths));
  46116. for (int i = 0; i < rootNames.size(); ++i)
  46117. {
  46118. if (separators [i])
  46119. currentPathBox->addSeparator();
  46120. currentPathBox->addItem (rootNames[i], i + 1);
  46121. }
  46122. currentPathBox->addSeparator();
  46123. currentPathBox->addListener (this);
  46124. addAndMakeVisible (filenameBox = new TextEditor());
  46125. filenameBox->setMultiLine (false);
  46126. filenameBox->setSelectAllWhenFocused (true);
  46127. filenameBox->setText (filename, false);
  46128. filenameBox->addListener (this);
  46129. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46130. Label* label = new Label ("f", TRANS("file:"));
  46131. addAndMakeVisible (label);
  46132. label->attachToComponent (filenameBox, true);
  46133. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46134. goUpButton->addButtonListener (this);
  46135. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46136. if (previewComp != 0)
  46137. addAndMakeVisible (previewComp);
  46138. setRoot (currentRoot);
  46139. thread.startThread (4);
  46140. }
  46141. FileBrowserComponent::~FileBrowserComponent()
  46142. {
  46143. if (previewComp != 0)
  46144. removeChildComponent (previewComp);
  46145. deleteAllChildren();
  46146. fileList = 0;
  46147. thread.stopThread (10000);
  46148. }
  46149. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46150. {
  46151. listeners.add (newListener);
  46152. }
  46153. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46154. {
  46155. listeners.remove (listener);
  46156. }
  46157. bool FileBrowserComponent::isSaveMode() const throw()
  46158. {
  46159. return (flags & saveMode) != 0;
  46160. }
  46161. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46162. {
  46163. if (chosenFiles.size() == 0 && currentFileIsValid())
  46164. return 1;
  46165. return chosenFiles.size();
  46166. }
  46167. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46168. {
  46169. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46170. return currentRoot;
  46171. if (! filenameBox->isReadOnly())
  46172. return currentRoot.getChildFile (filenameBox->getText());
  46173. return chosenFiles[index];
  46174. }
  46175. bool FileBrowserComponent::currentFileIsValid() const
  46176. {
  46177. if (isSaveMode())
  46178. return ! getSelectedFile (0).isDirectory();
  46179. else
  46180. return getSelectedFile (0).exists();
  46181. }
  46182. const File FileBrowserComponent::getHighlightedFile() const throw()
  46183. {
  46184. return fileListComponent->getSelectedFile (0);
  46185. }
  46186. void FileBrowserComponent::deselectAllFiles()
  46187. {
  46188. fileListComponent->deselectAllFiles();
  46189. }
  46190. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46191. {
  46192. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46193. : false;
  46194. }
  46195. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46196. {
  46197. return true;
  46198. }
  46199. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46200. {
  46201. if (f.isDirectory())
  46202. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46203. return (flags & canSelectFiles) != 0 && f.exists()
  46204. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46205. }
  46206. const File FileBrowserComponent::getRoot() const
  46207. {
  46208. return currentRoot;
  46209. }
  46210. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46211. {
  46212. if (currentRoot != newRootDirectory)
  46213. {
  46214. fileListComponent->scrollToTop();
  46215. String path (newRootDirectory.getFullPathName());
  46216. if (path.isEmpty())
  46217. path = File::separatorString;
  46218. StringArray rootNames, rootPaths;
  46219. getRoots (rootNames, rootPaths);
  46220. if (! rootPaths.contains (path, true))
  46221. {
  46222. bool alreadyListed = false;
  46223. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46224. {
  46225. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46226. {
  46227. alreadyListed = true;
  46228. break;
  46229. }
  46230. }
  46231. if (! alreadyListed)
  46232. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46233. }
  46234. }
  46235. currentRoot = newRootDirectory;
  46236. fileList->setDirectory (currentRoot, true, true);
  46237. String currentRootName (currentRoot.getFullPathName());
  46238. if (currentRootName.isEmpty())
  46239. currentRootName = File::separatorString;
  46240. currentPathBox->setText (currentRootName, true);
  46241. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46242. && currentRoot.getParentDirectory() != currentRoot);
  46243. }
  46244. void FileBrowserComponent::goUp()
  46245. {
  46246. setRoot (getRoot().getParentDirectory());
  46247. }
  46248. void FileBrowserComponent::refresh()
  46249. {
  46250. fileList->refresh();
  46251. }
  46252. const String FileBrowserComponent::getActionVerb() const
  46253. {
  46254. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46255. }
  46256. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46257. {
  46258. return previewComp;
  46259. }
  46260. void FileBrowserComponent::resized()
  46261. {
  46262. getLookAndFeel()
  46263. .layoutFileBrowserComponent (*this, fileListComponent,
  46264. previewComp, currentPathBox,
  46265. filenameBox, goUpButton);
  46266. }
  46267. void FileBrowserComponent::sendListenerChangeMessage()
  46268. {
  46269. Component::BailOutChecker checker (this);
  46270. if (previewComp != 0)
  46271. previewComp->selectedFileChanged (getSelectedFile (0));
  46272. // You shouldn't delete the browser when the file gets changed!
  46273. jassert (! checker.shouldBailOut());
  46274. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46275. }
  46276. void FileBrowserComponent::selectionChanged()
  46277. {
  46278. StringArray newFilenames;
  46279. bool resetChosenFiles = true;
  46280. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46281. {
  46282. const File f (fileListComponent->getSelectedFile (i));
  46283. if (isFileOrDirSuitable (f))
  46284. {
  46285. if (resetChosenFiles)
  46286. {
  46287. chosenFiles.clear();
  46288. resetChosenFiles = false;
  46289. }
  46290. chosenFiles.add (f);
  46291. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46292. }
  46293. }
  46294. if (newFilenames.size() > 0)
  46295. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46296. sendListenerChangeMessage();
  46297. }
  46298. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46299. {
  46300. Component::BailOutChecker checker (this);
  46301. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46302. }
  46303. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46304. {
  46305. if (f.isDirectory())
  46306. {
  46307. setRoot (f);
  46308. if ((flags & canSelectDirectories) != 0)
  46309. filenameBox->setText (String::empty);
  46310. }
  46311. else
  46312. {
  46313. Component::BailOutChecker checker (this);
  46314. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46315. }
  46316. }
  46317. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46318. {
  46319. (void) key;
  46320. #if JUCE_LINUX || JUCE_WINDOWS
  46321. if (key.getModifiers().isCommandDown()
  46322. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46323. {
  46324. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46325. fileList->refresh();
  46326. return true;
  46327. }
  46328. #endif
  46329. return false;
  46330. }
  46331. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46332. {
  46333. sendListenerChangeMessage();
  46334. }
  46335. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46336. {
  46337. if (filenameBox->getText().containsChar (File::separator))
  46338. {
  46339. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46340. if (f.isDirectory())
  46341. {
  46342. setRoot (f);
  46343. chosenFiles.clear();
  46344. filenameBox->setText (String::empty);
  46345. }
  46346. else
  46347. {
  46348. setRoot (f.getParentDirectory());
  46349. chosenFiles.clear();
  46350. chosenFiles.add (f);
  46351. filenameBox->setText (f.getFileName());
  46352. }
  46353. }
  46354. else
  46355. {
  46356. fileDoubleClicked (getSelectedFile (0));
  46357. }
  46358. }
  46359. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46360. {
  46361. }
  46362. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46363. {
  46364. if (! isSaveMode())
  46365. selectionChanged();
  46366. }
  46367. void FileBrowserComponent::buttonClicked (Button*)
  46368. {
  46369. goUp();
  46370. }
  46371. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46372. {
  46373. const String newText (currentPathBox->getText().trim().unquoted());
  46374. if (newText.isNotEmpty())
  46375. {
  46376. const int index = currentPathBox->getSelectedId() - 1;
  46377. StringArray rootNames, rootPaths;
  46378. getRoots (rootNames, rootPaths);
  46379. if (rootPaths [index].isNotEmpty())
  46380. {
  46381. setRoot (File (rootPaths [index]));
  46382. }
  46383. else
  46384. {
  46385. File f (newText);
  46386. for (;;)
  46387. {
  46388. if (f.isDirectory())
  46389. {
  46390. setRoot (f);
  46391. break;
  46392. }
  46393. if (f.getParentDirectory() == f)
  46394. break;
  46395. f = f.getParentDirectory();
  46396. }
  46397. }
  46398. }
  46399. }
  46400. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46401. {
  46402. BigInteger separators;
  46403. #if JUCE_WINDOWS
  46404. Array<File> roots;
  46405. File::findFileSystemRoots (roots);
  46406. rootPaths.clear();
  46407. for (int i = 0; i < roots.size(); ++i)
  46408. {
  46409. const File& drive = roots.getReference(i);
  46410. String name (drive.getFullPathName());
  46411. rootPaths.add (name);
  46412. if (drive.isOnHardDisk())
  46413. {
  46414. String volume (drive.getVolumeLabel());
  46415. if (volume.isEmpty())
  46416. volume = TRANS("Hard Drive");
  46417. name << " [" << drive.getVolumeLabel() << ']';
  46418. }
  46419. else if (drive.isOnCDRomDrive())
  46420. {
  46421. name << TRANS(" [CD/DVD drive]");
  46422. }
  46423. rootNames.add (name);
  46424. }
  46425. separators.setBit (rootPaths.size());
  46426. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46427. rootNames.add ("Documents");
  46428. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46429. rootNames.add ("Desktop");
  46430. #endif
  46431. #if JUCE_MAC
  46432. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46433. rootNames.add ("Home folder");
  46434. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46435. rootNames.add ("Documents");
  46436. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46437. rootNames.add ("Desktop");
  46438. separators.setBit (rootPaths.size());
  46439. Array <File> volumes;
  46440. File vol ("/Volumes");
  46441. vol.findChildFiles (volumes, File::findDirectories, false);
  46442. for (int i = 0; i < volumes.size(); ++i)
  46443. {
  46444. const File& volume = volumes.getReference(i);
  46445. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46446. {
  46447. rootPaths.add (volume.getFullPathName());
  46448. rootNames.add (volume.getFileName());
  46449. }
  46450. }
  46451. #endif
  46452. #if JUCE_LINUX
  46453. rootPaths.add ("/");
  46454. rootNames.add ("/");
  46455. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46456. rootNames.add ("Home folder");
  46457. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46458. rootNames.add ("Desktop");
  46459. #endif
  46460. return separators;
  46461. }
  46462. END_JUCE_NAMESPACE
  46463. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46464. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46465. BEGIN_JUCE_NAMESPACE
  46466. FileChooser::FileChooser (const String& chooserBoxTitle,
  46467. const File& currentFileOrDirectory,
  46468. const String& fileFilters,
  46469. const bool useNativeDialogBox_)
  46470. : title (chooserBoxTitle),
  46471. filters (fileFilters),
  46472. startingFile (currentFileOrDirectory),
  46473. useNativeDialogBox (useNativeDialogBox_)
  46474. {
  46475. #if JUCE_LINUX
  46476. useNativeDialogBox = false;
  46477. #endif
  46478. if (! fileFilters.containsNonWhitespaceChars())
  46479. filters = "*";
  46480. }
  46481. FileChooser::~FileChooser()
  46482. {
  46483. }
  46484. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46485. {
  46486. return showDialog (false, true, false, false, false, previewComponent);
  46487. }
  46488. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46489. {
  46490. return showDialog (false, true, false, false, true, previewComponent);
  46491. }
  46492. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46493. {
  46494. return showDialog (true, true, false, false, true, previewComponent);
  46495. }
  46496. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46497. {
  46498. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46499. }
  46500. bool FileChooser::browseForDirectory()
  46501. {
  46502. return showDialog (true, false, false, false, false, 0);
  46503. }
  46504. const File FileChooser::getResult() const
  46505. {
  46506. // if you've used a multiple-file select, you should use the getResults() method
  46507. // to retrieve all the files that were chosen.
  46508. jassert (results.size() <= 1);
  46509. return results.getFirst();
  46510. }
  46511. const Array<File>& FileChooser::getResults() const
  46512. {
  46513. return results;
  46514. }
  46515. bool FileChooser::showDialog (const bool selectsDirectories,
  46516. const bool selectsFiles,
  46517. const bool isSave,
  46518. const bool warnAboutOverwritingExistingFiles,
  46519. const bool selectMultipleFiles,
  46520. FilePreviewComponent* const previewComponent)
  46521. {
  46522. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46523. results.clear();
  46524. // the preview component needs to be the right size before you pass it in here..
  46525. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46526. && previewComponent->getHeight() > 10));
  46527. #if JUCE_WINDOWS
  46528. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46529. #elif JUCE_MAC
  46530. if (useNativeDialogBox && (previewComponent == 0))
  46531. #else
  46532. if (false)
  46533. #endif
  46534. {
  46535. showPlatformDialog (results, title, startingFile, filters,
  46536. selectsDirectories, selectsFiles, isSave,
  46537. warnAboutOverwritingExistingFiles,
  46538. selectMultipleFiles,
  46539. previewComponent);
  46540. }
  46541. else
  46542. {
  46543. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46544. selectsDirectories ? "*" : String::empty,
  46545. String::empty);
  46546. int flags = isSave ? FileBrowserComponent::saveMode
  46547. : FileBrowserComponent::openMode;
  46548. if (selectsFiles)
  46549. flags |= FileBrowserComponent::canSelectFiles;
  46550. if (selectsDirectories)
  46551. {
  46552. flags |= FileBrowserComponent::canSelectDirectories;
  46553. if (! isSave)
  46554. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46555. }
  46556. if (selectMultipleFiles)
  46557. flags |= FileBrowserComponent::canSelectMultipleItems;
  46558. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46559. FileChooserDialogBox box (title, String::empty,
  46560. browserComponent,
  46561. warnAboutOverwritingExistingFiles,
  46562. browserComponent.findColour (AlertWindow::backgroundColourId));
  46563. if (box.show())
  46564. {
  46565. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46566. results.add (browserComponent.getSelectedFile (i));
  46567. }
  46568. }
  46569. if (previouslyFocused != 0)
  46570. previouslyFocused->grabKeyboardFocus();
  46571. return results.size() > 0;
  46572. }
  46573. FilePreviewComponent::FilePreviewComponent()
  46574. {
  46575. }
  46576. FilePreviewComponent::~FilePreviewComponent()
  46577. {
  46578. }
  46579. END_JUCE_NAMESPACE
  46580. /*** End of inlined file: juce_FileChooser.cpp ***/
  46581. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46582. BEGIN_JUCE_NAMESPACE
  46583. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46584. const String& instructions,
  46585. FileBrowserComponent& chooserComponent,
  46586. const bool warnAboutOverwritingExistingFiles_,
  46587. const Colour& backgroundColour)
  46588. : ResizableWindow (name, backgroundColour, true),
  46589. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46590. {
  46591. content = new ContentComponent();
  46592. content->setName (name);
  46593. content->instructions = instructions;
  46594. content->chooserComponent = &chooserComponent;
  46595. content->addAndMakeVisible (&chooserComponent);
  46596. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46597. content->addAndMakeVisible (content->okButton);
  46598. content->okButton->addButtonListener (this);
  46599. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46600. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46601. content->cancelButton = new TextButton (TRANS("Cancel"));
  46602. content->addAndMakeVisible (content->cancelButton);
  46603. content->cancelButton->addButtonListener (this);
  46604. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46605. setContentComponent (content);
  46606. setResizable (true, true);
  46607. setResizeLimits (300, 300, 1200, 1000);
  46608. content->chooserComponent->addListener (this);
  46609. }
  46610. FileChooserDialogBox::~FileChooserDialogBox()
  46611. {
  46612. content->chooserComponent->removeListener (this);
  46613. }
  46614. bool FileChooserDialogBox::show (int w, int h)
  46615. {
  46616. return showAt (-1, -1, w, h);
  46617. }
  46618. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46619. {
  46620. if (w <= 0)
  46621. {
  46622. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46623. if (previewComp != 0)
  46624. w = 400 + previewComp->getWidth();
  46625. else
  46626. w = 600;
  46627. }
  46628. if (h <= 0)
  46629. h = 500;
  46630. if (x < 0 || y < 0)
  46631. centreWithSize (w, h);
  46632. else
  46633. setBounds (x, y, w, h);
  46634. const bool ok = (runModalLoop() != 0);
  46635. setVisible (false);
  46636. return ok;
  46637. }
  46638. void FileChooserDialogBox::buttonClicked (Button* button)
  46639. {
  46640. if (button == content->okButton)
  46641. {
  46642. if (warnAboutOverwritingExistingFiles
  46643. && content->chooserComponent->isSaveMode()
  46644. && content->chooserComponent->getSelectedFile(0).exists())
  46645. {
  46646. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46647. TRANS("File already exists"),
  46648. TRANS("There's already a file called:")
  46649. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46650. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46651. TRANS("overwrite"),
  46652. TRANS("cancel")))
  46653. {
  46654. return;
  46655. }
  46656. }
  46657. exitModalState (1);
  46658. }
  46659. else if (button == content->cancelButton)
  46660. closeButtonPressed();
  46661. }
  46662. void FileChooserDialogBox::closeButtonPressed()
  46663. {
  46664. setVisible (false);
  46665. }
  46666. void FileChooserDialogBox::selectionChanged()
  46667. {
  46668. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46669. }
  46670. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46671. {
  46672. }
  46673. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46674. {
  46675. selectionChanged();
  46676. content->okButton->triggerClick();
  46677. }
  46678. FileChooserDialogBox::ContentComponent::ContentComponent()
  46679. {
  46680. setInterceptsMouseClicks (false, true);
  46681. }
  46682. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46683. {
  46684. delete okButton;
  46685. delete cancelButton;
  46686. }
  46687. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46688. {
  46689. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46690. text.draw (g);
  46691. }
  46692. void FileChooserDialogBox::ContentComponent::resized()
  46693. {
  46694. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46695. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46696. const int y = roundToInt (bb.getBottom()) + 10;
  46697. const int buttonHeight = 26;
  46698. const int buttonY = getHeight() - buttonHeight - 8;
  46699. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46700. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46701. proportionOfWidth (0.2f), buttonHeight);
  46702. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46703. proportionOfWidth (0.2f), buttonHeight);
  46704. }
  46705. END_JUCE_NAMESPACE
  46706. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46707. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46708. BEGIN_JUCE_NAMESPACE
  46709. FileFilter::FileFilter (const String& filterDescription)
  46710. : description (filterDescription)
  46711. {
  46712. }
  46713. FileFilter::~FileFilter()
  46714. {
  46715. }
  46716. const String& FileFilter::getDescription() const throw()
  46717. {
  46718. return description;
  46719. }
  46720. END_JUCE_NAMESPACE
  46721. /*** End of inlined file: juce_FileFilter.cpp ***/
  46722. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46723. BEGIN_JUCE_NAMESPACE
  46724. const Image juce_createIconForFile (const File& file);
  46725. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46726. : ListBox (String::empty, 0),
  46727. DirectoryContentsDisplayComponent (listToShow)
  46728. {
  46729. setModel (this);
  46730. fileList.addChangeListener (this);
  46731. }
  46732. FileListComponent::~FileListComponent()
  46733. {
  46734. fileList.removeChangeListener (this);
  46735. }
  46736. int FileListComponent::getNumSelectedFiles() const
  46737. {
  46738. return getNumSelectedRows();
  46739. }
  46740. const File FileListComponent::getSelectedFile (int index) const
  46741. {
  46742. return fileList.getFile (getSelectedRow (index));
  46743. }
  46744. void FileListComponent::deselectAllFiles()
  46745. {
  46746. deselectAllRows();
  46747. }
  46748. void FileListComponent::scrollToTop()
  46749. {
  46750. getVerticalScrollBar()->setCurrentRangeStart (0);
  46751. }
  46752. void FileListComponent::changeListenerCallback (void*)
  46753. {
  46754. updateContent();
  46755. if (lastDirectory != fileList.getDirectory())
  46756. {
  46757. lastDirectory = fileList.getDirectory();
  46758. deselectAllRows();
  46759. }
  46760. }
  46761. class FileListItemComponent : public Component,
  46762. public TimeSliceClient,
  46763. public AsyncUpdater
  46764. {
  46765. public:
  46766. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46767. : owner (owner_), thread (thread_),
  46768. highlighted (false), index (0), icon (0)
  46769. {
  46770. }
  46771. ~FileListItemComponent()
  46772. {
  46773. thread.removeTimeSliceClient (this);
  46774. clearIcon();
  46775. }
  46776. void paint (Graphics& g)
  46777. {
  46778. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46779. file.getFileName(),
  46780. &icon,
  46781. fileSize, modTime,
  46782. isDirectory, highlighted,
  46783. index);
  46784. }
  46785. void mouseDown (const MouseEvent& e)
  46786. {
  46787. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46788. owner.sendMouseClickMessage (file, e);
  46789. }
  46790. void mouseDoubleClick (const MouseEvent&)
  46791. {
  46792. owner.sendDoubleClickMessage (file);
  46793. }
  46794. void update (const File& root,
  46795. const DirectoryContentsList::FileInfo* const fileInfo,
  46796. const int index_,
  46797. const bool highlighted_)
  46798. {
  46799. thread.removeTimeSliceClient (this);
  46800. if (highlighted_ != highlighted
  46801. || index_ != index)
  46802. {
  46803. index = index_;
  46804. highlighted = highlighted_;
  46805. repaint();
  46806. }
  46807. File newFile;
  46808. String newFileSize;
  46809. String newModTime;
  46810. if (fileInfo != 0)
  46811. {
  46812. newFile = root.getChildFile (fileInfo->filename);
  46813. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46814. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46815. }
  46816. if (newFile != file
  46817. || fileSize != newFileSize
  46818. || modTime != newModTime)
  46819. {
  46820. file = newFile;
  46821. fileSize = newFileSize;
  46822. modTime = newModTime;
  46823. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46824. repaint();
  46825. clearIcon();
  46826. }
  46827. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46828. {
  46829. updateIcon (true);
  46830. if (! icon.isValid())
  46831. thread.addTimeSliceClient (this);
  46832. }
  46833. }
  46834. bool useTimeSlice()
  46835. {
  46836. updateIcon (false);
  46837. return false;
  46838. }
  46839. void handleAsyncUpdate()
  46840. {
  46841. repaint();
  46842. }
  46843. juce_UseDebuggingNewOperator
  46844. private:
  46845. FileListComponent& owner;
  46846. TimeSliceThread& thread;
  46847. bool highlighted;
  46848. int index;
  46849. File file;
  46850. String fileSize;
  46851. String modTime;
  46852. Image icon;
  46853. bool isDirectory;
  46854. void clearIcon()
  46855. {
  46856. icon = Image();
  46857. }
  46858. void updateIcon (const bool onlyUpdateIfCached)
  46859. {
  46860. if (icon.isNull())
  46861. {
  46862. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46863. Image im (ImageCache::getFromHashCode (hashCode));
  46864. if (im.isNull() && ! onlyUpdateIfCached)
  46865. {
  46866. im = juce_createIconForFile (file);
  46867. if (im.isValid())
  46868. ImageCache::addImageToCache (im, hashCode);
  46869. }
  46870. if (im.isValid())
  46871. {
  46872. icon = im;
  46873. triggerAsyncUpdate();
  46874. }
  46875. }
  46876. }
  46877. };
  46878. int FileListComponent::getNumRows()
  46879. {
  46880. return fileList.getNumFiles();
  46881. }
  46882. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46883. {
  46884. }
  46885. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46886. {
  46887. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46888. if (comp == 0)
  46889. {
  46890. delete existingComponentToUpdate;
  46891. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46892. }
  46893. DirectoryContentsList::FileInfo fileInfo;
  46894. if (fileList.getFileInfo (row, fileInfo))
  46895. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46896. else
  46897. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46898. return comp;
  46899. }
  46900. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46901. {
  46902. sendSelectionChangeMessage();
  46903. }
  46904. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46905. {
  46906. }
  46907. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46908. {
  46909. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46910. }
  46911. END_JUCE_NAMESPACE
  46912. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46913. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46914. BEGIN_JUCE_NAMESPACE
  46915. FilenameComponent::FilenameComponent (const String& name,
  46916. const File& currentFile,
  46917. const bool canEditFilename,
  46918. const bool isDirectory,
  46919. const bool isForSaving,
  46920. const String& fileBrowserWildcard,
  46921. const String& enforcedSuffix_,
  46922. const String& textWhenNothingSelected)
  46923. : Component (name),
  46924. maxRecentFiles (30),
  46925. isDir (isDirectory),
  46926. isSaving (isForSaving),
  46927. isFileDragOver (false),
  46928. wildcard (fileBrowserWildcard),
  46929. enforcedSuffix (enforcedSuffix_)
  46930. {
  46931. addAndMakeVisible (&filenameBox);
  46932. filenameBox.setEditableText (canEditFilename);
  46933. filenameBox.addListener (this);
  46934. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46935. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46936. setBrowseButtonText ("...");
  46937. setCurrentFile (currentFile, true);
  46938. }
  46939. FilenameComponent::~FilenameComponent()
  46940. {
  46941. }
  46942. void FilenameComponent::paintOverChildren (Graphics& g)
  46943. {
  46944. if (isFileDragOver)
  46945. {
  46946. g.setColour (Colours::red.withAlpha (0.2f));
  46947. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46948. }
  46949. }
  46950. void FilenameComponent::resized()
  46951. {
  46952. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46953. }
  46954. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46955. {
  46956. browseButtonText = newBrowseButtonText;
  46957. lookAndFeelChanged();
  46958. }
  46959. void FilenameComponent::lookAndFeelChanged()
  46960. {
  46961. browseButton = 0;
  46962. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46963. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46964. resized();
  46965. browseButton->addButtonListener (this);
  46966. }
  46967. void FilenameComponent::setTooltip (const String& newTooltip)
  46968. {
  46969. SettableTooltipClient::setTooltip (newTooltip);
  46970. filenameBox.setTooltip (newTooltip);
  46971. }
  46972. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46973. {
  46974. defaultBrowseFile = newDefaultDirectory;
  46975. }
  46976. void FilenameComponent::buttonClicked (Button*)
  46977. {
  46978. FileChooser fc (TRANS("Choose a new file"),
  46979. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46980. : getCurrentFile(),
  46981. wildcard);
  46982. if (isDir ? fc.browseForDirectory()
  46983. : (isSaving ? fc.browseForFileToSave (false)
  46984. : fc.browseForFileToOpen()))
  46985. {
  46986. setCurrentFile (fc.getResult(), true);
  46987. }
  46988. }
  46989. void FilenameComponent::comboBoxChanged (ComboBox*)
  46990. {
  46991. setCurrentFile (getCurrentFile(), true);
  46992. }
  46993. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46994. {
  46995. return true;
  46996. }
  46997. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46998. {
  46999. isFileDragOver = false;
  47000. repaint();
  47001. const File f (filenames[0]);
  47002. if (f.exists() && (f.isDirectory() == isDir))
  47003. setCurrentFile (f, true);
  47004. }
  47005. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47006. {
  47007. isFileDragOver = true;
  47008. repaint();
  47009. }
  47010. void FilenameComponent::fileDragExit (const StringArray&)
  47011. {
  47012. isFileDragOver = false;
  47013. repaint();
  47014. }
  47015. const File FilenameComponent::getCurrentFile() const
  47016. {
  47017. File f (filenameBox.getText());
  47018. if (enforcedSuffix.isNotEmpty())
  47019. f = f.withFileExtension (enforcedSuffix);
  47020. return f;
  47021. }
  47022. void FilenameComponent::setCurrentFile (File newFile,
  47023. const bool addToRecentlyUsedList,
  47024. const bool sendChangeNotification)
  47025. {
  47026. if (enforcedSuffix.isNotEmpty())
  47027. newFile = newFile.withFileExtension (enforcedSuffix);
  47028. if (newFile.getFullPathName() != lastFilename)
  47029. {
  47030. lastFilename = newFile.getFullPathName();
  47031. if (addToRecentlyUsedList)
  47032. addRecentlyUsedFile (newFile);
  47033. filenameBox.setText (lastFilename, true);
  47034. if (sendChangeNotification)
  47035. triggerAsyncUpdate();
  47036. }
  47037. }
  47038. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47039. {
  47040. filenameBox.setEditableText (shouldBeEditable);
  47041. }
  47042. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47043. {
  47044. StringArray names;
  47045. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47046. names.add (filenameBox.getItemText (i));
  47047. return names;
  47048. }
  47049. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47050. {
  47051. if (filenames != getRecentlyUsedFilenames())
  47052. {
  47053. filenameBox.clear();
  47054. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47055. filenameBox.addItem (filenames[i], i + 1);
  47056. }
  47057. }
  47058. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47059. {
  47060. maxRecentFiles = jmax (1, newMaximum);
  47061. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47062. }
  47063. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47064. {
  47065. StringArray files (getRecentlyUsedFilenames());
  47066. if (file.getFullPathName().isNotEmpty())
  47067. {
  47068. files.removeString (file.getFullPathName(), true);
  47069. files.insert (0, file.getFullPathName());
  47070. setRecentlyUsedFilenames (files);
  47071. }
  47072. }
  47073. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47074. {
  47075. listeners.add (listener);
  47076. }
  47077. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47078. {
  47079. listeners.remove (listener);
  47080. }
  47081. void FilenameComponent::handleAsyncUpdate()
  47082. {
  47083. Component::BailOutChecker checker (this);
  47084. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47085. }
  47086. END_JUCE_NAMESPACE
  47087. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47088. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47089. BEGIN_JUCE_NAMESPACE
  47090. FileSearchPathListComponent::FileSearchPathListComponent()
  47091. {
  47092. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47093. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47094. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47095. listBox->setOutlineThickness (1);
  47096. addAndMakeVisible (addButton = new TextButton ("+"));
  47097. addButton->addButtonListener (this);
  47098. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47099. addAndMakeVisible (removeButton = new TextButton ("-"));
  47100. removeButton->addButtonListener (this);
  47101. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47102. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47103. changeButton->addButtonListener (this);
  47104. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47105. upButton->addButtonListener (this);
  47106. {
  47107. Path arrowPath;
  47108. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47109. DrawablePath arrowImage;
  47110. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47111. arrowImage.setPath (arrowPath);
  47112. upButton->setImages (&arrowImage);
  47113. }
  47114. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47115. downButton->addButtonListener (this);
  47116. {
  47117. Path arrowPath;
  47118. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47119. DrawablePath arrowImage;
  47120. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47121. arrowImage.setPath (arrowPath);
  47122. downButton->setImages (&arrowImage);
  47123. }
  47124. updateButtons();
  47125. }
  47126. FileSearchPathListComponent::~FileSearchPathListComponent()
  47127. {
  47128. deleteAllChildren();
  47129. }
  47130. void FileSearchPathListComponent::updateButtons()
  47131. {
  47132. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47133. removeButton->setEnabled (anythingSelected);
  47134. changeButton->setEnabled (anythingSelected);
  47135. upButton->setEnabled (anythingSelected);
  47136. downButton->setEnabled (anythingSelected);
  47137. }
  47138. void FileSearchPathListComponent::changed()
  47139. {
  47140. listBox->updateContent();
  47141. listBox->repaint();
  47142. updateButtons();
  47143. }
  47144. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47145. {
  47146. if (newPath.toString() != path.toString())
  47147. {
  47148. path = newPath;
  47149. changed();
  47150. }
  47151. }
  47152. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47153. {
  47154. defaultBrowseTarget = newDefaultDirectory;
  47155. }
  47156. int FileSearchPathListComponent::getNumRows()
  47157. {
  47158. return path.getNumPaths();
  47159. }
  47160. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47161. {
  47162. if (rowIsSelected)
  47163. g.fillAll (findColour (TextEditor::highlightColourId));
  47164. g.setColour (findColour (ListBox::textColourId));
  47165. Font f (height * 0.7f);
  47166. f.setHorizontalScale (0.9f);
  47167. g.setFont (f);
  47168. g.drawText (path [rowNumber].getFullPathName(),
  47169. 4, 0, width - 6, height,
  47170. Justification::centredLeft, true);
  47171. }
  47172. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47173. {
  47174. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47175. {
  47176. path.remove (row);
  47177. changed();
  47178. }
  47179. }
  47180. void FileSearchPathListComponent::returnKeyPressed (int row)
  47181. {
  47182. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47183. if (chooser.browseForDirectory())
  47184. {
  47185. path.remove (row);
  47186. path.add (chooser.getResult(), row);
  47187. changed();
  47188. }
  47189. }
  47190. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47191. {
  47192. returnKeyPressed (row);
  47193. }
  47194. void FileSearchPathListComponent::selectedRowsChanged (int)
  47195. {
  47196. updateButtons();
  47197. }
  47198. void FileSearchPathListComponent::paint (Graphics& g)
  47199. {
  47200. g.fillAll (findColour (backgroundColourId));
  47201. }
  47202. void FileSearchPathListComponent::resized()
  47203. {
  47204. const int buttonH = 22;
  47205. const int buttonY = getHeight() - buttonH - 4;
  47206. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47207. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47208. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47209. changeButton->changeWidthToFitText (buttonH);
  47210. downButton->setSize (buttonH * 2, buttonH);
  47211. upButton->setSize (buttonH * 2, buttonH);
  47212. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47213. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47214. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47215. }
  47216. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47217. {
  47218. return true;
  47219. }
  47220. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47221. {
  47222. for (int i = filenames.size(); --i >= 0;)
  47223. {
  47224. const File f (filenames[i]);
  47225. if (f.isDirectory())
  47226. {
  47227. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47228. path.add (f, row);
  47229. changed();
  47230. }
  47231. }
  47232. }
  47233. void FileSearchPathListComponent::buttonClicked (Button* button)
  47234. {
  47235. const int currentRow = listBox->getSelectedRow();
  47236. if (button == removeButton)
  47237. {
  47238. deleteKeyPressed (currentRow);
  47239. }
  47240. else if (button == addButton)
  47241. {
  47242. File start (defaultBrowseTarget);
  47243. if (start == File::nonexistent)
  47244. start = path [0];
  47245. if (start == File::nonexistent)
  47246. start = File::getCurrentWorkingDirectory();
  47247. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47248. if (chooser.browseForDirectory())
  47249. {
  47250. path.add (chooser.getResult(), currentRow);
  47251. }
  47252. }
  47253. else if (button == changeButton)
  47254. {
  47255. returnKeyPressed (currentRow);
  47256. }
  47257. else if (button == upButton)
  47258. {
  47259. if (currentRow > 0 && currentRow < path.getNumPaths())
  47260. {
  47261. const File f (path[currentRow]);
  47262. path.remove (currentRow);
  47263. path.add (f, currentRow - 1);
  47264. listBox->selectRow (currentRow - 1);
  47265. }
  47266. }
  47267. else if (button == downButton)
  47268. {
  47269. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47270. {
  47271. const File f (path[currentRow]);
  47272. path.remove (currentRow);
  47273. path.add (f, currentRow + 1);
  47274. listBox->selectRow (currentRow + 1);
  47275. }
  47276. }
  47277. changed();
  47278. }
  47279. END_JUCE_NAMESPACE
  47280. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47281. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47282. BEGIN_JUCE_NAMESPACE
  47283. const Image juce_createIconForFile (const File& file);
  47284. class FileListTreeItem : public TreeViewItem,
  47285. public TimeSliceClient,
  47286. public AsyncUpdater,
  47287. public ChangeListener
  47288. {
  47289. public:
  47290. FileListTreeItem (FileTreeComponent& owner_,
  47291. DirectoryContentsList* const parentContentsList_,
  47292. const int indexInContentsList_,
  47293. const File& file_,
  47294. TimeSliceThread& thread_)
  47295. : file (file_),
  47296. owner (owner_),
  47297. parentContentsList (parentContentsList_),
  47298. indexInContentsList (indexInContentsList_),
  47299. subContentsList (0),
  47300. canDeleteSubContentsList (false),
  47301. thread (thread_),
  47302. icon (0)
  47303. {
  47304. DirectoryContentsList::FileInfo fileInfo;
  47305. if (parentContentsList_ != 0
  47306. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47307. {
  47308. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47309. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47310. isDirectory = fileInfo.isDirectory;
  47311. }
  47312. else
  47313. {
  47314. isDirectory = true;
  47315. }
  47316. }
  47317. ~FileListTreeItem()
  47318. {
  47319. thread.removeTimeSliceClient (this);
  47320. clearSubItems();
  47321. if (canDeleteSubContentsList)
  47322. delete subContentsList;
  47323. }
  47324. bool mightContainSubItems() { return isDirectory; }
  47325. const String getUniqueName() const { return file.getFullPathName(); }
  47326. int getItemHeight() const { return 22; }
  47327. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47328. void itemOpennessChanged (bool isNowOpen)
  47329. {
  47330. if (isNowOpen)
  47331. {
  47332. clearSubItems();
  47333. isDirectory = file.isDirectory();
  47334. if (isDirectory)
  47335. {
  47336. if (subContentsList == 0)
  47337. {
  47338. jassert (parentContentsList != 0);
  47339. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47340. l->setDirectory (file, true, true);
  47341. setSubContentsList (l);
  47342. canDeleteSubContentsList = true;
  47343. }
  47344. changeListenerCallback (0);
  47345. }
  47346. }
  47347. }
  47348. void setSubContentsList (DirectoryContentsList* newList)
  47349. {
  47350. jassert (subContentsList == 0);
  47351. subContentsList = newList;
  47352. newList->addChangeListener (this);
  47353. }
  47354. void changeListenerCallback (void*)
  47355. {
  47356. clearSubItems();
  47357. if (isOpen() && subContentsList != 0)
  47358. {
  47359. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47360. {
  47361. FileListTreeItem* const item
  47362. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47363. addSubItem (item);
  47364. }
  47365. }
  47366. }
  47367. void paintItem (Graphics& g, int width, int height)
  47368. {
  47369. if (file != File::nonexistent)
  47370. {
  47371. updateIcon (true);
  47372. if (icon.isNull())
  47373. thread.addTimeSliceClient (this);
  47374. }
  47375. owner.getLookAndFeel()
  47376. .drawFileBrowserRow (g, width, height,
  47377. file.getFileName(),
  47378. &icon, fileSize, modTime,
  47379. isDirectory, isSelected(),
  47380. indexInContentsList);
  47381. }
  47382. void itemClicked (const MouseEvent& e)
  47383. {
  47384. owner.sendMouseClickMessage (file, e);
  47385. }
  47386. void itemDoubleClicked (const MouseEvent& e)
  47387. {
  47388. TreeViewItem::itemDoubleClicked (e);
  47389. owner.sendDoubleClickMessage (file);
  47390. }
  47391. void itemSelectionChanged (bool)
  47392. {
  47393. owner.sendSelectionChangeMessage();
  47394. }
  47395. bool useTimeSlice()
  47396. {
  47397. updateIcon (false);
  47398. thread.removeTimeSliceClient (this);
  47399. return false;
  47400. }
  47401. void handleAsyncUpdate()
  47402. {
  47403. owner.repaint();
  47404. }
  47405. const File file;
  47406. juce_UseDebuggingNewOperator
  47407. private:
  47408. FileTreeComponent& owner;
  47409. DirectoryContentsList* parentContentsList;
  47410. int indexInContentsList;
  47411. DirectoryContentsList* subContentsList;
  47412. bool isDirectory, canDeleteSubContentsList;
  47413. TimeSliceThread& thread;
  47414. Image icon;
  47415. String fileSize;
  47416. String modTime;
  47417. void updateIcon (const bool onlyUpdateIfCached)
  47418. {
  47419. if (icon.isNull())
  47420. {
  47421. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47422. Image im (ImageCache::getFromHashCode (hashCode));
  47423. if (im.isNull() && ! onlyUpdateIfCached)
  47424. {
  47425. im = juce_createIconForFile (file);
  47426. if (im.isValid())
  47427. ImageCache::addImageToCache (im, hashCode);
  47428. }
  47429. if (im.isValid())
  47430. {
  47431. icon = im;
  47432. triggerAsyncUpdate();
  47433. }
  47434. }
  47435. }
  47436. };
  47437. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47438. : DirectoryContentsDisplayComponent (listToShow)
  47439. {
  47440. FileListTreeItem* const root
  47441. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47442. listToShow.getTimeSliceThread());
  47443. root->setSubContentsList (&listToShow);
  47444. setRootItemVisible (false);
  47445. setRootItem (root);
  47446. }
  47447. FileTreeComponent::~FileTreeComponent()
  47448. {
  47449. deleteRootItem();
  47450. }
  47451. const File FileTreeComponent::getSelectedFile (const int index) const
  47452. {
  47453. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47454. return item != 0 ? item->file
  47455. : File::nonexistent;
  47456. }
  47457. void FileTreeComponent::deselectAllFiles()
  47458. {
  47459. clearSelectedItems();
  47460. }
  47461. void FileTreeComponent::scrollToTop()
  47462. {
  47463. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47464. }
  47465. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47466. {
  47467. dragAndDropDescription = description;
  47468. }
  47469. END_JUCE_NAMESPACE
  47470. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47471. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47472. BEGIN_JUCE_NAMESPACE
  47473. ImagePreviewComponent::ImagePreviewComponent()
  47474. {
  47475. }
  47476. ImagePreviewComponent::~ImagePreviewComponent()
  47477. {
  47478. }
  47479. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47480. {
  47481. const int availableW = proportionOfWidth (0.97f);
  47482. const int availableH = getHeight() - 13 * 4;
  47483. const double scale = jmin (1.0,
  47484. availableW / (double) w,
  47485. availableH / (double) h);
  47486. w = roundToInt (scale * w);
  47487. h = roundToInt (scale * h);
  47488. }
  47489. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47490. {
  47491. if (fileToLoad != file)
  47492. {
  47493. fileToLoad = file;
  47494. startTimer (100);
  47495. }
  47496. }
  47497. void ImagePreviewComponent::timerCallback()
  47498. {
  47499. stopTimer();
  47500. currentThumbnail = Image();
  47501. currentDetails = String::empty;
  47502. repaint();
  47503. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47504. if (in != 0)
  47505. {
  47506. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47507. if (format != 0)
  47508. {
  47509. currentThumbnail = format->decodeImage (*in);
  47510. if (currentThumbnail.isValid())
  47511. {
  47512. int w = currentThumbnail.getWidth();
  47513. int h = currentThumbnail.getHeight();
  47514. currentDetails
  47515. << fileToLoad.getFileName() << "\n"
  47516. << format->getFormatName() << "\n"
  47517. << w << " x " << h << " pixels\n"
  47518. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47519. getThumbSize (w, h);
  47520. currentThumbnail = currentThumbnail.rescaled (w, h);
  47521. }
  47522. }
  47523. }
  47524. }
  47525. void ImagePreviewComponent::paint (Graphics& g)
  47526. {
  47527. if (currentThumbnail.isValid())
  47528. {
  47529. g.setFont (13.0f);
  47530. int w = currentThumbnail.getWidth();
  47531. int h = currentThumbnail.getHeight();
  47532. getThumbSize (w, h);
  47533. const int numLines = 4;
  47534. const int totalH = 13 * numLines + h + 4;
  47535. const int y = (getHeight() - totalH) / 2;
  47536. g.drawImageWithin (currentThumbnail,
  47537. (getWidth() - w) / 2, y, w, h,
  47538. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47539. false);
  47540. g.drawFittedText (currentDetails,
  47541. 0, y + h + 4, getWidth(), 100,
  47542. Justification::centredTop, numLines);
  47543. }
  47544. }
  47545. END_JUCE_NAMESPACE
  47546. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47547. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47548. BEGIN_JUCE_NAMESPACE
  47549. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47550. const String& directoryWildcardPatterns,
  47551. const String& description_)
  47552. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47553. : (description_ + " (" + fileWildcardPatterns + ")"))
  47554. {
  47555. parse (fileWildcardPatterns, fileWildcards);
  47556. parse (directoryWildcardPatterns, directoryWildcards);
  47557. }
  47558. WildcardFileFilter::~WildcardFileFilter()
  47559. {
  47560. }
  47561. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47562. {
  47563. return match (file, fileWildcards);
  47564. }
  47565. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47566. {
  47567. return match (file, directoryWildcards);
  47568. }
  47569. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47570. {
  47571. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47572. result.trim();
  47573. result.removeEmptyStrings();
  47574. // special case for *.*, because people use it to mean "any file", but it
  47575. // would actually ignore files with no extension.
  47576. for (int i = result.size(); --i >= 0;)
  47577. if (result[i] == "*.*")
  47578. result.set (i, "*");
  47579. }
  47580. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47581. {
  47582. const String filename (file.getFileName());
  47583. for (int i = wildcards.size(); --i >= 0;)
  47584. if (filename.matchesWildcard (wildcards[i], true))
  47585. return true;
  47586. return false;
  47587. }
  47588. END_JUCE_NAMESPACE
  47589. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47590. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47591. BEGIN_JUCE_NAMESPACE
  47592. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47593. {
  47594. }
  47595. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47596. {
  47597. }
  47598. namespace KeyboardFocusHelpers
  47599. {
  47600. // This will sort a set of components, so that they are ordered in terms of
  47601. // left-to-right and then top-to-bottom.
  47602. class ScreenPositionComparator
  47603. {
  47604. public:
  47605. ScreenPositionComparator() {}
  47606. static int compareElements (const Component* const first, const Component* const second)
  47607. {
  47608. int explicitOrder1 = first->getExplicitFocusOrder();
  47609. if (explicitOrder1 <= 0)
  47610. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47611. int explicitOrder2 = second->getExplicitFocusOrder();
  47612. if (explicitOrder2 <= 0)
  47613. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47614. if (explicitOrder1 != explicitOrder2)
  47615. return explicitOrder1 - explicitOrder2;
  47616. const int diff = first->getY() - second->getY();
  47617. return (diff == 0) ? first->getX() - second->getX()
  47618. : diff;
  47619. }
  47620. };
  47621. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47622. {
  47623. if (parent->getNumChildComponents() > 0)
  47624. {
  47625. Array <Component*> localComps;
  47626. ScreenPositionComparator comparator;
  47627. int i;
  47628. for (i = parent->getNumChildComponents(); --i >= 0;)
  47629. {
  47630. Component* const c = parent->getChildComponent (i);
  47631. if (c->isVisible() && c->isEnabled())
  47632. localComps.addSorted (comparator, c);
  47633. }
  47634. for (i = 0; i < localComps.size(); ++i)
  47635. {
  47636. Component* const c = localComps.getUnchecked (i);
  47637. if (c->getWantsKeyboardFocus())
  47638. comps.add (c);
  47639. if (! c->isFocusContainer())
  47640. findAllFocusableComponents (c, comps);
  47641. }
  47642. }
  47643. }
  47644. }
  47645. static Component* getIncrementedComponent (Component* const current, const int delta)
  47646. {
  47647. Component* focusContainer = current->getParentComponent();
  47648. if (focusContainer != 0)
  47649. {
  47650. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47651. focusContainer = focusContainer->getParentComponent();
  47652. if (focusContainer != 0)
  47653. {
  47654. Array <Component*> comps;
  47655. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47656. if (comps.size() > 0)
  47657. {
  47658. const int index = comps.indexOf (current);
  47659. return comps [(index + comps.size() + delta) % comps.size()];
  47660. }
  47661. }
  47662. }
  47663. return 0;
  47664. }
  47665. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47666. {
  47667. return getIncrementedComponent (current, 1);
  47668. }
  47669. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47670. {
  47671. return getIncrementedComponent (current, -1);
  47672. }
  47673. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47674. {
  47675. Array <Component*> comps;
  47676. if (parentComponent != 0)
  47677. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47678. return comps.getFirst();
  47679. }
  47680. END_JUCE_NAMESPACE
  47681. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47682. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47683. BEGIN_JUCE_NAMESPACE
  47684. bool KeyListener::keyStateChanged (const bool, Component*)
  47685. {
  47686. return false;
  47687. }
  47688. END_JUCE_NAMESPACE
  47689. /*** End of inlined file: juce_KeyListener.cpp ***/
  47690. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47691. BEGIN_JUCE_NAMESPACE
  47692. // N.B. these two includes are put here deliberately to avoid problems with
  47693. // old GCCs failing on long include paths
  47694. const int maxKeys = 3;
  47695. class KeyMappingChangeButton : public Button
  47696. {
  47697. public:
  47698. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47699. const CommandID commandID_,
  47700. const String& keyName,
  47701. const int keyNum_)
  47702. : Button (keyName),
  47703. owner (owner_),
  47704. commandID (commandID_),
  47705. keyNum (keyNum_)
  47706. {
  47707. setWantsKeyboardFocus (false);
  47708. setTriggeredOnMouseDown (keyNum >= 0);
  47709. if (keyNum_ < 0)
  47710. setTooltip (TRANS("adds a new key-mapping"));
  47711. else
  47712. setTooltip (TRANS("click to change this key-mapping"));
  47713. }
  47714. ~KeyMappingChangeButton()
  47715. {
  47716. }
  47717. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47718. {
  47719. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47720. keyNum >= 0 ? getName() : String::empty);
  47721. }
  47722. void clicked()
  47723. {
  47724. if (keyNum >= 0)
  47725. {
  47726. // existing key clicked..
  47727. PopupMenu m;
  47728. m.addItem (1, TRANS("change this key-mapping"));
  47729. m.addSeparator();
  47730. m.addItem (2, TRANS("remove this key-mapping"));
  47731. const int res = m.show();
  47732. if (res == 1)
  47733. {
  47734. owner->assignNewKey (commandID, keyNum);
  47735. }
  47736. else if (res == 2)
  47737. {
  47738. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47739. }
  47740. }
  47741. else
  47742. {
  47743. // + button pressed..
  47744. owner->assignNewKey (commandID, -1);
  47745. }
  47746. }
  47747. void fitToContent (const int h) throw()
  47748. {
  47749. if (keyNum < 0)
  47750. {
  47751. setSize (h, h);
  47752. }
  47753. else
  47754. {
  47755. Font f (h * 0.6f);
  47756. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47757. }
  47758. }
  47759. juce_UseDebuggingNewOperator
  47760. private:
  47761. KeyMappingEditorComponent* const owner;
  47762. const CommandID commandID;
  47763. const int keyNum;
  47764. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47765. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47766. };
  47767. class KeyMappingItemComponent : public Component
  47768. {
  47769. public:
  47770. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47771. const CommandID commandID_)
  47772. : owner (owner_),
  47773. commandID (commandID_)
  47774. {
  47775. setInterceptsMouseClicks (false, true);
  47776. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47777. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47778. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47779. {
  47780. KeyMappingChangeButton* const kb
  47781. = new KeyMappingChangeButton (owner_, commandID,
  47782. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47783. kb->setEnabled (! isReadOnly);
  47784. addAndMakeVisible (kb);
  47785. }
  47786. KeyMappingChangeButton* const kb
  47787. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47788. addChildComponent (kb);
  47789. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47790. }
  47791. ~KeyMappingItemComponent()
  47792. {
  47793. deleteAllChildren();
  47794. }
  47795. void paint (Graphics& g)
  47796. {
  47797. g.setFont (getHeight() * 0.7f);
  47798. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47799. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47800. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47801. Justification::centredLeft, true);
  47802. }
  47803. void resized()
  47804. {
  47805. int x = getWidth() - 4;
  47806. for (int i = getNumChildComponents(); --i >= 0;)
  47807. {
  47808. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47809. kb->fitToContent (getHeight() - 2);
  47810. kb->setTopRightPosition (x, 1);
  47811. x -= kb->getWidth() + 5;
  47812. }
  47813. }
  47814. juce_UseDebuggingNewOperator
  47815. private:
  47816. KeyMappingEditorComponent* const owner;
  47817. const CommandID commandID;
  47818. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47819. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47820. };
  47821. class KeyMappingTreeViewItem : public TreeViewItem
  47822. {
  47823. public:
  47824. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47825. const CommandID commandID_)
  47826. : owner (owner_),
  47827. commandID (commandID_)
  47828. {
  47829. }
  47830. ~KeyMappingTreeViewItem()
  47831. {
  47832. }
  47833. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47834. bool mightContainSubItems() { return false; }
  47835. int getItemHeight() const { return 20; }
  47836. Component* createItemComponent()
  47837. {
  47838. return new KeyMappingItemComponent (owner, commandID);
  47839. }
  47840. juce_UseDebuggingNewOperator
  47841. private:
  47842. KeyMappingEditorComponent* const owner;
  47843. const CommandID commandID;
  47844. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47845. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47846. };
  47847. class KeyCategoryTreeViewItem : public TreeViewItem
  47848. {
  47849. public:
  47850. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47851. const String& name)
  47852. : owner (owner_),
  47853. categoryName (name)
  47854. {
  47855. }
  47856. ~KeyCategoryTreeViewItem()
  47857. {
  47858. }
  47859. const String getUniqueName() const { return categoryName + "_cat"; }
  47860. bool mightContainSubItems() { return true; }
  47861. int getItemHeight() const { return 28; }
  47862. void paintItem (Graphics& g, int width, int height)
  47863. {
  47864. g.setFont (height * 0.6f, Font::bold);
  47865. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47866. g.drawText (categoryName,
  47867. 2, 0, width - 2, height,
  47868. Justification::centredLeft, true);
  47869. }
  47870. void itemOpennessChanged (bool isNowOpen)
  47871. {
  47872. if (isNowOpen)
  47873. {
  47874. if (getNumSubItems() == 0)
  47875. {
  47876. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47877. for (int i = 0; i < commands.size(); ++i)
  47878. {
  47879. if (owner->shouldCommandBeIncluded (commands[i]))
  47880. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47881. }
  47882. }
  47883. }
  47884. else
  47885. {
  47886. clearSubItems();
  47887. }
  47888. }
  47889. juce_UseDebuggingNewOperator
  47890. private:
  47891. KeyMappingEditorComponent* owner;
  47892. String categoryName;
  47893. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47894. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47895. };
  47896. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47897. const bool showResetToDefaultButton)
  47898. : mappings (mappingManager)
  47899. {
  47900. jassert (mappingManager != 0); // can't be null!
  47901. mappingManager->addChangeListener (this);
  47902. setLinesDrawnForSubItems (false);
  47903. resetButton = 0;
  47904. if (showResetToDefaultButton)
  47905. {
  47906. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47907. resetButton->addButtonListener (this);
  47908. }
  47909. addAndMakeVisible (tree = new TreeView());
  47910. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47911. tree->setRootItemVisible (false);
  47912. tree->setDefaultOpenness (true);
  47913. tree->setRootItem (this);
  47914. }
  47915. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47916. {
  47917. mappings->removeChangeListener (this);
  47918. deleteAllChildren();
  47919. }
  47920. bool KeyMappingEditorComponent::mightContainSubItems()
  47921. {
  47922. return true;
  47923. }
  47924. const String KeyMappingEditorComponent::getUniqueName() const
  47925. {
  47926. return "keys";
  47927. }
  47928. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47929. const Colour& textColour)
  47930. {
  47931. setColour (backgroundColourId, mainBackground);
  47932. setColour (textColourId, textColour);
  47933. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47934. }
  47935. void KeyMappingEditorComponent::parentHierarchyChanged()
  47936. {
  47937. changeListenerCallback (0);
  47938. }
  47939. void KeyMappingEditorComponent::resized()
  47940. {
  47941. int h = getHeight();
  47942. if (resetButton != 0)
  47943. {
  47944. const int buttonHeight = 20;
  47945. h -= buttonHeight + 8;
  47946. int x = getWidth() - 8;
  47947. resetButton->changeWidthToFitText (buttonHeight);
  47948. resetButton->setTopRightPosition (x, h + 6);
  47949. }
  47950. tree->setBounds (0, 0, getWidth(), h);
  47951. }
  47952. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47953. {
  47954. if (button == resetButton)
  47955. {
  47956. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47957. TRANS("Reset to defaults"),
  47958. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47959. TRANS("Reset")))
  47960. {
  47961. mappings->resetToDefaultMappings();
  47962. }
  47963. }
  47964. }
  47965. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47966. {
  47967. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47968. clearSubItems();
  47969. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47970. for (int i = 0; i < categories.size(); ++i)
  47971. {
  47972. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47973. int count = 0;
  47974. for (int j = 0; j < commands.size(); ++j)
  47975. if (shouldCommandBeIncluded (commands[j]))
  47976. ++count;
  47977. if (count > 0)
  47978. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47979. }
  47980. if (oldOpenness != 0)
  47981. tree->restoreOpennessState (*oldOpenness);
  47982. }
  47983. class KeyEntryWindow : public AlertWindow
  47984. {
  47985. public:
  47986. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47987. : AlertWindow (TRANS("New key-mapping"),
  47988. TRANS("Please press a key combination now..."),
  47989. AlertWindow::NoIcon),
  47990. owner (owner_)
  47991. {
  47992. addButton (TRANS("ok"), 1);
  47993. addButton (TRANS("cancel"), 0);
  47994. // (avoid return + escape keys getting processed by the buttons..)
  47995. for (int i = getNumChildComponents(); --i >= 0;)
  47996. getChildComponent (i)->setWantsKeyboardFocus (false);
  47997. setWantsKeyboardFocus (true);
  47998. grabKeyboardFocus();
  47999. }
  48000. ~KeyEntryWindow()
  48001. {
  48002. }
  48003. bool keyPressed (const KeyPress& key)
  48004. {
  48005. lastPress = key;
  48006. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48007. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48008. if (previousCommand != 0)
  48009. {
  48010. message << "\n\n"
  48011. << TRANS("(Currently assigned to \"")
  48012. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48013. << "\")";
  48014. }
  48015. setMessage (message);
  48016. return true;
  48017. }
  48018. bool keyStateChanged (bool)
  48019. {
  48020. return true;
  48021. }
  48022. KeyPress lastPress;
  48023. juce_UseDebuggingNewOperator
  48024. private:
  48025. KeyMappingEditorComponent* owner;
  48026. KeyEntryWindow (const KeyEntryWindow&);
  48027. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48028. };
  48029. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48030. {
  48031. KeyEntryWindow entryWindow (this);
  48032. if (entryWindow.runModalLoop() != 0)
  48033. {
  48034. entryWindow.setVisible (false);
  48035. if (entryWindow.lastPress.isValid())
  48036. {
  48037. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48038. if (previousCommand != 0)
  48039. {
  48040. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48041. TRANS("Change key-mapping"),
  48042. TRANS("This key is already assigned to the command \"")
  48043. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48044. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48045. TRANS("re-assign"),
  48046. TRANS("cancel")))
  48047. {
  48048. return;
  48049. }
  48050. }
  48051. mappings->removeKeyPress (entryWindow.lastPress);
  48052. if (index >= 0)
  48053. mappings->removeKeyPress (commandID, index);
  48054. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48055. }
  48056. }
  48057. }
  48058. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48059. {
  48060. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48061. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48062. }
  48063. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48064. {
  48065. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48066. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48067. }
  48068. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48069. {
  48070. return key.getTextDescription();
  48071. }
  48072. END_JUCE_NAMESPACE
  48073. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48074. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48075. BEGIN_JUCE_NAMESPACE
  48076. KeyPress::KeyPress() throw()
  48077. : keyCode (0),
  48078. mods (0),
  48079. textCharacter (0)
  48080. {
  48081. }
  48082. KeyPress::KeyPress (const int keyCode_,
  48083. const ModifierKeys& mods_,
  48084. const juce_wchar textCharacter_) throw()
  48085. : keyCode (keyCode_),
  48086. mods (mods_),
  48087. textCharacter (textCharacter_)
  48088. {
  48089. }
  48090. KeyPress::KeyPress (const int keyCode_) throw()
  48091. : keyCode (keyCode_),
  48092. textCharacter (0)
  48093. {
  48094. }
  48095. KeyPress::KeyPress (const KeyPress& other) throw()
  48096. : keyCode (other.keyCode),
  48097. mods (other.mods),
  48098. textCharacter (other.textCharacter)
  48099. {
  48100. }
  48101. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48102. {
  48103. keyCode = other.keyCode;
  48104. mods = other.mods;
  48105. textCharacter = other.textCharacter;
  48106. return *this;
  48107. }
  48108. bool KeyPress::operator== (const KeyPress& other) const throw()
  48109. {
  48110. return mods.getRawFlags() == other.mods.getRawFlags()
  48111. && (textCharacter == other.textCharacter
  48112. || textCharacter == 0
  48113. || other.textCharacter == 0)
  48114. && (keyCode == other.keyCode
  48115. || (keyCode < 256
  48116. && other.keyCode < 256
  48117. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48118. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48119. }
  48120. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48121. {
  48122. return ! operator== (other);
  48123. }
  48124. bool KeyPress::isCurrentlyDown() const
  48125. {
  48126. return isKeyCurrentlyDown (keyCode)
  48127. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48128. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48129. }
  48130. namespace KeyPressHelpers
  48131. {
  48132. struct KeyNameAndCode
  48133. {
  48134. const char* name;
  48135. int code;
  48136. };
  48137. static const KeyNameAndCode translations[] =
  48138. {
  48139. { "spacebar", KeyPress::spaceKey },
  48140. { "return", KeyPress::returnKey },
  48141. { "escape", KeyPress::escapeKey },
  48142. { "backspace", KeyPress::backspaceKey },
  48143. { "cursor left", KeyPress::leftKey },
  48144. { "cursor right", KeyPress::rightKey },
  48145. { "cursor up", KeyPress::upKey },
  48146. { "cursor down", KeyPress::downKey },
  48147. { "page up", KeyPress::pageUpKey },
  48148. { "page down", KeyPress::pageDownKey },
  48149. { "home", KeyPress::homeKey },
  48150. { "end", KeyPress::endKey },
  48151. { "delete", KeyPress::deleteKey },
  48152. { "insert", KeyPress::insertKey },
  48153. { "tab", KeyPress::tabKey },
  48154. { "play", KeyPress::playKey },
  48155. { "stop", KeyPress::stopKey },
  48156. { "fast forward", KeyPress::fastForwardKey },
  48157. { "rewind", KeyPress::rewindKey }
  48158. };
  48159. static const String numberPadPrefix() { return "numpad "; }
  48160. }
  48161. const KeyPress KeyPress::createFromDescription (const String& desc)
  48162. {
  48163. int modifiers = 0;
  48164. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48165. || desc.containsWholeWordIgnoreCase ("control")
  48166. || desc.containsWholeWordIgnoreCase ("ctl"))
  48167. modifiers |= ModifierKeys::ctrlModifier;
  48168. if (desc.containsWholeWordIgnoreCase ("shift")
  48169. || desc.containsWholeWordIgnoreCase ("shft"))
  48170. modifiers |= ModifierKeys::shiftModifier;
  48171. if (desc.containsWholeWordIgnoreCase ("alt")
  48172. || desc.containsWholeWordIgnoreCase ("option"))
  48173. modifiers |= ModifierKeys::altModifier;
  48174. if (desc.containsWholeWordIgnoreCase ("command")
  48175. || desc.containsWholeWordIgnoreCase ("cmd"))
  48176. modifiers |= ModifierKeys::commandModifier;
  48177. int key = 0;
  48178. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48179. {
  48180. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48181. {
  48182. key = KeyPressHelpers::translations[i].code;
  48183. break;
  48184. }
  48185. }
  48186. if (key == 0)
  48187. {
  48188. // see if it's a numpad key..
  48189. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48190. {
  48191. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48192. if (lastChar >= '0' && lastChar <= '9')
  48193. key = numberPad0 + lastChar - '0';
  48194. else if (lastChar == '+')
  48195. key = numberPadAdd;
  48196. else if (lastChar == '-')
  48197. key = numberPadSubtract;
  48198. else if (lastChar == '*')
  48199. key = numberPadMultiply;
  48200. else if (lastChar == '/')
  48201. key = numberPadDivide;
  48202. else if (lastChar == '.')
  48203. key = numberPadDecimalPoint;
  48204. else if (lastChar == '=')
  48205. key = numberPadEquals;
  48206. else if (desc.endsWith ("separator"))
  48207. key = numberPadSeparator;
  48208. else if (desc.endsWith ("delete"))
  48209. key = numberPadDelete;
  48210. }
  48211. if (key == 0)
  48212. {
  48213. // see if it's a function key..
  48214. for (int i = 1; i <= 12; ++i)
  48215. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48216. key = F1Key + i - 1;
  48217. if (key == 0)
  48218. {
  48219. // give up and use the hex code..
  48220. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48221. .toLowerCase()
  48222. .retainCharacters ("0123456789abcdef")
  48223. .getHexValue32();
  48224. if (hexCode > 0)
  48225. key = hexCode;
  48226. else
  48227. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48228. }
  48229. }
  48230. }
  48231. return KeyPress (key, ModifierKeys (modifiers), 0);
  48232. }
  48233. const String KeyPress::getTextDescription() const
  48234. {
  48235. String desc;
  48236. if (keyCode > 0)
  48237. {
  48238. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48239. // want to store it as being a slash, not shift+whatever.
  48240. if (textCharacter == '/')
  48241. return "/";
  48242. if (mods.isCtrlDown())
  48243. desc << "ctrl + ";
  48244. if (mods.isShiftDown())
  48245. desc << "shift + ";
  48246. #if JUCE_MAC
  48247. // only do this on the mac, because on Windows ctrl and command are the same,
  48248. // and this would get confusing
  48249. if (mods.isCommandDown())
  48250. desc << "command + ";
  48251. if (mods.isAltDown())
  48252. desc << "option + ";
  48253. #else
  48254. if (mods.isAltDown())
  48255. desc << "alt + ";
  48256. #endif
  48257. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48258. if (keyCode == KeyPressHelpers::translations[i].code)
  48259. return desc + KeyPressHelpers::translations[i].name;
  48260. if (keyCode >= F1Key && keyCode <= F16Key)
  48261. desc << 'F' << (1 + keyCode - F1Key);
  48262. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48263. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48264. else if (keyCode >= 33 && keyCode < 176)
  48265. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48266. else if (keyCode == numberPadAdd)
  48267. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48268. else if (keyCode == numberPadSubtract)
  48269. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48270. else if (keyCode == numberPadMultiply)
  48271. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48272. else if (keyCode == numberPadDivide)
  48273. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48274. else if (keyCode == numberPadSeparator)
  48275. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48276. else if (keyCode == numberPadDecimalPoint)
  48277. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48278. else if (keyCode == numberPadDelete)
  48279. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48280. else
  48281. desc << '#' << String::toHexString (keyCode);
  48282. }
  48283. return desc;
  48284. }
  48285. END_JUCE_NAMESPACE
  48286. /*** End of inlined file: juce_KeyPress.cpp ***/
  48287. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48288. BEGIN_JUCE_NAMESPACE
  48289. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48290. : commandManager (commandManager_)
  48291. {
  48292. // A manager is needed to get the descriptions of commands, and will be called when
  48293. // a command is invoked. So you can't leave this null..
  48294. jassert (commandManager_ != 0);
  48295. Desktop::getInstance().addFocusChangeListener (this);
  48296. }
  48297. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48298. : commandManager (other.commandManager)
  48299. {
  48300. Desktop::getInstance().addFocusChangeListener (this);
  48301. }
  48302. KeyPressMappingSet::~KeyPressMappingSet()
  48303. {
  48304. Desktop::getInstance().removeFocusChangeListener (this);
  48305. }
  48306. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48307. {
  48308. for (int i = 0; i < mappings.size(); ++i)
  48309. if (mappings.getUnchecked(i)->commandID == commandID)
  48310. return mappings.getUnchecked (i)->keypresses;
  48311. return Array <KeyPress> ();
  48312. }
  48313. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48314. const KeyPress& newKeyPress,
  48315. int insertIndex)
  48316. {
  48317. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48318. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48319. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48320. && ! newKeyPress.getModifiers().isShiftDown()));
  48321. if (findCommandForKeyPress (newKeyPress) != commandID)
  48322. {
  48323. removeKeyPress (newKeyPress);
  48324. if (newKeyPress.isValid())
  48325. {
  48326. for (int i = mappings.size(); --i >= 0;)
  48327. {
  48328. if (mappings.getUnchecked(i)->commandID == commandID)
  48329. {
  48330. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48331. sendChangeMessage (this);
  48332. return;
  48333. }
  48334. }
  48335. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48336. if (ci != 0)
  48337. {
  48338. CommandMapping* const cm = new CommandMapping();
  48339. cm->commandID = commandID;
  48340. cm->keypresses.add (newKeyPress);
  48341. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48342. mappings.add (cm);
  48343. sendChangeMessage (this);
  48344. }
  48345. }
  48346. }
  48347. }
  48348. void KeyPressMappingSet::resetToDefaultMappings()
  48349. {
  48350. mappings.clear();
  48351. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48352. {
  48353. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48354. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48355. {
  48356. addKeyPress (ci->commandID,
  48357. ci->defaultKeypresses.getReference (j));
  48358. }
  48359. }
  48360. sendChangeMessage (this);
  48361. }
  48362. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48363. {
  48364. clearAllKeyPresses (commandID);
  48365. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48366. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48367. {
  48368. addKeyPress (ci->commandID,
  48369. ci->defaultKeypresses.getReference (j));
  48370. }
  48371. }
  48372. void KeyPressMappingSet::clearAllKeyPresses()
  48373. {
  48374. if (mappings.size() > 0)
  48375. {
  48376. sendChangeMessage (this);
  48377. mappings.clear();
  48378. }
  48379. }
  48380. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48381. {
  48382. for (int i = mappings.size(); --i >= 0;)
  48383. {
  48384. if (mappings.getUnchecked(i)->commandID == commandID)
  48385. {
  48386. mappings.remove (i);
  48387. sendChangeMessage (this);
  48388. }
  48389. }
  48390. }
  48391. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48392. {
  48393. if (keypress.isValid())
  48394. {
  48395. for (int i = mappings.size(); --i >= 0;)
  48396. {
  48397. CommandMapping* const cm = mappings.getUnchecked(i);
  48398. for (int j = cm->keypresses.size(); --j >= 0;)
  48399. {
  48400. if (keypress == cm->keypresses [j])
  48401. {
  48402. cm->keypresses.remove (j);
  48403. sendChangeMessage (this);
  48404. }
  48405. }
  48406. }
  48407. }
  48408. }
  48409. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48410. {
  48411. for (int i = mappings.size(); --i >= 0;)
  48412. {
  48413. if (mappings.getUnchecked(i)->commandID == commandID)
  48414. {
  48415. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48416. sendChangeMessage (this);
  48417. break;
  48418. }
  48419. }
  48420. }
  48421. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48422. {
  48423. for (int i = 0; i < mappings.size(); ++i)
  48424. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48425. return mappings.getUnchecked(i)->commandID;
  48426. return 0;
  48427. }
  48428. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48429. {
  48430. for (int i = mappings.size(); --i >= 0;)
  48431. if (mappings.getUnchecked(i)->commandID == commandID)
  48432. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48433. return false;
  48434. }
  48435. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48436. const KeyPress& key,
  48437. const bool isKeyDown,
  48438. const int millisecsSinceKeyPressed,
  48439. Component* const originatingComponent) const
  48440. {
  48441. ApplicationCommandTarget::InvocationInfo info (commandID);
  48442. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48443. info.isKeyDown = isKeyDown;
  48444. info.keyPress = key;
  48445. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48446. info.originatingComponent = originatingComponent;
  48447. commandManager->invoke (info, false);
  48448. }
  48449. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48450. {
  48451. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48452. {
  48453. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48454. {
  48455. // if the XML was created as a set of differences from the default mappings,
  48456. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48457. resetToDefaultMappings();
  48458. }
  48459. else
  48460. {
  48461. // if the XML was created calling createXml (false), then we need to clear all
  48462. // the keys and treat the xml as describing the entire set of mappings.
  48463. clearAllKeyPresses();
  48464. }
  48465. forEachXmlChildElement (xmlVersion, map)
  48466. {
  48467. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48468. if (commandId != 0)
  48469. {
  48470. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48471. if (map->hasTagName ("MAPPING"))
  48472. {
  48473. addKeyPress (commandId, key);
  48474. }
  48475. else if (map->hasTagName ("UNMAPPING"))
  48476. {
  48477. if (containsMapping (commandId, key))
  48478. removeKeyPress (key);
  48479. }
  48480. }
  48481. }
  48482. return true;
  48483. }
  48484. return false;
  48485. }
  48486. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48487. {
  48488. ScopedPointer <KeyPressMappingSet> defaultSet;
  48489. if (saveDifferencesFromDefaultSet)
  48490. {
  48491. defaultSet = new KeyPressMappingSet (commandManager);
  48492. defaultSet->resetToDefaultMappings();
  48493. }
  48494. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48495. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48496. int i;
  48497. for (i = 0; i < mappings.size(); ++i)
  48498. {
  48499. const CommandMapping* const cm = mappings.getUnchecked(i);
  48500. for (int j = 0; j < cm->keypresses.size(); ++j)
  48501. {
  48502. if (defaultSet == 0
  48503. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48504. {
  48505. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48506. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48507. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48508. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48509. }
  48510. }
  48511. }
  48512. if (defaultSet != 0)
  48513. {
  48514. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48515. {
  48516. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48517. for (int j = 0; j < cm->keypresses.size(); ++j)
  48518. {
  48519. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48520. {
  48521. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48522. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48523. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48524. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48525. }
  48526. }
  48527. }
  48528. }
  48529. return doc;
  48530. }
  48531. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48532. Component* originatingComponent)
  48533. {
  48534. bool used = false;
  48535. const CommandID commandID = findCommandForKeyPress (key);
  48536. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48537. if (ci != 0
  48538. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48539. {
  48540. ApplicationCommandInfo info (0);
  48541. if (commandManager->getTargetForCommand (commandID, info) != 0
  48542. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48543. {
  48544. invokeCommand (commandID, key, true, 0, originatingComponent);
  48545. used = true;
  48546. }
  48547. else
  48548. {
  48549. if (originatingComponent != 0)
  48550. originatingComponent->getLookAndFeel().playAlertSound();
  48551. }
  48552. }
  48553. return used;
  48554. }
  48555. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48556. {
  48557. bool used = false;
  48558. const uint32 now = Time::getMillisecondCounter();
  48559. for (int i = mappings.size(); --i >= 0;)
  48560. {
  48561. CommandMapping* const cm = mappings.getUnchecked(i);
  48562. if (cm->wantsKeyUpDownCallbacks)
  48563. {
  48564. for (int j = cm->keypresses.size(); --j >= 0;)
  48565. {
  48566. const KeyPress key (cm->keypresses.getReference (j));
  48567. const bool isDown = key.isCurrentlyDown();
  48568. int keyPressEntryIndex = 0;
  48569. bool wasDown = false;
  48570. for (int k = keysDown.size(); --k >= 0;)
  48571. {
  48572. if (key == keysDown.getUnchecked(k)->key)
  48573. {
  48574. keyPressEntryIndex = k;
  48575. wasDown = true;
  48576. used = true;
  48577. break;
  48578. }
  48579. }
  48580. if (isDown != wasDown)
  48581. {
  48582. int millisecs = 0;
  48583. if (isDown)
  48584. {
  48585. KeyPressTime* const k = new KeyPressTime();
  48586. k->key = key;
  48587. k->timeWhenPressed = now;
  48588. keysDown.add (k);
  48589. }
  48590. else
  48591. {
  48592. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48593. if (now > pressTime)
  48594. millisecs = now - pressTime;
  48595. keysDown.remove (keyPressEntryIndex);
  48596. }
  48597. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48598. used = true;
  48599. }
  48600. }
  48601. }
  48602. }
  48603. return used;
  48604. }
  48605. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48606. {
  48607. if (focusedComponent != 0)
  48608. focusedComponent->keyStateChanged (false);
  48609. }
  48610. END_JUCE_NAMESPACE
  48611. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48612. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48613. BEGIN_JUCE_NAMESPACE
  48614. ModifierKeys::ModifierKeys (const int flags_) throw()
  48615. : flags (flags_)
  48616. {
  48617. }
  48618. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48619. : flags (other.flags)
  48620. {
  48621. }
  48622. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48623. {
  48624. flags = other.flags;
  48625. return *this;
  48626. }
  48627. ModifierKeys ModifierKeys::currentModifiers;
  48628. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48629. {
  48630. return currentModifiers;
  48631. }
  48632. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48633. {
  48634. int num = 0;
  48635. if (isLeftButtonDown()) ++num;
  48636. if (isRightButtonDown()) ++num;
  48637. if (isMiddleButtonDown()) ++num;
  48638. return num;
  48639. }
  48640. END_JUCE_NAMESPACE
  48641. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48642. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48643. BEGIN_JUCE_NAMESPACE
  48644. class ComponentAnimator::AnimationTask
  48645. {
  48646. public:
  48647. AnimationTask (Component* const comp)
  48648. : component (comp)
  48649. {
  48650. }
  48651. Component::SafePointer<Component> component;
  48652. Rectangle<int> destination;
  48653. int msElapsed, msTotal;
  48654. double startSpeed, midSpeed, endSpeed, lastProgress;
  48655. double left, top, right, bottom;
  48656. bool useTimeslice (const int elapsed)
  48657. {
  48658. if (component == 0)
  48659. return false;
  48660. msElapsed += elapsed;
  48661. double newProgress = msElapsed / (double) msTotal;
  48662. if (newProgress >= 0 && newProgress < 1.0)
  48663. {
  48664. newProgress = timeToDistance (newProgress);
  48665. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48666. jassert (newProgress >= lastProgress);
  48667. lastProgress = newProgress;
  48668. left += (destination.getX() - left) * delta;
  48669. top += (destination.getY() - top) * delta;
  48670. right += (destination.getRight() - right) * delta;
  48671. bottom += (destination.getBottom() - bottom) * delta;
  48672. if (delta < 1.0)
  48673. {
  48674. const Rectangle<int> newBounds (roundToInt (left),
  48675. roundToInt (top),
  48676. roundToInt (right - left),
  48677. roundToInt (bottom - top));
  48678. if (newBounds != destination)
  48679. {
  48680. component->setBounds (newBounds);
  48681. return true;
  48682. }
  48683. }
  48684. }
  48685. component->setBounds (destination);
  48686. return false;
  48687. }
  48688. void moveToFinalDestination()
  48689. {
  48690. if (component != 0)
  48691. component->setBounds (destination);
  48692. }
  48693. private:
  48694. inline double timeToDistance (const double time) const
  48695. {
  48696. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48697. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48698. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48699. }
  48700. };
  48701. ComponentAnimator::ComponentAnimator()
  48702. : lastTime (0)
  48703. {
  48704. }
  48705. ComponentAnimator::~ComponentAnimator()
  48706. {
  48707. cancelAllAnimations (false);
  48708. jassert (tasks.size() == 0);
  48709. }
  48710. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48711. {
  48712. for (int i = tasks.size(); --i >= 0;)
  48713. if (component == tasks.getUnchecked(i)->component.getComponent())
  48714. return tasks.getUnchecked(i);
  48715. return 0;
  48716. }
  48717. void ComponentAnimator::animateComponent (Component* const component,
  48718. const Rectangle<int>& finalPosition,
  48719. const int millisecondsToSpendMoving,
  48720. const double startSpeed,
  48721. const double endSpeed)
  48722. {
  48723. if (component != 0)
  48724. {
  48725. AnimationTask* at = findTaskFor (component);
  48726. if (at == 0)
  48727. {
  48728. at = new AnimationTask (component);
  48729. tasks.add (at);
  48730. sendChangeMessage (this);
  48731. }
  48732. at->msElapsed = 0;
  48733. at->lastProgress = 0;
  48734. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48735. at->destination = finalPosition;
  48736. // the speeds must be 0 or greater!
  48737. jassert (startSpeed >= 0 && endSpeed >= 0)
  48738. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48739. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48740. at->midSpeed = invTotalDistance;
  48741. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48742. at->left = component->getX();
  48743. at->top = component->getY();
  48744. at->right = component->getRight();
  48745. at->bottom = component->getBottom();
  48746. if (! isTimerRunning())
  48747. {
  48748. lastTime = Time::getMillisecondCounter();
  48749. startTimer (1000 / 50);
  48750. }
  48751. }
  48752. }
  48753. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48754. {
  48755. for (int i = tasks.size(); --i >= 0;)
  48756. {
  48757. AnimationTask* const at = tasks.getUnchecked(i);
  48758. if (moveComponentsToTheirFinalPositions)
  48759. at->moveToFinalDestination();
  48760. delete at;
  48761. tasks.remove (i);
  48762. sendChangeMessage (this);
  48763. }
  48764. }
  48765. void ComponentAnimator::cancelAnimation (Component* const component,
  48766. const bool moveComponentToItsFinalPosition)
  48767. {
  48768. AnimationTask* const at = findTaskFor (component);
  48769. if (at != 0)
  48770. {
  48771. if (moveComponentToItsFinalPosition)
  48772. at->moveToFinalDestination();
  48773. tasks.removeValue (at);
  48774. delete at;
  48775. sendChangeMessage (this);
  48776. }
  48777. }
  48778. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48779. {
  48780. AnimationTask* const at = findTaskFor (component);
  48781. if (at != 0)
  48782. return at->destination;
  48783. else if (component != 0)
  48784. return component->getBounds();
  48785. return Rectangle<int>();
  48786. }
  48787. bool ComponentAnimator::isAnimating (Component* component) const
  48788. {
  48789. return findTaskFor (component) != 0;
  48790. }
  48791. void ComponentAnimator::timerCallback()
  48792. {
  48793. const uint32 timeNow = Time::getMillisecondCounter();
  48794. if (lastTime == 0 || lastTime == timeNow)
  48795. lastTime = timeNow;
  48796. const int elapsed = timeNow - lastTime;
  48797. for (int i = tasks.size(); --i >= 0;)
  48798. {
  48799. AnimationTask* const at = tasks.getUnchecked(i);
  48800. if (! at->useTimeslice (elapsed))
  48801. {
  48802. tasks.remove (i);
  48803. delete at;
  48804. sendChangeMessage (this);
  48805. }
  48806. }
  48807. lastTime = timeNow;
  48808. if (tasks.size() == 0)
  48809. stopTimer();
  48810. }
  48811. END_JUCE_NAMESPACE
  48812. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48813. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48814. BEGIN_JUCE_NAMESPACE
  48815. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48816. : minW (0),
  48817. maxW (0x3fffffff),
  48818. minH (0),
  48819. maxH (0x3fffffff),
  48820. minOffTop (0),
  48821. minOffLeft (0),
  48822. minOffBottom (0),
  48823. minOffRight (0),
  48824. aspectRatio (0.0)
  48825. {
  48826. }
  48827. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48828. {
  48829. }
  48830. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48831. {
  48832. minW = minimumWidth;
  48833. }
  48834. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48835. {
  48836. maxW = maximumWidth;
  48837. }
  48838. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48839. {
  48840. minH = minimumHeight;
  48841. }
  48842. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48843. {
  48844. maxH = maximumHeight;
  48845. }
  48846. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48847. {
  48848. jassert (maxW >= minimumWidth);
  48849. jassert (maxH >= minimumHeight);
  48850. jassert (minimumWidth > 0 && minimumHeight > 0);
  48851. minW = minimumWidth;
  48852. minH = minimumHeight;
  48853. if (minW > maxW)
  48854. maxW = minW;
  48855. if (minH > maxH)
  48856. maxH = minH;
  48857. }
  48858. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48859. {
  48860. jassert (maximumWidth >= minW);
  48861. jassert (maximumHeight >= minH);
  48862. jassert (maximumWidth > 0 && maximumHeight > 0);
  48863. maxW = jmax (minW, maximumWidth);
  48864. maxH = jmax (minH, maximumHeight);
  48865. }
  48866. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48867. const int minimumHeight,
  48868. const int maximumWidth,
  48869. const int maximumHeight) throw()
  48870. {
  48871. jassert (maximumWidth >= minimumWidth);
  48872. jassert (maximumHeight >= minimumHeight);
  48873. jassert (maximumWidth > 0 && maximumHeight > 0);
  48874. jassert (minimumWidth > 0 && minimumHeight > 0);
  48875. minW = jmax (0, minimumWidth);
  48876. minH = jmax (0, minimumHeight);
  48877. maxW = jmax (minW, maximumWidth);
  48878. maxH = jmax (minH, maximumHeight);
  48879. }
  48880. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48881. const int minimumWhenOffTheLeft,
  48882. const int minimumWhenOffTheBottom,
  48883. const int minimumWhenOffTheRight) throw()
  48884. {
  48885. minOffTop = minimumWhenOffTheTop;
  48886. minOffLeft = minimumWhenOffTheLeft;
  48887. minOffBottom = minimumWhenOffTheBottom;
  48888. minOffRight = minimumWhenOffTheRight;
  48889. }
  48890. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48891. {
  48892. aspectRatio = jmax (0.0, widthOverHeight);
  48893. }
  48894. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48895. {
  48896. return aspectRatio;
  48897. }
  48898. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48899. const Rectangle<int>& targetBounds,
  48900. const bool isStretchingTop,
  48901. const bool isStretchingLeft,
  48902. const bool isStretchingBottom,
  48903. const bool isStretchingRight)
  48904. {
  48905. jassert (component != 0);
  48906. Rectangle<int> limits, bounds (targetBounds);
  48907. BorderSize border;
  48908. Component* const parent = component->getParentComponent();
  48909. if (parent == 0)
  48910. {
  48911. ComponentPeer* peer = component->getPeer();
  48912. if (peer != 0)
  48913. border = peer->getFrameSize();
  48914. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48915. }
  48916. else
  48917. {
  48918. limits.setSize (parent->getWidth(), parent->getHeight());
  48919. }
  48920. border.addTo (bounds);
  48921. checkBounds (bounds,
  48922. border.addedTo (component->getBounds()), limits,
  48923. isStretchingTop, isStretchingLeft,
  48924. isStretchingBottom, isStretchingRight);
  48925. border.subtractFrom (bounds);
  48926. applyBoundsToComponent (component, bounds);
  48927. }
  48928. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48929. {
  48930. setBoundsForComponent (component, component->getBounds(),
  48931. false, false, false, false);
  48932. }
  48933. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48934. const Rectangle<int>& bounds)
  48935. {
  48936. component->setBounds (bounds);
  48937. }
  48938. void ComponentBoundsConstrainer::resizeStart()
  48939. {
  48940. }
  48941. void ComponentBoundsConstrainer::resizeEnd()
  48942. {
  48943. }
  48944. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48945. const Rectangle<int>& old,
  48946. const Rectangle<int>& limits,
  48947. const bool isStretchingTop,
  48948. const bool isStretchingLeft,
  48949. const bool isStretchingBottom,
  48950. const bool isStretchingRight)
  48951. {
  48952. int x = bounds.getX();
  48953. int y = bounds.getY();
  48954. int w = bounds.getWidth();
  48955. int h = bounds.getHeight();
  48956. // constrain the size if it's being stretched..
  48957. if (isStretchingLeft)
  48958. {
  48959. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48960. w = old.getRight() - x;
  48961. }
  48962. if (isStretchingRight)
  48963. {
  48964. w = jlimit (minW, maxW, w);
  48965. }
  48966. if (isStretchingTop)
  48967. {
  48968. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48969. h = old.getBottom() - y;
  48970. }
  48971. if (isStretchingBottom)
  48972. {
  48973. h = jlimit (minH, maxH, h);
  48974. }
  48975. // constrain the aspect ratio if one has been specified..
  48976. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48977. {
  48978. bool adjustWidth;
  48979. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48980. {
  48981. adjustWidth = true;
  48982. }
  48983. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48984. {
  48985. adjustWidth = false;
  48986. }
  48987. else
  48988. {
  48989. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48990. const double newRatio = std::abs (w / (double) h);
  48991. adjustWidth = (oldRatio > newRatio);
  48992. }
  48993. if (adjustWidth)
  48994. {
  48995. w = roundToInt (h * aspectRatio);
  48996. if (w > maxW || w < minW)
  48997. {
  48998. w = jlimit (minW, maxW, w);
  48999. h = roundToInt (w / aspectRatio);
  49000. }
  49001. }
  49002. else
  49003. {
  49004. h = roundToInt (w / aspectRatio);
  49005. if (h > maxH || h < minH)
  49006. {
  49007. h = jlimit (minH, maxH, h);
  49008. w = roundToInt (h * aspectRatio);
  49009. }
  49010. }
  49011. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49012. {
  49013. x = old.getX() + (old.getWidth() - w) / 2;
  49014. }
  49015. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49016. {
  49017. y = old.getY() + (old.getHeight() - h) / 2;
  49018. }
  49019. else
  49020. {
  49021. if (isStretchingLeft)
  49022. x = old.getRight() - w;
  49023. if (isStretchingTop)
  49024. y = old.getBottom() - h;
  49025. }
  49026. }
  49027. // ...and constrain the position if limits have been set for that.
  49028. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49029. {
  49030. if (minOffTop > 0)
  49031. {
  49032. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49033. if (y < limit)
  49034. {
  49035. if (isStretchingTop)
  49036. h -= (limit - y);
  49037. y = limit;
  49038. }
  49039. }
  49040. if (minOffLeft > 0)
  49041. {
  49042. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49043. if (x < limit)
  49044. {
  49045. if (isStretchingLeft)
  49046. w -= (limit - x);
  49047. x = limit;
  49048. }
  49049. }
  49050. if (minOffBottom > 0)
  49051. {
  49052. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49053. if (y > limit)
  49054. {
  49055. if (isStretchingBottom)
  49056. h += (limit - y);
  49057. else
  49058. y = limit;
  49059. }
  49060. }
  49061. if (minOffRight > 0)
  49062. {
  49063. const int limit = limits.getRight() - jmin (minOffRight, w);
  49064. if (x > limit)
  49065. {
  49066. if (isStretchingRight)
  49067. w += (limit - x);
  49068. else
  49069. x = limit;
  49070. }
  49071. }
  49072. }
  49073. jassert (w >= 0 && h >= 0);
  49074. bounds = Rectangle<int> (x, y, w, h);
  49075. }
  49076. END_JUCE_NAMESPACE
  49077. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49078. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49079. BEGIN_JUCE_NAMESPACE
  49080. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49081. : component (component_),
  49082. lastPeer (0),
  49083. reentrant (false)
  49084. {
  49085. jassert (component != 0); // can't use this with a null pointer..
  49086. component->addComponentListener (this);
  49087. registerWithParentComps();
  49088. }
  49089. ComponentMovementWatcher::~ComponentMovementWatcher()
  49090. {
  49091. component->removeComponentListener (this);
  49092. unregister();
  49093. }
  49094. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49095. {
  49096. // agh! don't delete the target component without deleting this object first!
  49097. jassert (component != 0);
  49098. if (! reentrant)
  49099. {
  49100. reentrant = true;
  49101. ComponentPeer* const peer = component->getPeer();
  49102. if (peer != lastPeer)
  49103. {
  49104. componentPeerChanged();
  49105. if (component == 0)
  49106. return;
  49107. lastPeer = peer;
  49108. }
  49109. unregister();
  49110. registerWithParentComps();
  49111. reentrant = false;
  49112. componentMovedOrResized (*component, true, true);
  49113. }
  49114. }
  49115. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49116. {
  49117. // agh! don't delete the target component without deleting this object first!
  49118. jassert (component != 0);
  49119. if (wasMoved)
  49120. {
  49121. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49122. wasMoved = lastBounds.getPosition() != pos;
  49123. lastBounds.setPosition (pos);
  49124. }
  49125. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49126. lastBounds.setSize (component->getWidth(), component->getHeight());
  49127. if (wasMoved || wasResized)
  49128. componentMovedOrResized (wasMoved, wasResized);
  49129. }
  49130. void ComponentMovementWatcher::registerWithParentComps() throw()
  49131. {
  49132. Component* p = component->getParentComponent();
  49133. while (p != 0)
  49134. {
  49135. p->addComponentListener (this);
  49136. registeredParentComps.add (p);
  49137. p = p->getParentComponent();
  49138. }
  49139. }
  49140. void ComponentMovementWatcher::unregister() throw()
  49141. {
  49142. for (int i = registeredParentComps.size(); --i >= 0;)
  49143. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49144. registeredParentComps.clear();
  49145. }
  49146. END_JUCE_NAMESPACE
  49147. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49148. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49149. BEGIN_JUCE_NAMESPACE
  49150. GroupComponent::GroupComponent (const String& componentName,
  49151. const String& labelText)
  49152. : Component (componentName),
  49153. text (labelText),
  49154. justification (Justification::left)
  49155. {
  49156. setInterceptsMouseClicks (false, true);
  49157. }
  49158. GroupComponent::~GroupComponent()
  49159. {
  49160. }
  49161. void GroupComponent::setText (const String& newText)
  49162. {
  49163. if (text != newText)
  49164. {
  49165. text = newText;
  49166. repaint();
  49167. }
  49168. }
  49169. const String GroupComponent::getText() const
  49170. {
  49171. return text;
  49172. }
  49173. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49174. {
  49175. if (justification != newJustification)
  49176. {
  49177. justification = newJustification;
  49178. repaint();
  49179. }
  49180. }
  49181. void GroupComponent::paint (Graphics& g)
  49182. {
  49183. getLookAndFeel()
  49184. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49185. text, justification,
  49186. *this);
  49187. }
  49188. void GroupComponent::enablementChanged()
  49189. {
  49190. repaint();
  49191. }
  49192. void GroupComponent::colourChanged()
  49193. {
  49194. repaint();
  49195. }
  49196. END_JUCE_NAMESPACE
  49197. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49198. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49199. BEGIN_JUCE_NAMESPACE
  49200. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49201. : DocumentWindow (String::empty, backgroundColour,
  49202. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49203. {
  49204. }
  49205. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49206. {
  49207. }
  49208. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49209. {
  49210. MultiDocumentPanel* const owner = getOwner();
  49211. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49212. if (owner != 0)
  49213. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49214. }
  49215. void MultiDocumentPanelWindow::closeButtonPressed()
  49216. {
  49217. MultiDocumentPanel* const owner = getOwner();
  49218. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49219. if (owner != 0)
  49220. owner->closeDocument (getContentComponent(), true);
  49221. }
  49222. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49223. {
  49224. DocumentWindow::activeWindowStatusChanged();
  49225. updateOrder();
  49226. }
  49227. void MultiDocumentPanelWindow::broughtToFront()
  49228. {
  49229. DocumentWindow::broughtToFront();
  49230. updateOrder();
  49231. }
  49232. void MultiDocumentPanelWindow::updateOrder()
  49233. {
  49234. MultiDocumentPanel* const owner = getOwner();
  49235. if (owner != 0)
  49236. owner->updateOrder();
  49237. }
  49238. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49239. {
  49240. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49241. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49242. }
  49243. class MDITabbedComponentInternal : public TabbedComponent
  49244. {
  49245. public:
  49246. MDITabbedComponentInternal()
  49247. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49248. {
  49249. }
  49250. ~MDITabbedComponentInternal()
  49251. {
  49252. }
  49253. void currentTabChanged (int, const String&)
  49254. {
  49255. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49256. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49257. if (owner != 0)
  49258. owner->updateOrder();
  49259. }
  49260. };
  49261. MultiDocumentPanel::MultiDocumentPanel()
  49262. : mode (MaximisedWindowsWithTabs),
  49263. tabComponent (0),
  49264. backgroundColour (Colours::lightblue),
  49265. maximumNumDocuments (0),
  49266. numDocsBeforeTabsUsed (0)
  49267. {
  49268. setOpaque (true);
  49269. }
  49270. MultiDocumentPanel::~MultiDocumentPanel()
  49271. {
  49272. closeAllDocuments (false);
  49273. }
  49274. static bool shouldDeleteComp (Component* const c)
  49275. {
  49276. return c->getProperties() ["mdiDocumentDelete_"];
  49277. }
  49278. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49279. {
  49280. while (components.size() > 0)
  49281. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49282. return false;
  49283. return true;
  49284. }
  49285. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49286. {
  49287. return new MultiDocumentPanelWindow (backgroundColour);
  49288. }
  49289. void MultiDocumentPanel::addWindow (Component* component)
  49290. {
  49291. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49292. dw->setResizable (true, false);
  49293. dw->setContentComponent (component, false, true);
  49294. dw->setName (component->getName());
  49295. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49296. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49297. int x = 4;
  49298. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49299. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49300. x += 16;
  49301. dw->setTopLeftPosition (x, x);
  49302. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49303. if (pos.toString().isNotEmpty())
  49304. dw->restoreWindowStateFromString (pos.toString());
  49305. addAndMakeVisible (dw);
  49306. dw->toFront (true);
  49307. }
  49308. bool MultiDocumentPanel::addDocument (Component* const component,
  49309. const Colour& docColour,
  49310. const bool deleteWhenRemoved)
  49311. {
  49312. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49313. // with a frame-within-a-frame! Just pass in the bare content component.
  49314. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49315. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49316. return false;
  49317. components.add (component);
  49318. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49319. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49320. component->addComponentListener (this);
  49321. if (mode == FloatingWindows)
  49322. {
  49323. if (isFullscreenWhenOneDocument())
  49324. {
  49325. if (components.size() == 1)
  49326. {
  49327. addAndMakeVisible (component);
  49328. }
  49329. else
  49330. {
  49331. if (components.size() == 2)
  49332. addWindow (components.getFirst());
  49333. addWindow (component);
  49334. }
  49335. }
  49336. else
  49337. {
  49338. addWindow (component);
  49339. }
  49340. }
  49341. else
  49342. {
  49343. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49344. {
  49345. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49346. Array <Component*> temp (components);
  49347. for (int i = 0; i < temp.size(); ++i)
  49348. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49349. resized();
  49350. }
  49351. else
  49352. {
  49353. if (tabComponent != 0)
  49354. tabComponent->addTab (component->getName(), docColour, component, false);
  49355. else
  49356. addAndMakeVisible (component);
  49357. }
  49358. setActiveDocument (component);
  49359. }
  49360. resized();
  49361. activeDocumentChanged();
  49362. return true;
  49363. }
  49364. bool MultiDocumentPanel::closeDocument (Component* component,
  49365. const bool checkItsOkToCloseFirst)
  49366. {
  49367. if (components.contains (component))
  49368. {
  49369. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49370. return false;
  49371. component->removeComponentListener (this);
  49372. const bool shouldDelete = shouldDeleteComp (component);
  49373. component->getProperties().remove ("mdiDocumentDelete_");
  49374. component->getProperties().remove ("mdiDocumentBkg_");
  49375. if (mode == FloatingWindows)
  49376. {
  49377. for (int i = getNumChildComponents(); --i >= 0;)
  49378. {
  49379. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49380. if (dw != 0 && dw->getContentComponent() == component)
  49381. {
  49382. dw->setContentComponent (0, false);
  49383. delete dw;
  49384. break;
  49385. }
  49386. }
  49387. if (shouldDelete)
  49388. delete component;
  49389. components.removeValue (component);
  49390. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49391. {
  49392. for (int i = getNumChildComponents(); --i >= 0;)
  49393. {
  49394. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49395. if (dw != 0)
  49396. {
  49397. dw->setContentComponent (0, false);
  49398. delete dw;
  49399. }
  49400. }
  49401. addAndMakeVisible (components.getFirst());
  49402. }
  49403. }
  49404. else
  49405. {
  49406. jassert (components.indexOf (component) >= 0);
  49407. if (tabComponent != 0)
  49408. {
  49409. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49410. if (tabComponent->getTabContentComponent (i) == component)
  49411. tabComponent->removeTab (i);
  49412. }
  49413. else
  49414. {
  49415. removeChildComponent (component);
  49416. }
  49417. if (shouldDelete)
  49418. delete component;
  49419. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49420. deleteAndZero (tabComponent);
  49421. components.removeValue (component);
  49422. if (components.size() > 0 && tabComponent == 0)
  49423. addAndMakeVisible (components.getFirst());
  49424. }
  49425. resized();
  49426. activeDocumentChanged();
  49427. }
  49428. else
  49429. {
  49430. jassertfalse;
  49431. }
  49432. return true;
  49433. }
  49434. int MultiDocumentPanel::getNumDocuments() const throw()
  49435. {
  49436. return components.size();
  49437. }
  49438. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49439. {
  49440. return components [index];
  49441. }
  49442. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49443. {
  49444. if (mode == FloatingWindows)
  49445. {
  49446. for (int i = getNumChildComponents(); --i >= 0;)
  49447. {
  49448. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49449. if (dw != 0 && dw->isActiveWindow())
  49450. return dw->getContentComponent();
  49451. }
  49452. }
  49453. return components.getLast();
  49454. }
  49455. void MultiDocumentPanel::setActiveDocument (Component* component)
  49456. {
  49457. if (mode == FloatingWindows)
  49458. {
  49459. component = getContainerComp (component);
  49460. if (component != 0)
  49461. component->toFront (true);
  49462. }
  49463. else if (tabComponent != 0)
  49464. {
  49465. jassert (components.indexOf (component) >= 0);
  49466. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49467. {
  49468. if (tabComponent->getTabContentComponent (i) == component)
  49469. {
  49470. tabComponent->setCurrentTabIndex (i);
  49471. break;
  49472. }
  49473. }
  49474. }
  49475. else
  49476. {
  49477. component->grabKeyboardFocus();
  49478. }
  49479. }
  49480. void MultiDocumentPanel::activeDocumentChanged()
  49481. {
  49482. }
  49483. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49484. {
  49485. maximumNumDocuments = newNumber;
  49486. }
  49487. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49488. {
  49489. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49490. }
  49491. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49492. {
  49493. return numDocsBeforeTabsUsed != 0;
  49494. }
  49495. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49496. {
  49497. if (mode != newLayoutMode)
  49498. {
  49499. mode = newLayoutMode;
  49500. if (mode == FloatingWindows)
  49501. {
  49502. deleteAndZero (tabComponent);
  49503. }
  49504. else
  49505. {
  49506. for (int i = getNumChildComponents(); --i >= 0;)
  49507. {
  49508. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49509. if (dw != 0)
  49510. {
  49511. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49512. dw->setContentComponent (0, false);
  49513. delete dw;
  49514. }
  49515. }
  49516. }
  49517. resized();
  49518. const Array <Component*> tempComps (components);
  49519. components.clear();
  49520. for (int i = 0; i < tempComps.size(); ++i)
  49521. {
  49522. Component* const c = tempComps.getUnchecked(i);
  49523. addDocument (c,
  49524. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49525. shouldDeleteComp (c));
  49526. }
  49527. }
  49528. }
  49529. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49530. {
  49531. if (backgroundColour != newBackgroundColour)
  49532. {
  49533. backgroundColour = newBackgroundColour;
  49534. setOpaque (newBackgroundColour.isOpaque());
  49535. repaint();
  49536. }
  49537. }
  49538. void MultiDocumentPanel::paint (Graphics& g)
  49539. {
  49540. g.fillAll (backgroundColour);
  49541. }
  49542. void MultiDocumentPanel::resized()
  49543. {
  49544. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49545. {
  49546. for (int i = getNumChildComponents(); --i >= 0;)
  49547. getChildComponent (i)->setBounds (getLocalBounds());
  49548. }
  49549. setWantsKeyboardFocus (components.size() == 0);
  49550. }
  49551. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49552. {
  49553. if (mode == FloatingWindows)
  49554. {
  49555. for (int i = 0; i < getNumChildComponents(); ++i)
  49556. {
  49557. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49558. if (dw != 0 && dw->getContentComponent() == c)
  49559. {
  49560. c = dw;
  49561. break;
  49562. }
  49563. }
  49564. }
  49565. return c;
  49566. }
  49567. void MultiDocumentPanel::componentNameChanged (Component&)
  49568. {
  49569. if (mode == FloatingWindows)
  49570. {
  49571. for (int i = 0; i < getNumChildComponents(); ++i)
  49572. {
  49573. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49574. if (dw != 0)
  49575. dw->setName (dw->getContentComponent()->getName());
  49576. }
  49577. }
  49578. else if (tabComponent != 0)
  49579. {
  49580. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49581. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49582. }
  49583. }
  49584. void MultiDocumentPanel::updateOrder()
  49585. {
  49586. const Array <Component*> oldList (components);
  49587. if (mode == FloatingWindows)
  49588. {
  49589. components.clear();
  49590. for (int i = 0; i < getNumChildComponents(); ++i)
  49591. {
  49592. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49593. if (dw != 0)
  49594. components.add (dw->getContentComponent());
  49595. }
  49596. }
  49597. else
  49598. {
  49599. if (tabComponent != 0)
  49600. {
  49601. Component* const current = tabComponent->getCurrentContentComponent();
  49602. if (current != 0)
  49603. {
  49604. components.removeValue (current);
  49605. components.add (current);
  49606. }
  49607. }
  49608. }
  49609. if (components != oldList)
  49610. activeDocumentChanged();
  49611. }
  49612. END_JUCE_NAMESPACE
  49613. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49614. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49615. BEGIN_JUCE_NAMESPACE
  49616. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49617. : zone (zoneFlags)
  49618. {
  49619. }
  49620. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49621. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49622. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49623. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49624. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49625. const BorderSize& border,
  49626. const Point<int>& position)
  49627. {
  49628. int z = 0;
  49629. if (totalSize.contains (position)
  49630. && ! border.subtractedFrom (totalSize).contains (position))
  49631. {
  49632. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49633. if (position.getX() < jmax (border.getLeft(), minW))
  49634. z |= left;
  49635. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49636. z |= right;
  49637. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49638. if (position.getY() < jmax (border.getTop(), minH))
  49639. z |= top;
  49640. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49641. z |= bottom;
  49642. }
  49643. return Zone (z);
  49644. }
  49645. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49646. {
  49647. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49648. switch (zone)
  49649. {
  49650. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49651. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49652. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49653. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49654. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49655. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49656. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49657. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49658. default: break;
  49659. }
  49660. return mc;
  49661. }
  49662. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49663. {
  49664. if (isDraggingWholeObject())
  49665. return b + offset;
  49666. if (isDraggingLeftEdge())
  49667. b.setLeft (b.getX() + offset.getX());
  49668. if (isDraggingRightEdge())
  49669. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49670. if (isDraggingTopEdge())
  49671. b.setTop (b.getY() + offset.getY());
  49672. if (isDraggingBottomEdge())
  49673. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49674. return b;
  49675. }
  49676. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49677. {
  49678. if (isDraggingWholeObject())
  49679. return b + offset;
  49680. if (isDraggingLeftEdge())
  49681. b.setLeft (b.getX() + offset.getX());
  49682. if (isDraggingRightEdge())
  49683. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49684. if (isDraggingTopEdge())
  49685. b.setTop (b.getY() + offset.getY());
  49686. if (isDraggingBottomEdge())
  49687. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49688. return b;
  49689. }
  49690. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49691. ComponentBoundsConstrainer* const constrainer_)
  49692. : component (componentToResize),
  49693. constrainer (constrainer_),
  49694. borderSize (5),
  49695. mouseZone (0)
  49696. {
  49697. }
  49698. ResizableBorderComponent::~ResizableBorderComponent()
  49699. {
  49700. }
  49701. void ResizableBorderComponent::paint (Graphics& g)
  49702. {
  49703. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49704. }
  49705. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49706. {
  49707. updateMouseZone (e);
  49708. }
  49709. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49710. {
  49711. updateMouseZone (e);
  49712. }
  49713. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49714. {
  49715. if (component == 0)
  49716. {
  49717. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49718. return;
  49719. }
  49720. updateMouseZone (e);
  49721. originalBounds = component->getBounds();
  49722. if (constrainer != 0)
  49723. constrainer->resizeStart();
  49724. }
  49725. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49726. {
  49727. if (component == 0)
  49728. {
  49729. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49730. return;
  49731. }
  49732. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49733. if (constrainer != 0)
  49734. constrainer->setBoundsForComponent (component, bounds,
  49735. mouseZone.isDraggingTopEdge(),
  49736. mouseZone.isDraggingLeftEdge(),
  49737. mouseZone.isDraggingBottomEdge(),
  49738. mouseZone.isDraggingRightEdge());
  49739. else
  49740. component->setBounds (bounds);
  49741. }
  49742. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49743. {
  49744. if (constrainer != 0)
  49745. constrainer->resizeEnd();
  49746. }
  49747. bool ResizableBorderComponent::hitTest (int x, int y)
  49748. {
  49749. return x < borderSize.getLeft()
  49750. || x >= getWidth() - borderSize.getRight()
  49751. || y < borderSize.getTop()
  49752. || y >= getHeight() - borderSize.getBottom();
  49753. }
  49754. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49755. {
  49756. if (borderSize != newBorderSize)
  49757. {
  49758. borderSize = newBorderSize;
  49759. repaint();
  49760. }
  49761. }
  49762. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49763. {
  49764. return borderSize;
  49765. }
  49766. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49767. {
  49768. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49769. if (mouseZone != newZone)
  49770. {
  49771. mouseZone = newZone;
  49772. setMouseCursor (newZone.getMouseCursor());
  49773. }
  49774. }
  49775. END_JUCE_NAMESPACE
  49776. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49777. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49778. BEGIN_JUCE_NAMESPACE
  49779. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49780. ComponentBoundsConstrainer* const constrainer_)
  49781. : component (componentToResize),
  49782. constrainer (constrainer_)
  49783. {
  49784. setRepaintsOnMouseActivity (true);
  49785. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49786. }
  49787. ResizableCornerComponent::~ResizableCornerComponent()
  49788. {
  49789. }
  49790. void ResizableCornerComponent::paint (Graphics& g)
  49791. {
  49792. getLookAndFeel()
  49793. .drawCornerResizer (g, getWidth(), getHeight(),
  49794. isMouseOverOrDragging(),
  49795. isMouseButtonDown());
  49796. }
  49797. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49798. {
  49799. if (component == 0)
  49800. {
  49801. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49802. return;
  49803. }
  49804. originalBounds = component->getBounds();
  49805. if (constrainer != 0)
  49806. constrainer->resizeStart();
  49807. }
  49808. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49809. {
  49810. if (component == 0)
  49811. {
  49812. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49813. return;
  49814. }
  49815. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49816. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49817. if (constrainer != 0)
  49818. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49819. else
  49820. component->setBounds (r);
  49821. }
  49822. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49823. {
  49824. if (constrainer != 0)
  49825. constrainer->resizeStart();
  49826. }
  49827. bool ResizableCornerComponent::hitTest (int x, int y)
  49828. {
  49829. if (getWidth() <= 0)
  49830. return false;
  49831. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49832. return y >= yAtX - getHeight() / 4;
  49833. }
  49834. END_JUCE_NAMESPACE
  49835. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49836. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49837. BEGIN_JUCE_NAMESPACE
  49838. class ScrollBar::ScrollbarButton : public Button
  49839. {
  49840. public:
  49841. int direction;
  49842. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49843. : Button (String::empty),
  49844. direction (direction_),
  49845. owner (owner_)
  49846. {
  49847. setWantsKeyboardFocus (false);
  49848. }
  49849. ~ScrollbarButton()
  49850. {
  49851. }
  49852. void paintButton (Graphics& g, bool over, bool down)
  49853. {
  49854. getLookAndFeel()
  49855. .drawScrollbarButton (g, owner,
  49856. getWidth(), getHeight(),
  49857. direction,
  49858. owner.isVertical(),
  49859. over, down);
  49860. }
  49861. void clicked()
  49862. {
  49863. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49864. }
  49865. juce_UseDebuggingNewOperator
  49866. private:
  49867. ScrollBar& owner;
  49868. ScrollbarButton (const ScrollbarButton&);
  49869. ScrollbarButton& operator= (const ScrollbarButton&);
  49870. };
  49871. ScrollBar::ScrollBar (const bool vertical_,
  49872. const bool buttonsAreVisible)
  49873. : totalRange (0.0, 1.0),
  49874. visibleRange (0.0, 0.1),
  49875. singleStepSize (0.1),
  49876. thumbAreaStart (0),
  49877. thumbAreaSize (0),
  49878. thumbStart (0),
  49879. thumbSize (0),
  49880. initialDelayInMillisecs (100),
  49881. repeatDelayInMillisecs (50),
  49882. minimumDelayInMillisecs (10),
  49883. vertical (vertical_),
  49884. isDraggingThumb (false),
  49885. autohides (true)
  49886. {
  49887. setButtonVisibility (buttonsAreVisible);
  49888. setRepaintsOnMouseActivity (true);
  49889. setFocusContainer (true);
  49890. }
  49891. ScrollBar::~ScrollBar()
  49892. {
  49893. upButton = 0;
  49894. downButton = 0;
  49895. }
  49896. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49897. {
  49898. if (totalRange != newRangeLimit)
  49899. {
  49900. totalRange = newRangeLimit;
  49901. setCurrentRange (visibleRange);
  49902. updateThumbPosition();
  49903. }
  49904. }
  49905. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49906. {
  49907. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49908. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49909. }
  49910. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49911. {
  49912. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49913. if (visibleRange != constrainedRange)
  49914. {
  49915. visibleRange = constrainedRange;
  49916. updateThumbPosition();
  49917. triggerAsyncUpdate();
  49918. }
  49919. }
  49920. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49921. {
  49922. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49923. }
  49924. void ScrollBar::setCurrentRangeStart (const double newStart)
  49925. {
  49926. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49927. }
  49928. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49929. {
  49930. singleStepSize = newSingleStepSize;
  49931. }
  49932. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49933. {
  49934. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49935. }
  49936. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49937. {
  49938. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49939. }
  49940. void ScrollBar::scrollToTop()
  49941. {
  49942. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49943. }
  49944. void ScrollBar::scrollToBottom()
  49945. {
  49946. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49947. }
  49948. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49949. const int repeatDelayInMillisecs_,
  49950. const int minimumDelayInMillisecs_)
  49951. {
  49952. initialDelayInMillisecs = initialDelayInMillisecs_;
  49953. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49954. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49955. if (upButton != 0)
  49956. {
  49957. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49958. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49959. }
  49960. }
  49961. void ScrollBar::addListener (ScrollBarListener* const listener)
  49962. {
  49963. listeners.add (listener);
  49964. }
  49965. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49966. {
  49967. listeners.remove (listener);
  49968. }
  49969. void ScrollBar::handleAsyncUpdate()
  49970. {
  49971. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49972. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49973. }
  49974. void ScrollBar::updateThumbPosition()
  49975. {
  49976. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49977. : thumbAreaSize);
  49978. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49979. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49980. if (newThumbSize > thumbAreaSize)
  49981. newThumbSize = thumbAreaSize;
  49982. int newThumbStart = thumbAreaStart;
  49983. if (totalRange.getLength() > visibleRange.getLength())
  49984. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49985. / (totalRange.getLength() - visibleRange.getLength()));
  49986. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49987. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49988. {
  49989. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49990. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49991. if (vertical)
  49992. repaint (0, repaintStart, getWidth(), repaintSize);
  49993. else
  49994. repaint (repaintStart, 0, repaintSize, getHeight());
  49995. thumbStart = newThumbStart;
  49996. thumbSize = newThumbSize;
  49997. }
  49998. }
  49999. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50000. {
  50001. if (vertical != shouldBeVertical)
  50002. {
  50003. vertical = shouldBeVertical;
  50004. if (upButton != 0)
  50005. {
  50006. upButton->direction = vertical ? 0 : 3;
  50007. downButton->direction = vertical ? 2 : 1;
  50008. }
  50009. updateThumbPosition();
  50010. }
  50011. }
  50012. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50013. {
  50014. upButton = 0;
  50015. downButton = 0;
  50016. if (buttonsAreVisible)
  50017. {
  50018. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50019. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50020. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50021. }
  50022. updateThumbPosition();
  50023. }
  50024. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50025. {
  50026. autohides = shouldHideWhenFullRange;
  50027. updateThumbPosition();
  50028. }
  50029. bool ScrollBar::autoHides() const throw()
  50030. {
  50031. return autohides;
  50032. }
  50033. void ScrollBar::paint (Graphics& g)
  50034. {
  50035. if (thumbAreaSize > 0)
  50036. {
  50037. LookAndFeel& lf = getLookAndFeel();
  50038. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50039. ? thumbSize : 0;
  50040. if (vertical)
  50041. {
  50042. lf.drawScrollbar (g, *this,
  50043. 0, thumbAreaStart,
  50044. getWidth(), thumbAreaSize,
  50045. vertical,
  50046. thumbStart, thumb,
  50047. isMouseOver(), isMouseButtonDown());
  50048. }
  50049. else
  50050. {
  50051. lf.drawScrollbar (g, *this,
  50052. thumbAreaStart, 0,
  50053. thumbAreaSize, getHeight(),
  50054. vertical,
  50055. thumbStart, thumb,
  50056. isMouseOver(), isMouseButtonDown());
  50057. }
  50058. }
  50059. }
  50060. void ScrollBar::lookAndFeelChanged()
  50061. {
  50062. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50063. }
  50064. void ScrollBar::resized()
  50065. {
  50066. const int length = ((vertical) ? getHeight() : getWidth());
  50067. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50068. : 0;
  50069. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50070. {
  50071. thumbAreaStart = length >> 1;
  50072. thumbAreaSize = 0;
  50073. }
  50074. else
  50075. {
  50076. thumbAreaStart = buttonSize;
  50077. thumbAreaSize = length - (buttonSize << 1);
  50078. }
  50079. if (upButton != 0)
  50080. {
  50081. if (vertical)
  50082. {
  50083. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50084. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50085. }
  50086. else
  50087. {
  50088. upButton->setBounds (0, 0, buttonSize, getHeight());
  50089. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50090. }
  50091. }
  50092. updateThumbPosition();
  50093. }
  50094. void ScrollBar::mouseDown (const MouseEvent& e)
  50095. {
  50096. isDraggingThumb = false;
  50097. lastMousePos = vertical ? e.y : e.x;
  50098. dragStartMousePos = lastMousePos;
  50099. dragStartRange = visibleRange.getStart();
  50100. if (dragStartMousePos < thumbStart)
  50101. {
  50102. moveScrollbarInPages (-1);
  50103. startTimer (400);
  50104. }
  50105. else if (dragStartMousePos >= thumbStart + thumbSize)
  50106. {
  50107. moveScrollbarInPages (1);
  50108. startTimer (400);
  50109. }
  50110. else
  50111. {
  50112. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50113. && (thumbAreaSize > thumbSize);
  50114. }
  50115. }
  50116. void ScrollBar::mouseDrag (const MouseEvent& e)
  50117. {
  50118. if (isDraggingThumb)
  50119. {
  50120. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50121. setCurrentRangeStart (dragStartRange
  50122. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50123. / (thumbAreaSize - thumbSize));
  50124. }
  50125. else
  50126. {
  50127. lastMousePos = (vertical) ? e.y : e.x;
  50128. }
  50129. }
  50130. void ScrollBar::mouseUp (const MouseEvent&)
  50131. {
  50132. isDraggingThumb = false;
  50133. stopTimer();
  50134. repaint();
  50135. }
  50136. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50137. float wheelIncrementX,
  50138. float wheelIncrementY)
  50139. {
  50140. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50141. if (increment < 0)
  50142. increment = jmin (increment * 10.0f, -1.0f);
  50143. else if (increment > 0)
  50144. increment = jmax (increment * 10.0f, 1.0f);
  50145. setCurrentRange (visibleRange - singleStepSize * increment);
  50146. }
  50147. void ScrollBar::timerCallback()
  50148. {
  50149. if (isMouseButtonDown())
  50150. {
  50151. startTimer (40);
  50152. if (lastMousePos < thumbStart)
  50153. setCurrentRange (visibleRange - visibleRange.getLength());
  50154. else if (lastMousePos > thumbStart + thumbSize)
  50155. setCurrentRangeStart (visibleRange.getEnd());
  50156. }
  50157. else
  50158. {
  50159. stopTimer();
  50160. }
  50161. }
  50162. bool ScrollBar::keyPressed (const KeyPress& key)
  50163. {
  50164. if (! isVisible())
  50165. return false;
  50166. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50167. moveScrollbarInSteps (-1);
  50168. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50169. moveScrollbarInSteps (1);
  50170. else if (key.isKeyCode (KeyPress::pageUpKey))
  50171. moveScrollbarInPages (-1);
  50172. else if (key.isKeyCode (KeyPress::pageDownKey))
  50173. moveScrollbarInPages (1);
  50174. else if (key.isKeyCode (KeyPress::homeKey))
  50175. scrollToTop();
  50176. else if (key.isKeyCode (KeyPress::endKey))
  50177. scrollToBottom();
  50178. else
  50179. return false;
  50180. return true;
  50181. }
  50182. END_JUCE_NAMESPACE
  50183. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50184. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50185. BEGIN_JUCE_NAMESPACE
  50186. StretchableLayoutManager::StretchableLayoutManager()
  50187. : totalSize (0)
  50188. {
  50189. }
  50190. StretchableLayoutManager::~StretchableLayoutManager()
  50191. {
  50192. }
  50193. void StretchableLayoutManager::clearAllItems()
  50194. {
  50195. items.clear();
  50196. totalSize = 0;
  50197. }
  50198. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50199. const double minimumSize,
  50200. const double maximumSize,
  50201. const double preferredSize)
  50202. {
  50203. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50204. if (layout == 0)
  50205. {
  50206. layout = new ItemLayoutProperties();
  50207. layout->itemIndex = itemIndex;
  50208. int i;
  50209. for (i = 0; i < items.size(); ++i)
  50210. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50211. break;
  50212. items.insert (i, layout);
  50213. }
  50214. layout->minSize = minimumSize;
  50215. layout->maxSize = maximumSize;
  50216. layout->preferredSize = preferredSize;
  50217. layout->currentSize = 0;
  50218. }
  50219. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50220. double& minimumSize,
  50221. double& maximumSize,
  50222. double& preferredSize) const
  50223. {
  50224. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50225. if (layout != 0)
  50226. {
  50227. minimumSize = layout->minSize;
  50228. maximumSize = layout->maxSize;
  50229. preferredSize = layout->preferredSize;
  50230. return true;
  50231. }
  50232. return false;
  50233. }
  50234. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50235. {
  50236. totalSize = newTotalSize;
  50237. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50238. }
  50239. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50240. {
  50241. int pos = 0;
  50242. for (int i = 0; i < itemIndex; ++i)
  50243. {
  50244. const ItemLayoutProperties* const layout = getInfoFor (i);
  50245. if (layout != 0)
  50246. pos += layout->currentSize;
  50247. }
  50248. return pos;
  50249. }
  50250. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50251. {
  50252. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50253. if (layout != 0)
  50254. return layout->currentSize;
  50255. return 0;
  50256. }
  50257. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50258. {
  50259. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50260. if (layout != 0)
  50261. return -layout->currentSize / (double) totalSize;
  50262. return 0;
  50263. }
  50264. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50265. int newPosition)
  50266. {
  50267. for (int i = items.size(); --i >= 0;)
  50268. {
  50269. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50270. if (layout->itemIndex == itemIndex)
  50271. {
  50272. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50273. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50274. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50275. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50276. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50277. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50278. endPos += layout->currentSize;
  50279. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50280. updatePrefSizesToMatchCurrentPositions();
  50281. break;
  50282. }
  50283. }
  50284. }
  50285. void StretchableLayoutManager::layOutComponents (Component** const components,
  50286. int numComponents,
  50287. int x, int y, int w, int h,
  50288. const bool vertically,
  50289. const bool resizeOtherDimension)
  50290. {
  50291. setTotalSize (vertically ? h : w);
  50292. int pos = vertically ? y : x;
  50293. for (int i = 0; i < numComponents; ++i)
  50294. {
  50295. const ItemLayoutProperties* const layout = getInfoFor (i);
  50296. if (layout != 0)
  50297. {
  50298. Component* const c = components[i];
  50299. if (c != 0)
  50300. {
  50301. if (i == numComponents - 1)
  50302. {
  50303. // if it's the last item, crop it to exactly fit the available space..
  50304. if (resizeOtherDimension)
  50305. {
  50306. if (vertically)
  50307. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50308. else
  50309. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50310. }
  50311. else
  50312. {
  50313. if (vertically)
  50314. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50315. else
  50316. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50317. }
  50318. }
  50319. else
  50320. {
  50321. if (resizeOtherDimension)
  50322. {
  50323. if (vertically)
  50324. c->setBounds (x, pos, w, layout->currentSize);
  50325. else
  50326. c->setBounds (pos, y, layout->currentSize, h);
  50327. }
  50328. else
  50329. {
  50330. if (vertically)
  50331. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50332. else
  50333. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50334. }
  50335. }
  50336. }
  50337. pos += layout->currentSize;
  50338. }
  50339. }
  50340. }
  50341. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50342. {
  50343. for (int i = items.size(); --i >= 0;)
  50344. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50345. return items.getUnchecked(i);
  50346. return 0;
  50347. }
  50348. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50349. const int endIndex,
  50350. const int availableSpace,
  50351. int startPos)
  50352. {
  50353. // calculate the total sizes
  50354. int i;
  50355. double totalIdealSize = 0.0;
  50356. int totalMinimums = 0;
  50357. for (i = startIndex; i < endIndex; ++i)
  50358. {
  50359. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50360. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50361. totalMinimums += layout->currentSize;
  50362. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50363. }
  50364. if (totalIdealSize <= 0)
  50365. totalIdealSize = 1.0;
  50366. // now calc the best sizes..
  50367. int extraSpace = availableSpace - totalMinimums;
  50368. while (extraSpace > 0)
  50369. {
  50370. int numWantingMoreSpace = 0;
  50371. int numHavingTakenExtraSpace = 0;
  50372. // first figure out how many comps want a slice of the extra space..
  50373. for (i = startIndex; i < endIndex; ++i)
  50374. {
  50375. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50376. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50377. const int bestSize = jlimit (layout->currentSize,
  50378. jmax (layout->currentSize,
  50379. sizeToRealSize (layout->maxSize, totalSize)),
  50380. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50381. if (bestSize > layout->currentSize)
  50382. ++numWantingMoreSpace;
  50383. }
  50384. // ..share out the extra space..
  50385. for (i = startIndex; i < endIndex; ++i)
  50386. {
  50387. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50388. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50389. int bestSize = jlimit (layout->currentSize,
  50390. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50391. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50392. const int extraWanted = bestSize - layout->currentSize;
  50393. if (extraWanted > 0)
  50394. {
  50395. const int extraAllowed = jmin (extraWanted,
  50396. extraSpace / jmax (1, numWantingMoreSpace));
  50397. if (extraAllowed > 0)
  50398. {
  50399. ++numHavingTakenExtraSpace;
  50400. --numWantingMoreSpace;
  50401. layout->currentSize += extraAllowed;
  50402. extraSpace -= extraAllowed;
  50403. }
  50404. }
  50405. }
  50406. if (numHavingTakenExtraSpace <= 0)
  50407. break;
  50408. }
  50409. // ..and calculate the end position
  50410. for (i = startIndex; i < endIndex; ++i)
  50411. {
  50412. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50413. startPos += layout->currentSize;
  50414. }
  50415. return startPos;
  50416. }
  50417. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50418. const int endIndex) const
  50419. {
  50420. int totalMinimums = 0;
  50421. for (int i = startIndex; i < endIndex; ++i)
  50422. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50423. return totalMinimums;
  50424. }
  50425. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50426. {
  50427. int totalMaximums = 0;
  50428. for (int i = startIndex; i < endIndex; ++i)
  50429. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50430. return totalMaximums;
  50431. }
  50432. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50433. {
  50434. for (int i = 0; i < items.size(); ++i)
  50435. {
  50436. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50437. layout->preferredSize
  50438. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50439. : getItemCurrentAbsoluteSize (i);
  50440. }
  50441. }
  50442. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50443. {
  50444. if (size < 0)
  50445. size *= -totalSpace;
  50446. return roundToInt (size);
  50447. }
  50448. END_JUCE_NAMESPACE
  50449. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50450. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50451. BEGIN_JUCE_NAMESPACE
  50452. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50453. const int itemIndex_,
  50454. const bool isVertical_)
  50455. : layout (layout_),
  50456. itemIndex (itemIndex_),
  50457. isVertical (isVertical_)
  50458. {
  50459. setRepaintsOnMouseActivity (true);
  50460. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50461. : MouseCursor::UpDownResizeCursor));
  50462. }
  50463. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50464. {
  50465. }
  50466. void StretchableLayoutResizerBar::paint (Graphics& g)
  50467. {
  50468. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50469. getWidth(), getHeight(),
  50470. isVertical,
  50471. isMouseOver(),
  50472. isMouseButtonDown());
  50473. }
  50474. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50475. {
  50476. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50477. }
  50478. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50479. {
  50480. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50481. : e.getDistanceFromDragStartY());
  50482. layout->setItemPosition (itemIndex, desiredPos);
  50483. hasBeenMoved();
  50484. }
  50485. void StretchableLayoutResizerBar::hasBeenMoved()
  50486. {
  50487. if (getParentComponent() != 0)
  50488. getParentComponent()->resized();
  50489. }
  50490. END_JUCE_NAMESPACE
  50491. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50492. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50493. BEGIN_JUCE_NAMESPACE
  50494. StretchableObjectResizer::StretchableObjectResizer()
  50495. {
  50496. }
  50497. StretchableObjectResizer::~StretchableObjectResizer()
  50498. {
  50499. }
  50500. void StretchableObjectResizer::addItem (const double size,
  50501. const double minSize, const double maxSize,
  50502. const int order)
  50503. {
  50504. // the order must be >= 0 but less than the maximum integer value.
  50505. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50506. Item* const item = new Item();
  50507. item->size = size;
  50508. item->minSize = minSize;
  50509. item->maxSize = maxSize;
  50510. item->order = order;
  50511. items.add (item);
  50512. }
  50513. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50514. {
  50515. const Item* const it = items [index];
  50516. return it != 0 ? it->size : 0;
  50517. }
  50518. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50519. {
  50520. int order = 0;
  50521. for (;;)
  50522. {
  50523. double currentSize = 0;
  50524. double minSize = 0;
  50525. double maxSize = 0;
  50526. int nextHighestOrder = std::numeric_limits<int>::max();
  50527. for (int i = 0; i < items.size(); ++i)
  50528. {
  50529. const Item* const it = items.getUnchecked(i);
  50530. currentSize += it->size;
  50531. if (it->order <= order)
  50532. {
  50533. minSize += it->minSize;
  50534. maxSize += it->maxSize;
  50535. }
  50536. else
  50537. {
  50538. minSize += it->size;
  50539. maxSize += it->size;
  50540. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50541. }
  50542. }
  50543. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50544. if (thisIterationTarget >= currentSize)
  50545. {
  50546. const double availableExtraSpace = maxSize - currentSize;
  50547. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50548. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50549. for (int i = 0; i < items.size(); ++i)
  50550. {
  50551. Item* const it = items.getUnchecked(i);
  50552. if (it->order <= order)
  50553. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50554. }
  50555. }
  50556. else
  50557. {
  50558. const double amountOfSlack = currentSize - minSize;
  50559. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50560. const double scale = targetAmountOfSlack / amountOfSlack;
  50561. for (int i = 0; i < items.size(); ++i)
  50562. {
  50563. Item* const it = items.getUnchecked(i);
  50564. if (it->order <= order)
  50565. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50566. }
  50567. }
  50568. if (nextHighestOrder < std::numeric_limits<int>::max())
  50569. order = nextHighestOrder;
  50570. else
  50571. break;
  50572. }
  50573. }
  50574. END_JUCE_NAMESPACE
  50575. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50576. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50577. BEGIN_JUCE_NAMESPACE
  50578. TabBarButton::TabBarButton (const String& name,
  50579. TabbedButtonBar* const owner_,
  50580. const int index)
  50581. : Button (name),
  50582. owner (owner_),
  50583. tabIndex (index),
  50584. overlapPixels (0)
  50585. {
  50586. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50587. setComponentEffect (&shadow);
  50588. setWantsKeyboardFocus (false);
  50589. }
  50590. TabBarButton::~TabBarButton()
  50591. {
  50592. }
  50593. void TabBarButton::paintButton (Graphics& g,
  50594. bool isMouseOverButton,
  50595. bool isButtonDown)
  50596. {
  50597. int x, y, w, h;
  50598. getActiveArea (x, y, w, h);
  50599. g.setOrigin (x, y);
  50600. getLookAndFeel()
  50601. .drawTabButton (g, w, h,
  50602. owner->getTabBackgroundColour (tabIndex),
  50603. tabIndex, getButtonText(), *this,
  50604. owner->getOrientation(),
  50605. isMouseOverButton, isButtonDown,
  50606. getToggleState());
  50607. }
  50608. void TabBarButton::clicked (const ModifierKeys& mods)
  50609. {
  50610. if (mods.isPopupMenu())
  50611. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50612. else
  50613. owner->setCurrentTabIndex (tabIndex);
  50614. }
  50615. bool TabBarButton::hitTest (int mx, int my)
  50616. {
  50617. int x, y, w, h;
  50618. getActiveArea (x, y, w, h);
  50619. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50620. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50621. {
  50622. if (((unsigned int) mx) < (unsigned int) getWidth()
  50623. && my >= y + overlapPixels
  50624. && my < y + h - overlapPixels)
  50625. return true;
  50626. }
  50627. else
  50628. {
  50629. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50630. && ((unsigned int) my) < (unsigned int) getHeight())
  50631. return true;
  50632. }
  50633. Path p;
  50634. getLookAndFeel()
  50635. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50636. owner->getOrientation(),
  50637. false, false, getToggleState());
  50638. return p.contains ((float) (mx - x),
  50639. (float) (my - y));
  50640. }
  50641. int TabBarButton::getBestTabLength (const int depth)
  50642. {
  50643. return jlimit (depth * 2,
  50644. depth * 7,
  50645. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50646. }
  50647. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50648. {
  50649. x = 0;
  50650. y = 0;
  50651. int r = getWidth();
  50652. int b = getHeight();
  50653. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50654. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50655. r -= spaceAroundImage;
  50656. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50657. x += spaceAroundImage;
  50658. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50659. y += spaceAroundImage;
  50660. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50661. b -= spaceAroundImage;
  50662. w = r - x;
  50663. h = b - y;
  50664. }
  50665. class TabAreaBehindFrontButtonComponent : public Component
  50666. {
  50667. public:
  50668. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50669. : owner (owner_)
  50670. {
  50671. setInterceptsMouseClicks (false, false);
  50672. }
  50673. ~TabAreaBehindFrontButtonComponent()
  50674. {
  50675. }
  50676. void paint (Graphics& g)
  50677. {
  50678. getLookAndFeel()
  50679. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50680. *owner, owner->getOrientation());
  50681. }
  50682. void enablementChanged()
  50683. {
  50684. repaint();
  50685. }
  50686. private:
  50687. TabbedButtonBar* const owner;
  50688. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50689. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50690. };
  50691. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50692. : orientation (orientation_),
  50693. currentTabIndex (-1)
  50694. {
  50695. setInterceptsMouseClicks (false, true);
  50696. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50697. setFocusContainer (true);
  50698. }
  50699. TabbedButtonBar::~TabbedButtonBar()
  50700. {
  50701. extraTabsButton = 0;
  50702. deleteAllChildren();
  50703. }
  50704. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50705. {
  50706. orientation = newOrientation;
  50707. for (int i = getNumChildComponents(); --i >= 0;)
  50708. getChildComponent (i)->resized();
  50709. resized();
  50710. }
  50711. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50712. {
  50713. return new TabBarButton (name, this, index);
  50714. }
  50715. void TabbedButtonBar::clearTabs()
  50716. {
  50717. tabs.clear();
  50718. tabColours.clear();
  50719. currentTabIndex = -1;
  50720. extraTabsButton = 0;
  50721. removeChildComponent (behindFrontTab);
  50722. deleteAllChildren();
  50723. addChildComponent (behindFrontTab);
  50724. setCurrentTabIndex (-1);
  50725. }
  50726. void TabbedButtonBar::addTab (const String& tabName,
  50727. const Colour& tabBackgroundColour,
  50728. int insertIndex)
  50729. {
  50730. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50731. if (tabName.isNotEmpty())
  50732. {
  50733. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50734. insertIndex = tabs.size();
  50735. for (int i = tabs.size(); --i >= insertIndex;)
  50736. {
  50737. TabBarButton* const tb = getTabButton (i);
  50738. if (tb != 0)
  50739. tb->tabIndex++;
  50740. }
  50741. tabs.insert (insertIndex, tabName);
  50742. tabColours.insert (insertIndex, tabBackgroundColour);
  50743. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50744. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50745. addAndMakeVisible (tb, insertIndex);
  50746. resized();
  50747. if (currentTabIndex < 0)
  50748. setCurrentTabIndex (0);
  50749. }
  50750. }
  50751. void TabbedButtonBar::setTabName (const int tabIndex,
  50752. const String& newName)
  50753. {
  50754. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50755. && tabs[tabIndex] != newName)
  50756. {
  50757. tabs.set (tabIndex, newName);
  50758. TabBarButton* const tb = getTabButton (tabIndex);
  50759. if (tb != 0)
  50760. tb->setButtonText (newName);
  50761. resized();
  50762. }
  50763. }
  50764. void TabbedButtonBar::removeTab (const int tabIndex)
  50765. {
  50766. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50767. {
  50768. const int oldTabIndex = currentTabIndex;
  50769. if (currentTabIndex == tabIndex)
  50770. currentTabIndex = -1;
  50771. tabs.remove (tabIndex);
  50772. tabColours.remove (tabIndex);
  50773. delete getTabButton (tabIndex);
  50774. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50775. {
  50776. TabBarButton* const tb = getTabButton (i);
  50777. if (tb != 0)
  50778. tb->tabIndex--;
  50779. }
  50780. resized();
  50781. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50782. }
  50783. }
  50784. void TabbedButtonBar::moveTab (const int currentIndex,
  50785. const int newIndex)
  50786. {
  50787. tabs.move (currentIndex, newIndex);
  50788. tabColours.move (currentIndex, newIndex);
  50789. resized();
  50790. }
  50791. int TabbedButtonBar::getNumTabs() const
  50792. {
  50793. return tabs.size();
  50794. }
  50795. const StringArray TabbedButtonBar::getTabNames() const
  50796. {
  50797. return tabs;
  50798. }
  50799. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50800. {
  50801. if (currentTabIndex != newIndex)
  50802. {
  50803. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50804. newIndex = -1;
  50805. currentTabIndex = newIndex;
  50806. for (int i = 0; i < getNumChildComponents(); ++i)
  50807. {
  50808. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50809. if (tb != 0)
  50810. tb->setToggleState (tb->tabIndex == newIndex, false);
  50811. }
  50812. resized();
  50813. if (sendChangeMessage_)
  50814. sendChangeMessage (this);
  50815. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50816. }
  50817. }
  50818. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50819. {
  50820. for (int i = getNumChildComponents(); --i >= 0;)
  50821. {
  50822. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50823. if (tb != 0 && tb->tabIndex == index)
  50824. return tb;
  50825. }
  50826. return 0;
  50827. }
  50828. void TabbedButtonBar::lookAndFeelChanged()
  50829. {
  50830. extraTabsButton = 0;
  50831. resized();
  50832. }
  50833. void TabbedButtonBar::resized()
  50834. {
  50835. const double minimumScale = 0.7;
  50836. int depth = getWidth();
  50837. int length = getHeight();
  50838. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50839. swapVariables (depth, length);
  50840. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50841. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50842. int i, totalLength = overlap;
  50843. int numVisibleButtons = tabs.size();
  50844. for (i = 0; i < getNumChildComponents(); ++i)
  50845. {
  50846. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50847. if (tb != 0)
  50848. {
  50849. totalLength += tb->getBestTabLength (depth) - overlap;
  50850. tb->overlapPixels = overlap / 2;
  50851. }
  50852. }
  50853. double scale = 1.0;
  50854. if (totalLength > length)
  50855. scale = jmax (minimumScale, length / (double) totalLength);
  50856. const bool isTooBig = totalLength * scale > length;
  50857. int tabsButtonPos = 0;
  50858. if (isTooBig)
  50859. {
  50860. if (extraTabsButton == 0)
  50861. {
  50862. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50863. extraTabsButton->addButtonListener (this);
  50864. extraTabsButton->setAlwaysOnTop (true);
  50865. extraTabsButton->setTriggeredOnMouseDown (true);
  50866. }
  50867. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50868. extraTabsButton->setSize (buttonSize, buttonSize);
  50869. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50870. {
  50871. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50872. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50873. }
  50874. else
  50875. {
  50876. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50877. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50878. }
  50879. totalLength = 0;
  50880. for (i = 0; i < tabs.size(); ++i)
  50881. {
  50882. TabBarButton* const tb = getTabButton (i);
  50883. if (tb != 0)
  50884. {
  50885. const int newLength = totalLength + tb->getBestTabLength (depth);
  50886. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50887. {
  50888. totalLength += overlap;
  50889. break;
  50890. }
  50891. numVisibleButtons = i + 1;
  50892. totalLength = newLength - overlap;
  50893. }
  50894. }
  50895. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50896. }
  50897. else
  50898. {
  50899. extraTabsButton = 0;
  50900. }
  50901. int pos = 0;
  50902. TabBarButton* frontTab = 0;
  50903. for (i = 0; i < tabs.size(); ++i)
  50904. {
  50905. TabBarButton* const tb = getTabButton (i);
  50906. if (tb != 0)
  50907. {
  50908. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50909. if (i < numVisibleButtons)
  50910. {
  50911. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50912. tb->setBounds (pos, 0, bestLength, getHeight());
  50913. else
  50914. tb->setBounds (0, pos, getWidth(), bestLength);
  50915. tb->toBack();
  50916. if (tb->tabIndex == currentTabIndex)
  50917. frontTab = tb;
  50918. tb->setVisible (true);
  50919. }
  50920. else
  50921. {
  50922. tb->setVisible (false);
  50923. }
  50924. pos += bestLength - overlap;
  50925. }
  50926. }
  50927. behindFrontTab->setBounds (getLocalBounds());
  50928. if (frontTab != 0)
  50929. {
  50930. frontTab->toFront (false);
  50931. behindFrontTab->toBehind (frontTab);
  50932. }
  50933. }
  50934. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50935. {
  50936. return tabColours [tabIndex];
  50937. }
  50938. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50939. {
  50940. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50941. && tabColours [tabIndex] != newColour)
  50942. {
  50943. tabColours.set (tabIndex, newColour);
  50944. repaint();
  50945. }
  50946. }
  50947. void TabbedButtonBar::buttonClicked (Button* button)
  50948. {
  50949. if (button == extraTabsButton)
  50950. {
  50951. PopupMenu m;
  50952. for (int i = 0; i < tabs.size(); ++i)
  50953. {
  50954. TabBarButton* const tb = getTabButton (i);
  50955. if (tb != 0 && ! tb->isVisible())
  50956. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50957. }
  50958. const int res = m.showAt (extraTabsButton);
  50959. if (res != 0)
  50960. setCurrentTabIndex (res - 1);
  50961. }
  50962. }
  50963. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50964. {
  50965. }
  50966. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50967. {
  50968. }
  50969. END_JUCE_NAMESPACE
  50970. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50971. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50972. BEGIN_JUCE_NAMESPACE
  50973. class TabCompButtonBar : public TabbedButtonBar
  50974. {
  50975. public:
  50976. TabCompButtonBar (TabbedComponent* const owner_,
  50977. const TabbedButtonBar::Orientation orientation_)
  50978. : TabbedButtonBar (orientation_),
  50979. owner (owner_)
  50980. {
  50981. }
  50982. ~TabCompButtonBar()
  50983. {
  50984. }
  50985. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50986. {
  50987. owner->changeCallback (newCurrentTabIndex, newTabName);
  50988. }
  50989. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50990. {
  50991. owner->popupMenuClickOnTab (tabIndex, tabName);
  50992. }
  50993. const Colour getTabBackgroundColour (const int tabIndex)
  50994. {
  50995. return owner->tabs->getTabBackgroundColour (tabIndex);
  50996. }
  50997. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50998. {
  50999. return owner->createTabButton (tabName, tabIndex);
  51000. }
  51001. juce_UseDebuggingNewOperator
  51002. private:
  51003. TabbedComponent* const owner;
  51004. TabCompButtonBar (const TabCompButtonBar&);
  51005. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51006. };
  51007. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51008. : panelComponent (0),
  51009. tabDepth (30),
  51010. outlineThickness (1),
  51011. edgeIndent (0)
  51012. {
  51013. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51014. }
  51015. TabbedComponent::~TabbedComponent()
  51016. {
  51017. clearTabs();
  51018. delete tabs;
  51019. }
  51020. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51021. {
  51022. tabs->setOrientation (orientation);
  51023. resized();
  51024. }
  51025. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51026. {
  51027. return tabs->getOrientation();
  51028. }
  51029. void TabbedComponent::setTabBarDepth (const int newDepth)
  51030. {
  51031. if (tabDepth != newDepth)
  51032. {
  51033. tabDepth = newDepth;
  51034. resized();
  51035. }
  51036. }
  51037. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51038. {
  51039. return new TabBarButton (tabName, tabs, tabIndex);
  51040. }
  51041. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51042. void TabbedComponent::clearTabs()
  51043. {
  51044. if (panelComponent != 0)
  51045. {
  51046. panelComponent->setVisible (false);
  51047. removeChildComponent (panelComponent);
  51048. panelComponent = 0;
  51049. }
  51050. tabs->clearTabs();
  51051. for (int i = contentComponents.size(); --i >= 0;)
  51052. {
  51053. Component* const c = contentComponents.getUnchecked(i);
  51054. // be careful not to delete these components until they've been removed from the tab component
  51055. jassert (c == 0 || c->isValidComponent());
  51056. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51057. delete c;
  51058. }
  51059. contentComponents.clear();
  51060. }
  51061. void TabbedComponent::addTab (const String& tabName,
  51062. const Colour& tabBackgroundColour,
  51063. Component* const contentComponent,
  51064. const bool deleteComponentWhenNotNeeded,
  51065. const int insertIndex)
  51066. {
  51067. contentComponents.insert (insertIndex, contentComponent);
  51068. if (contentComponent != 0)
  51069. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51070. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51071. }
  51072. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51073. {
  51074. tabs->setTabName (tabIndex, newName);
  51075. }
  51076. void TabbedComponent::removeTab (const int tabIndex)
  51077. {
  51078. Component* const c = contentComponents [tabIndex];
  51079. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51080. {
  51081. if (c == panelComponent)
  51082. panelComponent = 0;
  51083. delete c;
  51084. }
  51085. contentComponents.remove (tabIndex);
  51086. tabs->removeTab (tabIndex);
  51087. }
  51088. int TabbedComponent::getNumTabs() const
  51089. {
  51090. return tabs->getNumTabs();
  51091. }
  51092. const StringArray TabbedComponent::getTabNames() const
  51093. {
  51094. return tabs->getTabNames();
  51095. }
  51096. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51097. {
  51098. return contentComponents [tabIndex];
  51099. }
  51100. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51101. {
  51102. return tabs->getTabBackgroundColour (tabIndex);
  51103. }
  51104. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51105. {
  51106. tabs->setTabBackgroundColour (tabIndex, newColour);
  51107. if (getCurrentTabIndex() == tabIndex)
  51108. repaint();
  51109. }
  51110. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51111. {
  51112. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51113. }
  51114. int TabbedComponent::getCurrentTabIndex() const
  51115. {
  51116. return tabs->getCurrentTabIndex();
  51117. }
  51118. const String& TabbedComponent::getCurrentTabName() const
  51119. {
  51120. return tabs->getCurrentTabName();
  51121. }
  51122. void TabbedComponent::setOutline (int thickness)
  51123. {
  51124. outlineThickness = thickness;
  51125. repaint();
  51126. }
  51127. void TabbedComponent::setIndent (const int indentThickness)
  51128. {
  51129. edgeIndent = indentThickness;
  51130. }
  51131. void TabbedComponent::paint (Graphics& g)
  51132. {
  51133. g.fillAll (findColour (backgroundColourId));
  51134. const TabbedButtonBar::Orientation o = getOrientation();
  51135. int x = 0;
  51136. int y = 0;
  51137. int r = getWidth();
  51138. int b = getHeight();
  51139. if (o == TabbedButtonBar::TabsAtTop)
  51140. y += tabDepth;
  51141. else if (o == TabbedButtonBar::TabsAtBottom)
  51142. b -= tabDepth;
  51143. else if (o == TabbedButtonBar::TabsAtLeft)
  51144. x += tabDepth;
  51145. else if (o == TabbedButtonBar::TabsAtRight)
  51146. r -= tabDepth;
  51147. g.reduceClipRegion (x, y, r - x, b - y);
  51148. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51149. if (outlineThickness > 0)
  51150. {
  51151. if (o == TabbedButtonBar::TabsAtTop)
  51152. --y;
  51153. else if (o == TabbedButtonBar::TabsAtBottom)
  51154. ++b;
  51155. else if (o == TabbedButtonBar::TabsAtLeft)
  51156. --x;
  51157. else if (o == TabbedButtonBar::TabsAtRight)
  51158. ++r;
  51159. g.setColour (findColour (outlineColourId));
  51160. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51161. }
  51162. }
  51163. void TabbedComponent::resized()
  51164. {
  51165. const TabbedButtonBar::Orientation o = getOrientation();
  51166. const int indent = edgeIndent + outlineThickness;
  51167. BorderSize indents (indent);
  51168. if (o == TabbedButtonBar::TabsAtTop)
  51169. {
  51170. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51171. indents.setTop (tabDepth + edgeIndent);
  51172. }
  51173. else if (o == TabbedButtonBar::TabsAtBottom)
  51174. {
  51175. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51176. indents.setBottom (tabDepth + edgeIndent);
  51177. }
  51178. else if (o == TabbedButtonBar::TabsAtLeft)
  51179. {
  51180. tabs->setBounds (0, 0, tabDepth, getHeight());
  51181. indents.setLeft (tabDepth + edgeIndent);
  51182. }
  51183. else if (o == TabbedButtonBar::TabsAtRight)
  51184. {
  51185. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51186. indents.setRight (tabDepth + edgeIndent);
  51187. }
  51188. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51189. for (int i = contentComponents.size(); --i >= 0;)
  51190. if (contentComponents.getUnchecked (i) != 0)
  51191. contentComponents.getUnchecked (i)->setBounds (bounds);
  51192. }
  51193. void TabbedComponent::lookAndFeelChanged()
  51194. {
  51195. for (int i = contentComponents.size(); --i >= 0;)
  51196. if (contentComponents.getUnchecked (i) != 0)
  51197. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51198. }
  51199. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51200. const String& newTabName)
  51201. {
  51202. if (panelComponent != 0)
  51203. {
  51204. panelComponent->setVisible (false);
  51205. removeChildComponent (panelComponent);
  51206. panelComponent = 0;
  51207. }
  51208. if (getCurrentTabIndex() >= 0)
  51209. {
  51210. panelComponent = contentComponents [getCurrentTabIndex()];
  51211. if (panelComponent != 0)
  51212. {
  51213. // do these ops as two stages instead of addAndMakeVisible() so that the
  51214. // component has always got a parent when it gets the visibilityChanged() callback
  51215. addChildComponent (panelComponent);
  51216. panelComponent->setVisible (true);
  51217. panelComponent->toFront (true);
  51218. }
  51219. repaint();
  51220. }
  51221. resized();
  51222. currentTabChanged (newCurrentTabIndex, newTabName);
  51223. }
  51224. void TabbedComponent::currentTabChanged (const int, const String&)
  51225. {
  51226. }
  51227. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51228. {
  51229. }
  51230. END_JUCE_NAMESPACE
  51231. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51232. /*** Start of inlined file: juce_Viewport.cpp ***/
  51233. BEGIN_JUCE_NAMESPACE
  51234. Viewport::Viewport (const String& componentName)
  51235. : Component (componentName),
  51236. scrollBarThickness (0),
  51237. singleStepX (16),
  51238. singleStepY (16),
  51239. showHScrollbar (true),
  51240. showVScrollbar (true),
  51241. verticalScrollBar (true),
  51242. horizontalScrollBar (false)
  51243. {
  51244. // content holder is used to clip the contents so they don't overlap the scrollbars
  51245. addAndMakeVisible (&contentHolder);
  51246. contentHolder.setInterceptsMouseClicks (false, true);
  51247. addChildComponent (&verticalScrollBar);
  51248. addChildComponent (&horizontalScrollBar);
  51249. verticalScrollBar.addListener (this);
  51250. horizontalScrollBar.addListener (this);
  51251. setInterceptsMouseClicks (false, true);
  51252. setWantsKeyboardFocus (true);
  51253. }
  51254. Viewport::~Viewport()
  51255. {
  51256. contentHolder.deleteAllChildren();
  51257. }
  51258. void Viewport::visibleAreaChanged (int, int, int, int)
  51259. {
  51260. }
  51261. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51262. {
  51263. if (contentComp.getComponent() != newViewedComponent)
  51264. {
  51265. {
  51266. ScopedPointer<Component> oldCompDeleter (contentComp);
  51267. contentComp = 0;
  51268. }
  51269. contentComp = newViewedComponent;
  51270. if (contentComp != 0)
  51271. {
  51272. contentComp->setTopLeftPosition (0, 0);
  51273. contentHolder.addAndMakeVisible (contentComp);
  51274. contentComp->addComponentListener (this);
  51275. }
  51276. updateVisibleArea();
  51277. }
  51278. }
  51279. int Viewport::getMaximumVisibleWidth() const
  51280. {
  51281. return contentHolder.getWidth();
  51282. }
  51283. int Viewport::getMaximumVisibleHeight() const
  51284. {
  51285. return contentHolder.getHeight();
  51286. }
  51287. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51288. {
  51289. if (contentComp != 0)
  51290. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51291. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51292. }
  51293. void Viewport::setViewPosition (const Point<int>& newPosition)
  51294. {
  51295. setViewPosition (newPosition.getX(), newPosition.getY());
  51296. }
  51297. void Viewport::setViewPositionProportionately (const double x, const double y)
  51298. {
  51299. if (contentComp != 0)
  51300. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51301. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51302. }
  51303. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51304. {
  51305. if (contentComp != 0)
  51306. {
  51307. int dx = 0, dy = 0;
  51308. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51309. {
  51310. if (mouseX < activeBorderThickness)
  51311. dx = activeBorderThickness - mouseX;
  51312. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51313. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51314. if (dx < 0)
  51315. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51316. else
  51317. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51318. }
  51319. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51320. {
  51321. if (mouseY < activeBorderThickness)
  51322. dy = activeBorderThickness - mouseY;
  51323. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51324. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51325. if (dy < 0)
  51326. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51327. else
  51328. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51329. }
  51330. if (dx != 0 || dy != 0)
  51331. {
  51332. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51333. contentComp->getY() + dy);
  51334. return true;
  51335. }
  51336. }
  51337. return false;
  51338. }
  51339. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51340. {
  51341. updateVisibleArea();
  51342. }
  51343. void Viewport::resized()
  51344. {
  51345. updateVisibleArea();
  51346. }
  51347. void Viewport::updateVisibleArea()
  51348. {
  51349. const int scrollbarWidth = getScrollBarThickness();
  51350. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51351. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51352. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51353. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51354. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51355. Rectangle<int> contentArea (getLocalBounds());
  51356. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51357. {
  51358. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51359. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51360. if (vBarVisible)
  51361. contentArea.setWidth (getWidth() - scrollbarWidth);
  51362. if (hBarVisible)
  51363. contentArea.setHeight (getHeight() - scrollbarWidth);
  51364. if (! contentArea.contains (contentComp->getBounds()))
  51365. {
  51366. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51367. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51368. }
  51369. }
  51370. if (vBarVisible)
  51371. contentArea.setWidth (getWidth() - scrollbarWidth);
  51372. if (hBarVisible)
  51373. contentArea.setHeight (getHeight() - scrollbarWidth);
  51374. contentHolder.setBounds (contentArea);
  51375. Rectangle<int> contentBounds;
  51376. if (contentComp != 0)
  51377. contentBounds = contentComp->getBounds();
  51378. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51379. if (hBarVisible)
  51380. {
  51381. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51382. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51383. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51384. horizontalScrollBar.setSingleStepSize (singleStepX);
  51385. horizontalScrollBar.cancelPendingUpdate();
  51386. }
  51387. if (vBarVisible)
  51388. {
  51389. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51390. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51391. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51392. verticalScrollBar.setSingleStepSize (singleStepY);
  51393. verticalScrollBar.cancelPendingUpdate();
  51394. }
  51395. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51396. horizontalScrollBar.setVisible (hBarVisible);
  51397. verticalScrollBar.setVisible (vBarVisible);
  51398. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51399. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51400. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51401. if (lastVisibleArea != visibleArea)
  51402. {
  51403. lastVisibleArea = visibleArea;
  51404. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51405. }
  51406. horizontalScrollBar.handleUpdateNowIfNeeded();
  51407. verticalScrollBar.handleUpdateNowIfNeeded();
  51408. }
  51409. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51410. {
  51411. if (singleStepX != stepX || singleStepY != stepY)
  51412. {
  51413. singleStepX = stepX;
  51414. singleStepY = stepY;
  51415. updateVisibleArea();
  51416. }
  51417. }
  51418. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51419. const bool showHorizontalScrollbarIfNeeded)
  51420. {
  51421. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51422. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51423. {
  51424. showVScrollbar = showVerticalScrollbarIfNeeded;
  51425. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51426. updateVisibleArea();
  51427. }
  51428. }
  51429. void Viewport::setScrollBarThickness (const int thickness)
  51430. {
  51431. if (scrollBarThickness != thickness)
  51432. {
  51433. scrollBarThickness = thickness;
  51434. updateVisibleArea();
  51435. }
  51436. }
  51437. int Viewport::getScrollBarThickness() const
  51438. {
  51439. return scrollBarThickness > 0 ? scrollBarThickness
  51440. : getLookAndFeel().getDefaultScrollbarWidth();
  51441. }
  51442. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51443. {
  51444. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51445. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51446. }
  51447. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51448. {
  51449. const int newRangeStartInt = roundToInt (newRangeStart);
  51450. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51451. {
  51452. setViewPosition (newRangeStartInt, getViewPositionY());
  51453. }
  51454. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51455. {
  51456. setViewPosition (getViewPositionX(), newRangeStartInt);
  51457. }
  51458. }
  51459. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51460. {
  51461. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51462. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51463. }
  51464. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51465. {
  51466. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51467. {
  51468. const bool hasVertBar = verticalScrollBar.isVisible();
  51469. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51470. if (hasHorzBar || hasVertBar)
  51471. {
  51472. if (wheelIncrementX != 0)
  51473. {
  51474. wheelIncrementX *= 14.0f * singleStepX;
  51475. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51476. : jmax (wheelIncrementX, 1.0f);
  51477. }
  51478. if (wheelIncrementY != 0)
  51479. {
  51480. wheelIncrementY *= 14.0f * singleStepY;
  51481. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51482. : jmax (wheelIncrementY, 1.0f);
  51483. }
  51484. Point<int> pos (getViewPosition());
  51485. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51486. {
  51487. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51488. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51489. }
  51490. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51491. {
  51492. if (wheelIncrementX == 0 && ! hasVertBar)
  51493. wheelIncrementX = wheelIncrementY;
  51494. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51495. }
  51496. else if (hasVertBar && wheelIncrementY != 0)
  51497. {
  51498. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51499. }
  51500. if (pos != getViewPosition())
  51501. {
  51502. setViewPosition (pos);
  51503. return true;
  51504. }
  51505. }
  51506. }
  51507. return false;
  51508. }
  51509. bool Viewport::keyPressed (const KeyPress& key)
  51510. {
  51511. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51512. || key.isKeyCode (KeyPress::downKey)
  51513. || key.isKeyCode (KeyPress::pageUpKey)
  51514. || key.isKeyCode (KeyPress::pageDownKey)
  51515. || key.isKeyCode (KeyPress::homeKey)
  51516. || key.isKeyCode (KeyPress::endKey);
  51517. if (verticalScrollBar.isVisible() && isUpDownKey)
  51518. return verticalScrollBar.keyPressed (key);
  51519. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51520. || key.isKeyCode (KeyPress::rightKey);
  51521. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51522. return horizontalScrollBar.keyPressed (key);
  51523. return false;
  51524. }
  51525. END_JUCE_NAMESPACE
  51526. /*** End of inlined file: juce_Viewport.cpp ***/
  51527. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51528. BEGIN_JUCE_NAMESPACE
  51529. static const Colour createBaseColour (const Colour& buttonColour,
  51530. const bool hasKeyboardFocus,
  51531. const bool isMouseOverButton,
  51532. const bool isButtonDown) throw()
  51533. {
  51534. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51535. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51536. if (isButtonDown)
  51537. return baseColour.contrasting (0.2f);
  51538. else if (isMouseOverButton)
  51539. return baseColour.contrasting (0.1f);
  51540. return baseColour;
  51541. }
  51542. LookAndFeel::LookAndFeel()
  51543. {
  51544. /* if this fails it means you're trying to create a LookAndFeel object before
  51545. the static Colours have been initialised. That ain't gonna work. It probably
  51546. means that you're using a static LookAndFeel object and that your compiler has
  51547. decided to intialise it before the Colours class.
  51548. */
  51549. jassert (Colours::white == Colour (0xffffffff));
  51550. // set up the standard set of colours..
  51551. const int textButtonColour = 0xffbbbbff;
  51552. const int textHighlightColour = 0x401111ee;
  51553. const int standardOutlineColour = 0xb2808080;
  51554. static const int standardColours[] =
  51555. {
  51556. TextButton::buttonColourId, textButtonColour,
  51557. TextButton::buttonOnColourId, 0xff4444ff,
  51558. TextButton::textColourOnId, 0xff000000,
  51559. TextButton::textColourOffId, 0xff000000,
  51560. ComboBox::buttonColourId, 0xffbbbbff,
  51561. ComboBox::outlineColourId, standardOutlineColour,
  51562. ToggleButton::textColourId, 0xff000000,
  51563. TextEditor::backgroundColourId, 0xffffffff,
  51564. TextEditor::textColourId, 0xff000000,
  51565. TextEditor::highlightColourId, textHighlightColour,
  51566. TextEditor::highlightedTextColourId, 0xff000000,
  51567. TextEditor::caretColourId, 0xff000000,
  51568. TextEditor::outlineColourId, 0x00000000,
  51569. TextEditor::focusedOutlineColourId, textButtonColour,
  51570. TextEditor::shadowColourId, 0x38000000,
  51571. Label::backgroundColourId, 0x00000000,
  51572. Label::textColourId, 0xff000000,
  51573. Label::outlineColourId, 0x00000000,
  51574. ScrollBar::backgroundColourId, 0x00000000,
  51575. ScrollBar::thumbColourId, 0xffffffff,
  51576. ScrollBar::trackColourId, 0xffffffff,
  51577. TreeView::linesColourId, 0x4c000000,
  51578. TreeView::backgroundColourId, 0x00000000,
  51579. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51580. PopupMenu::backgroundColourId, 0xffffffff,
  51581. PopupMenu::textColourId, 0xff000000,
  51582. PopupMenu::headerTextColourId, 0xff000000,
  51583. PopupMenu::highlightedTextColourId, 0xffffffff,
  51584. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51585. ComboBox::textColourId, 0xff000000,
  51586. ComboBox::backgroundColourId, 0xffffffff,
  51587. ComboBox::arrowColourId, 0x99000000,
  51588. ListBox::backgroundColourId, 0xffffffff,
  51589. ListBox::outlineColourId, standardOutlineColour,
  51590. ListBox::textColourId, 0xff000000,
  51591. Slider::backgroundColourId, 0x00000000,
  51592. Slider::thumbColourId, textButtonColour,
  51593. Slider::trackColourId, 0x7fffffff,
  51594. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51595. Slider::rotarySliderOutlineColourId, 0x66000000,
  51596. Slider::textBoxTextColourId, 0xff000000,
  51597. Slider::textBoxBackgroundColourId, 0xffffffff,
  51598. Slider::textBoxHighlightColourId, textHighlightColour,
  51599. Slider::textBoxOutlineColourId, standardOutlineColour,
  51600. ResizableWindow::backgroundColourId, 0xff777777,
  51601. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51602. AlertWindow::backgroundColourId, 0xffededed,
  51603. AlertWindow::textColourId, 0xff000000,
  51604. AlertWindow::outlineColourId, 0xff666666,
  51605. ProgressBar::backgroundColourId, 0xffeeeeee,
  51606. ProgressBar::foregroundColourId, 0xffaaaaee,
  51607. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51608. TooltipWindow::textColourId, 0xff000000,
  51609. TooltipWindow::outlineColourId, 0x4c000000,
  51610. TabbedComponent::backgroundColourId, 0x00000000,
  51611. TabbedComponent::outlineColourId, 0xff777777,
  51612. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51613. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51614. Toolbar::backgroundColourId, 0xfff6f8f9,
  51615. Toolbar::separatorColourId, 0x4c000000,
  51616. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51617. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51618. Toolbar::labelTextColourId, 0xff000000,
  51619. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51620. HyperlinkButton::textColourId, 0xcc1111ee,
  51621. GroupComponent::outlineColourId, 0x66000000,
  51622. GroupComponent::textColourId, 0xff000000,
  51623. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51624. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51625. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51626. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51627. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51628. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51629. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51630. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51631. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51632. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51633. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51634. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51635. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51636. CodeEditorComponent::caretColourId, 0xff000000,
  51637. CodeEditorComponent::highlightColourId, textHighlightColour,
  51638. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51639. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51640. ColourSelector::labelTextColourId, 0xff000000,
  51641. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51642. KeyMappingEditorComponent::textColourId, 0xff000000,
  51643. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51644. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51645. };
  51646. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51647. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51648. static String defaultSansName, defaultSerifName, defaultFixedName;
  51649. if (defaultSansName.isEmpty())
  51650. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51651. defaultSans = defaultSansName;
  51652. defaultSerif = defaultSerifName;
  51653. defaultFixed = defaultFixedName;
  51654. }
  51655. LookAndFeel::~LookAndFeel()
  51656. {
  51657. }
  51658. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51659. {
  51660. const int index = colourIds.indexOf (colourId);
  51661. if (index >= 0)
  51662. return colours [index];
  51663. jassertfalse;
  51664. return Colours::black;
  51665. }
  51666. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51667. {
  51668. const int index = colourIds.indexOf (colourId);
  51669. if (index >= 0)
  51670. {
  51671. colours.set (index, colour);
  51672. }
  51673. else
  51674. {
  51675. colourIds.add (colourId);
  51676. colours.add (colour);
  51677. }
  51678. }
  51679. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51680. {
  51681. return colourIds.contains (colourId);
  51682. }
  51683. static LookAndFeel* defaultLF = 0;
  51684. static LookAndFeel* currentDefaultLF = 0;
  51685. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51686. {
  51687. // if this happens, your app hasn't initialised itself properly.. if you're
  51688. // trying to hack your own main() function, have a look at
  51689. // JUCEApplication::initialiseForGUI()
  51690. jassert (currentDefaultLF != 0);
  51691. return *currentDefaultLF;
  51692. }
  51693. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51694. {
  51695. if (newDefaultLookAndFeel == 0)
  51696. {
  51697. if (defaultLF == 0)
  51698. defaultLF = new LookAndFeel();
  51699. newDefaultLookAndFeel = defaultLF;
  51700. }
  51701. currentDefaultLF = newDefaultLookAndFeel;
  51702. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51703. {
  51704. Component* const c = Desktop::getInstance().getComponent (i);
  51705. if (c != 0)
  51706. c->sendLookAndFeelChange();
  51707. }
  51708. }
  51709. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51710. {
  51711. if (currentDefaultLF == defaultLF)
  51712. currentDefaultLF = 0;
  51713. deleteAndZero (defaultLF);
  51714. }
  51715. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51716. {
  51717. String faceName (font.getTypefaceName());
  51718. if (faceName == Font::getDefaultSansSerifFontName())
  51719. faceName = defaultSans;
  51720. else if (faceName == Font::getDefaultSerifFontName())
  51721. faceName = defaultSerif;
  51722. else if (faceName == Font::getDefaultMonospacedFontName())
  51723. faceName = defaultFixed;
  51724. Font f (font);
  51725. f.setTypefaceName (faceName);
  51726. return Typeface::createSystemTypefaceFor (f);
  51727. }
  51728. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51729. {
  51730. defaultSans = newName;
  51731. }
  51732. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51733. {
  51734. return component.getMouseCursor();
  51735. }
  51736. void LookAndFeel::drawButtonBackground (Graphics& g,
  51737. Button& button,
  51738. const Colour& backgroundColour,
  51739. bool isMouseOverButton,
  51740. bool isButtonDown)
  51741. {
  51742. const int width = button.getWidth();
  51743. const int height = button.getHeight();
  51744. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51745. const float halfThickness = outlineThickness * 0.5f;
  51746. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51747. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51748. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51749. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51750. const Colour baseColour (createBaseColour (backgroundColour,
  51751. button.hasKeyboardFocus (true),
  51752. isMouseOverButton, isButtonDown)
  51753. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51754. drawGlassLozenge (g,
  51755. indentL,
  51756. indentT,
  51757. width - indentL - indentR,
  51758. height - indentT - indentB,
  51759. baseColour, outlineThickness, -1.0f,
  51760. button.isConnectedOnLeft(),
  51761. button.isConnectedOnRight(),
  51762. button.isConnectedOnTop(),
  51763. button.isConnectedOnBottom());
  51764. }
  51765. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51766. {
  51767. return button.getFont();
  51768. }
  51769. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51770. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51771. {
  51772. Font font (getFontForTextButton (button));
  51773. g.setFont (font);
  51774. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51775. : TextButton::textColourOffId)
  51776. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51777. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51778. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51779. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51780. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51781. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51782. g.drawFittedText (button.getButtonText(),
  51783. leftIndent,
  51784. yIndent,
  51785. button.getWidth() - leftIndent - rightIndent,
  51786. button.getHeight() - yIndent * 2,
  51787. Justification::centred, 2);
  51788. }
  51789. void LookAndFeel::drawTickBox (Graphics& g,
  51790. Component& component,
  51791. float x, float y, float w, float h,
  51792. const bool ticked,
  51793. const bool isEnabled,
  51794. const bool isMouseOverButton,
  51795. const bool isButtonDown)
  51796. {
  51797. const float boxSize = w * 0.7f;
  51798. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51799. createBaseColour (component.findColour (TextButton::buttonColourId)
  51800. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51801. true,
  51802. isMouseOverButton,
  51803. isButtonDown),
  51804. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51805. if (ticked)
  51806. {
  51807. Path tick;
  51808. tick.startNewSubPath (1.5f, 3.0f);
  51809. tick.lineTo (3.0f, 6.0f);
  51810. tick.lineTo (6.0f, 0.0f);
  51811. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51812. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51813. .translated (x, y));
  51814. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51815. }
  51816. }
  51817. void LookAndFeel::drawToggleButton (Graphics& g,
  51818. ToggleButton& button,
  51819. bool isMouseOverButton,
  51820. bool isButtonDown)
  51821. {
  51822. if (button.hasKeyboardFocus (true))
  51823. {
  51824. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51825. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51826. }
  51827. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51828. const float tickWidth = fontSize * 1.1f;
  51829. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51830. tickWidth, tickWidth,
  51831. button.getToggleState(),
  51832. button.isEnabled(),
  51833. isMouseOverButton,
  51834. isButtonDown);
  51835. g.setColour (button.findColour (ToggleButton::textColourId));
  51836. g.setFont (fontSize);
  51837. if (! button.isEnabled())
  51838. g.setOpacity (0.5f);
  51839. const int textX = (int) tickWidth + 5;
  51840. g.drawFittedText (button.getButtonText(),
  51841. textX, 0,
  51842. button.getWidth() - textX - 2, button.getHeight(),
  51843. Justification::centredLeft, 10);
  51844. }
  51845. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51846. {
  51847. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51848. const int tickWidth = jmin (24, button.getHeight());
  51849. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51850. button.getHeight());
  51851. }
  51852. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51853. const String& message,
  51854. const String& button1,
  51855. const String& button2,
  51856. const String& button3,
  51857. AlertWindow::AlertIconType iconType,
  51858. int numButtons,
  51859. Component* associatedComponent)
  51860. {
  51861. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51862. if (numButtons == 1)
  51863. {
  51864. aw->addButton (button1, 0,
  51865. KeyPress (KeyPress::escapeKey, 0, 0),
  51866. KeyPress (KeyPress::returnKey, 0, 0));
  51867. }
  51868. else
  51869. {
  51870. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51871. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51872. if (button1ShortCut == button2ShortCut)
  51873. button2ShortCut = KeyPress();
  51874. if (numButtons == 2)
  51875. {
  51876. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51877. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51878. }
  51879. else if (numButtons == 3)
  51880. {
  51881. aw->addButton (button1, 1, button1ShortCut);
  51882. aw->addButton (button2, 2, button2ShortCut);
  51883. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51884. }
  51885. }
  51886. return aw;
  51887. }
  51888. void LookAndFeel::drawAlertBox (Graphics& g,
  51889. AlertWindow& alert,
  51890. const Rectangle<int>& textArea,
  51891. TextLayout& textLayout)
  51892. {
  51893. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51894. int iconSpaceUsed = 0;
  51895. Justification alignment (Justification::horizontallyCentred);
  51896. const int iconWidth = 80;
  51897. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51898. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51899. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51900. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51901. iconSize, iconSize);
  51902. if (alert.getAlertType() != AlertWindow::NoIcon)
  51903. {
  51904. Path icon;
  51905. uint32 colour;
  51906. char character;
  51907. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51908. {
  51909. colour = 0x55ff5555;
  51910. character = '!';
  51911. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51912. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51913. (float) iconRect.getX(), (float) iconRect.getBottom());
  51914. icon = icon.createPathWithRoundedCorners (5.0f);
  51915. }
  51916. else
  51917. {
  51918. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51919. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51920. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51921. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51922. }
  51923. GlyphArrangement ga;
  51924. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51925. String::charToString (character),
  51926. (float) iconRect.getX(), (float) iconRect.getY(),
  51927. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51928. Justification::centred, false);
  51929. ga.createPath (icon);
  51930. icon.setUsingNonZeroWinding (false);
  51931. g.setColour (Colour (colour));
  51932. g.fillPath (icon);
  51933. iconSpaceUsed = iconWidth;
  51934. alignment = Justification::left;
  51935. }
  51936. g.setColour (alert.findColour (AlertWindow::textColourId));
  51937. textLayout.drawWithin (g,
  51938. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51939. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51940. alignment.getFlags() | Justification::top);
  51941. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51942. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51943. }
  51944. int LookAndFeel::getAlertBoxWindowFlags()
  51945. {
  51946. return ComponentPeer::windowAppearsOnTaskbar
  51947. | ComponentPeer::windowHasDropShadow;
  51948. }
  51949. int LookAndFeel::getAlertWindowButtonHeight()
  51950. {
  51951. return 28;
  51952. }
  51953. const Font LookAndFeel::getAlertWindowFont()
  51954. {
  51955. return Font (12.0f);
  51956. }
  51957. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51958. int width, int height,
  51959. double progress, const String& textToShow)
  51960. {
  51961. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51962. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51963. g.fillAll (background);
  51964. if (progress >= 0.0f && progress < 1.0f)
  51965. {
  51966. drawGlassLozenge (g, 1.0f, 1.0f,
  51967. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51968. (float) (height - 2),
  51969. foreground,
  51970. 0.5f, 0.0f,
  51971. true, true, true, true);
  51972. }
  51973. else
  51974. {
  51975. // spinning bar..
  51976. g.setColour (foreground);
  51977. const int stripeWidth = height * 2;
  51978. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51979. Path p;
  51980. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51981. p.addQuadrilateral (x, 0.0f,
  51982. x + stripeWidth * 0.5f, 0.0f,
  51983. x, (float) height,
  51984. x - stripeWidth * 0.5f, (float) height);
  51985. Image im (Image::ARGB, width, height, true);
  51986. {
  51987. Graphics g2 (im);
  51988. drawGlassLozenge (g2, 1.0f, 1.0f,
  51989. (float) (width - 2),
  51990. (float) (height - 2),
  51991. foreground,
  51992. 0.5f, 0.0f,
  51993. true, true, true, true);
  51994. }
  51995. g.setTiledImageFill (im, 0, 0, 0.85f);
  51996. g.fillPath (p);
  51997. }
  51998. if (textToShow.isNotEmpty())
  51999. {
  52000. g.setColour (Colour::contrasting (background, foreground));
  52001. g.setFont (height * 0.6f);
  52002. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52003. }
  52004. }
  52005. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52006. {
  52007. const float radius = jmin (w, h) * 0.4f;
  52008. const float thickness = radius * 0.15f;
  52009. Path p;
  52010. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52011. radius * 0.6f, thickness,
  52012. thickness * 0.5f);
  52013. const float cx = x + w * 0.5f;
  52014. const float cy = y + h * 0.5f;
  52015. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52016. for (int i = 0; i < 12; ++i)
  52017. {
  52018. const int n = (i + 12 - animationIndex) % 12;
  52019. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52020. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52021. .translated (cx, cy));
  52022. }
  52023. }
  52024. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52025. ScrollBar& scrollbar,
  52026. int width, int height,
  52027. int buttonDirection,
  52028. bool /*isScrollbarVertical*/,
  52029. bool /*isMouseOverButton*/,
  52030. bool isButtonDown)
  52031. {
  52032. Path p;
  52033. if (buttonDirection == 0)
  52034. p.addTriangle (width * 0.5f, height * 0.2f,
  52035. width * 0.1f, height * 0.7f,
  52036. width * 0.9f, height * 0.7f);
  52037. else if (buttonDirection == 1)
  52038. p.addTriangle (width * 0.8f, height * 0.5f,
  52039. width * 0.3f, height * 0.1f,
  52040. width * 0.3f, height * 0.9f);
  52041. else if (buttonDirection == 2)
  52042. p.addTriangle (width * 0.5f, height * 0.8f,
  52043. width * 0.1f, height * 0.3f,
  52044. width * 0.9f, height * 0.3f);
  52045. else if (buttonDirection == 3)
  52046. p.addTriangle (width * 0.2f, height * 0.5f,
  52047. width * 0.7f, height * 0.1f,
  52048. width * 0.7f, height * 0.9f);
  52049. if (isButtonDown)
  52050. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52051. else
  52052. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52053. g.fillPath (p);
  52054. g.setColour (Colour (0x80000000));
  52055. g.strokePath (p, PathStrokeType (0.5f));
  52056. }
  52057. void LookAndFeel::drawScrollbar (Graphics& g,
  52058. ScrollBar& scrollbar,
  52059. int x, int y,
  52060. int width, int height,
  52061. bool isScrollbarVertical,
  52062. int thumbStartPosition,
  52063. int thumbSize,
  52064. bool /*isMouseOver*/,
  52065. bool /*isMouseDown*/)
  52066. {
  52067. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52068. Path slotPath, thumbPath;
  52069. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52070. const float slotIndentx2 = slotIndent * 2.0f;
  52071. const float thumbIndent = slotIndent + 1.0f;
  52072. const float thumbIndentx2 = thumbIndent * 2.0f;
  52073. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52074. if (isScrollbarVertical)
  52075. {
  52076. slotPath.addRoundedRectangle (x + slotIndent,
  52077. y + slotIndent,
  52078. width - slotIndentx2,
  52079. height - slotIndentx2,
  52080. (width - slotIndentx2) * 0.5f);
  52081. if (thumbSize > 0)
  52082. thumbPath.addRoundedRectangle (x + thumbIndent,
  52083. thumbStartPosition + thumbIndent,
  52084. width - thumbIndentx2,
  52085. thumbSize - thumbIndentx2,
  52086. (width - thumbIndentx2) * 0.5f);
  52087. gx1 = (float) x;
  52088. gx2 = x + width * 0.7f;
  52089. }
  52090. else
  52091. {
  52092. slotPath.addRoundedRectangle (x + slotIndent,
  52093. y + slotIndent,
  52094. width - slotIndentx2,
  52095. height - slotIndentx2,
  52096. (height - slotIndentx2) * 0.5f);
  52097. if (thumbSize > 0)
  52098. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52099. y + thumbIndent,
  52100. thumbSize - thumbIndentx2,
  52101. height - thumbIndentx2,
  52102. (height - thumbIndentx2) * 0.5f);
  52103. gy1 = (float) y;
  52104. gy2 = y + height * 0.7f;
  52105. }
  52106. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52107. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52108. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52109. g.fillPath (slotPath);
  52110. if (isScrollbarVertical)
  52111. {
  52112. gx1 = x + width * 0.6f;
  52113. gx2 = (float) x + width;
  52114. }
  52115. else
  52116. {
  52117. gy1 = y + height * 0.6f;
  52118. gy2 = (float) y + height;
  52119. }
  52120. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52121. Colour (0x19000000), gx2, gy2, false));
  52122. g.fillPath (slotPath);
  52123. g.setColour (thumbColour);
  52124. g.fillPath (thumbPath);
  52125. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52126. Colours::transparentBlack, gx2, gy2, false));
  52127. g.saveState();
  52128. if (isScrollbarVertical)
  52129. g.reduceClipRegion (x + width / 2, y, width, height);
  52130. else
  52131. g.reduceClipRegion (x, y + height / 2, width, height);
  52132. g.fillPath (thumbPath);
  52133. g.restoreState();
  52134. g.setColour (Colour (0x4c000000));
  52135. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52136. }
  52137. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52138. {
  52139. return 0;
  52140. }
  52141. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52142. {
  52143. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52144. }
  52145. int LookAndFeel::getDefaultScrollbarWidth()
  52146. {
  52147. return 18;
  52148. }
  52149. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52150. {
  52151. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52152. : scrollbar.getHeight());
  52153. }
  52154. const Path LookAndFeel::getTickShape (const float height)
  52155. {
  52156. static const unsigned char tickShapeData[] =
  52157. {
  52158. 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,
  52159. 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,
  52160. 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,
  52161. 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,
  52162. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52163. };
  52164. Path p;
  52165. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52166. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52167. return p;
  52168. }
  52169. const Path LookAndFeel::getCrossShape (const float height)
  52170. {
  52171. static const unsigned char crossShapeData[] =
  52172. {
  52173. 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,
  52174. 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,
  52175. 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,
  52176. 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,
  52177. 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,
  52178. 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,
  52179. 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
  52180. };
  52181. Path p;
  52182. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52183. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52184. return p;
  52185. }
  52186. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52187. {
  52188. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52189. x += (w - boxSize) >> 1;
  52190. y += (h - boxSize) >> 1;
  52191. w = boxSize;
  52192. h = boxSize;
  52193. g.setColour (Colour (0xe5ffffff));
  52194. g.fillRect (x, y, w, h);
  52195. g.setColour (Colour (0x80000000));
  52196. g.drawRect (x, y, w, h);
  52197. const float size = boxSize / 2 + 1.0f;
  52198. const float centre = (float) (boxSize / 2);
  52199. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52200. if (isPlus)
  52201. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52202. }
  52203. void LookAndFeel::drawBubble (Graphics& g,
  52204. float tipX, float tipY,
  52205. float boxX, float boxY,
  52206. float boxW, float boxH)
  52207. {
  52208. int side = 0;
  52209. if (tipX < boxX)
  52210. side = 1;
  52211. else if (tipX > boxX + boxW)
  52212. side = 3;
  52213. else if (tipY > boxY + boxH)
  52214. side = 2;
  52215. const float indent = 2.0f;
  52216. Path p;
  52217. p.addBubble (boxX + indent,
  52218. boxY + indent,
  52219. boxW - indent * 2.0f,
  52220. boxH - indent * 2.0f,
  52221. 5.0f,
  52222. tipX, tipY,
  52223. side,
  52224. 0.5f,
  52225. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52226. //xxx need to take comp as param for colour
  52227. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52228. g.fillPath (p);
  52229. //xxx as above
  52230. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52231. g.strokePath (p, PathStrokeType (1.33f));
  52232. }
  52233. const Font LookAndFeel::getPopupMenuFont()
  52234. {
  52235. return Font (17.0f);
  52236. }
  52237. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52238. const bool isSeparator,
  52239. int standardMenuItemHeight,
  52240. int& idealWidth,
  52241. int& idealHeight)
  52242. {
  52243. if (isSeparator)
  52244. {
  52245. idealWidth = 50;
  52246. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52247. }
  52248. else
  52249. {
  52250. Font font (getPopupMenuFont());
  52251. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52252. font.setHeight (standardMenuItemHeight / 1.3f);
  52253. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52254. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52255. }
  52256. }
  52257. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52258. {
  52259. const Colour background (findColour (PopupMenu::backgroundColourId));
  52260. g.fillAll (background);
  52261. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52262. for (int i = 0; i < height; i += 3)
  52263. g.fillRect (0, i, width, 1);
  52264. #if ! JUCE_MAC
  52265. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52266. g.drawRect (0, 0, width, height);
  52267. #endif
  52268. }
  52269. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52270. int width, int height,
  52271. bool isScrollUpArrow)
  52272. {
  52273. const Colour background (findColour (PopupMenu::backgroundColourId));
  52274. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52275. background.withAlpha (0.0f),
  52276. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52277. false));
  52278. g.fillRect (1, 1, width - 2, height - 2);
  52279. const float hw = width * 0.5f;
  52280. const float arrowW = height * 0.3f;
  52281. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52282. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52283. Path p;
  52284. p.addTriangle (hw - arrowW, y1,
  52285. hw + arrowW, y1,
  52286. hw, y2);
  52287. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52288. g.fillPath (p);
  52289. }
  52290. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52291. int width, int height,
  52292. const bool isSeparator,
  52293. const bool isActive,
  52294. const bool isHighlighted,
  52295. const bool isTicked,
  52296. const bool hasSubMenu,
  52297. const String& text,
  52298. const String& shortcutKeyText,
  52299. Image* image,
  52300. const Colour* const textColourToUse)
  52301. {
  52302. const float halfH = height * 0.5f;
  52303. if (isSeparator)
  52304. {
  52305. const float separatorIndent = 5.5f;
  52306. g.setColour (Colour (0x33000000));
  52307. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52308. g.setColour (Colour (0x66ffffff));
  52309. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52310. }
  52311. else
  52312. {
  52313. Colour textColour (findColour (PopupMenu::textColourId));
  52314. if (textColourToUse != 0)
  52315. textColour = *textColourToUse;
  52316. if (isHighlighted)
  52317. {
  52318. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52319. g.fillRect (1, 1, width - 2, height - 2);
  52320. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52321. }
  52322. else
  52323. {
  52324. g.setColour (textColour);
  52325. }
  52326. if (! isActive)
  52327. g.setOpacity (0.3f);
  52328. Font font (getPopupMenuFont());
  52329. if (font.getHeight() > height / 1.3f)
  52330. font.setHeight (height / 1.3f);
  52331. g.setFont (font);
  52332. const int leftBorder = (height * 5) / 4;
  52333. const int rightBorder = 4;
  52334. if (image != 0)
  52335. {
  52336. g.drawImageWithin (*image,
  52337. 2, 1, leftBorder - 4, height - 2,
  52338. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52339. }
  52340. else if (isTicked)
  52341. {
  52342. const Path tick (getTickShape (1.0f));
  52343. const float th = font.getAscent();
  52344. const float ty = halfH - th * 0.5f;
  52345. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52346. th, true));
  52347. }
  52348. g.drawFittedText (text,
  52349. leftBorder, 0,
  52350. width - (leftBorder + rightBorder), height,
  52351. Justification::centredLeft, 1);
  52352. if (shortcutKeyText.isNotEmpty())
  52353. {
  52354. Font f2 (font);
  52355. f2.setHeight (f2.getHeight() * 0.75f);
  52356. f2.setHorizontalScale (0.95f);
  52357. g.setFont (f2);
  52358. g.drawText (shortcutKeyText,
  52359. leftBorder,
  52360. 0,
  52361. width - (leftBorder + rightBorder + 4),
  52362. height,
  52363. Justification::centredRight,
  52364. true);
  52365. }
  52366. if (hasSubMenu)
  52367. {
  52368. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52369. const float x = width - height * 0.6f;
  52370. Path p;
  52371. p.addTriangle (x, halfH - arrowH * 0.5f,
  52372. x, halfH + arrowH * 0.5f,
  52373. x + arrowH * 0.6f, halfH);
  52374. g.fillPath (p);
  52375. }
  52376. }
  52377. }
  52378. int LookAndFeel::getMenuWindowFlags()
  52379. {
  52380. return ComponentPeer::windowHasDropShadow;
  52381. }
  52382. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52383. bool, MenuBarComponent& menuBar)
  52384. {
  52385. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52386. if (menuBar.isEnabled())
  52387. {
  52388. drawShinyButtonShape (g,
  52389. -4.0f, 0.0f,
  52390. width + 8.0f, (float) height,
  52391. 0.0f,
  52392. baseColour,
  52393. 0.4f,
  52394. true, true, true, true);
  52395. }
  52396. else
  52397. {
  52398. g.fillAll (baseColour);
  52399. }
  52400. }
  52401. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52402. {
  52403. return Font (menuBar.getHeight() * 0.7f);
  52404. }
  52405. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52406. {
  52407. return getMenuBarFont (menuBar, itemIndex, itemText)
  52408. .getStringWidth (itemText) + menuBar.getHeight();
  52409. }
  52410. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52411. int width, int height,
  52412. int itemIndex,
  52413. const String& itemText,
  52414. bool isMouseOverItem,
  52415. bool isMenuOpen,
  52416. bool /*isMouseOverBar*/,
  52417. MenuBarComponent& menuBar)
  52418. {
  52419. if (! menuBar.isEnabled())
  52420. {
  52421. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52422. .withMultipliedAlpha (0.5f));
  52423. }
  52424. else if (isMenuOpen || isMouseOverItem)
  52425. {
  52426. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52427. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52428. }
  52429. else
  52430. {
  52431. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52432. }
  52433. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52434. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52435. }
  52436. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52437. TextEditor& textEditor)
  52438. {
  52439. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52440. }
  52441. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52442. {
  52443. if (textEditor.isEnabled())
  52444. {
  52445. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52446. {
  52447. const int border = 2;
  52448. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52449. g.drawRect (0, 0, width, height, border);
  52450. g.setOpacity (1.0f);
  52451. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52452. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52453. }
  52454. else
  52455. {
  52456. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52457. g.drawRect (0, 0, width, height);
  52458. g.setOpacity (1.0f);
  52459. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52460. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52461. }
  52462. }
  52463. }
  52464. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52465. const bool isButtonDown,
  52466. int buttonX, int buttonY,
  52467. int buttonW, int buttonH,
  52468. ComboBox& box)
  52469. {
  52470. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52471. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52472. {
  52473. g.setColour (box.findColour (TextButton::buttonColourId));
  52474. g.drawRect (0, 0, width, height, 2);
  52475. }
  52476. else
  52477. {
  52478. g.setColour (box.findColour (ComboBox::outlineColourId));
  52479. g.drawRect (0, 0, width, height);
  52480. }
  52481. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52482. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52483. box.hasKeyboardFocus (true),
  52484. false, isButtonDown)
  52485. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52486. drawGlassLozenge (g,
  52487. buttonX + outlineThickness, buttonY + outlineThickness,
  52488. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52489. baseColour, outlineThickness, -1.0f,
  52490. true, true, true, true);
  52491. if (box.isEnabled())
  52492. {
  52493. const float arrowX = 0.3f;
  52494. const float arrowH = 0.2f;
  52495. Path p;
  52496. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52497. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52498. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52499. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52500. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52501. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52502. g.setColour (box.findColour (ComboBox::arrowColourId));
  52503. g.fillPath (p);
  52504. }
  52505. }
  52506. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52507. {
  52508. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52509. }
  52510. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52511. {
  52512. return new Label (String::empty, String::empty);
  52513. }
  52514. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52515. {
  52516. label.setBounds (1, 1,
  52517. box.getWidth() + 3 - box.getHeight(),
  52518. box.getHeight() - 2);
  52519. label.setFont (getComboBoxFont (box));
  52520. }
  52521. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52522. {
  52523. g.fillAll (label.findColour (Label::backgroundColourId));
  52524. if (! label.isBeingEdited())
  52525. {
  52526. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52527. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52528. g.setFont (label.getFont());
  52529. g.drawFittedText (label.getText(),
  52530. label.getHorizontalBorderSize(),
  52531. label.getVerticalBorderSize(),
  52532. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52533. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52534. label.getJustificationType(),
  52535. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52536. label.getMinimumHorizontalScale());
  52537. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52538. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52539. }
  52540. else if (label.isEnabled())
  52541. {
  52542. g.setColour (label.findColour (Label::outlineColourId));
  52543. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52544. }
  52545. }
  52546. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52547. int x, int y,
  52548. int width, int height,
  52549. float /*sliderPos*/,
  52550. float /*minSliderPos*/,
  52551. float /*maxSliderPos*/,
  52552. const Slider::SliderStyle /*style*/,
  52553. Slider& slider)
  52554. {
  52555. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52556. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52557. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52558. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52559. Path indent;
  52560. if (slider.isHorizontal())
  52561. {
  52562. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52563. const float ih = sliderRadius;
  52564. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52565. gradCol2, 0.0f, iy + ih, false));
  52566. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52567. width + sliderRadius, ih,
  52568. 5.0f);
  52569. g.fillPath (indent);
  52570. }
  52571. else
  52572. {
  52573. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52574. const float iw = sliderRadius;
  52575. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52576. gradCol2, ix + iw, 0.0f, false));
  52577. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52578. iw, height + sliderRadius,
  52579. 5.0f);
  52580. g.fillPath (indent);
  52581. }
  52582. g.setColour (Colour (0x4c000000));
  52583. g.strokePath (indent, PathStrokeType (0.5f));
  52584. }
  52585. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52586. int x, int y,
  52587. int width, int height,
  52588. float sliderPos,
  52589. float minSliderPos,
  52590. float maxSliderPos,
  52591. const Slider::SliderStyle style,
  52592. Slider& slider)
  52593. {
  52594. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52595. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52596. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52597. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52598. slider.isMouseButtonDown() && slider.isEnabled()));
  52599. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52600. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52601. {
  52602. float kx, ky;
  52603. if (style == Slider::LinearVertical)
  52604. {
  52605. kx = x + width * 0.5f;
  52606. ky = sliderPos;
  52607. }
  52608. else
  52609. {
  52610. kx = sliderPos;
  52611. ky = y + height * 0.5f;
  52612. }
  52613. drawGlassSphere (g,
  52614. kx - sliderRadius,
  52615. ky - sliderRadius,
  52616. sliderRadius * 2.0f,
  52617. knobColour, outlineThickness);
  52618. }
  52619. else
  52620. {
  52621. if (style == Slider::ThreeValueVertical)
  52622. {
  52623. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52624. sliderPos - sliderRadius,
  52625. sliderRadius * 2.0f,
  52626. knobColour, outlineThickness);
  52627. }
  52628. else if (style == Slider::ThreeValueHorizontal)
  52629. {
  52630. drawGlassSphere (g,sliderPos - sliderRadius,
  52631. y + height * 0.5f - sliderRadius,
  52632. sliderRadius * 2.0f,
  52633. knobColour, outlineThickness);
  52634. }
  52635. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52636. {
  52637. const float sr = jmin (sliderRadius, width * 0.4f);
  52638. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52639. minSliderPos - sliderRadius,
  52640. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52641. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52642. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52643. }
  52644. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52645. {
  52646. const float sr = jmin (sliderRadius, height * 0.4f);
  52647. drawGlassPointer (g, minSliderPos - sr,
  52648. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52649. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52650. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52651. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52652. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52653. }
  52654. }
  52655. }
  52656. void LookAndFeel::drawLinearSlider (Graphics& g,
  52657. int x, int y,
  52658. int width, int height,
  52659. float sliderPos,
  52660. float minSliderPos,
  52661. float maxSliderPos,
  52662. const Slider::SliderStyle style,
  52663. Slider& slider)
  52664. {
  52665. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52666. if (style == Slider::LinearBar)
  52667. {
  52668. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52669. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52670. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52671. false,
  52672. isMouseOver,
  52673. isMouseOver || slider.isMouseButtonDown()));
  52674. drawShinyButtonShape (g,
  52675. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52676. baseColour,
  52677. slider.isEnabled() ? 0.9f : 0.3f,
  52678. true, true, true, true);
  52679. }
  52680. else
  52681. {
  52682. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52683. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52684. }
  52685. }
  52686. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52687. {
  52688. return jmin (7,
  52689. slider.getHeight() / 2,
  52690. slider.getWidth() / 2) + 2;
  52691. }
  52692. void LookAndFeel::drawRotarySlider (Graphics& g,
  52693. int x, int y,
  52694. int width, int height,
  52695. float sliderPos,
  52696. const float rotaryStartAngle,
  52697. const float rotaryEndAngle,
  52698. Slider& slider)
  52699. {
  52700. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52701. const float centreX = x + width * 0.5f;
  52702. const float centreY = y + height * 0.5f;
  52703. const float rx = centreX - radius;
  52704. const float ry = centreY - radius;
  52705. const float rw = radius * 2.0f;
  52706. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52707. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52708. if (radius > 12.0f)
  52709. {
  52710. if (slider.isEnabled())
  52711. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52712. else
  52713. g.setColour (Colour (0x80808080));
  52714. const float thickness = 0.7f;
  52715. {
  52716. Path filledArc;
  52717. filledArc.addPieSegment (rx, ry, rw, rw,
  52718. rotaryStartAngle,
  52719. angle,
  52720. thickness);
  52721. g.fillPath (filledArc);
  52722. }
  52723. if (thickness > 0)
  52724. {
  52725. const float innerRadius = radius * 0.2f;
  52726. Path p;
  52727. p.addTriangle (-innerRadius, 0.0f,
  52728. 0.0f, -radius * thickness * 1.1f,
  52729. innerRadius, 0.0f);
  52730. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52731. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52732. }
  52733. if (slider.isEnabled())
  52734. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52735. else
  52736. g.setColour (Colour (0x80808080));
  52737. Path outlineArc;
  52738. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52739. outlineArc.closeSubPath();
  52740. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52741. }
  52742. else
  52743. {
  52744. if (slider.isEnabled())
  52745. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52746. else
  52747. g.setColour (Colour (0x80808080));
  52748. Path p;
  52749. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52750. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52751. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52752. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52753. }
  52754. }
  52755. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52756. {
  52757. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52758. }
  52759. class SliderLabelComp : public Label
  52760. {
  52761. public:
  52762. SliderLabelComp() : Label (String::empty, String::empty) {}
  52763. ~SliderLabelComp() {}
  52764. void mouseWheelMove (const MouseEvent&, float, float) {}
  52765. };
  52766. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52767. {
  52768. Label* const l = new SliderLabelComp();
  52769. l->setJustificationType (Justification::centred);
  52770. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52771. l->setColour (Label::backgroundColourId,
  52772. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52773. : slider.findColour (Slider::textBoxBackgroundColourId));
  52774. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52775. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52776. l->setColour (TextEditor::backgroundColourId,
  52777. slider.findColour (Slider::textBoxBackgroundColourId)
  52778. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52779. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52780. return l;
  52781. }
  52782. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52783. {
  52784. return 0;
  52785. }
  52786. static const TextLayout layoutTooltipText (const String& text) throw()
  52787. {
  52788. const float tooltipFontSize = 12.0f;
  52789. const int maxToolTipWidth = 400;
  52790. const Font f (tooltipFontSize, Font::bold);
  52791. TextLayout tl (text, f);
  52792. tl.layout (maxToolTipWidth, Justification::left, true);
  52793. return tl;
  52794. }
  52795. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52796. {
  52797. const TextLayout tl (layoutTooltipText (tipText));
  52798. width = tl.getWidth() + 14;
  52799. height = tl.getHeight() + 6;
  52800. }
  52801. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52802. {
  52803. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52804. const Colour textCol (findColour (TooltipWindow::textColourId));
  52805. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52806. g.setColour (findColour (TooltipWindow::outlineColourId));
  52807. g.drawRect (0, 0, width, height, 1);
  52808. #endif
  52809. const TextLayout tl (layoutTooltipText (text));
  52810. g.setColour (findColour (TooltipWindow::textColourId));
  52811. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52812. }
  52813. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52814. {
  52815. return new TextButton (text, TRANS("click to browse for a different file"));
  52816. }
  52817. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52818. ComboBox* filenameBox,
  52819. Button* browseButton)
  52820. {
  52821. browseButton->setSize (80, filenameComp.getHeight());
  52822. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52823. if (tb != 0)
  52824. tb->changeWidthToFitText();
  52825. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52826. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52827. }
  52828. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52829. int imageX, int imageY, int imageW, int imageH,
  52830. const Colour& overlayColour,
  52831. float imageOpacity,
  52832. ImageButton& button)
  52833. {
  52834. if (! button.isEnabled())
  52835. imageOpacity *= 0.3f;
  52836. if (! overlayColour.isOpaque())
  52837. {
  52838. g.setOpacity (imageOpacity);
  52839. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52840. 0, 0, image->getWidth(), image->getHeight(), false);
  52841. }
  52842. if (! overlayColour.isTransparent())
  52843. {
  52844. g.setColour (overlayColour);
  52845. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52846. 0, 0, image->getWidth(), image->getHeight(), true);
  52847. }
  52848. }
  52849. void LookAndFeel::drawCornerResizer (Graphics& g,
  52850. int w, int h,
  52851. bool /*isMouseOver*/,
  52852. bool /*isMouseDragging*/)
  52853. {
  52854. const float lineThickness = jmin (w, h) * 0.075f;
  52855. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52856. {
  52857. g.setColour (Colours::lightgrey);
  52858. g.drawLine (w * i,
  52859. h + 1.0f,
  52860. w + 1.0f,
  52861. h * i,
  52862. lineThickness);
  52863. g.setColour (Colours::darkgrey);
  52864. g.drawLine (w * i + lineThickness,
  52865. h + 1.0f,
  52866. w + 1.0f,
  52867. h * i + lineThickness,
  52868. lineThickness);
  52869. }
  52870. }
  52871. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52872. const BorderSize& /*borders*/)
  52873. {
  52874. }
  52875. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52876. const BorderSize& /*border*/, ResizableWindow& window)
  52877. {
  52878. g.fillAll (window.getBackgroundColour());
  52879. }
  52880. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52881. const BorderSize& border, ResizableWindow&)
  52882. {
  52883. g.setColour (Colour (0x80000000));
  52884. g.drawRect (0, 0, w, h);
  52885. g.setColour (Colour (0x19000000));
  52886. g.drawRect (border.getLeft() - 1,
  52887. border.getTop() - 1,
  52888. w + 2 - border.getLeftAndRight(),
  52889. h + 2 - border.getTopAndBottom());
  52890. }
  52891. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52892. Graphics& g, int w, int h,
  52893. int titleSpaceX, int titleSpaceW,
  52894. const Image* icon,
  52895. bool drawTitleTextOnLeft)
  52896. {
  52897. const bool isActive = window.isActiveWindow();
  52898. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52899. 0.0f, 0.0f,
  52900. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52901. 0.0f, (float) h, false));
  52902. g.fillAll();
  52903. Font font (h * 0.65f, Font::bold);
  52904. g.setFont (font);
  52905. int textW = font.getStringWidth (window.getName());
  52906. int iconW = 0;
  52907. int iconH = 0;
  52908. if (icon != 0)
  52909. {
  52910. iconH = (int) font.getHeight();
  52911. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52912. }
  52913. textW = jmin (titleSpaceW, textW + iconW);
  52914. int textX = drawTitleTextOnLeft ? titleSpaceX
  52915. : jmax (titleSpaceX, (w - textW) / 2);
  52916. if (textX + textW > titleSpaceX + titleSpaceW)
  52917. textX = titleSpaceX + titleSpaceW - textW;
  52918. if (icon != 0)
  52919. {
  52920. g.setOpacity (isActive ? 1.0f : 0.6f);
  52921. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52922. RectanglePlacement::centred, false);
  52923. textX += iconW;
  52924. textW -= iconW;
  52925. }
  52926. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52927. g.setColour (findColour (DocumentWindow::textColourId));
  52928. else
  52929. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52930. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52931. }
  52932. class GlassWindowButton : public Button
  52933. {
  52934. public:
  52935. GlassWindowButton (const String& name, const Colour& col,
  52936. const Path& normalShape_,
  52937. const Path& toggledShape_) throw()
  52938. : Button (name),
  52939. colour (col),
  52940. normalShape (normalShape_),
  52941. toggledShape (toggledShape_)
  52942. {
  52943. }
  52944. ~GlassWindowButton()
  52945. {
  52946. }
  52947. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52948. {
  52949. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52950. if (! isEnabled())
  52951. alpha *= 0.5f;
  52952. float x = 0, y = 0, diam;
  52953. if (getWidth() < getHeight())
  52954. {
  52955. diam = (float) getWidth();
  52956. y = (getHeight() - getWidth()) * 0.5f;
  52957. }
  52958. else
  52959. {
  52960. diam = (float) getHeight();
  52961. y = (getWidth() - getHeight()) * 0.5f;
  52962. }
  52963. x += diam * 0.05f;
  52964. y += diam * 0.05f;
  52965. diam *= 0.9f;
  52966. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52967. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52968. g.fillEllipse (x, y, diam, diam);
  52969. x += 2.0f;
  52970. y += 2.0f;
  52971. diam -= 4.0f;
  52972. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52973. Path& p = getToggleState() ? toggledShape : normalShape;
  52974. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52975. diam * 0.4f, diam * 0.4f, true));
  52976. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52977. g.fillPath (p, t);
  52978. }
  52979. juce_UseDebuggingNewOperator
  52980. private:
  52981. Colour colour;
  52982. Path normalShape, toggledShape;
  52983. GlassWindowButton (const GlassWindowButton&);
  52984. GlassWindowButton& operator= (const GlassWindowButton&);
  52985. };
  52986. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52987. {
  52988. Path shape;
  52989. const float crossThickness = 0.25f;
  52990. if (buttonType == DocumentWindow::closeButton)
  52991. {
  52992. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52993. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52994. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52995. }
  52996. else if (buttonType == DocumentWindow::minimiseButton)
  52997. {
  52998. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52999. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53000. }
  53001. else if (buttonType == DocumentWindow::maximiseButton)
  53002. {
  53003. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53004. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53005. Path fullscreenShape;
  53006. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53007. fullscreenShape.lineTo (0.0f, 100.0f);
  53008. fullscreenShape.lineTo (0.0f, 0.0f);
  53009. fullscreenShape.lineTo (100.0f, 0.0f);
  53010. fullscreenShape.lineTo (100.0f, 45.0f);
  53011. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53012. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53013. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53014. }
  53015. jassertfalse;
  53016. return 0;
  53017. }
  53018. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53019. int titleBarX,
  53020. int titleBarY,
  53021. int titleBarW,
  53022. int titleBarH,
  53023. Button* minimiseButton,
  53024. Button* maximiseButton,
  53025. Button* closeButton,
  53026. bool positionTitleBarButtonsOnLeft)
  53027. {
  53028. const int buttonW = titleBarH - titleBarH / 8;
  53029. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53030. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53031. if (closeButton != 0)
  53032. {
  53033. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53034. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53035. }
  53036. if (positionTitleBarButtonsOnLeft)
  53037. swapVariables (minimiseButton, maximiseButton);
  53038. if (maximiseButton != 0)
  53039. {
  53040. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53041. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53042. }
  53043. if (minimiseButton != 0)
  53044. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53045. }
  53046. int LookAndFeel::getDefaultMenuBarHeight()
  53047. {
  53048. return 24;
  53049. }
  53050. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53051. {
  53052. return new DropShadower (0.4f, 1, 5, 10);
  53053. }
  53054. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53055. int w, int h,
  53056. bool /*isVerticalBar*/,
  53057. bool isMouseOver,
  53058. bool isMouseDragging)
  53059. {
  53060. float alpha = 0.5f;
  53061. if (isMouseOver || isMouseDragging)
  53062. {
  53063. g.fillAll (Colour (0x190000ff));
  53064. alpha = 1.0f;
  53065. }
  53066. const float cx = w * 0.5f;
  53067. const float cy = h * 0.5f;
  53068. const float cr = jmin (w, h) * 0.4f;
  53069. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53070. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53071. true));
  53072. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53073. }
  53074. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53075. const String& text,
  53076. const Justification& position,
  53077. GroupComponent& group)
  53078. {
  53079. const float textH = 15.0f;
  53080. const float indent = 3.0f;
  53081. const float textEdgeGap = 4.0f;
  53082. float cs = 5.0f;
  53083. Font f (textH);
  53084. Path p;
  53085. float x = indent;
  53086. float y = f.getAscent() - 3.0f;
  53087. float w = jmax (0.0f, width - x * 2.0f);
  53088. float h = jmax (0.0f, height - y - indent);
  53089. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53090. const float cs2 = 2.0f * cs;
  53091. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53092. float textX = cs + textEdgeGap;
  53093. if (position.testFlags (Justification::horizontallyCentred))
  53094. textX = cs + (w - cs2 - textW) * 0.5f;
  53095. else if (position.testFlags (Justification::right))
  53096. textX = w - cs - textW - textEdgeGap;
  53097. p.startNewSubPath (x + textX + textW, y);
  53098. p.lineTo (x + w - cs, y);
  53099. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53100. p.lineTo (x + w, y + h - cs);
  53101. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53102. p.lineTo (x + cs, y + h);
  53103. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53104. p.lineTo (x, y + cs);
  53105. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53106. p.lineTo (x + textX, y);
  53107. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53108. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53109. .withMultipliedAlpha (alpha));
  53110. g.strokePath (p, PathStrokeType (2.0f));
  53111. g.setColour (group.findColour (GroupComponent::textColourId)
  53112. .withMultipliedAlpha (alpha));
  53113. g.setFont (f);
  53114. g.drawText (text,
  53115. roundToInt (x + textX), 0,
  53116. roundToInt (textW),
  53117. roundToInt (textH),
  53118. Justification::centred, true);
  53119. }
  53120. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53121. {
  53122. return 1 + tabDepth / 3;
  53123. }
  53124. int LookAndFeel::getTabButtonSpaceAroundImage()
  53125. {
  53126. return 4;
  53127. }
  53128. void LookAndFeel::createTabButtonShape (Path& p,
  53129. int width, int height,
  53130. int /*tabIndex*/,
  53131. const String& /*text*/,
  53132. Button& /*button*/,
  53133. TabbedButtonBar::Orientation orientation,
  53134. const bool /*isMouseOver*/,
  53135. const bool /*isMouseDown*/,
  53136. const bool /*isFrontTab*/)
  53137. {
  53138. const float w = (float) width;
  53139. const float h = (float) height;
  53140. float length = w;
  53141. float depth = h;
  53142. if (orientation == TabbedButtonBar::TabsAtLeft
  53143. || orientation == TabbedButtonBar::TabsAtRight)
  53144. {
  53145. swapVariables (length, depth);
  53146. }
  53147. const float indent = (float) getTabButtonOverlap ((int) depth);
  53148. const float overhang = 4.0f;
  53149. if (orientation == TabbedButtonBar::TabsAtLeft)
  53150. {
  53151. p.startNewSubPath (w, 0.0f);
  53152. p.lineTo (0.0f, indent);
  53153. p.lineTo (0.0f, h - indent);
  53154. p.lineTo (w, h);
  53155. p.lineTo (w + overhang, h + overhang);
  53156. p.lineTo (w + overhang, -overhang);
  53157. }
  53158. else if (orientation == TabbedButtonBar::TabsAtRight)
  53159. {
  53160. p.startNewSubPath (0.0f, 0.0f);
  53161. p.lineTo (w, indent);
  53162. p.lineTo (w, h - indent);
  53163. p.lineTo (0.0f, h);
  53164. p.lineTo (-overhang, h + overhang);
  53165. p.lineTo (-overhang, -overhang);
  53166. }
  53167. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53168. {
  53169. p.startNewSubPath (0.0f, 0.0f);
  53170. p.lineTo (indent, h);
  53171. p.lineTo (w - indent, h);
  53172. p.lineTo (w, 0.0f);
  53173. p.lineTo (w + overhang, -overhang);
  53174. p.lineTo (-overhang, -overhang);
  53175. }
  53176. else
  53177. {
  53178. p.startNewSubPath (0.0f, h);
  53179. p.lineTo (indent, 0.0f);
  53180. p.lineTo (w - indent, 0.0f);
  53181. p.lineTo (w, h);
  53182. p.lineTo (w + overhang, h + overhang);
  53183. p.lineTo (-overhang, h + overhang);
  53184. }
  53185. p.closeSubPath();
  53186. p = p.createPathWithRoundedCorners (3.0f);
  53187. }
  53188. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53189. const Path& path,
  53190. const Colour& preferredColour,
  53191. int /*tabIndex*/,
  53192. const String& /*text*/,
  53193. Button& button,
  53194. TabbedButtonBar::Orientation /*orientation*/,
  53195. const bool /*isMouseOver*/,
  53196. const bool /*isMouseDown*/,
  53197. const bool isFrontTab)
  53198. {
  53199. g.setColour (isFrontTab ? preferredColour
  53200. : preferredColour.withMultipliedAlpha (0.9f));
  53201. g.fillPath (path);
  53202. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53203. : TabbedButtonBar::tabOutlineColourId, false)
  53204. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53205. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53206. }
  53207. void LookAndFeel::drawTabButtonText (Graphics& g,
  53208. int x, int y, int w, int h,
  53209. const Colour& preferredBackgroundColour,
  53210. int /*tabIndex*/,
  53211. const String& text,
  53212. Button& button,
  53213. TabbedButtonBar::Orientation orientation,
  53214. const bool isMouseOver,
  53215. const bool isMouseDown,
  53216. const bool isFrontTab)
  53217. {
  53218. int length = w;
  53219. int depth = h;
  53220. if (orientation == TabbedButtonBar::TabsAtLeft
  53221. || orientation == TabbedButtonBar::TabsAtRight)
  53222. {
  53223. swapVariables (length, depth);
  53224. }
  53225. Font font (depth * 0.6f);
  53226. font.setUnderline (button.hasKeyboardFocus (false));
  53227. GlyphArrangement textLayout;
  53228. textLayout.addFittedText (font, text.trim(),
  53229. 0.0f, 0.0f, (float) length, (float) depth,
  53230. Justification::centred,
  53231. jmax (1, depth / 12));
  53232. AffineTransform transform;
  53233. if (orientation == TabbedButtonBar::TabsAtLeft)
  53234. {
  53235. transform = transform.rotated (float_Pi * -0.5f)
  53236. .translated ((float) x, (float) (y + h));
  53237. }
  53238. else if (orientation == TabbedButtonBar::TabsAtRight)
  53239. {
  53240. transform = transform.rotated (float_Pi * 0.5f)
  53241. .translated ((float) (x + w), (float) y);
  53242. }
  53243. else
  53244. {
  53245. transform = transform.translated ((float) x, (float) y);
  53246. }
  53247. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53248. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53249. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53250. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53251. else
  53252. g.setColour (preferredBackgroundColour.contrasting());
  53253. if (! (isMouseOver || isMouseDown))
  53254. g.setOpacity (0.8f);
  53255. if (! button.isEnabled())
  53256. g.setOpacity (0.3f);
  53257. textLayout.draw (g, transform);
  53258. }
  53259. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53260. const String& text,
  53261. int tabDepth,
  53262. Button&)
  53263. {
  53264. Font f (tabDepth * 0.6f);
  53265. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53266. }
  53267. void LookAndFeel::drawTabButton (Graphics& g,
  53268. int w, int h,
  53269. const Colour& preferredColour,
  53270. int tabIndex,
  53271. const String& text,
  53272. Button& button,
  53273. TabbedButtonBar::Orientation orientation,
  53274. const bool isMouseOver,
  53275. const bool isMouseDown,
  53276. const bool isFrontTab)
  53277. {
  53278. int length = w;
  53279. int depth = h;
  53280. if (orientation == TabbedButtonBar::TabsAtLeft
  53281. || orientation == TabbedButtonBar::TabsAtRight)
  53282. {
  53283. swapVariables (length, depth);
  53284. }
  53285. Path tabShape;
  53286. createTabButtonShape (tabShape, w, h,
  53287. tabIndex, text, button, orientation,
  53288. isMouseOver, isMouseDown, isFrontTab);
  53289. fillTabButtonShape (g, tabShape, preferredColour,
  53290. tabIndex, text, button, orientation,
  53291. isMouseOver, isMouseDown, isFrontTab);
  53292. const int indent = getTabButtonOverlap (depth);
  53293. int x = 0, y = 0;
  53294. if (orientation == TabbedButtonBar::TabsAtLeft
  53295. || orientation == TabbedButtonBar::TabsAtRight)
  53296. {
  53297. y += indent;
  53298. h -= indent * 2;
  53299. }
  53300. else
  53301. {
  53302. x += indent;
  53303. w -= indent * 2;
  53304. }
  53305. drawTabButtonText (g, x, y, w, h, preferredColour,
  53306. tabIndex, text, button, orientation,
  53307. isMouseOver, isMouseDown, isFrontTab);
  53308. }
  53309. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53310. int w, int h,
  53311. TabbedButtonBar& tabBar,
  53312. TabbedButtonBar::Orientation orientation)
  53313. {
  53314. const float shadowSize = 0.2f;
  53315. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53316. Rectangle<int> shadowRect;
  53317. if (orientation == TabbedButtonBar::TabsAtLeft)
  53318. {
  53319. x1 = (float) w;
  53320. x2 = w * (1.0f - shadowSize);
  53321. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53322. }
  53323. else if (orientation == TabbedButtonBar::TabsAtRight)
  53324. {
  53325. x2 = w * shadowSize;
  53326. shadowRect.setBounds (0, 0, (int) x2, h);
  53327. }
  53328. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53329. {
  53330. y2 = h * shadowSize;
  53331. shadowRect.setBounds (0, 0, w, (int) y2);
  53332. }
  53333. else
  53334. {
  53335. y1 = (float) h;
  53336. y2 = h * (1.0f - shadowSize);
  53337. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53338. }
  53339. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53340. Colours::transparentBlack, x2, y2, false));
  53341. shadowRect.expand (2, 2);
  53342. g.fillRect (shadowRect);
  53343. g.setColour (Colour (0x80000000));
  53344. if (orientation == TabbedButtonBar::TabsAtLeft)
  53345. {
  53346. g.fillRect (w - 1, 0, 1, h);
  53347. }
  53348. else if (orientation == TabbedButtonBar::TabsAtRight)
  53349. {
  53350. g.fillRect (0, 0, 1, h);
  53351. }
  53352. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53353. {
  53354. g.fillRect (0, 0, w, 1);
  53355. }
  53356. else
  53357. {
  53358. g.fillRect (0, h - 1, w, 1);
  53359. }
  53360. }
  53361. Button* LookAndFeel::createTabBarExtrasButton()
  53362. {
  53363. const float thickness = 7.0f;
  53364. const float indent = 22.0f;
  53365. Path p;
  53366. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53367. DrawablePath ellipse;
  53368. ellipse.setPath (p);
  53369. ellipse.setFill (Colour (0x99ffffff));
  53370. p.clear();
  53371. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53372. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53373. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53374. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53375. p.setUsingNonZeroWinding (false);
  53376. DrawablePath dp;
  53377. dp.setPath (p);
  53378. dp.setFill (Colour (0x59000000));
  53379. DrawableComposite normalImage;
  53380. normalImage.insertDrawable (ellipse);
  53381. normalImage.insertDrawable (dp);
  53382. dp.setFill (Colour (0xcc000000));
  53383. DrawableComposite overImage;
  53384. overImage.insertDrawable (ellipse);
  53385. overImage.insertDrawable (dp);
  53386. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53387. db->setImages (&normalImage, &overImage, 0);
  53388. return db;
  53389. }
  53390. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53391. {
  53392. g.fillAll (Colours::white);
  53393. const int w = header.getWidth();
  53394. const int h = header.getHeight();
  53395. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53396. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53397. false));
  53398. g.fillRect (0, h / 2, w, h);
  53399. g.setColour (Colour (0x33000000));
  53400. g.fillRect (0, h - 1, w, 1);
  53401. for (int i = header.getNumColumns (true); --i >= 0;)
  53402. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53403. }
  53404. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53405. int width, int height,
  53406. bool isMouseOver, bool isMouseDown,
  53407. int columnFlags)
  53408. {
  53409. if (isMouseDown)
  53410. g.fillAll (Colour (0x8899aadd));
  53411. else if (isMouseOver)
  53412. g.fillAll (Colour (0x5599aadd));
  53413. int rightOfText = width - 4;
  53414. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53415. {
  53416. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53417. const float bottom = height - top;
  53418. const float w = height * 0.5f;
  53419. const float x = rightOfText - (w * 1.25f);
  53420. rightOfText = (int) x;
  53421. Path sortArrow;
  53422. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53423. g.setColour (Colour (0x99000000));
  53424. g.fillPath (sortArrow);
  53425. }
  53426. g.setColour (Colours::black);
  53427. g.setFont (height * 0.5f, Font::bold);
  53428. const int textX = 4;
  53429. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53430. }
  53431. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53432. {
  53433. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53434. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53435. background.darker (0.1f),
  53436. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53437. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53438. false));
  53439. g.fillAll();
  53440. }
  53441. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53442. {
  53443. return createTabBarExtrasButton();
  53444. }
  53445. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53446. bool isMouseOver, bool isMouseDown,
  53447. ToolbarItemComponent& component)
  53448. {
  53449. if (isMouseDown)
  53450. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53451. else if (isMouseOver)
  53452. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53453. }
  53454. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53455. const String& text, ToolbarItemComponent& component)
  53456. {
  53457. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53458. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53459. const float fontHeight = jmin (14.0f, height * 0.85f);
  53460. g.setFont (fontHeight);
  53461. g.drawFittedText (text,
  53462. x, y, width, height,
  53463. Justification::centred,
  53464. jmax (1, height / (int) fontHeight));
  53465. }
  53466. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53467. bool isOpen, int width, int height)
  53468. {
  53469. const int buttonSize = (height * 3) / 4;
  53470. const int buttonIndent = (height - buttonSize) / 2;
  53471. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53472. const int textX = buttonIndent * 2 + buttonSize + 2;
  53473. g.setColour (Colours::black);
  53474. g.setFont (height * 0.7f, Font::bold);
  53475. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53476. }
  53477. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53478. PropertyComponent&)
  53479. {
  53480. g.setColour (Colour (0x66ffffff));
  53481. g.fillRect (0, 0, width, height - 1);
  53482. }
  53483. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53484. PropertyComponent& component)
  53485. {
  53486. g.setColour (Colours::black);
  53487. if (! component.isEnabled())
  53488. g.setOpacity (0.6f);
  53489. g.setFont (jmin (height, 24) * 0.65f);
  53490. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53491. g.drawFittedText (component.getName(),
  53492. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53493. Justification::centredLeft, 2);
  53494. }
  53495. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53496. {
  53497. return Rectangle<int> (component.getWidth() / 3, 1,
  53498. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53499. }
  53500. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53501. {
  53502. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53503. {
  53504. Graphics g2 (content);
  53505. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53506. g2.fillPath (path);
  53507. g2.setColour (Colours::white.withAlpha (0.8f));
  53508. g2.strokePath (path, PathStrokeType (2.0f));
  53509. }
  53510. DropShadowEffect shadow;
  53511. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53512. shadow.applyEffect (content, g);
  53513. }
  53514. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53515. const String& instructions,
  53516. GlyphArrangement& text,
  53517. int width)
  53518. {
  53519. text.clear();
  53520. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53521. 8.0f, 22.0f, width - 16.0f,
  53522. Justification::centred);
  53523. text.addJustifiedText (Font (14.0f), instructions,
  53524. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53525. Justification::centred);
  53526. }
  53527. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53528. const String& filename, Image* icon,
  53529. const String& fileSizeDescription,
  53530. const String& fileTimeDescription,
  53531. const bool isDirectory,
  53532. const bool isItemSelected,
  53533. const int /*itemIndex*/)
  53534. {
  53535. if (isItemSelected)
  53536. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53537. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53538. g.setFont (height * 0.7f);
  53539. Image im;
  53540. if (icon != 0)
  53541. im = *icon;
  53542. if (im.isNull())
  53543. im = isDirectory ? getDefaultFolderImage()
  53544. : getDefaultDocumentFileImage();
  53545. const int x = 32;
  53546. if (im.isValid())
  53547. {
  53548. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53549. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53550. false);
  53551. }
  53552. if (width > 450 && ! isDirectory)
  53553. {
  53554. const int sizeX = roundToInt (width * 0.7f);
  53555. const int dateX = roundToInt (width * 0.8f);
  53556. g.drawFittedText (filename,
  53557. x, 0, sizeX - x, height,
  53558. Justification::centredLeft, 1);
  53559. g.setFont (height * 0.5f);
  53560. g.setColour (Colours::darkgrey);
  53561. if (! isDirectory)
  53562. {
  53563. g.drawFittedText (fileSizeDescription,
  53564. sizeX, 0, dateX - sizeX - 8, height,
  53565. Justification::centredRight, 1);
  53566. g.drawFittedText (fileTimeDescription,
  53567. dateX, 0, width - 8 - dateX, height,
  53568. Justification::centredRight, 1);
  53569. }
  53570. }
  53571. else
  53572. {
  53573. g.drawFittedText (filename,
  53574. x, 0, width - x, height,
  53575. Justification::centredLeft, 1);
  53576. }
  53577. }
  53578. Button* LookAndFeel::createFileBrowserGoUpButton()
  53579. {
  53580. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53581. Path arrowPath;
  53582. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53583. DrawablePath arrowImage;
  53584. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53585. arrowImage.setPath (arrowPath);
  53586. goUpButton->setImages (&arrowImage);
  53587. return goUpButton;
  53588. }
  53589. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53590. DirectoryContentsDisplayComponent* fileListComponent,
  53591. FilePreviewComponent* previewComp,
  53592. ComboBox* currentPathBox,
  53593. TextEditor* filenameBox,
  53594. Button* goUpButton)
  53595. {
  53596. const int x = 8;
  53597. int w = browserComp.getWidth() - x - x;
  53598. if (previewComp != 0)
  53599. {
  53600. const int previewWidth = w / 3;
  53601. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53602. w -= previewWidth + 4;
  53603. }
  53604. int y = 4;
  53605. const int controlsHeight = 22;
  53606. const int bottomSectionHeight = controlsHeight + 8;
  53607. const int upButtonWidth = 50;
  53608. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53609. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53610. y += controlsHeight + 4;
  53611. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53612. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53613. y = listAsComp->getBottom() + 4;
  53614. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53615. }
  53616. const Image LookAndFeel::getDefaultFolderImage()
  53617. {
  53618. 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,
  53619. 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,
  53620. 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,
  53621. 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,
  53622. 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,
  53623. 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,
  53624. 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,
  53625. 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,
  53626. 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,
  53627. 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,
  53628. 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,
  53629. 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,
  53630. 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,
  53631. 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,
  53632. 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,
  53633. 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,
  53634. 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,
  53635. 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,
  53636. 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,
  53637. 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,
  53638. 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,
  53639. 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,
  53640. 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,
  53641. 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,
  53642. 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,
  53643. 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,
  53644. 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,
  53645. 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,
  53646. 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,
  53647. 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,
  53648. 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,
  53649. 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,
  53650. 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,
  53651. 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,
  53652. 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,
  53653. 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,
  53654. 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,
  53655. 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,
  53656. 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,
  53657. 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,
  53658. 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,
  53659. 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,
  53660. 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,
  53661. 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};
  53662. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53663. }
  53664. const Image LookAndFeel::getDefaultDocumentFileImage()
  53665. {
  53666. 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,
  53667. 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,
  53668. 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,
  53669. 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,
  53670. 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,
  53671. 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,
  53672. 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,
  53673. 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,
  53674. 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,
  53675. 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,
  53676. 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,
  53677. 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,
  53678. 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,
  53679. 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,
  53680. 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,
  53681. 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,
  53682. 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,
  53683. 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,
  53684. 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,
  53685. 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,
  53686. 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,
  53687. 174,66,96,130,0,0};
  53688. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53689. }
  53690. void LookAndFeel::playAlertSound()
  53691. {
  53692. PlatformUtilities::beep();
  53693. }
  53694. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53695. {
  53696. g.setColour (Colours::white.withAlpha (0.7f));
  53697. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53698. g.setColour (Colours::black.withAlpha (0.2f));
  53699. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53700. const int totalBlocks = 7;
  53701. const int numBlocks = roundToInt (totalBlocks * level);
  53702. const float w = (width - 6.0f) / (float) totalBlocks;
  53703. for (int i = 0; i < totalBlocks; ++i)
  53704. {
  53705. if (i >= numBlocks)
  53706. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53707. else
  53708. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53709. : Colours::red);
  53710. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53711. }
  53712. }
  53713. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53714. {
  53715. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53716. if (keyDescription.isNotEmpty())
  53717. {
  53718. if (button.isEnabled())
  53719. {
  53720. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53721. g.fillAll (textColour.withAlpha (alpha));
  53722. g.setOpacity (0.3f);
  53723. g.drawBevel (0, 0, width, height, 2);
  53724. }
  53725. g.setColour (textColour);
  53726. g.setFont (height * 0.6f);
  53727. g.drawFittedText (keyDescription,
  53728. 3, 0, width - 6, height,
  53729. Justification::centred, 1);
  53730. }
  53731. else
  53732. {
  53733. const float thickness = 7.0f;
  53734. const float indent = 22.0f;
  53735. Path p;
  53736. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53737. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53738. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53739. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53740. p.setUsingNonZeroWinding (false);
  53741. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53742. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53743. }
  53744. if (button.hasKeyboardFocus (false))
  53745. {
  53746. g.setColour (textColour.withAlpha (0.4f));
  53747. g.drawRect (0, 0, width, height);
  53748. }
  53749. }
  53750. static void createRoundedPath (Path& p,
  53751. const float x, const float y,
  53752. const float w, const float h,
  53753. const float cs,
  53754. const bool curveTopLeft, const bool curveTopRight,
  53755. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53756. {
  53757. const float cs2 = 2.0f * cs;
  53758. if (curveTopLeft)
  53759. {
  53760. p.startNewSubPath (x, y + cs);
  53761. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53762. }
  53763. else
  53764. {
  53765. p.startNewSubPath (x, y);
  53766. }
  53767. if (curveTopRight)
  53768. {
  53769. p.lineTo (x + w - cs, y);
  53770. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53771. }
  53772. else
  53773. {
  53774. p.lineTo (x + w, y);
  53775. }
  53776. if (curveBottomRight)
  53777. {
  53778. p.lineTo (x + w, y + h - cs);
  53779. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53780. }
  53781. else
  53782. {
  53783. p.lineTo (x + w, y + h);
  53784. }
  53785. if (curveBottomLeft)
  53786. {
  53787. p.lineTo (x + cs, y + h);
  53788. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53789. }
  53790. else
  53791. {
  53792. p.lineTo (x, y + h);
  53793. }
  53794. p.closeSubPath();
  53795. }
  53796. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53797. float x, float y, float w, float h,
  53798. float maxCornerSize,
  53799. const Colour& baseColour,
  53800. const float strokeWidth,
  53801. const bool flatOnLeft,
  53802. const bool flatOnRight,
  53803. const bool flatOnTop,
  53804. const bool flatOnBottom) throw()
  53805. {
  53806. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53807. return;
  53808. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53809. Path outline;
  53810. createRoundedPath (outline, x, y, w, h, cs,
  53811. ! (flatOnLeft || flatOnTop),
  53812. ! (flatOnRight || flatOnTop),
  53813. ! (flatOnLeft || flatOnBottom),
  53814. ! (flatOnRight || flatOnBottom));
  53815. ColourGradient cg (baseColour, 0.0f, y,
  53816. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53817. false);
  53818. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53819. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53820. g.setGradientFill (cg);
  53821. g.fillPath (outline);
  53822. g.setColour (Colour (0x80000000));
  53823. g.strokePath (outline, PathStrokeType (strokeWidth));
  53824. }
  53825. void LookAndFeel::drawGlassSphere (Graphics& g,
  53826. const float x, const float y,
  53827. const float diameter,
  53828. const Colour& colour,
  53829. const float outlineThickness) throw()
  53830. {
  53831. if (diameter <= outlineThickness)
  53832. return;
  53833. Path p;
  53834. p.addEllipse (x, y, diameter, diameter);
  53835. {
  53836. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53837. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53838. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53839. g.setGradientFill (cg);
  53840. g.fillPath (p);
  53841. }
  53842. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53843. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53844. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53845. ColourGradient cg (Colours::transparentBlack,
  53846. x + diameter * 0.5f, y + diameter * 0.5f,
  53847. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53848. x, y + diameter * 0.5f, true);
  53849. cg.addColour (0.7, Colours::transparentBlack);
  53850. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53851. g.setGradientFill (cg);
  53852. g.fillPath (p);
  53853. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53854. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53855. }
  53856. void LookAndFeel::drawGlassPointer (Graphics& g,
  53857. const float x, const float y,
  53858. const float diameter,
  53859. const Colour& colour, const float outlineThickness,
  53860. const int direction) throw()
  53861. {
  53862. if (diameter <= outlineThickness)
  53863. return;
  53864. Path p;
  53865. p.startNewSubPath (x + diameter * 0.5f, y);
  53866. p.lineTo (x + diameter, y + diameter * 0.6f);
  53867. p.lineTo (x + diameter, y + diameter);
  53868. p.lineTo (x, y + diameter);
  53869. p.lineTo (x, y + diameter * 0.6f);
  53870. p.closeSubPath();
  53871. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53872. {
  53873. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53874. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53875. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53876. g.setGradientFill (cg);
  53877. g.fillPath (p);
  53878. }
  53879. ColourGradient cg (Colours::transparentBlack,
  53880. x + diameter * 0.5f, y + diameter * 0.5f,
  53881. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53882. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53883. cg.addColour (0.5, Colours::transparentBlack);
  53884. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53885. g.setGradientFill (cg);
  53886. g.fillPath (p);
  53887. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53888. g.strokePath (p, PathStrokeType (outlineThickness));
  53889. }
  53890. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53891. const float x, const float y,
  53892. const float width, const float height,
  53893. const Colour& colour,
  53894. const float outlineThickness,
  53895. const float cornerSize,
  53896. const bool flatOnLeft,
  53897. const bool flatOnRight,
  53898. const bool flatOnTop,
  53899. const bool flatOnBottom) throw()
  53900. {
  53901. if (width <= outlineThickness || height <= outlineThickness)
  53902. return;
  53903. const int intX = (int) x;
  53904. const int intY = (int) y;
  53905. const int intW = (int) width;
  53906. const int intH = (int) height;
  53907. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53908. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53909. const int intEdge = (int) edgeBlurRadius;
  53910. Path outline;
  53911. createRoundedPath (outline, x, y, width, height, cs,
  53912. ! (flatOnLeft || flatOnTop),
  53913. ! (flatOnRight || flatOnTop),
  53914. ! (flatOnLeft || flatOnBottom),
  53915. ! (flatOnRight || flatOnBottom));
  53916. {
  53917. ColourGradient cg (colour.darker (0.2f), 0, y,
  53918. colour.darker (0.2f), 0, y + height, false);
  53919. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53920. cg.addColour (0.4, colour);
  53921. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53922. g.setGradientFill (cg);
  53923. g.fillPath (outline);
  53924. }
  53925. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53926. colour.darker (0.2f), x, y + height * 0.5f, true);
  53927. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53928. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53929. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53930. {
  53931. g.saveState();
  53932. g.setGradientFill (cg);
  53933. g.reduceClipRegion (intX, intY, intEdge, intH);
  53934. g.fillPath (outline);
  53935. g.restoreState();
  53936. }
  53937. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53938. {
  53939. cg.point1.setX (x + width - edgeBlurRadius);
  53940. cg.point2.setX (x + width);
  53941. g.saveState();
  53942. g.setGradientFill (cg);
  53943. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53944. g.fillPath (outline);
  53945. g.restoreState();
  53946. }
  53947. {
  53948. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53949. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53950. Path highlight;
  53951. createRoundedPath (highlight,
  53952. x + leftIndent,
  53953. y + cs * 0.1f,
  53954. width - (leftIndent + rightIndent),
  53955. height * 0.4f, cs * 0.4f,
  53956. ! (flatOnLeft || flatOnTop),
  53957. ! (flatOnRight || flatOnTop),
  53958. ! (flatOnLeft || flatOnBottom),
  53959. ! (flatOnRight || flatOnBottom));
  53960. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53961. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53962. g.fillPath (highlight);
  53963. }
  53964. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53965. g.strokePath (outline, PathStrokeType (outlineThickness));
  53966. }
  53967. END_JUCE_NAMESPACE
  53968. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53969. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53970. BEGIN_JUCE_NAMESPACE
  53971. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53972. {
  53973. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53974. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53975. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53976. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53977. setColour (Slider::thumbColourId, Colours::white);
  53978. setColour (Slider::trackColourId, Colour (0x7f000000));
  53979. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53980. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53981. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53982. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53983. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53984. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53985. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53986. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53987. }
  53988. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53989. {
  53990. }
  53991. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53992. Button& button,
  53993. const Colour& backgroundColour,
  53994. bool isMouseOverButton,
  53995. bool isButtonDown)
  53996. {
  53997. const int width = button.getWidth();
  53998. const int height = button.getHeight();
  53999. const float indent = 2.0f;
  54000. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54001. roundToInt (height * 0.4f));
  54002. Path p;
  54003. p.addRoundedRectangle (indent, indent,
  54004. width - indent * 2.0f,
  54005. height - indent * 2.0f,
  54006. (float) cornerSize);
  54007. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54008. if (isMouseOverButton)
  54009. {
  54010. if (isButtonDown)
  54011. bc = bc.brighter();
  54012. else if (bc.getBrightness() > 0.5f)
  54013. bc = bc.darker (0.1f);
  54014. else
  54015. bc = bc.brighter (0.1f);
  54016. }
  54017. g.setColour (bc);
  54018. g.fillPath (p);
  54019. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54020. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54021. }
  54022. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54023. Component& /*component*/,
  54024. float x, float y, float w, float h,
  54025. const bool ticked,
  54026. const bool isEnabled,
  54027. const bool /*isMouseOverButton*/,
  54028. const bool isButtonDown)
  54029. {
  54030. Path box;
  54031. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54032. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54033. : Colours::lightgrey.withAlpha (0.1f));
  54034. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54035. g.fillPath (box, trans);
  54036. g.setColour (Colours::black.withAlpha (0.6f));
  54037. g.strokePath (box, PathStrokeType (0.9f), trans);
  54038. if (ticked)
  54039. {
  54040. Path tick;
  54041. tick.startNewSubPath (1.5f, 3.0f);
  54042. tick.lineTo (3.0f, 6.0f);
  54043. tick.lineTo (6.0f, 0.0f);
  54044. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54045. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54046. }
  54047. }
  54048. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54049. ToggleButton& button,
  54050. bool isMouseOverButton,
  54051. bool isButtonDown)
  54052. {
  54053. if (button.hasKeyboardFocus (true))
  54054. {
  54055. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54056. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54057. }
  54058. const int tickWidth = jmin (20, button.getHeight() - 4);
  54059. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54060. (float) tickWidth, (float) tickWidth,
  54061. button.getToggleState(),
  54062. button.isEnabled(),
  54063. isMouseOverButton,
  54064. isButtonDown);
  54065. g.setColour (button.findColour (ToggleButton::textColourId));
  54066. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54067. if (! button.isEnabled())
  54068. g.setOpacity (0.5f);
  54069. const int textX = tickWidth + 5;
  54070. g.drawFittedText (button.getButtonText(),
  54071. textX, 4,
  54072. button.getWidth() - textX - 2, button.getHeight() - 8,
  54073. Justification::centredLeft, 10);
  54074. }
  54075. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54076. int width, int height,
  54077. double progress, const String& textToShow)
  54078. {
  54079. if (progress < 0 || progress >= 1.0)
  54080. {
  54081. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54082. }
  54083. else
  54084. {
  54085. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54086. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54087. g.fillAll (background);
  54088. g.setColour (foreground);
  54089. g.fillRect (1, 1,
  54090. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54091. height - 2);
  54092. if (textToShow.isNotEmpty())
  54093. {
  54094. g.setColour (Colour::contrasting (background, foreground));
  54095. g.setFont (height * 0.6f);
  54096. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54097. }
  54098. }
  54099. }
  54100. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54101. ScrollBar& bar,
  54102. int width, int height,
  54103. int buttonDirection,
  54104. bool isScrollbarVertical,
  54105. bool isMouseOverButton,
  54106. bool isButtonDown)
  54107. {
  54108. if (isScrollbarVertical)
  54109. width -= 2;
  54110. else
  54111. height -= 2;
  54112. Path p;
  54113. if (buttonDirection == 0)
  54114. p.addTriangle (width * 0.5f, height * 0.2f,
  54115. width * 0.1f, height * 0.7f,
  54116. width * 0.9f, height * 0.7f);
  54117. else if (buttonDirection == 1)
  54118. p.addTriangle (width * 0.8f, height * 0.5f,
  54119. width * 0.3f, height * 0.1f,
  54120. width * 0.3f, height * 0.9f);
  54121. else if (buttonDirection == 2)
  54122. p.addTriangle (width * 0.5f, height * 0.8f,
  54123. width * 0.1f, height * 0.3f,
  54124. width * 0.9f, height * 0.3f);
  54125. else if (buttonDirection == 3)
  54126. p.addTriangle (width * 0.2f, height * 0.5f,
  54127. width * 0.7f, height * 0.1f,
  54128. width * 0.7f, height * 0.9f);
  54129. if (isButtonDown)
  54130. g.setColour (Colours::white);
  54131. else if (isMouseOverButton)
  54132. g.setColour (Colours::white.withAlpha (0.7f));
  54133. else
  54134. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54135. g.fillPath (p);
  54136. g.setColour (Colours::black.withAlpha (0.5f));
  54137. g.strokePath (p, PathStrokeType (0.5f));
  54138. }
  54139. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54140. ScrollBar& bar,
  54141. int x, int y,
  54142. int width, int height,
  54143. bool isScrollbarVertical,
  54144. int thumbStartPosition,
  54145. int thumbSize,
  54146. bool isMouseOver,
  54147. bool isMouseDown)
  54148. {
  54149. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54150. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54151. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54152. if (thumbSize > 0.0f)
  54153. {
  54154. Rectangle<int> thumb;
  54155. if (isScrollbarVertical)
  54156. {
  54157. width -= 2;
  54158. g.fillRect (x + roundToInt (width * 0.35f), y,
  54159. roundToInt (width * 0.3f), height);
  54160. thumb.setBounds (x + 1, thumbStartPosition,
  54161. width - 2, thumbSize);
  54162. }
  54163. else
  54164. {
  54165. height -= 2;
  54166. g.fillRect (x, y + roundToInt (height * 0.35f),
  54167. width, roundToInt (height * 0.3f));
  54168. thumb.setBounds (thumbStartPosition, y + 1,
  54169. thumbSize, height - 2);
  54170. }
  54171. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54172. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54173. g.fillRect (thumb);
  54174. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54175. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54176. if (thumbSize > 16)
  54177. {
  54178. for (int i = 3; --i >= 0;)
  54179. {
  54180. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54181. g.setColour (Colours::black.withAlpha (0.15f));
  54182. if (isScrollbarVertical)
  54183. {
  54184. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54185. g.setColour (Colours::white.withAlpha (0.15f));
  54186. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54187. }
  54188. else
  54189. {
  54190. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54191. g.setColour (Colours::white.withAlpha (0.15f));
  54192. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54193. }
  54194. }
  54195. }
  54196. }
  54197. }
  54198. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54199. {
  54200. return &scrollbarShadow;
  54201. }
  54202. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54203. {
  54204. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54205. g.setColour (Colours::black.withAlpha (0.6f));
  54206. g.drawRect (0, 0, width, height);
  54207. }
  54208. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54209. bool, MenuBarComponent& menuBar)
  54210. {
  54211. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54212. }
  54213. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54214. {
  54215. if (textEditor.isEnabled())
  54216. {
  54217. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54218. g.drawRect (0, 0, width, height);
  54219. }
  54220. }
  54221. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54222. const bool isButtonDown,
  54223. int buttonX, int buttonY,
  54224. int buttonW, int buttonH,
  54225. ComboBox& box)
  54226. {
  54227. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54228. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54229. : ComboBox::backgroundColourId));
  54230. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54231. g.setColour (box.findColour (ComboBox::outlineColourId));
  54232. g.drawRect (0, 0, width, height);
  54233. const float arrowX = 0.2f;
  54234. const float arrowH = 0.3f;
  54235. if (box.isEnabled())
  54236. {
  54237. Path p;
  54238. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54239. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54240. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54241. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54242. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54243. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54244. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54245. : ComboBox::buttonColourId));
  54246. g.fillPath (p);
  54247. }
  54248. }
  54249. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54250. {
  54251. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54252. f.setHorizontalScale (0.9f);
  54253. return f;
  54254. }
  54255. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54256. {
  54257. Path p;
  54258. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54259. g.setColour (fill);
  54260. g.fillPath (p);
  54261. g.setColour (outline);
  54262. g.strokePath (p, PathStrokeType (0.3f));
  54263. }
  54264. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54265. int x, int y,
  54266. int w, int h,
  54267. float sliderPos,
  54268. float minSliderPos,
  54269. float maxSliderPos,
  54270. const Slider::SliderStyle style,
  54271. Slider& slider)
  54272. {
  54273. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54274. if (style == Slider::LinearBar)
  54275. {
  54276. g.setColour (slider.findColour (Slider::thumbColourId));
  54277. g.fillRect (x, y, (int) sliderPos - x, h);
  54278. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54279. g.drawRect (x, y, (int) sliderPos - x, h);
  54280. }
  54281. else
  54282. {
  54283. g.setColour (slider.findColour (Slider::trackColourId)
  54284. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54285. if (slider.isHorizontal())
  54286. {
  54287. g.fillRect (x, y + roundToInt (h * 0.6f),
  54288. w, roundToInt (h * 0.2f));
  54289. }
  54290. else
  54291. {
  54292. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54293. jmin (4, roundToInt (w * 0.2f)), h);
  54294. }
  54295. float alpha = 0.35f;
  54296. if (slider.isEnabled())
  54297. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54298. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54299. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54300. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54301. {
  54302. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54303. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54304. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54305. fill, outline);
  54306. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54307. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54308. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54309. fill, outline);
  54310. }
  54311. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54312. {
  54313. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54314. minSliderPos - 7.0f, y + h * 0.9f ,
  54315. minSliderPos, y + h * 0.9f,
  54316. fill, outline);
  54317. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54318. maxSliderPos, y + h * 0.9f,
  54319. maxSliderPos + 7.0f, y + h * 0.9f,
  54320. fill, outline);
  54321. }
  54322. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54323. {
  54324. drawTriangle (g, sliderPos, y + h * 0.9f,
  54325. sliderPos - 7.0f, y + h * 0.2f,
  54326. sliderPos + 7.0f, y + h * 0.2f,
  54327. fill, outline);
  54328. }
  54329. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54330. {
  54331. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54332. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54333. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54334. fill, outline);
  54335. }
  54336. }
  54337. }
  54338. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54339. {
  54340. if (isIncrement)
  54341. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54342. else
  54343. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54344. }
  54345. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54346. {
  54347. return &scrollbarShadow;
  54348. }
  54349. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54350. {
  54351. return 8;
  54352. }
  54353. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54354. int w, int h,
  54355. bool isMouseOver,
  54356. bool isMouseDragging)
  54357. {
  54358. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54359. : Colours::darkgrey);
  54360. const float lineThickness = jmin (w, h) * 0.1f;
  54361. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54362. {
  54363. g.drawLine (w * i,
  54364. h + 1.0f,
  54365. w + 1.0f,
  54366. h * i,
  54367. lineThickness);
  54368. }
  54369. }
  54370. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54371. {
  54372. Path shape;
  54373. if (buttonType == DocumentWindow::closeButton)
  54374. {
  54375. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54376. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54377. ShapeButton* const b = new ShapeButton ("close",
  54378. Colour (0x7fff3333),
  54379. Colour (0xd7ff3333),
  54380. Colour (0xf7ff3333));
  54381. b->setShape (shape, true, true, true);
  54382. return b;
  54383. }
  54384. else if (buttonType == DocumentWindow::minimiseButton)
  54385. {
  54386. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54387. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54388. DrawablePath dp;
  54389. dp.setPath (shape);
  54390. dp.setFill (Colours::black.withAlpha (0.3f));
  54391. b->setImages (&dp);
  54392. return b;
  54393. }
  54394. else if (buttonType == DocumentWindow::maximiseButton)
  54395. {
  54396. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54397. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54398. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54399. DrawablePath dp;
  54400. dp.setPath (shape);
  54401. dp.setFill (Colours::black.withAlpha (0.3f));
  54402. b->setImages (&dp);
  54403. return b;
  54404. }
  54405. jassertfalse;
  54406. return 0;
  54407. }
  54408. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54409. int titleBarX,
  54410. int titleBarY,
  54411. int titleBarW,
  54412. int titleBarH,
  54413. Button* minimiseButton,
  54414. Button* maximiseButton,
  54415. Button* closeButton,
  54416. bool positionTitleBarButtonsOnLeft)
  54417. {
  54418. titleBarY += titleBarH / 8;
  54419. titleBarH -= titleBarH / 4;
  54420. const int buttonW = titleBarH;
  54421. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54422. : titleBarX + titleBarW - buttonW - 4;
  54423. if (closeButton != 0)
  54424. {
  54425. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54426. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54427. : -(buttonW + buttonW / 5);
  54428. }
  54429. if (positionTitleBarButtonsOnLeft)
  54430. swapVariables (minimiseButton, maximiseButton);
  54431. if (maximiseButton != 0)
  54432. {
  54433. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54434. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54435. }
  54436. if (minimiseButton != 0)
  54437. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54438. }
  54439. END_JUCE_NAMESPACE
  54440. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54441. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54442. BEGIN_JUCE_NAMESPACE
  54443. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54444. : model (0),
  54445. itemUnderMouse (-1),
  54446. currentPopupIndex (-1),
  54447. topLevelIndexClicked (0),
  54448. lastMouseX (0),
  54449. lastMouseY (0)
  54450. {
  54451. setRepaintsOnMouseActivity (true);
  54452. setWantsKeyboardFocus (false);
  54453. setMouseClickGrabsKeyboardFocus (false);
  54454. setModel (model_);
  54455. }
  54456. MenuBarComponent::~MenuBarComponent()
  54457. {
  54458. setModel (0);
  54459. Desktop::getInstance().removeGlobalMouseListener (this);
  54460. }
  54461. MenuBarModel* MenuBarComponent::getModel() const throw()
  54462. {
  54463. return model;
  54464. }
  54465. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54466. {
  54467. if (model != newModel)
  54468. {
  54469. if (model != 0)
  54470. model->removeListener (this);
  54471. model = newModel;
  54472. if (model != 0)
  54473. model->addListener (this);
  54474. repaint();
  54475. menuBarItemsChanged (0);
  54476. }
  54477. }
  54478. void MenuBarComponent::paint (Graphics& g)
  54479. {
  54480. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54481. getLookAndFeel().drawMenuBarBackground (g,
  54482. getWidth(),
  54483. getHeight(),
  54484. isMouseOverBar,
  54485. *this);
  54486. if (model != 0)
  54487. {
  54488. for (int i = 0; i < menuNames.size(); ++i)
  54489. {
  54490. g.saveState();
  54491. g.setOrigin (xPositions [i], 0);
  54492. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54493. getLookAndFeel().drawMenuBarItem (g,
  54494. xPositions[i + 1] - xPositions[i],
  54495. getHeight(),
  54496. i,
  54497. menuNames[i],
  54498. i == itemUnderMouse,
  54499. i == currentPopupIndex,
  54500. isMouseOverBar,
  54501. *this);
  54502. g.restoreState();
  54503. }
  54504. }
  54505. }
  54506. void MenuBarComponent::resized()
  54507. {
  54508. xPositions.clear();
  54509. int x = 2;
  54510. xPositions.add (x);
  54511. for (int i = 0; i < menuNames.size(); ++i)
  54512. {
  54513. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54514. xPositions.add (x);
  54515. }
  54516. }
  54517. int MenuBarComponent::getItemAt (const int x, const int y)
  54518. {
  54519. for (int i = 0; i < xPositions.size(); ++i)
  54520. if (x >= xPositions[i] && x < xPositions[i + 1])
  54521. return reallyContains (x, y, true) ? i : -1;
  54522. return -1;
  54523. }
  54524. void MenuBarComponent::repaintMenuItem (int index)
  54525. {
  54526. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54527. {
  54528. const int x1 = xPositions [index];
  54529. const int x2 = xPositions [index + 1];
  54530. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54531. }
  54532. }
  54533. void MenuBarComponent::setItemUnderMouse (const int index)
  54534. {
  54535. if (itemUnderMouse != index)
  54536. {
  54537. repaintMenuItem (itemUnderMouse);
  54538. itemUnderMouse = index;
  54539. repaintMenuItem (itemUnderMouse);
  54540. }
  54541. }
  54542. void MenuBarComponent::setOpenItem (int index)
  54543. {
  54544. if (currentPopupIndex != index)
  54545. {
  54546. repaintMenuItem (currentPopupIndex);
  54547. currentPopupIndex = index;
  54548. repaintMenuItem (currentPopupIndex);
  54549. if (index >= 0)
  54550. Desktop::getInstance().addGlobalMouseListener (this);
  54551. else
  54552. Desktop::getInstance().removeGlobalMouseListener (this);
  54553. }
  54554. }
  54555. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54556. {
  54557. setItemUnderMouse (getItemAt (x, y));
  54558. }
  54559. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  54560. {
  54561. public:
  54562. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  54563. : bar (bar_), topLevelIndex (topLevelIndex_)
  54564. {
  54565. }
  54566. ~AsyncCallback() {}
  54567. void modalStateFinished (int returnValue)
  54568. {
  54569. if (bar != 0)
  54570. bar->menuDismissed (topLevelIndex, returnValue);
  54571. }
  54572. private:
  54573. Component::SafePointer<MenuBarComponent> bar;
  54574. const int topLevelIndex;
  54575. AsyncCallback (const AsyncCallback&);
  54576. AsyncCallback& operator= (const AsyncCallback&);
  54577. };
  54578. void MenuBarComponent::showMenu (int index)
  54579. {
  54580. if (index != currentPopupIndex)
  54581. {
  54582. PopupMenu::dismissAllActiveMenus();
  54583. menuBarItemsChanged (0);
  54584. setOpenItem (index);
  54585. setItemUnderMouse (index);
  54586. if (index >= 0)
  54587. {
  54588. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54589. menuNames [itemUnderMouse]));
  54590. if (m.lookAndFeel == 0)
  54591. m.setLookAndFeel (&getLookAndFeel());
  54592. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  54593. m.showMenu (itemPos + getScreenPosition(),
  54594. 0, itemPos.getWidth(), 0, 0, true, this,
  54595. new AsyncCallback (this, index));
  54596. }
  54597. }
  54598. }
  54599. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  54600. {
  54601. topLevelIndexClicked = topLevelIndex;
  54602. postCommandMessage (itemId);
  54603. }
  54604. void MenuBarComponent::handleCommandMessage (int commandId)
  54605. {
  54606. const Point<int> mousePos (getMouseXYRelative());
  54607. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54608. if (! isCurrentlyBlockedByAnotherModalComponent())
  54609. setOpenItem (-1);
  54610. if (commandId != 0 && model != 0)
  54611. model->menuItemSelected (commandId, topLevelIndexClicked);
  54612. }
  54613. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54614. {
  54615. if (e.eventComponent == this)
  54616. updateItemUnderMouse (e.x, e.y);
  54617. }
  54618. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54619. {
  54620. if (e.eventComponent == this)
  54621. updateItemUnderMouse (e.x, e.y);
  54622. }
  54623. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54624. {
  54625. if (currentPopupIndex < 0)
  54626. {
  54627. const MouseEvent e2 (e.getEventRelativeTo (this));
  54628. updateItemUnderMouse (e2.x, e2.y);
  54629. currentPopupIndex = -2;
  54630. showMenu (itemUnderMouse);
  54631. }
  54632. }
  54633. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54634. {
  54635. const MouseEvent e2 (e.getEventRelativeTo (this));
  54636. const int item = getItemAt (e2.x, e2.y);
  54637. if (item >= 0)
  54638. showMenu (item);
  54639. }
  54640. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54641. {
  54642. const MouseEvent e2 (e.getEventRelativeTo (this));
  54643. updateItemUnderMouse (e2.x, e2.y);
  54644. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  54645. {
  54646. setOpenItem (-1);
  54647. PopupMenu::dismissAllActiveMenus();
  54648. }
  54649. }
  54650. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54651. {
  54652. const MouseEvent e2 (e.getEventRelativeTo (this));
  54653. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54654. {
  54655. if (currentPopupIndex >= 0)
  54656. {
  54657. const int item = getItemAt (e2.x, e2.y);
  54658. if (item >= 0)
  54659. showMenu (item);
  54660. }
  54661. else
  54662. {
  54663. updateItemUnderMouse (e2.x, e2.y);
  54664. }
  54665. lastMouseX = e2.x;
  54666. lastMouseY = e2.y;
  54667. }
  54668. }
  54669. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54670. {
  54671. bool used = false;
  54672. const int numMenus = menuNames.size();
  54673. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54674. if (key.isKeyCode (KeyPress::leftKey))
  54675. {
  54676. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54677. used = true;
  54678. }
  54679. else if (key.isKeyCode (KeyPress::rightKey))
  54680. {
  54681. showMenu ((currentIndex + 1) % numMenus);
  54682. used = true;
  54683. }
  54684. return used;
  54685. }
  54686. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54687. {
  54688. StringArray newNames;
  54689. if (model != 0)
  54690. newNames = model->getMenuBarNames();
  54691. if (newNames != menuNames)
  54692. {
  54693. menuNames = newNames;
  54694. repaint();
  54695. resized();
  54696. }
  54697. }
  54698. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54699. const ApplicationCommandTarget::InvocationInfo& info)
  54700. {
  54701. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54702. return;
  54703. for (int i = 0; i < menuNames.size(); ++i)
  54704. {
  54705. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54706. if (menu.containsCommandItem (info.commandID))
  54707. {
  54708. setItemUnderMouse (i);
  54709. startTimer (200);
  54710. break;
  54711. }
  54712. }
  54713. }
  54714. void MenuBarComponent::timerCallback()
  54715. {
  54716. stopTimer();
  54717. const Point<int> mousePos (getMouseXYRelative());
  54718. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54719. }
  54720. END_JUCE_NAMESPACE
  54721. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54722. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54723. BEGIN_JUCE_NAMESPACE
  54724. MenuBarModel::MenuBarModel() throw()
  54725. : manager (0)
  54726. {
  54727. }
  54728. MenuBarModel::~MenuBarModel()
  54729. {
  54730. setApplicationCommandManagerToWatch (0);
  54731. }
  54732. void MenuBarModel::menuItemsChanged()
  54733. {
  54734. triggerAsyncUpdate();
  54735. }
  54736. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54737. {
  54738. if (manager != newManager)
  54739. {
  54740. if (manager != 0)
  54741. manager->removeListener (this);
  54742. manager = newManager;
  54743. if (manager != 0)
  54744. manager->addListener (this);
  54745. }
  54746. }
  54747. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54748. {
  54749. listeners.add (newListener);
  54750. }
  54751. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54752. {
  54753. // Trying to remove a listener that isn't on the list!
  54754. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54755. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54756. jassert (listeners.contains (listenerToRemove));
  54757. listeners.remove (listenerToRemove);
  54758. }
  54759. void MenuBarModel::handleAsyncUpdate()
  54760. {
  54761. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54762. }
  54763. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54764. {
  54765. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54766. }
  54767. void MenuBarModel::applicationCommandListChanged()
  54768. {
  54769. menuItemsChanged();
  54770. }
  54771. END_JUCE_NAMESPACE
  54772. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54773. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54774. BEGIN_JUCE_NAMESPACE
  54775. class PopupMenu::Item
  54776. {
  54777. public:
  54778. Item()
  54779. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54780. usesColour (false), customComp (0), commandManager (0)
  54781. {
  54782. }
  54783. Item (const int itemId_,
  54784. const String& text_,
  54785. const bool active_,
  54786. const bool isTicked_,
  54787. const Image& im,
  54788. const Colour& textColour_,
  54789. const bool usesColour_,
  54790. PopupMenuCustomComponent* const customComp_,
  54791. const PopupMenu* const subMenu_,
  54792. ApplicationCommandManager* const commandManager_)
  54793. : itemId (itemId_), text (text_), textColour (textColour_),
  54794. active (active_), isSeparator (false), isTicked (isTicked_),
  54795. usesColour (usesColour_), image (im), customComp (customComp_),
  54796. commandManager (commandManager_)
  54797. {
  54798. if (subMenu_ != 0)
  54799. subMenu = new PopupMenu (*subMenu_);
  54800. if (commandManager_ != 0 && itemId_ != 0)
  54801. {
  54802. String shortcutKey;
  54803. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54804. ->getKeyPressesAssignedToCommand (itemId_));
  54805. for (int i = 0; i < keyPresses.size(); ++i)
  54806. {
  54807. const String key (keyPresses.getReference(i).getTextDescription());
  54808. if (shortcutKey.isNotEmpty())
  54809. shortcutKey << ", ";
  54810. if (key.length() == 1)
  54811. shortcutKey << "shortcut: '" << key << '\'';
  54812. else
  54813. shortcutKey << key;
  54814. }
  54815. shortcutKey = shortcutKey.trim();
  54816. if (shortcutKey.isNotEmpty())
  54817. text << "<end>" << shortcutKey;
  54818. }
  54819. }
  54820. Item (const Item& other)
  54821. : itemId (other.itemId),
  54822. text (other.text),
  54823. textColour (other.textColour),
  54824. active (other.active),
  54825. isSeparator (other.isSeparator),
  54826. isTicked (other.isTicked),
  54827. usesColour (other.usesColour),
  54828. image (other.image),
  54829. customComp (other.customComp),
  54830. commandManager (other.commandManager)
  54831. {
  54832. if (other.subMenu != 0)
  54833. subMenu = new PopupMenu (*(other.subMenu));
  54834. }
  54835. ~Item()
  54836. {
  54837. customComp = 0;
  54838. }
  54839. bool canBeTriggered() const throw()
  54840. {
  54841. return active && ! (isSeparator || (subMenu != 0));
  54842. }
  54843. bool hasActiveSubMenu() const throw()
  54844. {
  54845. return active && (subMenu != 0);
  54846. }
  54847. const int itemId;
  54848. String text;
  54849. const Colour textColour;
  54850. const bool active, isSeparator, isTicked, usesColour;
  54851. Image image;
  54852. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54853. ScopedPointer <PopupMenu> subMenu;
  54854. ApplicationCommandManager* const commandManager;
  54855. juce_UseDebuggingNewOperator
  54856. private:
  54857. Item& operator= (const Item&);
  54858. };
  54859. class PopupMenu::ItemComponent : public Component
  54860. {
  54861. public:
  54862. ItemComponent (const PopupMenu::Item& itemInfo_)
  54863. : itemInfo (itemInfo_),
  54864. isHighlighted (false)
  54865. {
  54866. if (itemInfo.customComp != 0)
  54867. addAndMakeVisible (itemInfo.customComp);
  54868. }
  54869. ~ItemComponent()
  54870. {
  54871. if (itemInfo.customComp != 0)
  54872. removeChildComponent (itemInfo.customComp);
  54873. }
  54874. void getIdealSize (int& idealWidth,
  54875. int& idealHeight,
  54876. const int standardItemHeight)
  54877. {
  54878. if (itemInfo.customComp != 0)
  54879. {
  54880. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54881. }
  54882. else
  54883. {
  54884. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54885. itemInfo.isSeparator,
  54886. standardItemHeight,
  54887. idealWidth,
  54888. idealHeight);
  54889. }
  54890. }
  54891. void paint (Graphics& g)
  54892. {
  54893. if (itemInfo.customComp == 0)
  54894. {
  54895. String mainText (itemInfo.text);
  54896. String endText;
  54897. const int endIndex = mainText.indexOf ("<end>");
  54898. if (endIndex >= 0)
  54899. {
  54900. endText = mainText.substring (endIndex + 5).trim();
  54901. mainText = mainText.substring (0, endIndex);
  54902. }
  54903. getLookAndFeel()
  54904. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54905. itemInfo.isSeparator,
  54906. itemInfo.active,
  54907. isHighlighted,
  54908. itemInfo.isTicked,
  54909. itemInfo.subMenu != 0,
  54910. mainText, endText,
  54911. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54912. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54913. }
  54914. }
  54915. void resized()
  54916. {
  54917. if (getNumChildComponents() > 0)
  54918. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54919. }
  54920. void setHighlighted (bool shouldBeHighlighted)
  54921. {
  54922. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54923. if (isHighlighted != shouldBeHighlighted)
  54924. {
  54925. isHighlighted = shouldBeHighlighted;
  54926. if (itemInfo.customComp != 0)
  54927. {
  54928. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54929. itemInfo.customComp->repaint();
  54930. }
  54931. repaint();
  54932. }
  54933. }
  54934. PopupMenu::Item itemInfo;
  54935. juce_UseDebuggingNewOperator
  54936. private:
  54937. bool isHighlighted;
  54938. ItemComponent (const ItemComponent&);
  54939. ItemComponent& operator= (const ItemComponent&);
  54940. };
  54941. namespace PopupMenuSettings
  54942. {
  54943. static const int scrollZone = 24;
  54944. static const int borderSize = 2;
  54945. static const int timerInterval = 50;
  54946. static const int dismissCommandId = 0x6287345f;
  54947. }
  54948. class PopupMenu::Window : public Component,
  54949. private Timer
  54950. {
  54951. public:
  54952. Window()
  54953. : Component ("menu"),
  54954. owner (0),
  54955. currentChild (0),
  54956. activeSubMenu (0),
  54957. managerOfChosenCommand (0),
  54958. minimumWidth (0),
  54959. maximumNumColumns (7),
  54960. standardItemHeight (0),
  54961. isOver (false),
  54962. hasBeenOver (false),
  54963. isDown (false),
  54964. needsToScroll (false),
  54965. hideOnExit (false),
  54966. disableMouseMoves (false),
  54967. hasAnyJuceCompHadFocus (false),
  54968. numColumns (0),
  54969. contentHeight (0),
  54970. childYOffset (0),
  54971. timeEnteredCurrentChildComp (0),
  54972. scrollAcceleration (1.0)
  54973. {
  54974. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54975. setWantsKeyboardFocus (true);
  54976. setMouseClickGrabsKeyboardFocus (false);
  54977. setOpaque (true);
  54978. setAlwaysOnTop (true);
  54979. Desktop::getInstance().addGlobalMouseListener (this);
  54980. getActiveWindows().add (this);
  54981. }
  54982. ~Window()
  54983. {
  54984. getActiveWindows().removeValue (this);
  54985. Desktop::getInstance().removeGlobalMouseListener (this);
  54986. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54987. activeSubMenu = 0;
  54988. deleteAllChildren();
  54989. }
  54990. static Window* create (const PopupMenu& menu,
  54991. const bool dismissOnMouseUp,
  54992. Window* const owner_,
  54993. const Rectangle<int>& target,
  54994. const int minimumWidth,
  54995. const int maximumNumColumns,
  54996. const int standardItemHeight,
  54997. const bool alignToRectangle,
  54998. const int itemIdThatMustBeVisible,
  54999. ApplicationCommandManager** managerOfChosenCommand,
  55000. Component* const componentAttachedTo)
  55001. {
  55002. if (menu.items.size() > 0)
  55003. {
  55004. int totalItems = 0;
  55005. ScopedPointer <Window> mw (new Window());
  55006. mw->setLookAndFeel (menu.lookAndFeel);
  55007. mw->setWantsKeyboardFocus (false);
  55008. mw->minimumWidth = minimumWidth;
  55009. mw->maximumNumColumns = maximumNumColumns;
  55010. mw->standardItemHeight = standardItemHeight;
  55011. mw->dismissOnMouseUp = dismissOnMouseUp;
  55012. for (int i = 0; i < menu.items.size(); ++i)
  55013. {
  55014. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55015. mw->addItem (*item);
  55016. ++totalItems;
  55017. }
  55018. if (totalItems > 0)
  55019. {
  55020. mw->owner = owner_;
  55021. mw->managerOfChosenCommand = managerOfChosenCommand;
  55022. mw->componentAttachedTo = componentAttachedTo;
  55023. mw->componentAttachedToOriginal = componentAttachedTo;
  55024. mw->calculateWindowPos (target, alignToRectangle);
  55025. mw->setTopLeftPosition (mw->windowPos.getX(),
  55026. mw->windowPos.getY());
  55027. mw->updateYPositions();
  55028. if (itemIdThatMustBeVisible != 0)
  55029. {
  55030. const int y = target.getY() - mw->windowPos.getY();
  55031. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55032. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55033. }
  55034. mw->resizeToBestWindowPos();
  55035. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55036. | mw->getLookAndFeel().getMenuWindowFlags());
  55037. return mw.release();
  55038. }
  55039. }
  55040. return 0;
  55041. }
  55042. void paint (Graphics& g)
  55043. {
  55044. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55045. }
  55046. void paintOverChildren (Graphics& g)
  55047. {
  55048. if (isScrolling())
  55049. {
  55050. LookAndFeel& lf = getLookAndFeel();
  55051. if (isScrollZoneActive (false))
  55052. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55053. if (isScrollZoneActive (true))
  55054. {
  55055. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55056. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55057. }
  55058. }
  55059. }
  55060. bool isScrollZoneActive (bool bottomOne) const
  55061. {
  55062. return isScrolling()
  55063. && (bottomOne
  55064. ? childYOffset < contentHeight - windowPos.getHeight()
  55065. : childYOffset > 0);
  55066. }
  55067. void addItem (const PopupMenu::Item& item)
  55068. {
  55069. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55070. addAndMakeVisible (mic);
  55071. int itemW = 80;
  55072. int itemH = 16;
  55073. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55074. mic->setSize (itemW, jlimit (2, 600, itemH));
  55075. mic->addMouseListener (this, false);
  55076. }
  55077. // hide this and all sub-comps
  55078. void hide (const PopupMenu::Item* const item)
  55079. {
  55080. if (isVisible())
  55081. {
  55082. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55083. activeSubMenu = 0;
  55084. currentChild = 0;
  55085. exitModalState (item != 0 ? item->itemId : 0);
  55086. setVisible (false);
  55087. if (item != 0
  55088. && item->commandManager != 0
  55089. && item->itemId != 0)
  55090. {
  55091. *managerOfChosenCommand = item->commandManager;
  55092. }
  55093. }
  55094. }
  55095. void dismissMenu (const PopupMenu::Item* const item)
  55096. {
  55097. if (owner != 0)
  55098. {
  55099. owner->dismissMenu (item);
  55100. }
  55101. else
  55102. {
  55103. if (item != 0)
  55104. {
  55105. // need a copy of this on the stack as the one passed in will get deleted during this call
  55106. const PopupMenu::Item mi (*item);
  55107. hide (&mi);
  55108. }
  55109. else
  55110. {
  55111. hide (0);
  55112. }
  55113. }
  55114. }
  55115. void mouseMove (const MouseEvent&)
  55116. {
  55117. timerCallback();
  55118. }
  55119. void mouseDown (const MouseEvent&)
  55120. {
  55121. timerCallback();
  55122. }
  55123. void mouseDrag (const MouseEvent&)
  55124. {
  55125. timerCallback();
  55126. }
  55127. void mouseUp (const MouseEvent&)
  55128. {
  55129. timerCallback();
  55130. }
  55131. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55132. {
  55133. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55134. lastMouse = Point<int> (-1, -1);
  55135. }
  55136. bool keyPressed (const KeyPress& key)
  55137. {
  55138. if (key.isKeyCode (KeyPress::downKey))
  55139. {
  55140. selectNextItem (1);
  55141. }
  55142. else if (key.isKeyCode (KeyPress::upKey))
  55143. {
  55144. selectNextItem (-1);
  55145. }
  55146. else if (key.isKeyCode (KeyPress::leftKey))
  55147. {
  55148. if (owner != 0)
  55149. {
  55150. Component::SafePointer<Window> parentWindow (owner);
  55151. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55152. hide (0);
  55153. if (parentWindow != 0)
  55154. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55155. disableTimerUntilMouseMoves();
  55156. }
  55157. else if (componentAttachedTo != 0)
  55158. {
  55159. componentAttachedTo->keyPressed (key);
  55160. }
  55161. }
  55162. else if (key.isKeyCode (KeyPress::rightKey))
  55163. {
  55164. disableTimerUntilMouseMoves();
  55165. if (showSubMenuFor (currentChild))
  55166. {
  55167. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55168. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55169. activeSubMenu->selectNextItem (1);
  55170. }
  55171. else if (componentAttachedTo != 0)
  55172. {
  55173. componentAttachedTo->keyPressed (key);
  55174. }
  55175. }
  55176. else if (key.isKeyCode (KeyPress::returnKey))
  55177. {
  55178. triggerCurrentlyHighlightedItem();
  55179. }
  55180. else if (key.isKeyCode (KeyPress::escapeKey))
  55181. {
  55182. dismissMenu (0);
  55183. }
  55184. else
  55185. {
  55186. return false;
  55187. }
  55188. return true;
  55189. }
  55190. void inputAttemptWhenModal()
  55191. {
  55192. Component::SafePointer<Component> deletionChecker (this);
  55193. timerCallback();
  55194. if (deletionChecker != 0 && ! isOverAnyMenu())
  55195. {
  55196. if (componentAttachedTo != 0)
  55197. {
  55198. // we want to dismiss the menu, but if we do it synchronously, then
  55199. // the mouse-click will be allowed to pass through. That's good, except
  55200. // when the user clicks on the button that orginally popped the menu up,
  55201. // as they'll expect the menu to go away, and in fact it'll just
  55202. // come back. So only dismiss synchronously if they're not on the original
  55203. // comp that we're attached to.
  55204. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55205. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55206. {
  55207. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55208. return;
  55209. }
  55210. }
  55211. dismissMenu (0);
  55212. }
  55213. }
  55214. void handleCommandMessage (int commandId)
  55215. {
  55216. Component::handleCommandMessage (commandId);
  55217. if (commandId == PopupMenuSettings::dismissCommandId)
  55218. dismissMenu (0);
  55219. }
  55220. void timerCallback()
  55221. {
  55222. if (! isVisible())
  55223. return;
  55224. if (componentAttachedTo != componentAttachedToOriginal)
  55225. {
  55226. dismissMenu (0);
  55227. return;
  55228. }
  55229. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55230. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55231. return;
  55232. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55233. // move rather than a real timer callback
  55234. const Point<int> globalMousePos (Desktop::getMousePosition());
  55235. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55236. const uint32 now = Time::getMillisecondCounter();
  55237. if (now > timeEnteredCurrentChildComp + 100
  55238. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55239. && currentChild->isValidComponent()
  55240. && (! disableMouseMoves)
  55241. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55242. {
  55243. showSubMenuFor (currentChild);
  55244. }
  55245. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55246. {
  55247. highlightItemUnderMouse (globalMousePos, localMousePos);
  55248. }
  55249. bool overScrollArea = false;
  55250. if (isScrolling()
  55251. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55252. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55253. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55254. {
  55255. if (now > lastScroll + 20)
  55256. {
  55257. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55258. int amount = 0;
  55259. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55260. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55261. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55262. lastScroll = now;
  55263. }
  55264. overScrollArea = true;
  55265. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55266. }
  55267. else
  55268. {
  55269. scrollAcceleration = 1.0;
  55270. }
  55271. const bool wasDown = isDown;
  55272. bool isOverAny = isOverAnyMenu();
  55273. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55274. {
  55275. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55276. isOverAny = isOverAnyMenu();
  55277. }
  55278. if (hideOnExit && hasBeenOver && ! isOverAny)
  55279. {
  55280. hide (0);
  55281. }
  55282. else
  55283. {
  55284. isDown = hasBeenOver
  55285. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55286. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55287. bool anyFocused = Process::isForegroundProcess();
  55288. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55289. {
  55290. // because no component at all may have focus, our test here will
  55291. // only be triggered when something has focus and then loses it.
  55292. anyFocused = ! hasAnyJuceCompHadFocus;
  55293. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55294. {
  55295. if (ComponentPeer::getPeer (i)->isFocused())
  55296. {
  55297. anyFocused = true;
  55298. hasAnyJuceCompHadFocus = true;
  55299. break;
  55300. }
  55301. }
  55302. }
  55303. if (! anyFocused)
  55304. {
  55305. if (now > lastFocused + 10)
  55306. {
  55307. wasHiddenBecauseOfAppChange() = true;
  55308. dismissMenu (0);
  55309. return; // may have been deleted by the previous call..
  55310. }
  55311. }
  55312. else if (wasDown && now > menuCreationTime + 250
  55313. && ! (isDown || overScrollArea))
  55314. {
  55315. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55316. if (isOver)
  55317. {
  55318. triggerCurrentlyHighlightedItem();
  55319. }
  55320. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55321. {
  55322. dismissMenu (0);
  55323. }
  55324. return; // may have been deleted by the previous calls..
  55325. }
  55326. else
  55327. {
  55328. lastFocused = now;
  55329. }
  55330. }
  55331. }
  55332. static Array<Window*>& getActiveWindows()
  55333. {
  55334. static Array<Window*> activeMenuWindows;
  55335. return activeMenuWindows;
  55336. }
  55337. static bool& wasHiddenBecauseOfAppChange() throw()
  55338. {
  55339. static bool b = false;
  55340. return b;
  55341. }
  55342. juce_UseDebuggingNewOperator
  55343. private:
  55344. Window* owner;
  55345. PopupMenu::ItemComponent* currentChild;
  55346. ScopedPointer <Window> activeSubMenu;
  55347. ApplicationCommandManager** managerOfChosenCommand;
  55348. Component::SafePointer<Component> componentAttachedTo;
  55349. Component* componentAttachedToOriginal;
  55350. Rectangle<int> windowPos;
  55351. Point<int> lastMouse;
  55352. int minimumWidth, maximumNumColumns, standardItemHeight;
  55353. bool isOver, hasBeenOver, isDown, needsToScroll;
  55354. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55355. int numColumns, contentHeight, childYOffset;
  55356. Array <int> columnWidths;
  55357. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55358. double scrollAcceleration;
  55359. bool overlaps (const Rectangle<int>& r) const
  55360. {
  55361. return r.intersects (getBounds())
  55362. || (owner != 0 && owner->overlaps (r));
  55363. }
  55364. bool isOverAnyMenu() const
  55365. {
  55366. return (owner != 0) ? owner->isOverAnyMenu()
  55367. : isOverChildren();
  55368. }
  55369. bool isOverChildren() const
  55370. {
  55371. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55372. return isVisible()
  55373. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55374. }
  55375. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55376. {
  55377. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55378. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55379. if (activeSubMenu != 0)
  55380. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55381. }
  55382. bool treeContains (const Window* const window) const throw()
  55383. {
  55384. const Window* mw = this;
  55385. while (mw->owner != 0)
  55386. mw = mw->owner;
  55387. while (mw != 0)
  55388. {
  55389. if (mw == window)
  55390. return true;
  55391. mw = mw->activeSubMenu;
  55392. }
  55393. return false;
  55394. }
  55395. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55396. {
  55397. const Rectangle<int> mon (Desktop::getInstance()
  55398. .getMonitorAreaContaining (target.getCentre(),
  55399. #if JUCE_MAC
  55400. true));
  55401. #else
  55402. false)); // on windows, don't stop the menu overlapping the taskbar
  55403. #endif
  55404. int x, y, widthToUse, heightToUse;
  55405. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55406. if (alignToRectangle)
  55407. {
  55408. x = target.getX();
  55409. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55410. const int spaceOver = target.getY() - mon.getY();
  55411. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55412. y = target.getBottom();
  55413. else
  55414. y = target.getY() - heightToUse;
  55415. }
  55416. else
  55417. {
  55418. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55419. if (owner != 0)
  55420. {
  55421. if (owner->owner != 0)
  55422. {
  55423. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55424. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55425. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55426. tendTowardsRight = true;
  55427. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55428. tendTowardsRight = false;
  55429. }
  55430. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55431. {
  55432. tendTowardsRight = true;
  55433. }
  55434. }
  55435. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55436. target.getX() - mon.getX()) - 32;
  55437. if (biggestSpace < widthToUse)
  55438. {
  55439. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55440. if (numColumns > 1)
  55441. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55442. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55443. }
  55444. if (tendTowardsRight)
  55445. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55446. else
  55447. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55448. y = target.getY();
  55449. if (target.getCentreY() > mon.getCentreY())
  55450. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55451. }
  55452. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55453. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55454. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55455. // sets this flag if it's big enough to obscure any of its parent menus
  55456. hideOnExit = (owner != 0)
  55457. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55458. }
  55459. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55460. {
  55461. numColumns = 0;
  55462. contentHeight = 0;
  55463. const int maxMenuH = getParentHeight() - 24;
  55464. int totalW;
  55465. do
  55466. {
  55467. ++numColumns;
  55468. totalW = workOutBestSize (maxMenuW);
  55469. if (totalW > maxMenuW)
  55470. {
  55471. numColumns = jmax (1, numColumns - 1);
  55472. totalW = workOutBestSize (maxMenuW); // to update col widths
  55473. break;
  55474. }
  55475. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55476. {
  55477. break;
  55478. }
  55479. } while (numColumns < maximumNumColumns);
  55480. const int actualH = jmin (contentHeight, maxMenuH);
  55481. needsToScroll = contentHeight > actualH;
  55482. width = updateYPositions();
  55483. height = actualH + PopupMenuSettings::borderSize * 2;
  55484. }
  55485. int workOutBestSize (const int maxMenuW)
  55486. {
  55487. int totalW = 0;
  55488. contentHeight = 0;
  55489. int childNum = 0;
  55490. for (int col = 0; col < numColumns; ++col)
  55491. {
  55492. int i, colW = 50, colH = 0;
  55493. const int numChildren = jmin (getNumChildComponents() - childNum,
  55494. (getNumChildComponents() + numColumns - 1) / numColumns);
  55495. for (i = numChildren; --i >= 0;)
  55496. {
  55497. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55498. colH += getChildComponent (childNum + i)->getHeight();
  55499. }
  55500. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55501. columnWidths.set (col, colW);
  55502. totalW += colW;
  55503. contentHeight = jmax (contentHeight, colH);
  55504. childNum += numChildren;
  55505. }
  55506. if (totalW < minimumWidth)
  55507. {
  55508. totalW = minimumWidth;
  55509. for (int col = 0; col < numColumns; ++col)
  55510. columnWidths.set (0, totalW / numColumns);
  55511. }
  55512. return totalW;
  55513. }
  55514. void ensureItemIsVisible (const int itemId, int wantedY)
  55515. {
  55516. jassert (itemId != 0)
  55517. for (int i = getNumChildComponents(); --i >= 0;)
  55518. {
  55519. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55520. if (m != 0
  55521. && m->itemInfo.itemId == itemId
  55522. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55523. {
  55524. const int currentY = m->getY();
  55525. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55526. {
  55527. if (wantedY < 0)
  55528. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55529. jmax (PopupMenuSettings::scrollZone,
  55530. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55531. currentY);
  55532. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55533. int deltaY = wantedY - currentY;
  55534. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55535. jmin (windowPos.getHeight(), mon.getHeight()));
  55536. const int newY = jlimit (mon.getY(),
  55537. mon.getBottom() - windowPos.getHeight(),
  55538. windowPos.getY() + deltaY);
  55539. deltaY -= newY - windowPos.getY();
  55540. childYOffset -= deltaY;
  55541. windowPos.setPosition (windowPos.getX(), newY);
  55542. updateYPositions();
  55543. }
  55544. break;
  55545. }
  55546. }
  55547. }
  55548. void resizeToBestWindowPos()
  55549. {
  55550. Rectangle<int> r (windowPos);
  55551. if (childYOffset < 0)
  55552. {
  55553. r.setBounds (r.getX(), r.getY() - childYOffset,
  55554. r.getWidth(), r.getHeight() + childYOffset);
  55555. }
  55556. else if (childYOffset > 0)
  55557. {
  55558. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55559. if (spaceAtBottom > 0)
  55560. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55561. }
  55562. setBounds (r);
  55563. updateYPositions();
  55564. }
  55565. void alterChildYPos (const int delta)
  55566. {
  55567. if (isScrolling())
  55568. {
  55569. childYOffset += delta;
  55570. if (delta < 0)
  55571. {
  55572. childYOffset = jmax (childYOffset, 0);
  55573. }
  55574. else if (delta > 0)
  55575. {
  55576. childYOffset = jmin (childYOffset,
  55577. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55578. }
  55579. updateYPositions();
  55580. }
  55581. else
  55582. {
  55583. childYOffset = 0;
  55584. }
  55585. resizeToBestWindowPos();
  55586. repaint();
  55587. }
  55588. int updateYPositions()
  55589. {
  55590. int x = 0;
  55591. int childNum = 0;
  55592. for (int col = 0; col < numColumns; ++col)
  55593. {
  55594. const int numChildren = jmin (getNumChildComponents() - childNum,
  55595. (getNumChildComponents() + numColumns - 1) / numColumns);
  55596. const int colW = columnWidths [col];
  55597. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55598. for (int i = 0; i < numChildren; ++i)
  55599. {
  55600. Component* const c = getChildComponent (childNum + i);
  55601. c->setBounds (x, y, colW, c->getHeight());
  55602. y += c->getHeight();
  55603. }
  55604. x += colW;
  55605. childNum += numChildren;
  55606. }
  55607. return x;
  55608. }
  55609. bool isScrolling() const throw()
  55610. {
  55611. return childYOffset != 0 || needsToScroll;
  55612. }
  55613. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55614. {
  55615. if (currentChild->isValidComponent())
  55616. currentChild->setHighlighted (false);
  55617. currentChild = child;
  55618. if (currentChild != 0)
  55619. {
  55620. currentChild->setHighlighted (true);
  55621. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55622. }
  55623. }
  55624. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55625. {
  55626. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55627. activeSubMenu = 0;
  55628. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55629. {
  55630. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55631. dismissOnMouseUp,
  55632. this,
  55633. childComp->getScreenBounds(),
  55634. 0, maximumNumColumns,
  55635. standardItemHeight,
  55636. false, 0, managerOfChosenCommand,
  55637. componentAttachedTo);
  55638. if (activeSubMenu != 0)
  55639. {
  55640. activeSubMenu->setVisible (true);
  55641. activeSubMenu->enterModalState (false);
  55642. activeSubMenu->toFront (false);
  55643. return true;
  55644. }
  55645. }
  55646. return false;
  55647. }
  55648. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55649. {
  55650. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55651. if (isOver)
  55652. hasBeenOver = true;
  55653. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55654. {
  55655. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55656. if (disableMouseMoves && isOver)
  55657. disableMouseMoves = false;
  55658. }
  55659. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55660. return;
  55661. bool isMovingTowardsMenu = false;
  55662. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55663. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55664. {
  55665. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55666. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55667. // extends from the last mouse pos to the submenu's rectangle..
  55668. float subX = (float) activeSubMenu->getScreenX();
  55669. if (activeSubMenu->getX() > getX())
  55670. {
  55671. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55672. }
  55673. else
  55674. {
  55675. lastMouse += Point<int> (2, 0);
  55676. subX += activeSubMenu->getWidth();
  55677. }
  55678. Path areaTowardsSubMenu;
  55679. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55680. (float) lastMouse.getY(),
  55681. subX,
  55682. (float) activeSubMenu->getScreenY(),
  55683. subX,
  55684. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55685. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55686. }
  55687. lastMouse = globalMousePos;
  55688. if (! isMovingTowardsMenu)
  55689. {
  55690. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55691. if (c == this)
  55692. c = 0;
  55693. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55694. if (mic == 0 && c != 0)
  55695. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55696. if (mic != currentChild
  55697. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55698. {
  55699. if (isOver && (c != 0) && (activeSubMenu != 0))
  55700. {
  55701. activeSubMenu->hide (0);
  55702. }
  55703. if (! isOver)
  55704. mic = 0;
  55705. setCurrentlyHighlightedChild (mic);
  55706. }
  55707. }
  55708. }
  55709. void triggerCurrentlyHighlightedItem()
  55710. {
  55711. if (currentChild->isValidComponent()
  55712. && currentChild->itemInfo.canBeTriggered()
  55713. && (currentChild->itemInfo.customComp == 0
  55714. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55715. {
  55716. dismissMenu (&currentChild->itemInfo);
  55717. }
  55718. }
  55719. void selectNextItem (const int delta)
  55720. {
  55721. disableTimerUntilMouseMoves();
  55722. PopupMenu::ItemComponent* mic = 0;
  55723. bool wasLastOne = (currentChild == 0);
  55724. const int numItems = getNumChildComponents();
  55725. for (int i = 0; i < numItems + 1; ++i)
  55726. {
  55727. int index = (delta > 0) ? i : (numItems - 1 - i);
  55728. index = (index + numItems) % numItems;
  55729. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55730. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55731. && wasLastOne)
  55732. break;
  55733. if (mic == currentChild)
  55734. wasLastOne = true;
  55735. }
  55736. setCurrentlyHighlightedChild (mic);
  55737. }
  55738. void disableTimerUntilMouseMoves()
  55739. {
  55740. disableMouseMoves = true;
  55741. if (owner != 0)
  55742. owner->disableTimerUntilMouseMoves();
  55743. }
  55744. Window (const Window&);
  55745. Window& operator= (const Window&);
  55746. };
  55747. PopupMenu::PopupMenu()
  55748. : lookAndFeel (0),
  55749. separatorPending (false)
  55750. {
  55751. }
  55752. PopupMenu::PopupMenu (const PopupMenu& other)
  55753. : lookAndFeel (other.lookAndFeel),
  55754. separatorPending (false)
  55755. {
  55756. items.addCopiesOf (other.items);
  55757. }
  55758. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55759. {
  55760. if (this != &other)
  55761. {
  55762. lookAndFeel = other.lookAndFeel;
  55763. clear();
  55764. items.addCopiesOf (other.items);
  55765. }
  55766. return *this;
  55767. }
  55768. PopupMenu::~PopupMenu()
  55769. {
  55770. clear();
  55771. }
  55772. void PopupMenu::clear()
  55773. {
  55774. items.clear();
  55775. separatorPending = false;
  55776. }
  55777. void PopupMenu::addSeparatorIfPending()
  55778. {
  55779. if (separatorPending)
  55780. {
  55781. separatorPending = false;
  55782. if (items.size() > 0)
  55783. items.add (new Item());
  55784. }
  55785. }
  55786. void PopupMenu::addItem (const int itemResultId,
  55787. const String& itemText,
  55788. const bool isActive,
  55789. const bool isTicked,
  55790. const Image& iconToUse)
  55791. {
  55792. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55793. // didn't pick anything, so you shouldn't use it as the id
  55794. // for an item..
  55795. addSeparatorIfPending();
  55796. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55797. Colours::black, false, 0, 0, 0));
  55798. }
  55799. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55800. const int commandID,
  55801. const String& displayName)
  55802. {
  55803. jassert (commandManager != 0 && commandID != 0);
  55804. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55805. if (registeredInfo != 0)
  55806. {
  55807. ApplicationCommandInfo info (*registeredInfo);
  55808. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55809. addSeparatorIfPending();
  55810. items.add (new Item (commandID,
  55811. displayName.isNotEmpty() ? displayName
  55812. : info.shortName,
  55813. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55814. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55815. Image(),
  55816. Colours::black,
  55817. false,
  55818. 0, 0,
  55819. commandManager));
  55820. }
  55821. }
  55822. void PopupMenu::addColouredItem (const int itemResultId,
  55823. const String& itemText,
  55824. const Colour& itemTextColour,
  55825. const bool isActive,
  55826. const bool isTicked,
  55827. const Image& iconToUse)
  55828. {
  55829. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55830. // didn't pick anything, so you shouldn't use it as the id
  55831. // for an item..
  55832. addSeparatorIfPending();
  55833. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55834. itemTextColour, true, 0, 0, 0));
  55835. }
  55836. void PopupMenu::addCustomItem (const int itemResultId,
  55837. PopupMenuCustomComponent* const customComponent)
  55838. {
  55839. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55840. // didn't pick anything, so you shouldn't use it as the id
  55841. // for an item..
  55842. addSeparatorIfPending();
  55843. items.add (new Item (itemResultId, String::empty, true, false, Image(),
  55844. Colours::black, false, customComponent, 0, 0));
  55845. }
  55846. class NormalComponentWrapper : public PopupMenuCustomComponent
  55847. {
  55848. public:
  55849. NormalComponentWrapper (Component* const comp,
  55850. const int w, const int h,
  55851. const bool triggerMenuItemAutomaticallyWhenClicked)
  55852. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55853. width (w),
  55854. height (h)
  55855. {
  55856. addAndMakeVisible (comp);
  55857. }
  55858. ~NormalComponentWrapper() {}
  55859. void getIdealSize (int& idealWidth, int& idealHeight)
  55860. {
  55861. idealWidth = width;
  55862. idealHeight = height;
  55863. }
  55864. void resized()
  55865. {
  55866. if (getChildComponent(0) != 0)
  55867. getChildComponent(0)->setBounds (getLocalBounds());
  55868. }
  55869. juce_UseDebuggingNewOperator
  55870. private:
  55871. const int width, height;
  55872. NormalComponentWrapper (const NormalComponentWrapper&);
  55873. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55874. };
  55875. void PopupMenu::addCustomItem (const int itemResultId,
  55876. Component* customComponent,
  55877. int idealWidth, int idealHeight,
  55878. const bool triggerMenuItemAutomaticallyWhenClicked)
  55879. {
  55880. addCustomItem (itemResultId,
  55881. new NormalComponentWrapper (customComponent,
  55882. idealWidth, idealHeight,
  55883. triggerMenuItemAutomaticallyWhenClicked));
  55884. }
  55885. void PopupMenu::addSubMenu (const String& subMenuName,
  55886. const PopupMenu& subMenu,
  55887. const bool isActive,
  55888. const Image& iconToUse,
  55889. const bool isTicked)
  55890. {
  55891. addSeparatorIfPending();
  55892. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55893. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55894. }
  55895. void PopupMenu::addSeparator()
  55896. {
  55897. separatorPending = true;
  55898. }
  55899. class HeaderItemComponent : public PopupMenuCustomComponent
  55900. {
  55901. public:
  55902. HeaderItemComponent (const String& name)
  55903. : PopupMenuCustomComponent (false)
  55904. {
  55905. setName (name);
  55906. }
  55907. ~HeaderItemComponent()
  55908. {
  55909. }
  55910. void paint (Graphics& g)
  55911. {
  55912. Font f (getLookAndFeel().getPopupMenuFont());
  55913. f.setBold (true);
  55914. g.setFont (f);
  55915. g.setColour (findColour (PopupMenu::headerTextColourId));
  55916. g.drawFittedText (getName(),
  55917. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55918. Justification::bottomLeft, 1);
  55919. }
  55920. void getIdealSize (int& idealWidth,
  55921. int& idealHeight)
  55922. {
  55923. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55924. idealHeight += idealHeight / 2;
  55925. idealWidth += idealWidth / 4;
  55926. }
  55927. juce_UseDebuggingNewOperator
  55928. };
  55929. void PopupMenu::addSectionHeader (const String& title)
  55930. {
  55931. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55932. }
  55933. // This invokes any command manager commands and deletes the menu window when it is dismissed
  55934. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  55935. {
  55936. public:
  55937. PopupMenuCompletionCallback()
  55938. : managerOfChosenCommand (0)
  55939. {
  55940. }
  55941. ~PopupMenuCompletionCallback() {}
  55942. void modalStateFinished (int result)
  55943. {
  55944. if (managerOfChosenCommand != 0 && result != 0)
  55945. {
  55946. ApplicationCommandTarget::InvocationInfo info (result);
  55947. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55948. managerOfChosenCommand->invoke (info, true);
  55949. }
  55950. }
  55951. ApplicationCommandManager* managerOfChosenCommand;
  55952. ScopedPointer<Component> component;
  55953. private:
  55954. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  55955. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  55956. };
  55957. int PopupMenu::showMenu (const Rectangle<int>& target,
  55958. const int itemIdThatMustBeVisible,
  55959. const int minimumWidth,
  55960. const int maximumNumColumns,
  55961. const int standardItemHeight,
  55962. const bool alignToRectangle,
  55963. Component* const componentAttachedTo,
  55964. ModalComponentManager::Callback* userCallback)
  55965. {
  55966. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  55967. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55968. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55969. Window::wasHiddenBecauseOfAppChange() = false;
  55970. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  55971. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  55972. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55973. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  55974. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  55975. &callback->managerOfChosenCommand, componentAttachedTo);
  55976. if (callback->component == 0)
  55977. return 0;
  55978. callbackDeleter.release();
  55979. callback->component->enterModalState (false, userCallbackDeleter.release());
  55980. callback->component->toFront (false); // need to do this after making it modal, or it could
  55981. // be stuck behind other comps that are already modal..
  55982. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  55983. if (userCallback != 0)
  55984. return 0;
  55985. const int result = callback->component->runModalLoop();
  55986. if (! Window::wasHiddenBecauseOfAppChange())
  55987. {
  55988. if (prevTopLevel != 0)
  55989. prevTopLevel->toFront (true);
  55990. if (prevFocused != 0)
  55991. prevFocused->grabKeyboardFocus();
  55992. }
  55993. return result;
  55994. }
  55995. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55996. const int minimumWidth,
  55997. const int maximumNumColumns,
  55998. const int standardItemHeight,
  55999. ModalComponentManager::Callback* callback)
  56000. {
  56001. const Point<int> mousePos (Desktop::getMousePosition());
  56002. return showAt (mousePos.getX(), mousePos.getY(),
  56003. itemIdThatMustBeVisible,
  56004. minimumWidth,
  56005. maximumNumColumns,
  56006. standardItemHeight,
  56007. callback);
  56008. }
  56009. int PopupMenu::showAt (const int screenX,
  56010. const int screenY,
  56011. const int itemIdThatMustBeVisible,
  56012. const int minimumWidth,
  56013. const int maximumNumColumns,
  56014. const int standardItemHeight,
  56015. ModalComponentManager::Callback* callback)
  56016. {
  56017. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56018. itemIdThatMustBeVisible,
  56019. minimumWidth, maximumNumColumns,
  56020. standardItemHeight,
  56021. false, 0, callback);
  56022. }
  56023. int PopupMenu::showAt (Component* componentToAttachTo,
  56024. const int itemIdThatMustBeVisible,
  56025. const int minimumWidth,
  56026. const int maximumNumColumns,
  56027. const int standardItemHeight,
  56028. ModalComponentManager::Callback* callback)
  56029. {
  56030. if (componentToAttachTo != 0)
  56031. {
  56032. return showMenu (componentToAttachTo->getScreenBounds(),
  56033. itemIdThatMustBeVisible,
  56034. minimumWidth,
  56035. maximumNumColumns,
  56036. standardItemHeight,
  56037. true, componentToAttachTo, callback);
  56038. }
  56039. else
  56040. {
  56041. return show (itemIdThatMustBeVisible,
  56042. minimumWidth,
  56043. maximumNumColumns,
  56044. standardItemHeight,
  56045. callback);
  56046. }
  56047. }
  56048. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56049. {
  56050. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56051. {
  56052. Window* const pmw = Window::getActiveWindows()[i];
  56053. if (pmw != 0)
  56054. pmw->dismissMenu (0);
  56055. }
  56056. }
  56057. int PopupMenu::getNumItems() const throw()
  56058. {
  56059. int num = 0;
  56060. for (int i = items.size(); --i >= 0;)
  56061. if (! (items.getUnchecked(i))->isSeparator)
  56062. ++num;
  56063. return num;
  56064. }
  56065. bool PopupMenu::containsCommandItem (const int commandID) const
  56066. {
  56067. for (int i = items.size(); --i >= 0;)
  56068. {
  56069. const Item* mi = items.getUnchecked (i);
  56070. if ((mi->itemId == commandID && mi->commandManager != 0)
  56071. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56072. {
  56073. return true;
  56074. }
  56075. }
  56076. return false;
  56077. }
  56078. bool PopupMenu::containsAnyActiveItems() const throw()
  56079. {
  56080. for (int i = items.size(); --i >= 0;)
  56081. {
  56082. const Item* const mi = items.getUnchecked (i);
  56083. if (mi->subMenu != 0)
  56084. {
  56085. if (mi->subMenu->containsAnyActiveItems())
  56086. return true;
  56087. }
  56088. else if (mi->active)
  56089. {
  56090. return true;
  56091. }
  56092. }
  56093. return false;
  56094. }
  56095. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56096. {
  56097. lookAndFeel = newLookAndFeel;
  56098. }
  56099. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56100. : isHighlighted (false),
  56101. isTriggeredAutomatically (isTriggeredAutomatically_)
  56102. {
  56103. }
  56104. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56105. {
  56106. }
  56107. void PopupMenuCustomComponent::triggerMenuItem()
  56108. {
  56109. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56110. if (mic != 0)
  56111. {
  56112. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56113. if (pmw != 0)
  56114. {
  56115. pmw->dismissMenu (&mic->itemInfo);
  56116. }
  56117. else
  56118. {
  56119. // something must have gone wrong with the component hierarchy if this happens..
  56120. jassertfalse;
  56121. }
  56122. }
  56123. else
  56124. {
  56125. // why isn't this component inside a menu? Not much point triggering the item if
  56126. // there's no menu.
  56127. jassertfalse;
  56128. }
  56129. }
  56130. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56131. : subMenu (0),
  56132. itemId (0),
  56133. isSeparator (false),
  56134. isTicked (false),
  56135. isEnabled (false),
  56136. isCustomComponent (false),
  56137. isSectionHeader (false),
  56138. customColour (0),
  56139. customImage (0),
  56140. menu (menu_),
  56141. index (0)
  56142. {
  56143. }
  56144. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56145. {
  56146. }
  56147. bool PopupMenu::MenuItemIterator::next()
  56148. {
  56149. if (index >= menu.items.size())
  56150. return false;
  56151. const Item* const item = menu.items.getUnchecked (index);
  56152. ++index;
  56153. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56154. subMenu = item->subMenu;
  56155. itemId = item->itemId;
  56156. isSeparator = item->isSeparator;
  56157. isTicked = item->isTicked;
  56158. isEnabled = item->active;
  56159. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56160. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56161. customColour = item->usesColour ? &(item->textColour) : 0;
  56162. customImage = item->image;
  56163. commandManager = item->commandManager;
  56164. return true;
  56165. }
  56166. END_JUCE_NAMESPACE
  56167. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56168. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56169. BEGIN_JUCE_NAMESPACE
  56170. ComponentDragger::ComponentDragger()
  56171. : constrainer (0)
  56172. {
  56173. }
  56174. ComponentDragger::~ComponentDragger()
  56175. {
  56176. }
  56177. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56178. ComponentBoundsConstrainer* const constrainer_)
  56179. {
  56180. jassert (componentToDrag->isValidComponent());
  56181. if (componentToDrag != 0)
  56182. {
  56183. constrainer = constrainer_;
  56184. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56185. }
  56186. }
  56187. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56188. {
  56189. jassert (componentToDrag->isValidComponent());
  56190. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56191. if (componentToDrag != 0)
  56192. {
  56193. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56194. const Component* const parentComp = componentToDrag->getParentComponent();
  56195. if (parentComp != 0)
  56196. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56197. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56198. if (constrainer != 0)
  56199. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56200. else
  56201. componentToDrag->setBounds (bounds);
  56202. }
  56203. }
  56204. END_JUCE_NAMESPACE
  56205. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56206. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56207. BEGIN_JUCE_NAMESPACE
  56208. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56209. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56210. class DragImageComponent : public Component,
  56211. public Timer
  56212. {
  56213. public:
  56214. DragImageComponent (const Image& im,
  56215. const String& desc,
  56216. Component* const sourceComponent,
  56217. Component* const mouseDragSource_,
  56218. DragAndDropContainer* const o,
  56219. const Point<int>& imageOffset_)
  56220. : image (im),
  56221. source (sourceComponent),
  56222. mouseDragSource (mouseDragSource_),
  56223. owner (o),
  56224. dragDesc (desc),
  56225. imageOffset (imageOffset_),
  56226. hasCheckedForExternalDrag (false),
  56227. drawImage (true)
  56228. {
  56229. setSize (im.getWidth(), im.getHeight());
  56230. if (mouseDragSource == 0)
  56231. mouseDragSource = source;
  56232. mouseDragSource->addMouseListener (this, false);
  56233. startTimer (200);
  56234. setInterceptsMouseClicks (false, false);
  56235. setAlwaysOnTop (true);
  56236. }
  56237. ~DragImageComponent()
  56238. {
  56239. if (owner->dragImageComponent == this)
  56240. owner->dragImageComponent.release();
  56241. if (mouseDragSource != 0)
  56242. {
  56243. mouseDragSource->removeMouseListener (this);
  56244. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56245. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56246. }
  56247. }
  56248. void paint (Graphics& g)
  56249. {
  56250. if (isOpaque())
  56251. g.fillAll (Colours::white);
  56252. if (drawImage)
  56253. {
  56254. g.setOpacity (1.0f);
  56255. g.drawImageAt (image, 0, 0);
  56256. }
  56257. }
  56258. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56259. {
  56260. Component* hit = getParentComponent();
  56261. if (hit == 0)
  56262. {
  56263. hit = Desktop::getInstance().findComponentAt (screenPos);
  56264. }
  56265. else
  56266. {
  56267. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56268. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56269. }
  56270. // (note: use a local copy of the dragDesc member in case the callback runs
  56271. // a modal loop and deletes this object before the method completes)
  56272. const String dragDescLocal (dragDesc);
  56273. while (hit != 0)
  56274. {
  56275. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56276. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56277. {
  56278. relativePos = hit->globalPositionToRelative (screenPos);
  56279. return ddt;
  56280. }
  56281. hit = hit->getParentComponent();
  56282. }
  56283. return 0;
  56284. }
  56285. void mouseUp (const MouseEvent& e)
  56286. {
  56287. if (e.originalComponent != this)
  56288. {
  56289. if (mouseDragSource != 0)
  56290. mouseDragSource->removeMouseListener (this);
  56291. bool dropAccepted = false;
  56292. DragAndDropTarget* ddt = 0;
  56293. Point<int> relPos;
  56294. if (isVisible())
  56295. {
  56296. setVisible (false);
  56297. ddt = findTarget (e.getScreenPosition(), relPos);
  56298. // fade this component and remove it - it'll be deleted later by the timer callback
  56299. dropAccepted = ddt != 0;
  56300. setVisible (true);
  56301. if (dropAccepted || source == 0)
  56302. {
  56303. fadeOutComponent (120);
  56304. }
  56305. else
  56306. {
  56307. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56308. source->getHeight() / 2)));
  56309. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56310. getHeight() / 2)));
  56311. fadeOutComponent (120,
  56312. target.getX() - ourCentre.getX(),
  56313. target.getY() - ourCentre.getY());
  56314. }
  56315. }
  56316. if (getParentComponent() != 0)
  56317. getParentComponent()->removeChildComponent (this);
  56318. if (dropAccepted && ddt != 0)
  56319. {
  56320. // (note: use a local copy of the dragDesc member in case the callback runs
  56321. // a modal loop and deletes this object before the method completes)
  56322. const String dragDescLocal (dragDesc);
  56323. currentlyOverComp = 0;
  56324. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56325. }
  56326. // careful - this object could now be deleted..
  56327. }
  56328. }
  56329. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56330. {
  56331. // (note: use a local copy of the dragDesc member in case the callback runs
  56332. // a modal loop and deletes this object before it returns)
  56333. const String dragDescLocal (dragDesc);
  56334. Point<int> newPos (screenPos + imageOffset);
  56335. if (getParentComponent() != 0)
  56336. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56337. //if (newX != getX() || newY != getY())
  56338. {
  56339. setTopLeftPosition (newPos.getX(), newPos.getY());
  56340. Point<int> relPos;
  56341. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56342. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56343. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56344. if (ddtComp != currentlyOverComp)
  56345. {
  56346. if (currentlyOverComp != 0 && source != 0
  56347. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56348. {
  56349. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56350. }
  56351. currentlyOverComp = ddtComp;
  56352. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56353. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56354. }
  56355. DragAndDropTarget* target = getCurrentlyOver();
  56356. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56357. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56358. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56359. {
  56360. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56361. {
  56362. hasCheckedForExternalDrag = true;
  56363. StringArray files;
  56364. bool canMoveFiles = false;
  56365. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56366. && files.size() > 0)
  56367. {
  56368. Component::SafePointer<Component> cdw (this);
  56369. setVisible (false);
  56370. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56371. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56372. if (cdw != 0)
  56373. delete this;
  56374. return;
  56375. }
  56376. }
  56377. }
  56378. }
  56379. }
  56380. void mouseDrag (const MouseEvent& e)
  56381. {
  56382. if (e.originalComponent != this)
  56383. updateLocation (true, e.getScreenPosition());
  56384. }
  56385. void timerCallback()
  56386. {
  56387. if (source == 0)
  56388. {
  56389. delete this;
  56390. }
  56391. else if (! isMouseButtonDownAnywhere())
  56392. {
  56393. if (mouseDragSource != 0)
  56394. mouseDragSource->removeMouseListener (this);
  56395. delete this;
  56396. }
  56397. }
  56398. private:
  56399. Image image;
  56400. Component::SafePointer<Component> source;
  56401. Component::SafePointer<Component> mouseDragSource;
  56402. DragAndDropContainer* const owner;
  56403. Component::SafePointer<Component> currentlyOverComp;
  56404. DragAndDropTarget* getCurrentlyOver()
  56405. {
  56406. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56407. }
  56408. String dragDesc;
  56409. const Point<int> imageOffset;
  56410. bool hasCheckedForExternalDrag, drawImage;
  56411. DragImageComponent (const DragImageComponent&);
  56412. DragImageComponent& operator= (const DragImageComponent&);
  56413. };
  56414. DragAndDropContainer::DragAndDropContainer()
  56415. {
  56416. }
  56417. DragAndDropContainer::~DragAndDropContainer()
  56418. {
  56419. dragImageComponent = 0;
  56420. }
  56421. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56422. Component* sourceComponent,
  56423. const Image& dragImage_,
  56424. const bool allowDraggingToExternalWindows,
  56425. const Point<int>* imageOffsetFromMouse)
  56426. {
  56427. Image dragImage (dragImage_);
  56428. if (dragImageComponent == 0)
  56429. {
  56430. Component* const thisComp = dynamic_cast <Component*> (this);
  56431. if (thisComp == 0)
  56432. {
  56433. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56434. return;
  56435. }
  56436. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56437. if (draggingSource == 0 || ! draggingSource->isDragging())
  56438. {
  56439. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56440. return;
  56441. }
  56442. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56443. Point<int> imageOffset;
  56444. if (dragImage.isNull())
  56445. {
  56446. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56447. .convertedToFormat (Image::ARGB);
  56448. dragImage.multiplyAllAlphas (0.6f);
  56449. const int lo = 150;
  56450. const int hi = 400;
  56451. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56452. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56453. for (int y = dragImage.getHeight(); --y >= 0;)
  56454. {
  56455. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56456. for (int x = dragImage.getWidth(); --x >= 0;)
  56457. {
  56458. const int dx = x - clipped.getX();
  56459. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56460. if (distance > lo)
  56461. {
  56462. const float alpha = (distance > hi) ? 0
  56463. : (hi - distance) / (float) (hi - lo)
  56464. + Random::getSystemRandom().nextFloat() * 0.008f;
  56465. dragImage.multiplyAlphaAt (x, y, alpha);
  56466. }
  56467. }
  56468. }
  56469. imageOffset = -clipped;
  56470. }
  56471. else
  56472. {
  56473. if (imageOffsetFromMouse == 0)
  56474. imageOffset = -dragImage.getBounds().getCentre();
  56475. else
  56476. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56477. }
  56478. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56479. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56480. currentDragDesc = sourceDescription;
  56481. if (allowDraggingToExternalWindows)
  56482. {
  56483. if (! Desktop::canUseSemiTransparentWindows())
  56484. dragImageComponent->setOpaque (true);
  56485. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56486. | ComponentPeer::windowIsTemporary
  56487. | ComponentPeer::windowIgnoresKeyPresses);
  56488. }
  56489. else
  56490. thisComp->addChildComponent (dragImageComponent);
  56491. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56492. dragImageComponent->setVisible (true);
  56493. }
  56494. }
  56495. bool DragAndDropContainer::isDragAndDropActive() const
  56496. {
  56497. return dragImageComponent != 0;
  56498. }
  56499. const String DragAndDropContainer::getCurrentDragDescription() const
  56500. {
  56501. return (dragImageComponent != 0) ? currentDragDesc
  56502. : String::empty;
  56503. }
  56504. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56505. {
  56506. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56507. }
  56508. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56509. {
  56510. return false;
  56511. }
  56512. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56513. {
  56514. }
  56515. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56516. {
  56517. }
  56518. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56519. {
  56520. }
  56521. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56522. {
  56523. return true;
  56524. }
  56525. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56526. {
  56527. }
  56528. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56529. {
  56530. }
  56531. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56532. {
  56533. }
  56534. END_JUCE_NAMESPACE
  56535. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56536. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56537. BEGIN_JUCE_NAMESPACE
  56538. class MouseCursor::SharedCursorHandle
  56539. {
  56540. public:
  56541. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56542. : handle (createStandardMouseCursor (type)),
  56543. refCount (1),
  56544. standardType (type),
  56545. isStandard (true)
  56546. {
  56547. }
  56548. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56549. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56550. refCount (1),
  56551. standardType (MouseCursor::NormalCursor),
  56552. isStandard (false)
  56553. {
  56554. }
  56555. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56556. {
  56557. const ScopedLock sl (getLock());
  56558. for (int i = getCursors().size(); --i >= 0;)
  56559. {
  56560. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56561. if (sc->standardType == type)
  56562. return sc->retain();
  56563. }
  56564. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56565. getCursors().add (sc);
  56566. return sc;
  56567. }
  56568. SharedCursorHandle* retain() throw()
  56569. {
  56570. ++refCount;
  56571. return this;
  56572. }
  56573. void release()
  56574. {
  56575. if (--refCount == 0)
  56576. {
  56577. if (isStandard)
  56578. {
  56579. const ScopedLock sl (getLock());
  56580. getCursors().removeValue (this);
  56581. }
  56582. delete this;
  56583. }
  56584. }
  56585. void* getHandle() const throw() { return handle; }
  56586. juce_UseDebuggingNewOperator
  56587. private:
  56588. void* const handle;
  56589. Atomic <int> refCount;
  56590. const MouseCursor::StandardCursorType standardType;
  56591. const bool isStandard;
  56592. static CriticalSection& getLock()
  56593. {
  56594. static CriticalSection lock;
  56595. return lock;
  56596. }
  56597. static Array <SharedCursorHandle*>& getCursors()
  56598. {
  56599. static Array <SharedCursorHandle*> cursors;
  56600. return cursors;
  56601. }
  56602. ~SharedCursorHandle()
  56603. {
  56604. deleteMouseCursor (handle, isStandard);
  56605. }
  56606. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56607. };
  56608. MouseCursor::MouseCursor()
  56609. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56610. {
  56611. jassert (cursorHandle != 0);
  56612. }
  56613. MouseCursor::MouseCursor (const StandardCursorType type)
  56614. : cursorHandle (SharedCursorHandle::createStandard (type))
  56615. {
  56616. jassert (cursorHandle != 0);
  56617. }
  56618. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56619. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56620. {
  56621. }
  56622. MouseCursor::MouseCursor (const MouseCursor& other)
  56623. : cursorHandle (other.cursorHandle->retain())
  56624. {
  56625. }
  56626. MouseCursor::~MouseCursor()
  56627. {
  56628. cursorHandle->release();
  56629. }
  56630. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56631. {
  56632. other.cursorHandle->retain();
  56633. cursorHandle->release();
  56634. cursorHandle = other.cursorHandle;
  56635. return *this;
  56636. }
  56637. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56638. {
  56639. return getHandle() == other.getHandle();
  56640. }
  56641. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56642. {
  56643. return getHandle() != other.getHandle();
  56644. }
  56645. void* MouseCursor::getHandle() const throw()
  56646. {
  56647. return cursorHandle->getHandle();
  56648. }
  56649. void MouseCursor::showWaitCursor()
  56650. {
  56651. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56652. }
  56653. void MouseCursor::hideWaitCursor()
  56654. {
  56655. Desktop::getInstance().getMainMouseSource().revealCursor();
  56656. }
  56657. END_JUCE_NAMESPACE
  56658. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56659. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56660. BEGIN_JUCE_NAMESPACE
  56661. MouseEvent::MouseEvent (MouseInputSource& source_,
  56662. const Point<int>& position,
  56663. const ModifierKeys& mods_,
  56664. Component* const eventComponent_,
  56665. Component* const originator,
  56666. const Time& eventTime_,
  56667. const Point<int> mouseDownPos_,
  56668. const Time& mouseDownTime_,
  56669. const int numberOfClicks_,
  56670. const bool mouseWasDragged) throw()
  56671. : x (position.getX()),
  56672. y (position.getY()),
  56673. mods (mods_),
  56674. eventComponent (eventComponent_),
  56675. originalComponent (originator),
  56676. eventTime (eventTime_),
  56677. source (source_),
  56678. mouseDownPos (mouseDownPos_),
  56679. mouseDownTime (mouseDownTime_),
  56680. numberOfClicks (numberOfClicks_),
  56681. wasMovedSinceMouseDown (mouseWasDragged)
  56682. {
  56683. }
  56684. MouseEvent::~MouseEvent() throw()
  56685. {
  56686. }
  56687. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56688. {
  56689. if (otherComponent == 0)
  56690. {
  56691. jassertfalse;
  56692. return *this;
  56693. }
  56694. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56695. mods, otherComponent, originalComponent, eventTime,
  56696. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56697. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56698. }
  56699. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56700. {
  56701. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56702. eventTime, mouseDownPos, mouseDownTime,
  56703. numberOfClicks, wasMovedSinceMouseDown);
  56704. }
  56705. bool MouseEvent::mouseWasClicked() const throw()
  56706. {
  56707. return ! wasMovedSinceMouseDown;
  56708. }
  56709. int MouseEvent::getMouseDownX() const throw()
  56710. {
  56711. return mouseDownPos.getX();
  56712. }
  56713. int MouseEvent::getMouseDownY() const throw()
  56714. {
  56715. return mouseDownPos.getY();
  56716. }
  56717. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56718. {
  56719. return mouseDownPos;
  56720. }
  56721. int MouseEvent::getDistanceFromDragStartX() const throw()
  56722. {
  56723. return x - mouseDownPos.getX();
  56724. }
  56725. int MouseEvent::getDistanceFromDragStartY() const throw()
  56726. {
  56727. return y - mouseDownPos.getY();
  56728. }
  56729. int MouseEvent::getDistanceFromDragStart() const throw()
  56730. {
  56731. return mouseDownPos.getDistanceFrom (getPosition());
  56732. }
  56733. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56734. {
  56735. return getPosition() - mouseDownPos;
  56736. }
  56737. int MouseEvent::getLengthOfMousePress() const throw()
  56738. {
  56739. if (mouseDownTime.toMilliseconds() > 0)
  56740. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56741. return 0;
  56742. }
  56743. const Point<int> MouseEvent::getPosition() const throw()
  56744. {
  56745. return Point<int> (x, y);
  56746. }
  56747. int MouseEvent::getScreenX() const
  56748. {
  56749. return getScreenPosition().getX();
  56750. }
  56751. int MouseEvent::getScreenY() const
  56752. {
  56753. return getScreenPosition().getY();
  56754. }
  56755. const Point<int> MouseEvent::getScreenPosition() const
  56756. {
  56757. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56758. }
  56759. int MouseEvent::getMouseDownScreenX() const
  56760. {
  56761. return getMouseDownScreenPosition().getX();
  56762. }
  56763. int MouseEvent::getMouseDownScreenY() const
  56764. {
  56765. return getMouseDownScreenPosition().getY();
  56766. }
  56767. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56768. {
  56769. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56770. }
  56771. int MouseEvent::doubleClickTimeOutMs = 400;
  56772. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56773. {
  56774. doubleClickTimeOutMs = newTime;
  56775. }
  56776. int MouseEvent::getDoubleClickTimeout() throw()
  56777. {
  56778. return doubleClickTimeOutMs;
  56779. }
  56780. END_JUCE_NAMESPACE
  56781. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56782. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56783. BEGIN_JUCE_NAMESPACE
  56784. class MouseInputSourceInternal : public AsyncUpdater
  56785. {
  56786. public:
  56787. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56788. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56789. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56790. mouseEventCounter (0)
  56791. {
  56792. zerostruct (mouseDowns);
  56793. }
  56794. ~MouseInputSourceInternal()
  56795. {
  56796. }
  56797. bool isDragging() const throw()
  56798. {
  56799. return buttonState.isAnyMouseButtonDown();
  56800. }
  56801. Component* getComponentUnderMouse() const
  56802. {
  56803. return static_cast <Component*> (componentUnderMouse);
  56804. }
  56805. const ModifierKeys getCurrentModifiers() const
  56806. {
  56807. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56808. }
  56809. ComponentPeer* getPeer()
  56810. {
  56811. if (! ComponentPeer::isValidPeer (lastPeer))
  56812. lastPeer = 0;
  56813. return lastPeer;
  56814. }
  56815. Component* findComponentAt (const Point<int>& screenPos)
  56816. {
  56817. ComponentPeer* const peer = getPeer();
  56818. if (peer != 0)
  56819. {
  56820. Component* const comp = peer->getComponent();
  56821. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56822. // (the contains() call is needed to test for overlapping desktop windows)
  56823. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56824. return comp->getComponentAt (relativePos);
  56825. }
  56826. return 0;
  56827. }
  56828. const Point<int> getScreenPosition() const throw()
  56829. {
  56830. return lastScreenPos + unboundedMouseOffset;
  56831. }
  56832. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56833. {
  56834. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56835. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56836. }
  56837. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56838. {
  56839. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56840. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56841. }
  56842. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56843. {
  56844. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56845. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56846. }
  56847. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56848. {
  56849. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56850. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56851. }
  56852. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56853. {
  56854. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56855. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56856. }
  56857. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56858. {
  56859. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56860. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56861. }
  56862. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56863. {
  56864. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56865. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56866. }
  56867. // (returns true if the button change caused a modal event loop)
  56868. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56869. {
  56870. if (buttonState == newButtonState)
  56871. return false;
  56872. setScreenPos (screenPos, time, false);
  56873. // (ignore secondary clicks when there's already a button down)
  56874. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56875. {
  56876. buttonState = newButtonState;
  56877. return false;
  56878. }
  56879. const int lastCounter = mouseEventCounter;
  56880. if (buttonState.isAnyMouseButtonDown())
  56881. {
  56882. Component* const current = getComponentUnderMouse();
  56883. if (current != 0)
  56884. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56885. enableUnboundedMouseMovement (false, false);
  56886. }
  56887. buttonState = newButtonState;
  56888. if (buttonState.isAnyMouseButtonDown())
  56889. {
  56890. Desktop::getInstance().incrementMouseClickCounter();
  56891. Component* const current = getComponentUnderMouse();
  56892. if (current != 0)
  56893. {
  56894. registerMouseDown (screenPos, time, current);
  56895. sendMouseDown (current, screenPos, time);
  56896. }
  56897. }
  56898. return lastCounter != mouseEventCounter;
  56899. }
  56900. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56901. {
  56902. Component* current = getComponentUnderMouse();
  56903. if (newComponent != current)
  56904. {
  56905. Component::SafePointer<Component> safeNewComp (newComponent);
  56906. const ModifierKeys originalButtonState (buttonState);
  56907. if (current != 0)
  56908. {
  56909. setButtons (screenPos, time, ModifierKeys());
  56910. sendMouseExit (current, screenPos, time);
  56911. buttonState = originalButtonState;
  56912. }
  56913. componentUnderMouse = safeNewComp;
  56914. current = getComponentUnderMouse();
  56915. if (current != 0)
  56916. sendMouseEnter (current, screenPos, time);
  56917. revealCursor (false);
  56918. setButtons (screenPos, time, originalButtonState);
  56919. }
  56920. }
  56921. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56922. {
  56923. ModifierKeys::updateCurrentModifiers();
  56924. if (newPeer != lastPeer)
  56925. {
  56926. setComponentUnderMouse (0, screenPos, time);
  56927. lastPeer = newPeer;
  56928. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56929. }
  56930. }
  56931. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56932. {
  56933. if (! isDragging())
  56934. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56935. if (newScreenPos != lastScreenPos || forceUpdate)
  56936. {
  56937. cancelPendingUpdate();
  56938. lastScreenPos = newScreenPos;
  56939. Component* const current = getComponentUnderMouse();
  56940. if (current != 0)
  56941. {
  56942. if (isDragging())
  56943. {
  56944. registerMouseDrag (newScreenPos);
  56945. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56946. if (isUnboundedMouseModeOn)
  56947. handleUnboundedDrag (current);
  56948. }
  56949. else
  56950. {
  56951. sendMouseMove (current, newScreenPos, time);
  56952. }
  56953. }
  56954. revealCursor (false);
  56955. }
  56956. }
  56957. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56958. {
  56959. jassert (newPeer != 0);
  56960. lastTime = time;
  56961. ++mouseEventCounter;
  56962. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56963. if (isDragging() && newMods.isAnyMouseButtonDown())
  56964. {
  56965. setScreenPos (screenPos, time, false);
  56966. }
  56967. else
  56968. {
  56969. setPeer (newPeer, screenPos, time);
  56970. ComponentPeer* peer = getPeer();
  56971. if (peer != 0)
  56972. {
  56973. if (setButtons (screenPos, time, newMods))
  56974. return; // some modal events have been dispatched, so the current event is now out-of-date
  56975. peer = getPeer();
  56976. if (peer != 0)
  56977. setScreenPos (screenPos, time, false);
  56978. }
  56979. }
  56980. }
  56981. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56982. {
  56983. jassert (peer != 0);
  56984. lastTime = time;
  56985. ++mouseEventCounter;
  56986. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56987. setPeer (peer, screenPos, time);
  56988. setScreenPos (screenPos, time, false);
  56989. triggerFakeMove();
  56990. if (! isDragging())
  56991. {
  56992. Component* current = getComponentUnderMouse();
  56993. if (current != 0)
  56994. sendMouseWheel (current, screenPos, time, x, y);
  56995. }
  56996. }
  56997. const Time getLastMouseDownTime() const throw()
  56998. {
  56999. return Time (mouseDowns[0].time);
  57000. }
  57001. const Point<int> getLastMouseDownPosition() const throw()
  57002. {
  57003. return mouseDowns[0].position;
  57004. }
  57005. int getNumberOfMultipleClicks() const throw()
  57006. {
  57007. int numClicks = 0;
  57008. if (mouseDowns[0].time != 0)
  57009. {
  57010. if (! mouseMovedSignificantlySincePressed)
  57011. ++numClicks;
  57012. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57013. {
  57014. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57015. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57016. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57017. {
  57018. ++numClicks;
  57019. }
  57020. else
  57021. {
  57022. break;
  57023. }
  57024. }
  57025. }
  57026. return numClicks;
  57027. }
  57028. bool hasMouseMovedSignificantlySincePressed() const throw()
  57029. {
  57030. return mouseMovedSignificantlySincePressed
  57031. || lastTime > mouseDowns[0].time + 300;
  57032. }
  57033. void triggerFakeMove()
  57034. {
  57035. triggerAsyncUpdate();
  57036. }
  57037. void handleAsyncUpdate()
  57038. {
  57039. if (! isDragging())
  57040. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  57041. }
  57042. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57043. {
  57044. enable = enable && isDragging();
  57045. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57046. if (enable != isUnboundedMouseModeOn)
  57047. {
  57048. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57049. {
  57050. // when released, return the mouse to within the component's bounds
  57051. Component* current = getComponentUnderMouse();
  57052. if (current != 0)
  57053. Desktop::setMousePosition (current->getScreenBounds()
  57054. .getConstrainedPoint (current->getMouseXYRelative()));
  57055. }
  57056. isUnboundedMouseModeOn = enable;
  57057. unboundedMouseOffset = Point<int>();
  57058. revealCursor (true);
  57059. }
  57060. }
  57061. void handleUnboundedDrag (Component* current)
  57062. {
  57063. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57064. if (! screenArea.contains (lastScreenPos))
  57065. {
  57066. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57067. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57068. Desktop::setMousePosition (componentCentre);
  57069. }
  57070. else if (isCursorVisibleUntilOffscreen
  57071. && (! unboundedMouseOffset.isOrigin())
  57072. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57073. {
  57074. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57075. unboundedMouseOffset = Point<int>();
  57076. }
  57077. }
  57078. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57079. {
  57080. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57081. {
  57082. cursor = MouseCursor::NoCursor;
  57083. forcedUpdate = true;
  57084. }
  57085. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57086. {
  57087. currentCursorHandle = cursor.getHandle();
  57088. cursor.showInWindow (getPeer());
  57089. }
  57090. }
  57091. void hideCursor()
  57092. {
  57093. showMouseCursor (MouseCursor::NoCursor, true);
  57094. }
  57095. void revealCursor (bool forcedUpdate)
  57096. {
  57097. MouseCursor mc (MouseCursor::NormalCursor);
  57098. Component* current = getComponentUnderMouse();
  57099. if (current != 0)
  57100. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57101. showMouseCursor (mc, forcedUpdate);
  57102. }
  57103. int index;
  57104. bool isMouseDevice;
  57105. Point<int> lastScreenPos;
  57106. ModifierKeys buttonState;
  57107. private:
  57108. MouseInputSource& source;
  57109. Component::SafePointer<Component> componentUnderMouse;
  57110. ComponentPeer* lastPeer;
  57111. Point<int> unboundedMouseOffset;
  57112. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57113. void* currentCursorHandle;
  57114. int mouseEventCounter;
  57115. struct RecentMouseDown
  57116. {
  57117. Point<int> position;
  57118. int64 time;
  57119. Component* component;
  57120. };
  57121. RecentMouseDown mouseDowns[4];
  57122. bool mouseMovedSignificantlySincePressed;
  57123. int64 lastTime;
  57124. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57125. {
  57126. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57127. mouseDowns[i] = mouseDowns[i - 1];
  57128. mouseDowns[0].position = screenPos;
  57129. mouseDowns[0].time = time;
  57130. mouseDowns[0].component = component;
  57131. mouseMovedSignificantlySincePressed = false;
  57132. }
  57133. void registerMouseDrag (const Point<int>& screenPos) throw()
  57134. {
  57135. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57136. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57137. }
  57138. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57139. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57140. };
  57141. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57142. {
  57143. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57144. }
  57145. MouseInputSource::~MouseInputSource()
  57146. {
  57147. }
  57148. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57149. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57150. bool MouseInputSource::canHover() const { return isMouse(); }
  57151. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57152. int MouseInputSource::getIndex() const { return pimpl->index; }
  57153. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57154. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57155. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57156. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57157. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57158. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57159. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57160. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57161. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57162. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57163. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57164. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57165. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57166. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57167. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57168. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57169. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57170. {
  57171. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57172. }
  57173. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57174. {
  57175. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57176. }
  57177. END_JUCE_NAMESPACE
  57178. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57179. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57180. BEGIN_JUCE_NAMESPACE
  57181. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57182. : source (0),
  57183. hoverTimeMillisecs (hoverTimeMillisecs_),
  57184. hasJustHovered (false)
  57185. {
  57186. internalTimer.owner = this;
  57187. }
  57188. MouseHoverDetector::~MouseHoverDetector()
  57189. {
  57190. setHoverComponent (0);
  57191. }
  57192. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57193. {
  57194. hoverTimeMillisecs = newTimeInMillisecs;
  57195. }
  57196. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57197. {
  57198. if (source != newSourceComponent)
  57199. {
  57200. internalTimer.stopTimer();
  57201. hasJustHovered = false;
  57202. if (source != 0)
  57203. {
  57204. // ! you need to delete the hover detector before deleting its component
  57205. jassert (source->isValidComponent());
  57206. source->removeMouseListener (&internalTimer);
  57207. }
  57208. source = newSourceComponent;
  57209. if (newSourceComponent != 0)
  57210. newSourceComponent->addMouseListener (&internalTimer, false);
  57211. }
  57212. }
  57213. void MouseHoverDetector::hoverTimerCallback()
  57214. {
  57215. internalTimer.stopTimer();
  57216. if (source != 0)
  57217. {
  57218. const Point<int> pos (source->getMouseXYRelative());
  57219. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57220. {
  57221. hasJustHovered = true;
  57222. mouseHovered (pos.getX(), pos.getY());
  57223. }
  57224. }
  57225. }
  57226. void MouseHoverDetector::checkJustHoveredCallback()
  57227. {
  57228. if (hasJustHovered)
  57229. {
  57230. hasJustHovered = false;
  57231. mouseMovedAfterHover();
  57232. }
  57233. }
  57234. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57235. {
  57236. owner->hoverTimerCallback();
  57237. }
  57238. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57239. {
  57240. stopTimer();
  57241. owner->checkJustHoveredCallback();
  57242. }
  57243. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57244. {
  57245. stopTimer();
  57246. owner->checkJustHoveredCallback();
  57247. }
  57248. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57249. {
  57250. stopTimer();
  57251. owner->checkJustHoveredCallback();
  57252. }
  57253. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57254. {
  57255. stopTimer();
  57256. owner->checkJustHoveredCallback();
  57257. }
  57258. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57259. {
  57260. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57261. {
  57262. lastX = e.x;
  57263. lastY = e.y;
  57264. if (owner->source != 0)
  57265. startTimer (owner->hoverTimeMillisecs);
  57266. owner->checkJustHoveredCallback();
  57267. }
  57268. }
  57269. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57270. {
  57271. stopTimer();
  57272. owner->checkJustHoveredCallback();
  57273. }
  57274. END_JUCE_NAMESPACE
  57275. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57276. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57277. BEGIN_JUCE_NAMESPACE
  57278. void MouseListener::mouseEnter (const MouseEvent&)
  57279. {
  57280. }
  57281. void MouseListener::mouseExit (const MouseEvent&)
  57282. {
  57283. }
  57284. void MouseListener::mouseDown (const MouseEvent&)
  57285. {
  57286. }
  57287. void MouseListener::mouseUp (const MouseEvent&)
  57288. {
  57289. }
  57290. void MouseListener::mouseDrag (const MouseEvent&)
  57291. {
  57292. }
  57293. void MouseListener::mouseMove (const MouseEvent&)
  57294. {
  57295. }
  57296. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57297. {
  57298. }
  57299. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57300. {
  57301. }
  57302. END_JUCE_NAMESPACE
  57303. /*** End of inlined file: juce_MouseListener.cpp ***/
  57304. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57305. BEGIN_JUCE_NAMESPACE
  57306. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57307. const String& buttonTextWhenTrue,
  57308. const String& buttonTextWhenFalse)
  57309. : PropertyComponent (name),
  57310. onText (buttonTextWhenTrue),
  57311. offText (buttonTextWhenFalse)
  57312. {
  57313. addAndMakeVisible (&button);
  57314. button.setClickingTogglesState (false);
  57315. button.addButtonListener (this);
  57316. }
  57317. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57318. const String& name,
  57319. const String& buttonText)
  57320. : PropertyComponent (name),
  57321. onText (buttonText),
  57322. offText (buttonText)
  57323. {
  57324. addAndMakeVisible (&button);
  57325. button.setClickingTogglesState (false);
  57326. button.setButtonText (buttonText);
  57327. button.getToggleStateValue().referTo (valueToControl);
  57328. button.setClickingTogglesState (true);
  57329. }
  57330. BooleanPropertyComponent::~BooleanPropertyComponent()
  57331. {
  57332. }
  57333. void BooleanPropertyComponent::setState (const bool newState)
  57334. {
  57335. button.setToggleState (newState, true);
  57336. }
  57337. bool BooleanPropertyComponent::getState() const
  57338. {
  57339. return button.getToggleState();
  57340. }
  57341. void BooleanPropertyComponent::paint (Graphics& g)
  57342. {
  57343. PropertyComponent::paint (g);
  57344. g.setColour (Colours::white);
  57345. g.fillRect (button.getBounds());
  57346. g.setColour (findColour (ComboBox::outlineColourId));
  57347. g.drawRect (button.getBounds());
  57348. }
  57349. void BooleanPropertyComponent::refresh()
  57350. {
  57351. button.setToggleState (getState(), false);
  57352. button.setButtonText (button.getToggleState() ? onText : offText);
  57353. }
  57354. void BooleanPropertyComponent::buttonClicked (Button*)
  57355. {
  57356. setState (! getState());
  57357. }
  57358. END_JUCE_NAMESPACE
  57359. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57360. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57361. BEGIN_JUCE_NAMESPACE
  57362. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57363. const bool triggerOnMouseDown)
  57364. : PropertyComponent (name)
  57365. {
  57366. addAndMakeVisible (&button);
  57367. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57368. button.addButtonListener (this);
  57369. }
  57370. ButtonPropertyComponent::~ButtonPropertyComponent()
  57371. {
  57372. }
  57373. void ButtonPropertyComponent::refresh()
  57374. {
  57375. button.setButtonText (getButtonText());
  57376. }
  57377. void ButtonPropertyComponent::buttonClicked (Button*)
  57378. {
  57379. buttonClicked();
  57380. }
  57381. END_JUCE_NAMESPACE
  57382. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57383. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57384. BEGIN_JUCE_NAMESPACE
  57385. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57386. public Value::Listener
  57387. {
  57388. public:
  57389. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57390. : sourceValue (sourceValue_),
  57391. mappings (mappings_)
  57392. {
  57393. sourceValue.addListener (this);
  57394. }
  57395. ~RemapperValueSource() {}
  57396. const var getValue() const
  57397. {
  57398. return mappings.indexOf (sourceValue.getValue()) + 1;
  57399. }
  57400. void setValue (const var& newValue)
  57401. {
  57402. const var remappedVal (mappings [(int) newValue - 1]);
  57403. if (remappedVal != sourceValue)
  57404. sourceValue = remappedVal;
  57405. }
  57406. void valueChanged (Value&)
  57407. {
  57408. sendChangeMessage (true);
  57409. }
  57410. juce_UseDebuggingNewOperator
  57411. protected:
  57412. Value sourceValue;
  57413. Array<var> mappings;
  57414. RemapperValueSource (const RemapperValueSource&);
  57415. const RemapperValueSource& operator= (const RemapperValueSource&);
  57416. };
  57417. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57418. : PropertyComponent (name),
  57419. isCustomClass (true)
  57420. {
  57421. }
  57422. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57423. const String& name,
  57424. const StringArray& choices_,
  57425. const Array <var>& correspondingValues)
  57426. : PropertyComponent (name),
  57427. choices (choices_),
  57428. isCustomClass (false)
  57429. {
  57430. // The array of corresponding values must contain one value for each of the items in
  57431. // the choices array!
  57432. jassert (correspondingValues.size() == choices.size());
  57433. createComboBox();
  57434. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57435. }
  57436. ChoicePropertyComponent::~ChoicePropertyComponent()
  57437. {
  57438. }
  57439. void ChoicePropertyComponent::createComboBox()
  57440. {
  57441. addAndMakeVisible (&comboBox);
  57442. for (int i = 0; i < choices.size(); ++i)
  57443. {
  57444. if (choices[i].isNotEmpty())
  57445. comboBox.addItem (choices[i], i + 1);
  57446. else
  57447. comboBox.addSeparator();
  57448. }
  57449. comboBox.setEditableText (false);
  57450. }
  57451. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57452. {
  57453. jassertfalse; // you need to override this method in your subclass!
  57454. }
  57455. int ChoicePropertyComponent::getIndex() const
  57456. {
  57457. jassertfalse; // you need to override this method in your subclass!
  57458. return -1;
  57459. }
  57460. const StringArray& ChoicePropertyComponent::getChoices() const
  57461. {
  57462. return choices;
  57463. }
  57464. void ChoicePropertyComponent::refresh()
  57465. {
  57466. if (isCustomClass)
  57467. {
  57468. if (! comboBox.isVisible())
  57469. {
  57470. createComboBox();
  57471. comboBox.addListener (this);
  57472. }
  57473. comboBox.setSelectedId (getIndex() + 1, true);
  57474. }
  57475. }
  57476. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57477. {
  57478. if (isCustomClass)
  57479. {
  57480. const int newIndex = comboBox.getSelectedId() - 1;
  57481. if (newIndex != getIndex())
  57482. setIndex (newIndex);
  57483. }
  57484. }
  57485. END_JUCE_NAMESPACE
  57486. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57487. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57488. BEGIN_JUCE_NAMESPACE
  57489. PropertyComponent::PropertyComponent (const String& name,
  57490. const int preferredHeight_)
  57491. : Component (name),
  57492. preferredHeight (preferredHeight_)
  57493. {
  57494. jassert (name.isNotEmpty());
  57495. }
  57496. PropertyComponent::~PropertyComponent()
  57497. {
  57498. }
  57499. void PropertyComponent::paint (Graphics& g)
  57500. {
  57501. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57502. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57503. }
  57504. void PropertyComponent::resized()
  57505. {
  57506. if (getNumChildComponents() > 0)
  57507. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57508. }
  57509. void PropertyComponent::enablementChanged()
  57510. {
  57511. repaint();
  57512. }
  57513. END_JUCE_NAMESPACE
  57514. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57515. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57516. BEGIN_JUCE_NAMESPACE
  57517. class PropertyPanel::PropertyHolderComponent : public Component
  57518. {
  57519. public:
  57520. PropertyHolderComponent()
  57521. {
  57522. }
  57523. ~PropertyHolderComponent()
  57524. {
  57525. deleteAllChildren();
  57526. }
  57527. void paint (Graphics&)
  57528. {
  57529. }
  57530. void updateLayout (int width);
  57531. void refreshAll() const;
  57532. private:
  57533. PropertyHolderComponent (const PropertyHolderComponent&);
  57534. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57535. };
  57536. class PropertySectionComponent : public Component
  57537. {
  57538. public:
  57539. PropertySectionComponent (const String& sectionTitle,
  57540. const Array <PropertyComponent*>& newProperties,
  57541. const bool open)
  57542. : Component (sectionTitle),
  57543. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57544. isOpen_ (open)
  57545. {
  57546. for (int i = newProperties.size(); --i >= 0;)
  57547. {
  57548. addAndMakeVisible (newProperties.getUnchecked(i));
  57549. newProperties.getUnchecked(i)->refresh();
  57550. }
  57551. }
  57552. ~PropertySectionComponent()
  57553. {
  57554. deleteAllChildren();
  57555. }
  57556. void paint (Graphics& g)
  57557. {
  57558. if (titleHeight > 0)
  57559. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57560. }
  57561. void resized()
  57562. {
  57563. int y = titleHeight;
  57564. for (int i = getNumChildComponents(); --i >= 0;)
  57565. {
  57566. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57567. if (pec != 0)
  57568. {
  57569. const int prefH = pec->getPreferredHeight();
  57570. pec->setBounds (1, y, getWidth() - 2, prefH);
  57571. y += prefH;
  57572. }
  57573. }
  57574. }
  57575. int getPreferredHeight() const
  57576. {
  57577. int y = titleHeight;
  57578. if (isOpen())
  57579. {
  57580. for (int i = 0; i < getNumChildComponents(); ++i)
  57581. {
  57582. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57583. if (pec != 0)
  57584. y += pec->getPreferredHeight();
  57585. }
  57586. }
  57587. return y;
  57588. }
  57589. void setOpen (const bool open)
  57590. {
  57591. if (isOpen_ != open)
  57592. {
  57593. isOpen_ = open;
  57594. for (int i = 0; i < getNumChildComponents(); ++i)
  57595. {
  57596. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57597. if (pec != 0)
  57598. pec->setVisible (open);
  57599. }
  57600. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57601. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57602. if (pp != 0)
  57603. pp->resized();
  57604. }
  57605. }
  57606. bool isOpen() const
  57607. {
  57608. return isOpen_;
  57609. }
  57610. void refreshAll() const
  57611. {
  57612. for (int i = 0; i < getNumChildComponents(); ++i)
  57613. {
  57614. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57615. if (pec != 0)
  57616. pec->refresh();
  57617. }
  57618. }
  57619. void mouseDown (const MouseEvent&)
  57620. {
  57621. }
  57622. void mouseUp (const MouseEvent& e)
  57623. {
  57624. if (e.getMouseDownX() < titleHeight
  57625. && e.x < titleHeight
  57626. && e.y < titleHeight
  57627. && e.getNumberOfClicks() != 2)
  57628. {
  57629. setOpen (! isOpen());
  57630. }
  57631. }
  57632. void mouseDoubleClick (const MouseEvent& e)
  57633. {
  57634. if (e.y < titleHeight)
  57635. setOpen (! isOpen());
  57636. }
  57637. private:
  57638. int titleHeight;
  57639. bool isOpen_;
  57640. PropertySectionComponent (const PropertySectionComponent&);
  57641. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57642. };
  57643. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57644. {
  57645. int y = 0;
  57646. for (int i = getNumChildComponents(); --i >= 0;)
  57647. {
  57648. PropertySectionComponent* const section
  57649. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57650. if (section != 0)
  57651. {
  57652. const int prefH = section->getPreferredHeight();
  57653. section->setBounds (0, y, width, prefH);
  57654. y += prefH;
  57655. }
  57656. }
  57657. setSize (width, y);
  57658. repaint();
  57659. }
  57660. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57661. {
  57662. for (int i = getNumChildComponents(); --i >= 0;)
  57663. {
  57664. PropertySectionComponent* const section
  57665. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57666. if (section != 0)
  57667. section->refreshAll();
  57668. }
  57669. }
  57670. PropertyPanel::PropertyPanel()
  57671. {
  57672. messageWhenEmpty = TRANS("(nothing selected)");
  57673. addAndMakeVisible (&viewport);
  57674. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57675. viewport.setFocusContainer (true);
  57676. }
  57677. PropertyPanel::~PropertyPanel()
  57678. {
  57679. clear();
  57680. }
  57681. void PropertyPanel::paint (Graphics& g)
  57682. {
  57683. if (propertyHolderComponent->getNumChildComponents() == 0)
  57684. {
  57685. g.setColour (Colours::black.withAlpha (0.5f));
  57686. g.setFont (14.0f);
  57687. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57688. Justification::centred, true);
  57689. }
  57690. }
  57691. void PropertyPanel::resized()
  57692. {
  57693. viewport.setBounds (getLocalBounds());
  57694. updatePropHolderLayout();
  57695. }
  57696. void PropertyPanel::clear()
  57697. {
  57698. if (propertyHolderComponent->getNumChildComponents() > 0)
  57699. {
  57700. propertyHolderComponent->deleteAllChildren();
  57701. repaint();
  57702. }
  57703. }
  57704. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57705. {
  57706. if (propertyHolderComponent->getNumChildComponents() == 0)
  57707. repaint();
  57708. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57709. newProperties,
  57710. true), 0);
  57711. updatePropHolderLayout();
  57712. }
  57713. void PropertyPanel::addSection (const String& sectionTitle,
  57714. const Array <PropertyComponent*>& newProperties,
  57715. const bool shouldBeOpen)
  57716. {
  57717. jassert (sectionTitle.isNotEmpty());
  57718. if (propertyHolderComponent->getNumChildComponents() == 0)
  57719. repaint();
  57720. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57721. newProperties,
  57722. shouldBeOpen), 0);
  57723. updatePropHolderLayout();
  57724. }
  57725. void PropertyPanel::updatePropHolderLayout() const
  57726. {
  57727. const int maxWidth = viewport.getMaximumVisibleWidth();
  57728. propertyHolderComponent->updateLayout (maxWidth);
  57729. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57730. if (maxWidth != newMaxWidth)
  57731. {
  57732. // need to do this twice because of scrollbars changing the size, etc.
  57733. propertyHolderComponent->updateLayout (newMaxWidth);
  57734. }
  57735. }
  57736. void PropertyPanel::refreshAll() const
  57737. {
  57738. propertyHolderComponent->refreshAll();
  57739. }
  57740. const StringArray PropertyPanel::getSectionNames() const
  57741. {
  57742. StringArray s;
  57743. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57744. {
  57745. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57746. if (section != 0 && section->getName().isNotEmpty())
  57747. s.add (section->getName());
  57748. }
  57749. return s;
  57750. }
  57751. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57752. {
  57753. int index = 0;
  57754. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57755. {
  57756. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57757. if (section != 0 && section->getName().isNotEmpty())
  57758. {
  57759. if (index == sectionIndex)
  57760. return section->isOpen();
  57761. ++index;
  57762. }
  57763. }
  57764. return false;
  57765. }
  57766. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57767. {
  57768. int index = 0;
  57769. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57770. {
  57771. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57772. if (section != 0 && section->getName().isNotEmpty())
  57773. {
  57774. if (index == sectionIndex)
  57775. {
  57776. section->setOpen (shouldBeOpen);
  57777. break;
  57778. }
  57779. ++index;
  57780. }
  57781. }
  57782. }
  57783. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57784. {
  57785. int index = 0;
  57786. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57787. {
  57788. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57789. if (section != 0 && section->getName().isNotEmpty())
  57790. {
  57791. if (index == sectionIndex)
  57792. {
  57793. section->setEnabled (shouldBeEnabled);
  57794. break;
  57795. }
  57796. ++index;
  57797. }
  57798. }
  57799. }
  57800. XmlElement* PropertyPanel::getOpennessState() const
  57801. {
  57802. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57803. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57804. const StringArray sections (getSectionNames());
  57805. for (int i = 0; i < sections.size(); ++i)
  57806. {
  57807. if (sections[i].isNotEmpty())
  57808. {
  57809. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57810. e->setAttribute ("name", sections[i]);
  57811. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57812. }
  57813. }
  57814. return xml;
  57815. }
  57816. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57817. {
  57818. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57819. {
  57820. const StringArray sections (getSectionNames());
  57821. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57822. {
  57823. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57824. e->getBoolAttribute ("open"));
  57825. }
  57826. viewport.setViewPosition (viewport.getViewPositionX(),
  57827. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57828. }
  57829. }
  57830. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57831. {
  57832. if (messageWhenEmpty != newMessage)
  57833. {
  57834. messageWhenEmpty = newMessage;
  57835. repaint();
  57836. }
  57837. }
  57838. const String& PropertyPanel::getMessageWhenEmpty() const
  57839. {
  57840. return messageWhenEmpty;
  57841. }
  57842. END_JUCE_NAMESPACE
  57843. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57844. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57845. BEGIN_JUCE_NAMESPACE
  57846. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57847. const double rangeMin,
  57848. const double rangeMax,
  57849. const double interval,
  57850. const double skewFactor)
  57851. : PropertyComponent (name)
  57852. {
  57853. addAndMakeVisible (&slider);
  57854. slider.setRange (rangeMin, rangeMax, interval);
  57855. slider.setSkewFactor (skewFactor);
  57856. slider.setSliderStyle (Slider::LinearBar);
  57857. slider.addListener (this);
  57858. }
  57859. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57860. const String& name,
  57861. const double rangeMin,
  57862. const double rangeMax,
  57863. const double interval,
  57864. const double skewFactor)
  57865. : PropertyComponent (name)
  57866. {
  57867. addAndMakeVisible (&slider);
  57868. slider.setRange (rangeMin, rangeMax, interval);
  57869. slider.setSkewFactor (skewFactor);
  57870. slider.setSliderStyle (Slider::LinearBar);
  57871. slider.getValueObject().referTo (valueToControl);
  57872. }
  57873. SliderPropertyComponent::~SliderPropertyComponent()
  57874. {
  57875. }
  57876. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57877. {
  57878. }
  57879. double SliderPropertyComponent::getValue() const
  57880. {
  57881. return slider.getValue();
  57882. }
  57883. void SliderPropertyComponent::refresh()
  57884. {
  57885. slider.setValue (getValue(), false);
  57886. }
  57887. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57888. {
  57889. if (getValue() != slider.getValue())
  57890. setValue (slider.getValue());
  57891. }
  57892. END_JUCE_NAMESPACE
  57893. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57894. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57895. BEGIN_JUCE_NAMESPACE
  57896. class TextPropLabel : public Label
  57897. {
  57898. TextPropertyComponent& owner;
  57899. int maxChars;
  57900. bool isMultiline;
  57901. public:
  57902. TextPropLabel (TextPropertyComponent& owner_,
  57903. const int maxChars_, const bool isMultiline_)
  57904. : Label (String::empty, String::empty),
  57905. owner (owner_),
  57906. maxChars (maxChars_),
  57907. isMultiline (isMultiline_)
  57908. {
  57909. setEditable (true, true, false);
  57910. setColour (backgroundColourId, Colours::white);
  57911. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57912. }
  57913. ~TextPropLabel()
  57914. {
  57915. }
  57916. TextEditor* createEditorComponent()
  57917. {
  57918. TextEditor* const textEditor = Label::createEditorComponent();
  57919. textEditor->setInputRestrictions (maxChars);
  57920. if (isMultiline)
  57921. {
  57922. textEditor->setMultiLine (true, true);
  57923. textEditor->setReturnKeyStartsNewLine (true);
  57924. }
  57925. return textEditor;
  57926. }
  57927. void textWasEdited()
  57928. {
  57929. owner.textWasEdited();
  57930. }
  57931. };
  57932. TextPropertyComponent::TextPropertyComponent (const String& name,
  57933. const int maxNumChars,
  57934. const bool isMultiLine)
  57935. : PropertyComponent (name)
  57936. {
  57937. createEditor (maxNumChars, isMultiLine);
  57938. }
  57939. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57940. const String& name,
  57941. const int maxNumChars,
  57942. const bool isMultiLine)
  57943. : PropertyComponent (name)
  57944. {
  57945. createEditor (maxNumChars, isMultiLine);
  57946. textEditor->getTextValue().referTo (valueToControl);
  57947. }
  57948. TextPropertyComponent::~TextPropertyComponent()
  57949. {
  57950. deleteAllChildren();
  57951. }
  57952. void TextPropertyComponent::setText (const String& newText)
  57953. {
  57954. textEditor->setText (newText, true);
  57955. }
  57956. const String TextPropertyComponent::getText() const
  57957. {
  57958. return textEditor->getText();
  57959. }
  57960. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57961. {
  57962. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57963. if (isMultiLine)
  57964. {
  57965. textEditor->setJustificationType (Justification::topLeft);
  57966. preferredHeight = 120;
  57967. }
  57968. }
  57969. void TextPropertyComponent::refresh()
  57970. {
  57971. textEditor->setText (getText(), false);
  57972. }
  57973. void TextPropertyComponent::textWasEdited()
  57974. {
  57975. const String newText (textEditor->getText());
  57976. if (getText() != newText)
  57977. setText (newText);
  57978. }
  57979. END_JUCE_NAMESPACE
  57980. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57981. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57982. BEGIN_JUCE_NAMESPACE
  57983. class SimpleDeviceManagerInputLevelMeter : public Component,
  57984. public Timer
  57985. {
  57986. public:
  57987. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57988. : manager (manager_),
  57989. level (0)
  57990. {
  57991. startTimer (50);
  57992. manager->enableInputLevelMeasurement (true);
  57993. }
  57994. ~SimpleDeviceManagerInputLevelMeter()
  57995. {
  57996. manager->enableInputLevelMeasurement (false);
  57997. }
  57998. void timerCallback()
  57999. {
  58000. const float newLevel = (float) manager->getCurrentInputLevel();
  58001. if (std::abs (level - newLevel) > 0.005f)
  58002. {
  58003. level = newLevel;
  58004. repaint();
  58005. }
  58006. }
  58007. void paint (Graphics& g)
  58008. {
  58009. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58010. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58011. }
  58012. private:
  58013. AudioDeviceManager* const manager;
  58014. float level;
  58015. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58016. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58017. };
  58018. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58019. public ListBoxModel
  58020. {
  58021. public:
  58022. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58023. const String& noItemsMessage_,
  58024. const int minNumber_,
  58025. const int maxNumber_)
  58026. : ListBox (String::empty, 0),
  58027. deviceManager (deviceManager_),
  58028. noItemsMessage (noItemsMessage_),
  58029. minNumber (minNumber_),
  58030. maxNumber (maxNumber_)
  58031. {
  58032. items = MidiInput::getDevices();
  58033. setModel (this);
  58034. setOutlineThickness (1);
  58035. }
  58036. ~MidiInputSelectorComponentListBox()
  58037. {
  58038. }
  58039. int getNumRows()
  58040. {
  58041. return items.size();
  58042. }
  58043. void paintListBoxItem (int row,
  58044. Graphics& g,
  58045. int width, int height,
  58046. bool rowIsSelected)
  58047. {
  58048. if (((unsigned int) row) < (unsigned int) items.size())
  58049. {
  58050. if (rowIsSelected)
  58051. g.fillAll (findColour (TextEditor::highlightColourId)
  58052. .withMultipliedAlpha (0.3f));
  58053. const String item (items [row]);
  58054. bool enabled = deviceManager.isMidiInputEnabled (item);
  58055. const int x = getTickX();
  58056. const float tickW = height * 0.75f;
  58057. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58058. enabled, true, true, false);
  58059. g.setFont (height * 0.6f);
  58060. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58061. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58062. }
  58063. }
  58064. void listBoxItemClicked (int row, const MouseEvent& e)
  58065. {
  58066. selectRow (row);
  58067. if (e.x < getTickX())
  58068. flipEnablement (row);
  58069. }
  58070. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58071. {
  58072. flipEnablement (row);
  58073. }
  58074. void returnKeyPressed (int row)
  58075. {
  58076. flipEnablement (row);
  58077. }
  58078. void paint (Graphics& g)
  58079. {
  58080. ListBox::paint (g);
  58081. if (items.size() == 0)
  58082. {
  58083. g.setColour (Colours::grey);
  58084. g.setFont (13.0f);
  58085. g.drawText (noItemsMessage,
  58086. 0, 0, getWidth(), getHeight() / 2,
  58087. Justification::centred, true);
  58088. }
  58089. }
  58090. int getBestHeight (const int preferredHeight)
  58091. {
  58092. const int extra = getOutlineThickness() * 2;
  58093. return jmax (getRowHeight() * 2 + extra,
  58094. jmin (getRowHeight() * getNumRows() + extra,
  58095. preferredHeight));
  58096. }
  58097. juce_UseDebuggingNewOperator
  58098. private:
  58099. AudioDeviceManager& deviceManager;
  58100. const String noItemsMessage;
  58101. StringArray items;
  58102. int minNumber, maxNumber;
  58103. void flipEnablement (const int row)
  58104. {
  58105. if (((unsigned int) row) < (unsigned int) items.size())
  58106. {
  58107. const String item (items [row]);
  58108. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58109. }
  58110. }
  58111. int getTickX() const
  58112. {
  58113. return getRowHeight() + 5;
  58114. }
  58115. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58116. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58117. };
  58118. class AudioDeviceSettingsPanel : public Component,
  58119. public ComboBoxListener,
  58120. public ChangeListener,
  58121. public ButtonListener
  58122. {
  58123. public:
  58124. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58125. AudioIODeviceType::DeviceSetupDetails& setup_,
  58126. const bool hideAdvancedOptionsWithButton)
  58127. : type (type_),
  58128. setup (setup_)
  58129. {
  58130. if (hideAdvancedOptionsWithButton)
  58131. {
  58132. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58133. showAdvancedSettingsButton->addButtonListener (this);
  58134. }
  58135. type->scanForDevices();
  58136. setup.manager->addChangeListener (this);
  58137. changeListenerCallback (0);
  58138. }
  58139. ~AudioDeviceSettingsPanel()
  58140. {
  58141. setup.manager->removeChangeListener (this);
  58142. }
  58143. void resized()
  58144. {
  58145. const int lx = proportionOfWidth (0.35f);
  58146. const int w = proportionOfWidth (0.4f);
  58147. const int h = 24;
  58148. const int space = 6;
  58149. const int dh = h + space;
  58150. int y = 0;
  58151. if (outputDeviceDropDown != 0)
  58152. {
  58153. outputDeviceDropDown->setBounds (lx, y, w, h);
  58154. if (testButton != 0)
  58155. testButton->setBounds (proportionOfWidth (0.77f),
  58156. outputDeviceDropDown->getY(),
  58157. proportionOfWidth (0.18f),
  58158. h);
  58159. y += dh;
  58160. }
  58161. if (inputDeviceDropDown != 0)
  58162. {
  58163. inputDeviceDropDown->setBounds (lx, y, w, h);
  58164. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58165. inputDeviceDropDown->getY(),
  58166. proportionOfWidth (0.18f),
  58167. h);
  58168. y += dh;
  58169. }
  58170. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58171. if (outputChanList != 0)
  58172. {
  58173. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58174. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58175. y += bh + space;
  58176. }
  58177. if (inputChanList != 0)
  58178. {
  58179. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58180. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58181. y += bh + space;
  58182. }
  58183. y += space * 2;
  58184. if (showAdvancedSettingsButton != 0)
  58185. {
  58186. showAdvancedSettingsButton->changeWidthToFitText (h);
  58187. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58188. }
  58189. if (sampleRateDropDown != 0)
  58190. {
  58191. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58192. || ! showAdvancedSettingsButton->isVisible());
  58193. sampleRateDropDown->setBounds (lx, y, w, h);
  58194. y += dh;
  58195. }
  58196. if (bufferSizeDropDown != 0)
  58197. {
  58198. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58199. || ! showAdvancedSettingsButton->isVisible());
  58200. bufferSizeDropDown->setBounds (lx, y, w, h);
  58201. y += dh;
  58202. }
  58203. if (showUIButton != 0)
  58204. {
  58205. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58206. || ! showAdvancedSettingsButton->isVisible());
  58207. showUIButton->changeWidthToFitText (h);
  58208. showUIButton->setTopLeftPosition (lx, y);
  58209. }
  58210. }
  58211. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58212. {
  58213. if (comboBoxThatHasChanged == 0)
  58214. return;
  58215. AudioDeviceManager::AudioDeviceSetup config;
  58216. setup.manager->getAudioDeviceSetup (config);
  58217. String error;
  58218. if (comboBoxThatHasChanged == outputDeviceDropDown
  58219. || comboBoxThatHasChanged == inputDeviceDropDown)
  58220. {
  58221. if (outputDeviceDropDown != 0)
  58222. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58223. : outputDeviceDropDown->getText();
  58224. if (inputDeviceDropDown != 0)
  58225. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58226. : inputDeviceDropDown->getText();
  58227. if (! type->hasSeparateInputsAndOutputs())
  58228. config.inputDeviceName = config.outputDeviceName;
  58229. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58230. config.useDefaultInputChannels = true;
  58231. else
  58232. config.useDefaultOutputChannels = true;
  58233. error = setup.manager->setAudioDeviceSetup (config, true);
  58234. showCorrectDeviceName (inputDeviceDropDown, true);
  58235. showCorrectDeviceName (outputDeviceDropDown, false);
  58236. updateControlPanelButton();
  58237. resized();
  58238. }
  58239. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58240. {
  58241. if (sampleRateDropDown->getSelectedId() > 0)
  58242. {
  58243. config.sampleRate = sampleRateDropDown->getSelectedId();
  58244. error = setup.manager->setAudioDeviceSetup (config, true);
  58245. }
  58246. }
  58247. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58248. {
  58249. if (bufferSizeDropDown->getSelectedId() > 0)
  58250. {
  58251. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58252. error = setup.manager->setAudioDeviceSetup (config, true);
  58253. }
  58254. }
  58255. if (error.isNotEmpty())
  58256. {
  58257. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58258. "Error when trying to open audio device!",
  58259. error);
  58260. }
  58261. }
  58262. void buttonClicked (Button* button)
  58263. {
  58264. if (button == showAdvancedSettingsButton)
  58265. {
  58266. showAdvancedSettingsButton->setVisible (false);
  58267. resized();
  58268. }
  58269. else if (button == showUIButton)
  58270. {
  58271. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58272. if (device != 0 && device->showControlPanel())
  58273. {
  58274. setup.manager->closeAudioDevice();
  58275. setup.manager->restartLastAudioDevice();
  58276. getTopLevelComponent()->toFront (true);
  58277. }
  58278. }
  58279. else if (button == testButton && testButton != 0)
  58280. {
  58281. setup.manager->playTestSound();
  58282. }
  58283. }
  58284. void updateControlPanelButton()
  58285. {
  58286. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58287. showUIButton = 0;
  58288. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58289. {
  58290. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58291. TRANS ("opens the device's own control panel")));
  58292. showUIButton->addButtonListener (this);
  58293. }
  58294. resized();
  58295. }
  58296. void changeListenerCallback (void*)
  58297. {
  58298. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58299. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58300. {
  58301. if (outputDeviceDropDown == 0)
  58302. {
  58303. outputDeviceDropDown = new ComboBox (String::empty);
  58304. outputDeviceDropDown->addListener (this);
  58305. addAndMakeVisible (outputDeviceDropDown);
  58306. outputDeviceLabel = new Label (String::empty,
  58307. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58308. : TRANS ("device:"));
  58309. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58310. if (setup.maxNumOutputChannels > 0)
  58311. {
  58312. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58313. testButton->addButtonListener (this);
  58314. }
  58315. }
  58316. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58317. }
  58318. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58319. {
  58320. if (inputDeviceDropDown == 0)
  58321. {
  58322. inputDeviceDropDown = new ComboBox (String::empty);
  58323. inputDeviceDropDown->addListener (this);
  58324. addAndMakeVisible (inputDeviceDropDown);
  58325. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58326. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58327. addAndMakeVisible (inputLevelMeter
  58328. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58329. }
  58330. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58331. }
  58332. updateControlPanelButton();
  58333. showCorrectDeviceName (inputDeviceDropDown, true);
  58334. showCorrectDeviceName (outputDeviceDropDown, false);
  58335. if (currentDevice != 0)
  58336. {
  58337. if (setup.maxNumOutputChannels > 0
  58338. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58339. {
  58340. if (outputChanList == 0)
  58341. {
  58342. addAndMakeVisible (outputChanList
  58343. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58344. TRANS ("(no audio output channels found)")));
  58345. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58346. outputChanLabel->attachToComponent (outputChanList, true);
  58347. }
  58348. outputChanList->refresh();
  58349. }
  58350. else
  58351. {
  58352. outputChanLabel = 0;
  58353. outputChanList = 0;
  58354. }
  58355. if (setup.maxNumInputChannels > 0
  58356. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58357. {
  58358. if (inputChanList == 0)
  58359. {
  58360. addAndMakeVisible (inputChanList
  58361. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58362. TRANS ("(no audio input channels found)")));
  58363. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58364. inputChanLabel->attachToComponent (inputChanList, true);
  58365. }
  58366. inputChanList->refresh();
  58367. }
  58368. else
  58369. {
  58370. inputChanLabel = 0;
  58371. inputChanList = 0;
  58372. }
  58373. // sample rate..
  58374. {
  58375. if (sampleRateDropDown == 0)
  58376. {
  58377. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58378. sampleRateDropDown->addListener (this);
  58379. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58380. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58381. }
  58382. else
  58383. {
  58384. sampleRateDropDown->clear();
  58385. sampleRateDropDown->removeListener (this);
  58386. }
  58387. const int numRates = currentDevice->getNumSampleRates();
  58388. for (int i = 0; i < numRates; ++i)
  58389. {
  58390. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58391. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58392. }
  58393. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58394. sampleRateDropDown->addListener (this);
  58395. }
  58396. // buffer size
  58397. {
  58398. if (bufferSizeDropDown == 0)
  58399. {
  58400. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58401. bufferSizeDropDown->addListener (this);
  58402. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58403. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58404. }
  58405. else
  58406. {
  58407. bufferSizeDropDown->clear();
  58408. }
  58409. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58410. double currentRate = currentDevice->getCurrentSampleRate();
  58411. if (currentRate == 0)
  58412. currentRate = 48000.0;
  58413. for (int i = 0; i < numBufferSizes; ++i)
  58414. {
  58415. const int bs = currentDevice->getBufferSizeSamples (i);
  58416. bufferSizeDropDown->addItem (String (bs)
  58417. + " samples ("
  58418. + String (bs * 1000.0 / currentRate, 1)
  58419. + " ms)",
  58420. bs);
  58421. }
  58422. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58423. }
  58424. }
  58425. else
  58426. {
  58427. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58428. sampleRateLabel = 0;
  58429. bufferSizeLabel = 0;
  58430. sampleRateDropDown = 0;
  58431. bufferSizeDropDown = 0;
  58432. if (outputDeviceDropDown != 0)
  58433. outputDeviceDropDown->setSelectedId (-1, true);
  58434. if (inputDeviceDropDown != 0)
  58435. inputDeviceDropDown->setSelectedId (-1, true);
  58436. }
  58437. resized();
  58438. setSize (getWidth(), getLowestY() + 4);
  58439. }
  58440. private:
  58441. AudioIODeviceType* const type;
  58442. const AudioIODeviceType::DeviceSetupDetails setup;
  58443. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58444. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58445. ScopedPointer<TextButton> testButton;
  58446. ScopedPointer<Component> inputLevelMeter;
  58447. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58448. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58449. {
  58450. if (box != 0)
  58451. {
  58452. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58453. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58454. box->setSelectedId (index + 1, true);
  58455. if (testButton != 0 && ! isInput)
  58456. testButton->setEnabled (index >= 0);
  58457. }
  58458. }
  58459. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58460. {
  58461. const StringArray devs (type->getDeviceNames (isInputs));
  58462. combo.clear (true);
  58463. for (int i = 0; i < devs.size(); ++i)
  58464. combo.addItem (devs[i], i + 1);
  58465. combo.addItem (TRANS("<< none >>"), -1);
  58466. combo.setSelectedId (-1, true);
  58467. }
  58468. int getLowestY() const
  58469. {
  58470. int y = 0;
  58471. for (int i = getNumChildComponents(); --i >= 0;)
  58472. y = jmax (y, getChildComponent (i)->getBottom());
  58473. return y;
  58474. }
  58475. public:
  58476. class ChannelSelectorListBox : public ListBox,
  58477. public ListBoxModel
  58478. {
  58479. public:
  58480. enum BoxType
  58481. {
  58482. audioInputType,
  58483. audioOutputType
  58484. };
  58485. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58486. const BoxType type_,
  58487. const String& noItemsMessage_)
  58488. : ListBox (String::empty, 0),
  58489. setup (setup_),
  58490. type (type_),
  58491. noItemsMessage (noItemsMessage_)
  58492. {
  58493. refresh();
  58494. setModel (this);
  58495. setOutlineThickness (1);
  58496. }
  58497. ~ChannelSelectorListBox()
  58498. {
  58499. }
  58500. void refresh()
  58501. {
  58502. items.clear();
  58503. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58504. if (currentDevice != 0)
  58505. {
  58506. if (type == audioInputType)
  58507. items = currentDevice->getInputChannelNames();
  58508. else if (type == audioOutputType)
  58509. items = currentDevice->getOutputChannelNames();
  58510. if (setup.useStereoPairs)
  58511. {
  58512. StringArray pairs;
  58513. for (int i = 0; i < items.size(); i += 2)
  58514. {
  58515. const String name (items[i]);
  58516. const String name2 (items[i + 1]);
  58517. String commonBit;
  58518. for (int j = 0; j < name.length(); ++j)
  58519. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58520. commonBit = name.substring (0, j);
  58521. // Make sure we only split the name at a space, because otherwise, things
  58522. // like "input 11" + "input 12" would become "input 11 + 2"
  58523. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58524. commonBit = commonBit.dropLastCharacters (1);
  58525. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58526. }
  58527. items = pairs;
  58528. }
  58529. }
  58530. updateContent();
  58531. repaint();
  58532. }
  58533. int getNumRows()
  58534. {
  58535. return items.size();
  58536. }
  58537. void paintListBoxItem (int row,
  58538. Graphics& g,
  58539. int width, int height,
  58540. bool rowIsSelected)
  58541. {
  58542. if (((unsigned int) row) < (unsigned int) items.size())
  58543. {
  58544. if (rowIsSelected)
  58545. g.fillAll (findColour (TextEditor::highlightColourId)
  58546. .withMultipliedAlpha (0.3f));
  58547. const String item (items [row]);
  58548. bool enabled = false;
  58549. AudioDeviceManager::AudioDeviceSetup config;
  58550. setup.manager->getAudioDeviceSetup (config);
  58551. if (setup.useStereoPairs)
  58552. {
  58553. if (type == audioInputType)
  58554. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58555. else if (type == audioOutputType)
  58556. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58557. }
  58558. else
  58559. {
  58560. if (type == audioInputType)
  58561. enabled = config.inputChannels [row];
  58562. else if (type == audioOutputType)
  58563. enabled = config.outputChannels [row];
  58564. }
  58565. const int x = getTickX();
  58566. const float tickW = height * 0.75f;
  58567. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58568. enabled, true, true, false);
  58569. g.setFont (height * 0.6f);
  58570. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58571. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58572. }
  58573. }
  58574. void listBoxItemClicked (int row, const MouseEvent& e)
  58575. {
  58576. selectRow (row);
  58577. if (e.x < getTickX())
  58578. flipEnablement (row);
  58579. }
  58580. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58581. {
  58582. flipEnablement (row);
  58583. }
  58584. void returnKeyPressed (int row)
  58585. {
  58586. flipEnablement (row);
  58587. }
  58588. void paint (Graphics& g)
  58589. {
  58590. ListBox::paint (g);
  58591. if (items.size() == 0)
  58592. {
  58593. g.setColour (Colours::grey);
  58594. g.setFont (13.0f);
  58595. g.drawText (noItemsMessage,
  58596. 0, 0, getWidth(), getHeight() / 2,
  58597. Justification::centred, true);
  58598. }
  58599. }
  58600. int getBestHeight (int maxHeight)
  58601. {
  58602. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58603. getNumRows())
  58604. + getOutlineThickness() * 2;
  58605. }
  58606. juce_UseDebuggingNewOperator
  58607. private:
  58608. const AudioIODeviceType::DeviceSetupDetails setup;
  58609. const BoxType type;
  58610. const String noItemsMessage;
  58611. StringArray items;
  58612. void flipEnablement (const int row)
  58613. {
  58614. jassert (type == audioInputType || type == audioOutputType);
  58615. if (((unsigned int) row) < (unsigned int) items.size())
  58616. {
  58617. AudioDeviceManager::AudioDeviceSetup config;
  58618. setup.manager->getAudioDeviceSetup (config);
  58619. if (setup.useStereoPairs)
  58620. {
  58621. BigInteger bits;
  58622. BigInteger& original = (type == audioInputType ? config.inputChannels
  58623. : config.outputChannels);
  58624. int i;
  58625. for (i = 0; i < 256; i += 2)
  58626. bits.setBit (i / 2, original [i] || original [i + 1]);
  58627. if (type == audioInputType)
  58628. {
  58629. config.useDefaultInputChannels = false;
  58630. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58631. }
  58632. else
  58633. {
  58634. config.useDefaultOutputChannels = false;
  58635. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58636. }
  58637. for (i = 0; i < 256; ++i)
  58638. original.setBit (i, bits [i / 2]);
  58639. }
  58640. else
  58641. {
  58642. if (type == audioInputType)
  58643. {
  58644. config.useDefaultInputChannels = false;
  58645. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58646. }
  58647. else
  58648. {
  58649. config.useDefaultOutputChannels = false;
  58650. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58651. }
  58652. }
  58653. String error (setup.manager->setAudioDeviceSetup (config, true));
  58654. if (! error.isEmpty())
  58655. {
  58656. //xxx
  58657. }
  58658. }
  58659. }
  58660. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58661. {
  58662. const int numActive = chans.countNumberOfSetBits();
  58663. if (chans [index])
  58664. {
  58665. if (numActive > minNumber)
  58666. chans.setBit (index, false);
  58667. }
  58668. else
  58669. {
  58670. if (numActive >= maxNumber)
  58671. {
  58672. const int firstActiveChan = chans.findNextSetBit();
  58673. chans.setBit (index > firstActiveChan
  58674. ? firstActiveChan : chans.getHighestBit(),
  58675. false);
  58676. }
  58677. chans.setBit (index, true);
  58678. }
  58679. }
  58680. int getTickX() const
  58681. {
  58682. return getRowHeight() + 5;
  58683. }
  58684. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58685. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58686. };
  58687. private:
  58688. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58689. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58690. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58691. };
  58692. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58693. const int minInputChannels_,
  58694. const int maxInputChannels_,
  58695. const int minOutputChannels_,
  58696. const int maxOutputChannels_,
  58697. const bool showMidiInputOptions,
  58698. const bool showMidiOutputSelector,
  58699. const bool showChannelsAsStereoPairs_,
  58700. const bool hideAdvancedOptionsWithButton_)
  58701. : deviceManager (deviceManager_),
  58702. deviceTypeDropDown (0),
  58703. deviceTypeDropDownLabel (0),
  58704. minOutputChannels (minOutputChannels_),
  58705. maxOutputChannels (maxOutputChannels_),
  58706. minInputChannels (minInputChannels_),
  58707. maxInputChannels (maxInputChannels_),
  58708. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58709. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58710. {
  58711. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58712. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58713. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58714. {
  58715. deviceTypeDropDown = new ComboBox (String::empty);
  58716. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58717. {
  58718. deviceTypeDropDown
  58719. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58720. i + 1);
  58721. }
  58722. addAndMakeVisible (deviceTypeDropDown);
  58723. deviceTypeDropDown->addListener (this);
  58724. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58725. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58726. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58727. }
  58728. if (showMidiInputOptions)
  58729. {
  58730. addAndMakeVisible (midiInputsList
  58731. = new MidiInputSelectorComponentListBox (deviceManager,
  58732. TRANS("(no midi inputs available)"),
  58733. 0, 0));
  58734. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58735. midiInputsLabel->setJustificationType (Justification::topRight);
  58736. midiInputsLabel->attachToComponent (midiInputsList, true);
  58737. }
  58738. else
  58739. {
  58740. midiInputsList = 0;
  58741. midiInputsLabel = 0;
  58742. }
  58743. if (showMidiOutputSelector)
  58744. {
  58745. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58746. midiOutputSelector->addListener (this);
  58747. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58748. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58749. }
  58750. else
  58751. {
  58752. midiOutputSelector = 0;
  58753. midiOutputLabel = 0;
  58754. }
  58755. deviceManager_.addChangeListener (this);
  58756. changeListenerCallback (0);
  58757. }
  58758. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58759. {
  58760. deviceManager.removeChangeListener (this);
  58761. }
  58762. void AudioDeviceSelectorComponent::resized()
  58763. {
  58764. const int lx = proportionOfWidth (0.35f);
  58765. const int w = proportionOfWidth (0.4f);
  58766. const int h = 24;
  58767. const int space = 6;
  58768. const int dh = h + space;
  58769. int y = 15;
  58770. if (deviceTypeDropDown != 0)
  58771. {
  58772. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58773. y += dh + space * 2;
  58774. }
  58775. if (audioDeviceSettingsComp != 0)
  58776. {
  58777. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58778. y += audioDeviceSettingsComp->getHeight() + space;
  58779. }
  58780. if (midiInputsList != 0)
  58781. {
  58782. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58783. midiInputsList->setBounds (lx, y, w, bh);
  58784. y += bh + space;
  58785. }
  58786. if (midiOutputSelector != 0)
  58787. midiOutputSelector->setBounds (lx, y, w, h);
  58788. }
  58789. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58790. {
  58791. if (child == audioDeviceSettingsComp)
  58792. resized();
  58793. }
  58794. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58795. {
  58796. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58797. if (device != 0 && device->hasControlPanel())
  58798. {
  58799. if (device->showControlPanel())
  58800. deviceManager.restartLastAudioDevice();
  58801. getTopLevelComponent()->toFront (true);
  58802. }
  58803. }
  58804. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58805. {
  58806. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58807. {
  58808. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58809. if (type != 0)
  58810. {
  58811. audioDeviceSettingsComp = 0;
  58812. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58813. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58814. }
  58815. }
  58816. else if (comboBoxThatHasChanged == midiOutputSelector)
  58817. {
  58818. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58819. }
  58820. }
  58821. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58822. {
  58823. if (deviceTypeDropDown != 0)
  58824. {
  58825. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58826. }
  58827. if (audioDeviceSettingsComp == 0
  58828. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58829. {
  58830. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58831. audioDeviceSettingsComp = 0;
  58832. AudioIODeviceType* const type
  58833. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58834. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58835. if (type != 0)
  58836. {
  58837. AudioIODeviceType::DeviceSetupDetails details;
  58838. details.manager = &deviceManager;
  58839. details.minNumInputChannels = minInputChannels;
  58840. details.maxNumInputChannels = maxInputChannels;
  58841. details.minNumOutputChannels = minOutputChannels;
  58842. details.maxNumOutputChannels = maxOutputChannels;
  58843. details.useStereoPairs = showChannelsAsStereoPairs;
  58844. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58845. if (audioDeviceSettingsComp != 0)
  58846. {
  58847. addAndMakeVisible (audioDeviceSettingsComp);
  58848. audioDeviceSettingsComp->resized();
  58849. }
  58850. }
  58851. }
  58852. if (midiInputsList != 0)
  58853. {
  58854. midiInputsList->updateContent();
  58855. midiInputsList->repaint();
  58856. }
  58857. if (midiOutputSelector != 0)
  58858. {
  58859. midiOutputSelector->clear();
  58860. const StringArray midiOuts (MidiOutput::getDevices());
  58861. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58862. midiOutputSelector->addSeparator();
  58863. for (int i = 0; i < midiOuts.size(); ++i)
  58864. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58865. int current = -1;
  58866. if (deviceManager.getDefaultMidiOutput() != 0)
  58867. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58868. midiOutputSelector->setSelectedId (current, true);
  58869. }
  58870. resized();
  58871. }
  58872. END_JUCE_NAMESPACE
  58873. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58874. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58875. BEGIN_JUCE_NAMESPACE
  58876. BubbleComponent::BubbleComponent()
  58877. : side (0),
  58878. allowablePlacements (above | below | left | right),
  58879. arrowTipX (0.0f),
  58880. arrowTipY (0.0f)
  58881. {
  58882. setInterceptsMouseClicks (false, false);
  58883. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58884. setComponentEffect (&shadow);
  58885. }
  58886. BubbleComponent::~BubbleComponent()
  58887. {
  58888. }
  58889. void BubbleComponent::paint (Graphics& g)
  58890. {
  58891. int x = content.getX();
  58892. int y = content.getY();
  58893. int w = content.getWidth();
  58894. int h = content.getHeight();
  58895. int cw, ch;
  58896. getContentSize (cw, ch);
  58897. if (side == 3)
  58898. x += w - cw;
  58899. else if (side != 1)
  58900. x += (w - cw) / 2;
  58901. w = cw;
  58902. if (side == 2)
  58903. y += h - ch;
  58904. else if (side != 0)
  58905. y += (h - ch) / 2;
  58906. h = ch;
  58907. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58908. (float) x, (float) y,
  58909. (float) w, (float) h);
  58910. const int cx = x + (w - cw) / 2;
  58911. const int cy = y + (h - ch) / 2;
  58912. const int indent = 3;
  58913. g.setOrigin (cx + indent, cy + indent);
  58914. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58915. paintContent (g, cw - indent * 2, ch - indent * 2);
  58916. }
  58917. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58918. {
  58919. allowablePlacements = newPlacement;
  58920. }
  58921. void BubbleComponent::setPosition (Component* componentToPointTo)
  58922. {
  58923. jassert (componentToPointTo->isValidComponent());
  58924. Point<int> pos;
  58925. if (getParentComponent() != 0)
  58926. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58927. else
  58928. pos = componentToPointTo->relativePositionToGlobal (pos);
  58929. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58930. }
  58931. void BubbleComponent::setPosition (const int arrowTipX_,
  58932. const int arrowTipY_)
  58933. {
  58934. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58935. }
  58936. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58937. {
  58938. Rectangle<int> availableSpace;
  58939. if (getParentComponent() != 0)
  58940. {
  58941. availableSpace.setSize (getParentComponent()->getWidth(),
  58942. getParentComponent()->getHeight());
  58943. }
  58944. else
  58945. {
  58946. availableSpace = getParentMonitorArea();
  58947. }
  58948. int x = 0;
  58949. int y = 0;
  58950. int w = 150;
  58951. int h = 30;
  58952. getContentSize (w, h);
  58953. w += 30;
  58954. h += 30;
  58955. const float edgeIndent = 2.0f;
  58956. const int arrowLength = jmin (10, h / 3, w / 3);
  58957. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58958. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58959. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58960. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58961. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58962. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58963. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58964. {
  58965. spaceLeft = spaceRight = 0;
  58966. }
  58967. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58968. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58969. {
  58970. spaceAbove = spaceBelow = 0;
  58971. }
  58972. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58973. {
  58974. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58975. arrowTipX = w * 0.5f;
  58976. content.setSize (w, h - arrowLength);
  58977. if (spaceAbove >= spaceBelow)
  58978. {
  58979. // above
  58980. y = rectangleToPointTo.getY() - h;
  58981. content.setPosition (0, 0);
  58982. arrowTipY = h - edgeIndent;
  58983. side = 2;
  58984. }
  58985. else
  58986. {
  58987. // below
  58988. y = rectangleToPointTo.getBottom();
  58989. content.setPosition (0, arrowLength);
  58990. arrowTipY = edgeIndent;
  58991. side = 0;
  58992. }
  58993. }
  58994. else
  58995. {
  58996. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58997. arrowTipY = h * 0.5f;
  58998. content.setSize (w - arrowLength, h);
  58999. if (spaceLeft > spaceRight)
  59000. {
  59001. // on the left
  59002. x = rectangleToPointTo.getX() - w;
  59003. content.setPosition (0, 0);
  59004. arrowTipX = w - edgeIndent;
  59005. side = 3;
  59006. }
  59007. else
  59008. {
  59009. // on the right
  59010. x = rectangleToPointTo.getRight();
  59011. content.setPosition (arrowLength, 0);
  59012. arrowTipX = edgeIndent;
  59013. side = 1;
  59014. }
  59015. }
  59016. setBounds (x, y, w, h);
  59017. }
  59018. END_JUCE_NAMESPACE
  59019. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59020. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59021. BEGIN_JUCE_NAMESPACE
  59022. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59023. : fadeOutLength (fadeOutLengthMs),
  59024. deleteAfterUse (false)
  59025. {
  59026. }
  59027. BubbleMessageComponent::~BubbleMessageComponent()
  59028. {
  59029. fadeOutComponent (fadeOutLength);
  59030. }
  59031. void BubbleMessageComponent::showAt (int x, int y,
  59032. const String& text,
  59033. const int numMillisecondsBeforeRemoving,
  59034. const bool removeWhenMouseClicked,
  59035. const bool deleteSelfAfterUse)
  59036. {
  59037. textLayout.clear();
  59038. textLayout.setText (text, Font (14.0f));
  59039. textLayout.layout (256, Justification::centredLeft, true);
  59040. setPosition (x, y);
  59041. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59042. }
  59043. void BubbleMessageComponent::showAt (Component* const component,
  59044. const String& text,
  59045. const int numMillisecondsBeforeRemoving,
  59046. const bool removeWhenMouseClicked,
  59047. const bool deleteSelfAfterUse)
  59048. {
  59049. textLayout.clear();
  59050. textLayout.setText (text, Font (14.0f));
  59051. textLayout.layout (256, Justification::centredLeft, true);
  59052. setPosition (component);
  59053. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59054. }
  59055. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59056. const bool removeWhenMouseClicked,
  59057. const bool deleteSelfAfterUse)
  59058. {
  59059. setVisible (true);
  59060. deleteAfterUse = deleteSelfAfterUse;
  59061. if (numMillisecondsBeforeRemoving > 0)
  59062. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59063. else
  59064. expiryTime = 0;
  59065. startTimer (77);
  59066. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59067. if (! (removeWhenMouseClicked && isShowing()))
  59068. mouseClickCounter += 0xfffff;
  59069. repaint();
  59070. }
  59071. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59072. {
  59073. w = textLayout.getWidth() + 16;
  59074. h = textLayout.getHeight() + 16;
  59075. }
  59076. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59077. {
  59078. g.setColour (findColour (TooltipWindow::textColourId));
  59079. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59080. }
  59081. void BubbleMessageComponent::timerCallback()
  59082. {
  59083. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59084. {
  59085. stopTimer();
  59086. setVisible (false);
  59087. if (deleteAfterUse)
  59088. delete this;
  59089. }
  59090. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59091. {
  59092. stopTimer();
  59093. fadeOutComponent (fadeOutLength);
  59094. if (deleteAfterUse)
  59095. delete this;
  59096. }
  59097. }
  59098. END_JUCE_NAMESPACE
  59099. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59100. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59101. BEGIN_JUCE_NAMESPACE
  59102. class ColourComponentSlider : public Slider
  59103. {
  59104. public:
  59105. ColourComponentSlider (const String& name)
  59106. : Slider (name)
  59107. {
  59108. setRange (0.0, 255.0, 1.0);
  59109. }
  59110. ~ColourComponentSlider()
  59111. {
  59112. }
  59113. const String getTextFromValue (double value)
  59114. {
  59115. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59116. }
  59117. double getValueFromText (const String& text)
  59118. {
  59119. return (double) text.getHexValue32();
  59120. }
  59121. private:
  59122. ColourComponentSlider (const ColourComponentSlider&);
  59123. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59124. };
  59125. class ColourSpaceMarker : public Component
  59126. {
  59127. public:
  59128. ColourSpaceMarker()
  59129. {
  59130. setInterceptsMouseClicks (false, false);
  59131. }
  59132. ~ColourSpaceMarker()
  59133. {
  59134. }
  59135. void paint (Graphics& g)
  59136. {
  59137. g.setColour (Colour::greyLevel (0.1f));
  59138. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59139. g.setColour (Colour::greyLevel (0.9f));
  59140. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59141. }
  59142. private:
  59143. ColourSpaceMarker (const ColourSpaceMarker&);
  59144. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59145. };
  59146. class ColourSelector::ColourSpaceView : public Component
  59147. {
  59148. public:
  59149. ColourSpaceView (ColourSelector* owner_,
  59150. float& h_, float& s_, float& v_,
  59151. const int edgeSize)
  59152. : owner (owner_),
  59153. h (h_), s (s_), v (v_),
  59154. lastHue (0.0f),
  59155. edge (edgeSize)
  59156. {
  59157. addAndMakeVisible (&marker);
  59158. setMouseCursor (MouseCursor::CrosshairCursor);
  59159. }
  59160. ~ColourSpaceView()
  59161. {
  59162. }
  59163. void paint (Graphics& g)
  59164. {
  59165. if (colours.isNull())
  59166. {
  59167. const int width = getWidth() / 2;
  59168. const int height = getHeight() / 2;
  59169. colours = Image (Image::RGB, width, height, false);
  59170. Image::BitmapData pixels (colours, 0, 0, width, height, true);
  59171. for (int y = 0; y < height; ++y)
  59172. {
  59173. const float val = 1.0f - y / (float) height;
  59174. for (int x = 0; x < width; ++x)
  59175. {
  59176. const float sat = x / (float) width;
  59177. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59178. }
  59179. }
  59180. }
  59181. g.setOpacity (1.0f);
  59182. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59183. 0, 0, colours.getWidth(), colours.getHeight());
  59184. }
  59185. void mouseDown (const MouseEvent& e)
  59186. {
  59187. mouseDrag (e);
  59188. }
  59189. void mouseDrag (const MouseEvent& e)
  59190. {
  59191. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59192. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59193. owner->setSV (sat, val);
  59194. }
  59195. void updateIfNeeded()
  59196. {
  59197. if (lastHue != h)
  59198. {
  59199. lastHue = h;
  59200. colours = Image();
  59201. repaint();
  59202. }
  59203. updateMarker();
  59204. }
  59205. void resized()
  59206. {
  59207. colours = Image();
  59208. updateMarker();
  59209. }
  59210. private:
  59211. ColourSelector* const owner;
  59212. float& h;
  59213. float& s;
  59214. float& v;
  59215. float lastHue;
  59216. ColourSpaceMarker marker;
  59217. const int edge;
  59218. Image colours;
  59219. void updateMarker()
  59220. {
  59221. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59222. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59223. edge * 2, edge * 2);
  59224. }
  59225. ColourSpaceView (const ColourSpaceView&);
  59226. ColourSpaceView& operator= (const ColourSpaceView&);
  59227. };
  59228. class HueSelectorMarker : public Component
  59229. {
  59230. public:
  59231. HueSelectorMarker()
  59232. {
  59233. setInterceptsMouseClicks (false, false);
  59234. }
  59235. ~HueSelectorMarker()
  59236. {
  59237. }
  59238. void paint (Graphics& g)
  59239. {
  59240. Path p;
  59241. p.addTriangle (1.0f, 1.0f,
  59242. getWidth() * 0.3f, getHeight() * 0.5f,
  59243. 1.0f, getHeight() - 1.0f);
  59244. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59245. getWidth() * 0.7f, getHeight() * 0.5f,
  59246. getWidth() - 1.0f, getHeight() - 1.0f);
  59247. g.setColour (Colours::white.withAlpha (0.75f));
  59248. g.fillPath (p);
  59249. g.setColour (Colours::black.withAlpha (0.75f));
  59250. g.strokePath (p, PathStrokeType (1.2f));
  59251. }
  59252. private:
  59253. HueSelectorMarker (const HueSelectorMarker&);
  59254. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59255. };
  59256. class ColourSelector::HueSelectorComp : public Component
  59257. {
  59258. public:
  59259. HueSelectorComp (ColourSelector* owner_,
  59260. float& h_, float& s_, float& v_,
  59261. const int edgeSize)
  59262. : owner (owner_),
  59263. h (h_), s (s_), v (v_),
  59264. lastHue (0.0f),
  59265. edge (edgeSize)
  59266. {
  59267. addAndMakeVisible (&marker);
  59268. }
  59269. ~HueSelectorComp()
  59270. {
  59271. }
  59272. void paint (Graphics& g)
  59273. {
  59274. const float yScale = 1.0f / (getHeight() - edge * 2);
  59275. const Rectangle<int> clip (g.getClipBounds());
  59276. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59277. {
  59278. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59279. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59280. }
  59281. }
  59282. void resized()
  59283. {
  59284. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59285. getWidth(), edge * 2);
  59286. }
  59287. void mouseDown (const MouseEvent& e)
  59288. {
  59289. mouseDrag (e);
  59290. }
  59291. void mouseDrag (const MouseEvent& e)
  59292. {
  59293. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59294. owner->setHue (hue);
  59295. }
  59296. void updateIfNeeded()
  59297. {
  59298. resized();
  59299. }
  59300. private:
  59301. ColourSelector* const owner;
  59302. float& h;
  59303. float& s;
  59304. float& v;
  59305. float lastHue;
  59306. HueSelectorMarker marker;
  59307. const int edge;
  59308. HueSelectorComp (const HueSelectorComp&);
  59309. HueSelectorComp& operator= (const HueSelectorComp&);
  59310. };
  59311. class ColourSelector::SwatchComponent : public Component
  59312. {
  59313. public:
  59314. SwatchComponent (ColourSelector* owner_, int index_)
  59315. : owner (owner_),
  59316. index (index_)
  59317. {
  59318. }
  59319. ~SwatchComponent()
  59320. {
  59321. }
  59322. void paint (Graphics& g)
  59323. {
  59324. const Colour colour (owner->getSwatchColour (index));
  59325. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59326. Colour (0xffdddddd).overlaidWith (colour),
  59327. Colour (0xffffffff).overlaidWith (colour));
  59328. }
  59329. void mouseDown (const MouseEvent&)
  59330. {
  59331. PopupMenu m;
  59332. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59333. m.addSeparator();
  59334. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59335. const int r = m.showAt (this);
  59336. if (r == 1)
  59337. {
  59338. owner->setCurrentColour (owner->getSwatchColour (index));
  59339. }
  59340. else if (r == 2)
  59341. {
  59342. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59343. {
  59344. owner->setSwatchColour (index, owner->getCurrentColour());
  59345. repaint();
  59346. }
  59347. }
  59348. }
  59349. private:
  59350. ColourSelector* const owner;
  59351. const int index;
  59352. SwatchComponent (const SwatchComponent&);
  59353. SwatchComponent& operator= (const SwatchComponent&);
  59354. };
  59355. ColourSelector::ColourSelector (const int flags_,
  59356. const int edgeGap_,
  59357. const int gapAroundColourSpaceComponent)
  59358. : colour (Colours::white),
  59359. colourSpace (0),
  59360. hueSelector (0),
  59361. flags (flags_),
  59362. edgeGap (edgeGap_)
  59363. {
  59364. // not much point having a selector with no components in it!
  59365. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59366. updateHSV();
  59367. if ((flags & showSliders) != 0)
  59368. {
  59369. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59370. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59371. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59372. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59373. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59374. for (int i = 4; --i >= 0;)
  59375. sliders[i]->addListener (this);
  59376. }
  59377. else
  59378. {
  59379. zeromem (sliders, sizeof (sliders));
  59380. }
  59381. if ((flags & showColourspace) != 0)
  59382. {
  59383. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59384. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59385. }
  59386. update();
  59387. }
  59388. ColourSelector::~ColourSelector()
  59389. {
  59390. dispatchPendingMessages();
  59391. swatchComponents.clear();
  59392. deleteAllChildren();
  59393. }
  59394. const Colour ColourSelector::getCurrentColour() const
  59395. {
  59396. return ((flags & showAlphaChannel) != 0) ? colour
  59397. : colour.withAlpha ((uint8) 0xff);
  59398. }
  59399. void ColourSelector::setCurrentColour (const Colour& c)
  59400. {
  59401. if (c != colour)
  59402. {
  59403. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59404. updateHSV();
  59405. update();
  59406. }
  59407. }
  59408. void ColourSelector::setHue (float newH)
  59409. {
  59410. newH = jlimit (0.0f, 1.0f, newH);
  59411. if (h != newH)
  59412. {
  59413. h = newH;
  59414. colour = Colour (h, s, v, colour.getFloatAlpha());
  59415. update();
  59416. }
  59417. }
  59418. void ColourSelector::setSV (float newS, float newV)
  59419. {
  59420. newS = jlimit (0.0f, 1.0f, newS);
  59421. newV = jlimit (0.0f, 1.0f, newV);
  59422. if (s != newS || v != newV)
  59423. {
  59424. s = newS;
  59425. v = newV;
  59426. colour = Colour (h, s, v, colour.getFloatAlpha());
  59427. update();
  59428. }
  59429. }
  59430. void ColourSelector::updateHSV()
  59431. {
  59432. colour.getHSB (h, s, v);
  59433. }
  59434. void ColourSelector::update()
  59435. {
  59436. if (sliders[0] != 0)
  59437. {
  59438. sliders[0]->setValue ((int) colour.getRed());
  59439. sliders[1]->setValue ((int) colour.getGreen());
  59440. sliders[2]->setValue ((int) colour.getBlue());
  59441. sliders[3]->setValue ((int) colour.getAlpha());
  59442. }
  59443. if (colourSpace != 0)
  59444. {
  59445. colourSpace->updateIfNeeded();
  59446. hueSelector->updateIfNeeded();
  59447. }
  59448. if ((flags & showColourAtTop) != 0)
  59449. repaint (previewArea);
  59450. sendChangeMessage (this);
  59451. }
  59452. void ColourSelector::paint (Graphics& g)
  59453. {
  59454. g.fillAll (findColour (backgroundColourId));
  59455. if ((flags & showColourAtTop) != 0)
  59456. {
  59457. const Colour currentColour (getCurrentColour());
  59458. g.fillCheckerBoard (previewArea, 10, 10,
  59459. Colour (0xffdddddd).overlaidWith (currentColour),
  59460. Colour (0xffffffff).overlaidWith (currentColour));
  59461. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59462. g.setFont (14.0f, true);
  59463. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59464. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59465. Justification::centred, false);
  59466. }
  59467. if ((flags & showSliders) != 0)
  59468. {
  59469. g.setColour (findColour (labelTextColourId));
  59470. g.setFont (11.0f);
  59471. for (int i = 4; --i >= 0;)
  59472. {
  59473. if (sliders[i]->isVisible())
  59474. g.drawText (sliders[i]->getName() + ":",
  59475. 0, sliders[i]->getY(),
  59476. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59477. Justification::centredRight, false);
  59478. }
  59479. }
  59480. }
  59481. void ColourSelector::resized()
  59482. {
  59483. const int swatchesPerRow = 8;
  59484. const int swatchHeight = 22;
  59485. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59486. const int numSwatches = getNumSwatches();
  59487. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59488. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59489. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59490. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59491. int y = topSpace;
  59492. if ((flags & showColourspace) != 0)
  59493. {
  59494. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59495. colourSpace->setBounds (edgeGap, y,
  59496. getWidth() - hueWidth - edgeGap - 4,
  59497. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59498. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59499. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59500. colourSpace->getHeight());
  59501. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59502. }
  59503. if ((flags & showSliders) != 0)
  59504. {
  59505. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59506. for (int i = 0; i < numSliders; ++i)
  59507. {
  59508. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59509. proportionOfWidth (0.72f), sliderHeight - 2);
  59510. y += sliderHeight;
  59511. }
  59512. }
  59513. if (numSwatches > 0)
  59514. {
  59515. const int startX = 8;
  59516. const int xGap = 4;
  59517. const int yGap = 4;
  59518. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59519. y += edgeGap;
  59520. if (swatchComponents.size() != numSwatches)
  59521. {
  59522. swatchComponents.clear();
  59523. for (int i = 0; i < numSwatches; ++i)
  59524. {
  59525. SwatchComponent* const sc = new SwatchComponent (this, i);
  59526. swatchComponents.add (sc);
  59527. addAndMakeVisible (sc);
  59528. }
  59529. }
  59530. int x = startX;
  59531. for (int i = 0; i < swatchComponents.size(); ++i)
  59532. {
  59533. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59534. sc->setBounds (x + xGap / 2,
  59535. y + yGap / 2,
  59536. swatchWidth - xGap,
  59537. swatchHeight - yGap);
  59538. if (((i + 1) % swatchesPerRow) == 0)
  59539. {
  59540. x = startX;
  59541. y += swatchHeight;
  59542. }
  59543. else
  59544. {
  59545. x += swatchWidth;
  59546. }
  59547. }
  59548. }
  59549. }
  59550. void ColourSelector::sliderValueChanged (Slider*)
  59551. {
  59552. if (sliders[0] != 0)
  59553. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59554. (uint8) sliders[1]->getValue(),
  59555. (uint8) sliders[2]->getValue(),
  59556. (uint8) sliders[3]->getValue()));
  59557. }
  59558. int ColourSelector::getNumSwatches() const
  59559. {
  59560. return 0;
  59561. }
  59562. const Colour ColourSelector::getSwatchColour (const int) const
  59563. {
  59564. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59565. return Colours::black;
  59566. }
  59567. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59568. {
  59569. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59570. }
  59571. END_JUCE_NAMESPACE
  59572. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59573. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59574. BEGIN_JUCE_NAMESPACE
  59575. class ShadowWindow : public Component
  59576. {
  59577. Component* owner;
  59578. Image shadowImageSections [12];
  59579. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59580. public:
  59581. ShadowWindow (Component* const owner_,
  59582. const int type_,
  59583. const Image shadowImageSections_ [12])
  59584. : owner (owner_),
  59585. type (type_)
  59586. {
  59587. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59588. shadowImageSections [i] = shadowImageSections_ [i];
  59589. setInterceptsMouseClicks (false, false);
  59590. if (owner_->isOnDesktop())
  59591. {
  59592. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59593. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59594. | ComponentPeer::windowIsTemporary
  59595. | ComponentPeer::windowIgnoresKeyPresses);
  59596. }
  59597. else if (owner_->getParentComponent() != 0)
  59598. {
  59599. owner_->getParentComponent()->addChildComponent (this);
  59600. }
  59601. }
  59602. ~ShadowWindow()
  59603. {
  59604. }
  59605. void paint (Graphics& g)
  59606. {
  59607. const Image& topLeft = shadowImageSections [type * 3];
  59608. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59609. const Image& filler = shadowImageSections [type * 3 + 2];
  59610. g.setOpacity (1.0f);
  59611. if (type < 2)
  59612. {
  59613. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59614. g.drawImage (topLeft,
  59615. 0, 0, topLeft.getWidth(), imH,
  59616. 0, 0, topLeft.getWidth(), imH);
  59617. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59618. g.drawImage (bottomRight,
  59619. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59620. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59621. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59622. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59623. }
  59624. else
  59625. {
  59626. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59627. g.drawImage (topLeft,
  59628. 0, 0, imW, topLeft.getHeight(),
  59629. 0, 0, imW, topLeft.getHeight());
  59630. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59631. g.drawImage (bottomRight,
  59632. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59633. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59634. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59635. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59636. }
  59637. }
  59638. void resized()
  59639. {
  59640. repaint(); // (needed for correct repainting)
  59641. }
  59642. private:
  59643. ShadowWindow (const ShadowWindow&);
  59644. ShadowWindow& operator= (const ShadowWindow&);
  59645. };
  59646. DropShadower::DropShadower (const float alpha_,
  59647. const int xOffset_,
  59648. const int yOffset_,
  59649. const float blurRadius_)
  59650. : owner (0),
  59651. numShadows (0),
  59652. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59653. xOffset (xOffset_),
  59654. yOffset (yOffset_),
  59655. alpha (alpha_),
  59656. blurRadius (blurRadius_),
  59657. inDestructor (false),
  59658. reentrant (false)
  59659. {
  59660. }
  59661. DropShadower::~DropShadower()
  59662. {
  59663. if (owner != 0)
  59664. owner->removeComponentListener (this);
  59665. inDestructor = true;
  59666. deleteShadowWindows();
  59667. }
  59668. void DropShadower::deleteShadowWindows()
  59669. {
  59670. if (numShadows > 0)
  59671. {
  59672. int i;
  59673. for (i = numShadows; --i >= 0;)
  59674. delete shadowWindows[i];
  59675. numShadows = 0;
  59676. }
  59677. }
  59678. void DropShadower::setOwner (Component* componentToFollow)
  59679. {
  59680. if (componentToFollow != owner)
  59681. {
  59682. if (owner != 0)
  59683. owner->removeComponentListener (this);
  59684. // (the component can't be null)
  59685. jassert (componentToFollow != 0);
  59686. owner = componentToFollow;
  59687. jassert (owner != 0);
  59688. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59689. owner->addComponentListener (this);
  59690. updateShadows();
  59691. }
  59692. }
  59693. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59694. {
  59695. updateShadows();
  59696. }
  59697. void DropShadower::componentBroughtToFront (Component&)
  59698. {
  59699. bringShadowWindowsToFront();
  59700. }
  59701. void DropShadower::componentChildrenChanged (Component&)
  59702. {
  59703. }
  59704. void DropShadower::componentParentHierarchyChanged (Component&)
  59705. {
  59706. deleteShadowWindows();
  59707. updateShadows();
  59708. }
  59709. void DropShadower::componentVisibilityChanged (Component&)
  59710. {
  59711. updateShadows();
  59712. }
  59713. void DropShadower::updateShadows()
  59714. {
  59715. if (reentrant || inDestructor || (owner == 0))
  59716. return;
  59717. reentrant = true;
  59718. ComponentPeer* const nw = owner->getPeer();
  59719. const bool isOwnerVisible = owner->isVisible()
  59720. && (nw == 0 || ! nw->isMinimised());
  59721. const bool createShadowWindows = numShadows == 0
  59722. && owner->getWidth() > 0
  59723. && owner->getHeight() > 0
  59724. && isOwnerVisible
  59725. && (Desktop::canUseSemiTransparentWindows()
  59726. || owner->getParentComponent() != 0);
  59727. if (createShadowWindows)
  59728. {
  59729. // keep a cached version of the image to save doing the gaussian too often
  59730. String imageId;
  59731. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59732. const int hash = imageId.hashCode();
  59733. Image bigIm (ImageCache::getFromHashCode (hash));
  59734. if (bigIm.isNull())
  59735. {
  59736. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59737. Graphics bigG (bigIm);
  59738. bigG.setColour (Colours::black.withAlpha (alpha));
  59739. bigG.fillRect (shadowEdge + xOffset,
  59740. shadowEdge + yOffset,
  59741. bigIm.getWidth() - (shadowEdge * 2),
  59742. bigIm.getHeight() - (shadowEdge * 2));
  59743. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59744. blurKernel.createGaussianBlur (blurRadius);
  59745. blurKernel.applyToImage (bigIm, bigIm,
  59746. Rectangle<int> (xOffset, yOffset,
  59747. bigIm.getWidth(), bigIm.getHeight()));
  59748. ImageCache::addImageToCache (bigIm, hash);
  59749. }
  59750. const int iw = bigIm.getWidth();
  59751. const int ih = bigIm.getHeight();
  59752. const int shadowEdge2 = shadowEdge * 2;
  59753. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59754. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59755. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59756. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59757. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59758. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59759. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59760. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59761. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59762. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59763. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59764. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59765. for (int i = 0; i < 4; ++i)
  59766. {
  59767. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59768. ++numShadows;
  59769. }
  59770. }
  59771. if (numShadows > 0)
  59772. {
  59773. for (int i = numShadows; --i >= 0;)
  59774. {
  59775. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59776. shadowWindows[i]->setVisible (isOwnerVisible);
  59777. }
  59778. const int x = owner->getX();
  59779. const int y = owner->getY() - shadowEdge;
  59780. const int w = owner->getWidth();
  59781. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59782. shadowWindows[0]->setBounds (x - shadowEdge,
  59783. y,
  59784. shadowEdge,
  59785. h);
  59786. shadowWindows[1]->setBounds (x + w,
  59787. y,
  59788. shadowEdge,
  59789. h);
  59790. shadowWindows[2]->setBounds (x,
  59791. y,
  59792. w,
  59793. shadowEdge);
  59794. shadowWindows[3]->setBounds (x,
  59795. owner->getBottom(),
  59796. w,
  59797. shadowEdge);
  59798. }
  59799. reentrant = false;
  59800. if (createShadowWindows)
  59801. bringShadowWindowsToFront();
  59802. }
  59803. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59804. const int sx, const int sy)
  59805. {
  59806. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59807. Graphics g (shadowImageSections[num]);
  59808. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59809. }
  59810. void DropShadower::bringShadowWindowsToFront()
  59811. {
  59812. if (! (inDestructor || reentrant))
  59813. {
  59814. updateShadows();
  59815. reentrant = true;
  59816. for (int i = numShadows; --i >= 0;)
  59817. shadowWindows[i]->toBehind (owner);
  59818. reentrant = false;
  59819. }
  59820. }
  59821. END_JUCE_NAMESPACE
  59822. /*** End of inlined file: juce_DropShadower.cpp ***/
  59823. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59824. BEGIN_JUCE_NAMESPACE
  59825. class MagnifyingPeer : public ComponentPeer
  59826. {
  59827. public:
  59828. MagnifyingPeer (Component* const component_,
  59829. MagnifierComponent* const magnifierComp_)
  59830. : ComponentPeer (component_, 0),
  59831. magnifierComp (magnifierComp_)
  59832. {
  59833. }
  59834. ~MagnifyingPeer()
  59835. {
  59836. }
  59837. void* getNativeHandle() const { return 0; }
  59838. void setVisible (bool) {}
  59839. void setTitle (const String&) {}
  59840. void setPosition (int, int) {}
  59841. void setSize (int, int) {}
  59842. void setBounds (int, int, int, int, bool) {}
  59843. void setMinimised (bool) {}
  59844. bool isMinimised() const { return false; }
  59845. void setFullScreen (bool) {}
  59846. bool isFullScreen() const { return false; }
  59847. const BorderSize getFrameSize() const { return BorderSize (0); }
  59848. bool setAlwaysOnTop (bool) { return true; }
  59849. void toFront (bool) {}
  59850. void toBehind (ComponentPeer*) {}
  59851. void setIcon (const Image&) {}
  59852. bool isFocused() const
  59853. {
  59854. return magnifierComp->hasKeyboardFocus (true);
  59855. }
  59856. void grabFocus()
  59857. {
  59858. ComponentPeer* peer = magnifierComp->getPeer();
  59859. if (peer != 0)
  59860. peer->grabFocus();
  59861. }
  59862. void textInputRequired (const Point<int>& position)
  59863. {
  59864. ComponentPeer* peer = magnifierComp->getPeer();
  59865. if (peer != 0)
  59866. peer->textInputRequired (position);
  59867. }
  59868. const Rectangle<int> getBounds() const
  59869. {
  59870. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59871. component->getWidth(), component->getHeight());
  59872. }
  59873. const Point<int> getScreenPosition() const
  59874. {
  59875. return magnifierComp->getScreenPosition();
  59876. }
  59877. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59878. {
  59879. const double zoom = magnifierComp->getScaleFactor();
  59880. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59881. roundToInt (relativePosition.getY() * zoom)));
  59882. }
  59883. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59884. {
  59885. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59886. const double zoom = magnifierComp->getScaleFactor();
  59887. return Point<int> (roundToInt (p.getX() / zoom),
  59888. roundToInt (p.getY() / zoom));
  59889. }
  59890. bool contains (const Point<int>& position, bool) const
  59891. {
  59892. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59893. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59894. }
  59895. void repaint (const Rectangle<int>& area)
  59896. {
  59897. const double zoom = magnifierComp->getScaleFactor();
  59898. magnifierComp->repaint ((int) (area.getX() * zoom),
  59899. (int) (area.getY() * zoom),
  59900. roundToInt (area.getWidth() * zoom) + 1,
  59901. roundToInt (area.getHeight() * zoom) + 1);
  59902. }
  59903. void performAnyPendingRepaintsNow()
  59904. {
  59905. }
  59906. juce_UseDebuggingNewOperator
  59907. private:
  59908. MagnifierComponent* const magnifierComp;
  59909. MagnifyingPeer (const MagnifyingPeer&);
  59910. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59911. };
  59912. class PeerHolderComp : public Component
  59913. {
  59914. public:
  59915. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59916. : magnifierComp (magnifierComp_)
  59917. {
  59918. setVisible (true);
  59919. }
  59920. ~PeerHolderComp()
  59921. {
  59922. }
  59923. ComponentPeer* createNewPeer (int, void*)
  59924. {
  59925. return new MagnifyingPeer (this, magnifierComp);
  59926. }
  59927. void childBoundsChanged (Component* c)
  59928. {
  59929. if (c != 0)
  59930. {
  59931. setSize (c->getWidth(), c->getHeight());
  59932. magnifierComp->childBoundsChanged (this);
  59933. }
  59934. }
  59935. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59936. {
  59937. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59938. Component* const p = magnifierComp->getParentComponent();
  59939. if (p != 0)
  59940. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59941. }
  59942. private:
  59943. MagnifierComponent* const magnifierComp;
  59944. PeerHolderComp (const PeerHolderComp&);
  59945. PeerHolderComp& operator= (const PeerHolderComp&);
  59946. };
  59947. MagnifierComponent::MagnifierComponent (Component* const content_,
  59948. const bool deleteContentCompWhenNoLongerNeeded)
  59949. : content (content_),
  59950. scaleFactor (0.0),
  59951. peer (0),
  59952. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59953. quality (Graphics::lowResamplingQuality),
  59954. mouseSource (0, true)
  59955. {
  59956. holderComp = new PeerHolderComp (this);
  59957. setScaleFactor (1.0);
  59958. }
  59959. MagnifierComponent::~MagnifierComponent()
  59960. {
  59961. delete holderComp;
  59962. if (deleteContent)
  59963. delete content;
  59964. }
  59965. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59966. {
  59967. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59968. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59969. if (scaleFactor != newScaleFactor)
  59970. {
  59971. scaleFactor = newScaleFactor;
  59972. if (scaleFactor == 1.0)
  59973. {
  59974. holderComp->removeFromDesktop();
  59975. peer = 0;
  59976. addChildComponent (content);
  59977. childBoundsChanged (content);
  59978. }
  59979. else
  59980. {
  59981. holderComp->addAndMakeVisible (content);
  59982. holderComp->childBoundsChanged (content);
  59983. childBoundsChanged (holderComp);
  59984. holderComp->addToDesktop (0);
  59985. peer = holderComp->getPeer();
  59986. }
  59987. repaint();
  59988. }
  59989. }
  59990. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59991. {
  59992. quality = newQuality;
  59993. }
  59994. void MagnifierComponent::paint (Graphics& g)
  59995. {
  59996. const int w = holderComp->getWidth();
  59997. const int h = holderComp->getHeight();
  59998. if (w == 0 || h == 0)
  59999. return;
  60000. const Rectangle<int> r (g.getClipBounds());
  60001. const int srcX = (int) (r.getX() / scaleFactor);
  60002. const int srcY = (int) (r.getY() / scaleFactor);
  60003. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60004. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60005. if (scaleFactor >= 1.0)
  60006. {
  60007. ++srcW;
  60008. ++srcH;
  60009. }
  60010. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60011. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60012. {
  60013. Graphics g2 (temp);
  60014. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60015. holderComp->paintEntireComponent (g2);
  60016. }
  60017. g.setImageResamplingQuality (quality);
  60018. g.drawImageTransformed (temp, temp.getBounds(),
  60019. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  60020. false);
  60021. }
  60022. void MagnifierComponent::childBoundsChanged (Component* c)
  60023. {
  60024. if (c != 0)
  60025. setSize (roundToInt (c->getWidth() * scaleFactor),
  60026. roundToInt (c->getHeight() * scaleFactor));
  60027. }
  60028. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60029. {
  60030. if (peer != 0)
  60031. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60032. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60033. }
  60034. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60035. {
  60036. passOnMouseEventToPeer (e);
  60037. }
  60038. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60039. {
  60040. passOnMouseEventToPeer (e);
  60041. }
  60042. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60043. {
  60044. passOnMouseEventToPeer (e);
  60045. }
  60046. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60047. {
  60048. passOnMouseEventToPeer (e);
  60049. }
  60050. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60051. {
  60052. passOnMouseEventToPeer (e);
  60053. }
  60054. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60055. {
  60056. passOnMouseEventToPeer (e);
  60057. }
  60058. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60059. {
  60060. if (peer != 0)
  60061. peer->handleMouseWheel (e.source.getIndex(),
  60062. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60063. ix * 256.0f, iy * 256.0f);
  60064. else
  60065. Component::mouseWheelMove (e, ix, iy);
  60066. }
  60067. int MagnifierComponent::scaleInt (const int n) const
  60068. {
  60069. return roundToInt (n / scaleFactor);
  60070. }
  60071. END_JUCE_NAMESPACE
  60072. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60073. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60074. BEGIN_JUCE_NAMESPACE
  60075. class MidiKeyboardUpDownButton : public Button
  60076. {
  60077. public:
  60078. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60079. const int delta_)
  60080. : Button (String::empty),
  60081. owner (owner_),
  60082. delta (delta_)
  60083. {
  60084. setOpaque (true);
  60085. }
  60086. ~MidiKeyboardUpDownButton()
  60087. {
  60088. }
  60089. void clicked()
  60090. {
  60091. int note = owner->getLowestVisibleKey();
  60092. if (delta < 0)
  60093. note = (note - 1) / 12;
  60094. else
  60095. note = note / 12 + 1;
  60096. owner->setLowestVisibleKey (note * 12);
  60097. }
  60098. void paintButton (Graphics& g,
  60099. bool isMouseOverButton,
  60100. bool isButtonDown)
  60101. {
  60102. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60103. isMouseOverButton, isButtonDown,
  60104. delta > 0);
  60105. }
  60106. private:
  60107. MidiKeyboardComponent* const owner;
  60108. const int delta;
  60109. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60110. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60111. };
  60112. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60113. const Orientation orientation_)
  60114. : state (state_),
  60115. xOffset (0),
  60116. blackNoteLength (1),
  60117. keyWidth (16.0f),
  60118. orientation (orientation_),
  60119. midiChannel (1),
  60120. midiInChannelMask (0xffff),
  60121. velocity (1.0f),
  60122. noteUnderMouse (-1),
  60123. mouseDownNote (-1),
  60124. rangeStart (0),
  60125. rangeEnd (127),
  60126. firstKey (12 * 4),
  60127. canScroll (true),
  60128. mouseDragging (false),
  60129. useMousePositionForVelocity (true),
  60130. keyMappingOctave (6),
  60131. octaveNumForMiddleC (3)
  60132. {
  60133. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60134. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60135. // initialise with a default set of querty key-mappings..
  60136. const char* const keymap = "awsedftgyhujkolp;";
  60137. for (int i = String (keymap).length(); --i >= 0;)
  60138. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60139. setOpaque (true);
  60140. setWantsKeyboardFocus (true);
  60141. state.addListener (this);
  60142. }
  60143. MidiKeyboardComponent::~MidiKeyboardComponent()
  60144. {
  60145. state.removeListener (this);
  60146. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60147. deleteAllChildren();
  60148. }
  60149. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60150. {
  60151. keyWidth = widthInPixels;
  60152. resized();
  60153. }
  60154. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60155. {
  60156. if (orientation != newOrientation)
  60157. {
  60158. orientation = newOrientation;
  60159. resized();
  60160. }
  60161. }
  60162. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60163. const int highestNote)
  60164. {
  60165. jassert (lowestNote >= 0 && lowestNote <= 127);
  60166. jassert (highestNote >= 0 && highestNote <= 127);
  60167. jassert (lowestNote <= highestNote);
  60168. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60169. {
  60170. rangeStart = jlimit (0, 127, lowestNote);
  60171. rangeEnd = jlimit (0, 127, highestNote);
  60172. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60173. resized();
  60174. }
  60175. }
  60176. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60177. {
  60178. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60179. if (noteNumber != firstKey)
  60180. {
  60181. firstKey = noteNumber;
  60182. sendChangeMessage (this);
  60183. resized();
  60184. }
  60185. }
  60186. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60187. {
  60188. if (canScroll != canScroll_)
  60189. {
  60190. canScroll = canScroll_;
  60191. resized();
  60192. }
  60193. }
  60194. void MidiKeyboardComponent::colourChanged()
  60195. {
  60196. repaint();
  60197. }
  60198. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60199. {
  60200. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60201. if (midiChannel != midiChannelNumber)
  60202. {
  60203. resetAnyKeysInUse();
  60204. midiChannel = jlimit (1, 16, midiChannelNumber);
  60205. }
  60206. }
  60207. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60208. {
  60209. midiInChannelMask = midiChannelMask;
  60210. triggerAsyncUpdate();
  60211. }
  60212. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60213. {
  60214. velocity = jlimit (0.0f, 1.0f, velocity_);
  60215. useMousePositionForVelocity = useMousePositionForVelocity_;
  60216. }
  60217. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60218. {
  60219. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60220. static const float blackNoteWidth = 0.7f;
  60221. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60222. 1.0f, 2 - blackNoteWidth * 0.4f,
  60223. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60224. 4.0f, 5 - blackNoteWidth * 0.5f,
  60225. 5.0f, 6 - blackNoteWidth * 0.3f,
  60226. 6.0f };
  60227. static const float widths[] = { 1.0f, blackNoteWidth,
  60228. 1.0f, blackNoteWidth,
  60229. 1.0f, 1.0f, blackNoteWidth,
  60230. 1.0f, blackNoteWidth,
  60231. 1.0f, blackNoteWidth,
  60232. 1.0f };
  60233. const int octave = midiNoteNumber / 12;
  60234. const int note = midiNoteNumber % 12;
  60235. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60236. w = roundToInt (widths [note] * keyWidth_);
  60237. }
  60238. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60239. {
  60240. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60241. int rx, rw;
  60242. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60243. x -= xOffset + rx;
  60244. }
  60245. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60246. {
  60247. int x, y;
  60248. getKeyPos (midiNoteNumber, x, y);
  60249. return x;
  60250. }
  60251. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60252. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60253. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60254. {
  60255. if (! reallyContains (pos.getX(), pos.getY(), false))
  60256. return -1;
  60257. Point<int> p (pos);
  60258. if (orientation != horizontalKeyboard)
  60259. {
  60260. p = Point<int> (p.getY(), p.getX());
  60261. if (orientation == verticalKeyboardFacingLeft)
  60262. p = Point<int> (p.getX(), getWidth() - p.getY());
  60263. else
  60264. p = Point<int> (getHeight() - p.getX(), p.getY());
  60265. }
  60266. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60267. }
  60268. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60269. {
  60270. if (pos.getY() < blackNoteLength)
  60271. {
  60272. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60273. {
  60274. for (int i = 0; i < 5; ++i)
  60275. {
  60276. const int note = octaveStart + blackNotes [i];
  60277. if (note >= rangeStart && note <= rangeEnd)
  60278. {
  60279. int kx, kw;
  60280. getKeyPos (note, kx, kw);
  60281. kx += xOffset;
  60282. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60283. {
  60284. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60285. return note;
  60286. }
  60287. }
  60288. }
  60289. }
  60290. }
  60291. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60292. {
  60293. for (int i = 0; i < 7; ++i)
  60294. {
  60295. const int note = octaveStart + whiteNotes [i];
  60296. if (note >= rangeStart && note <= rangeEnd)
  60297. {
  60298. int kx, kw;
  60299. getKeyPos (note, kx, kw);
  60300. kx += xOffset;
  60301. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60302. {
  60303. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60304. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60305. return note;
  60306. }
  60307. }
  60308. }
  60309. }
  60310. mousePositionVelocity = 0;
  60311. return -1;
  60312. }
  60313. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60314. {
  60315. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60316. {
  60317. int x, w;
  60318. getKeyPos (noteNum, x, w);
  60319. if (orientation == horizontalKeyboard)
  60320. repaint (x, 0, w, getHeight());
  60321. else if (orientation == verticalKeyboardFacingLeft)
  60322. repaint (0, x, getWidth(), w);
  60323. else if (orientation == verticalKeyboardFacingRight)
  60324. repaint (0, getHeight() - x - w, getWidth(), w);
  60325. }
  60326. }
  60327. void MidiKeyboardComponent::paint (Graphics& g)
  60328. {
  60329. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60330. const Colour lineColour (findColour (keySeparatorLineColourId));
  60331. const Colour textColour (findColour (textLabelColourId));
  60332. int x, w, octave;
  60333. for (octave = 0; octave < 128; octave += 12)
  60334. {
  60335. for (int white = 0; white < 7; ++white)
  60336. {
  60337. const int noteNum = octave + whiteNotes [white];
  60338. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60339. {
  60340. getKeyPos (noteNum, x, w);
  60341. if (orientation == horizontalKeyboard)
  60342. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60343. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60344. noteUnderMouse == noteNum,
  60345. lineColour, textColour);
  60346. else if (orientation == verticalKeyboardFacingLeft)
  60347. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60348. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60349. noteUnderMouse == noteNum,
  60350. lineColour, textColour);
  60351. else if (orientation == verticalKeyboardFacingRight)
  60352. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60353. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60354. noteUnderMouse == noteNum,
  60355. lineColour, textColour);
  60356. }
  60357. }
  60358. }
  60359. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60360. if (orientation == verticalKeyboardFacingLeft)
  60361. {
  60362. x1 = getWidth() - 1.0f;
  60363. x2 = getWidth() - 5.0f;
  60364. }
  60365. else if (orientation == verticalKeyboardFacingRight)
  60366. x2 = 5.0f;
  60367. else
  60368. y2 = 5.0f;
  60369. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60370. Colours::transparentBlack, x2, y2, false));
  60371. getKeyPos (rangeEnd, x, w);
  60372. x += w;
  60373. if (orientation == verticalKeyboardFacingLeft)
  60374. g.fillRect (getWidth() - 5, 0, 5, x);
  60375. else if (orientation == verticalKeyboardFacingRight)
  60376. g.fillRect (0, 0, 5, x);
  60377. else
  60378. g.fillRect (0, 0, x, 5);
  60379. g.setColour (lineColour);
  60380. if (orientation == verticalKeyboardFacingLeft)
  60381. g.fillRect (0, 0, 1, x);
  60382. else if (orientation == verticalKeyboardFacingRight)
  60383. g.fillRect (getWidth() - 1, 0, 1, x);
  60384. else
  60385. g.fillRect (0, getHeight() - 1, x, 1);
  60386. const Colour blackNoteColour (findColour (blackNoteColourId));
  60387. for (octave = 0; octave < 128; octave += 12)
  60388. {
  60389. for (int black = 0; black < 5; ++black)
  60390. {
  60391. const int noteNum = octave + blackNotes [black];
  60392. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60393. {
  60394. getKeyPos (noteNum, x, w);
  60395. if (orientation == horizontalKeyboard)
  60396. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60397. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60398. noteUnderMouse == noteNum,
  60399. blackNoteColour);
  60400. else if (orientation == verticalKeyboardFacingLeft)
  60401. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60402. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60403. noteUnderMouse == noteNum,
  60404. blackNoteColour);
  60405. else if (orientation == verticalKeyboardFacingRight)
  60406. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60407. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60408. noteUnderMouse == noteNum,
  60409. blackNoteColour);
  60410. }
  60411. }
  60412. }
  60413. }
  60414. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60415. Graphics& g, int x, int y, int w, int h,
  60416. bool isDown, bool isOver,
  60417. const Colour& lineColour,
  60418. const Colour& textColour)
  60419. {
  60420. Colour c (Colours::transparentWhite);
  60421. if (isDown)
  60422. c = findColour (keyDownOverlayColourId);
  60423. if (isOver)
  60424. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60425. g.setColour (c);
  60426. g.fillRect (x, y, w, h);
  60427. const String text (getWhiteNoteText (midiNoteNumber));
  60428. if (! text.isEmpty())
  60429. {
  60430. g.setColour (textColour);
  60431. Font f (jmin (12.0f, keyWidth * 0.9f));
  60432. f.setHorizontalScale (0.8f);
  60433. g.setFont (f);
  60434. Justification justification (Justification::centredBottom);
  60435. if (orientation == verticalKeyboardFacingLeft)
  60436. justification = Justification::centredLeft;
  60437. else if (orientation == verticalKeyboardFacingRight)
  60438. justification = Justification::centredRight;
  60439. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60440. }
  60441. g.setColour (lineColour);
  60442. if (orientation == horizontalKeyboard)
  60443. g.fillRect (x, y, 1, h);
  60444. else if (orientation == verticalKeyboardFacingLeft)
  60445. g.fillRect (x, y, w, 1);
  60446. else if (orientation == verticalKeyboardFacingRight)
  60447. g.fillRect (x, y + h - 1, w, 1);
  60448. if (midiNoteNumber == rangeEnd)
  60449. {
  60450. if (orientation == horizontalKeyboard)
  60451. g.fillRect (x + w, y, 1, h);
  60452. else if (orientation == verticalKeyboardFacingLeft)
  60453. g.fillRect (x, y + h, w, 1);
  60454. else if (orientation == verticalKeyboardFacingRight)
  60455. g.fillRect (x, y - 1, w, 1);
  60456. }
  60457. }
  60458. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60459. Graphics& g, int x, int y, int w, int h,
  60460. bool isDown, bool isOver,
  60461. const Colour& noteFillColour)
  60462. {
  60463. Colour c (noteFillColour);
  60464. if (isDown)
  60465. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60466. if (isOver)
  60467. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60468. g.setColour (c);
  60469. g.fillRect (x, y, w, h);
  60470. if (isDown)
  60471. {
  60472. g.setColour (noteFillColour);
  60473. g.drawRect (x, y, w, h);
  60474. }
  60475. else
  60476. {
  60477. const int xIndent = jmax (1, jmin (w, h) / 8);
  60478. g.setColour (c.brighter());
  60479. if (orientation == horizontalKeyboard)
  60480. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60481. else if (orientation == verticalKeyboardFacingLeft)
  60482. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60483. else if (orientation == verticalKeyboardFacingRight)
  60484. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60485. }
  60486. }
  60487. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60488. {
  60489. octaveNumForMiddleC = octaveNumForMiddleC_;
  60490. repaint();
  60491. }
  60492. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60493. {
  60494. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60495. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60496. return String::empty;
  60497. }
  60498. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60499. const bool isMouseOver_,
  60500. const bool isButtonDown,
  60501. const bool movesOctavesUp)
  60502. {
  60503. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60504. float angle;
  60505. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60506. angle = movesOctavesUp ? 0.0f : 0.5f;
  60507. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60508. angle = movesOctavesUp ? 0.25f : 0.75f;
  60509. else
  60510. angle = movesOctavesUp ? 0.75f : 0.25f;
  60511. Path path;
  60512. path.lineTo (0.0f, 1.0f);
  60513. path.lineTo (1.0f, 0.5f);
  60514. path.closeSubPath();
  60515. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60516. g.setColour (findColour (upDownButtonArrowColourId)
  60517. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60518. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60519. w - 2.0f,
  60520. h - 2.0f,
  60521. true));
  60522. }
  60523. void MidiKeyboardComponent::resized()
  60524. {
  60525. int w = getWidth();
  60526. int h = getHeight();
  60527. if (w > 0 && h > 0)
  60528. {
  60529. if (orientation != horizontalKeyboard)
  60530. swapVariables (w, h);
  60531. blackNoteLength = roundToInt (h * 0.7f);
  60532. int kx2, kw2;
  60533. getKeyPos (rangeEnd, kx2, kw2);
  60534. kx2 += kw2;
  60535. if (firstKey != rangeStart)
  60536. {
  60537. int kx1, kw1;
  60538. getKeyPos (rangeStart, kx1, kw1);
  60539. if (kx2 - kx1 <= w)
  60540. {
  60541. firstKey = rangeStart;
  60542. sendChangeMessage (this);
  60543. repaint();
  60544. }
  60545. }
  60546. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60547. scrollDown->setVisible (showScrollButtons);
  60548. scrollUp->setVisible (showScrollButtons);
  60549. xOffset = 0;
  60550. if (showScrollButtons)
  60551. {
  60552. const int scrollButtonW = jmin (12, w / 2);
  60553. if (orientation == horizontalKeyboard)
  60554. {
  60555. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60556. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60557. }
  60558. else if (orientation == verticalKeyboardFacingLeft)
  60559. {
  60560. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60561. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60562. }
  60563. else if (orientation == verticalKeyboardFacingRight)
  60564. {
  60565. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60566. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60567. }
  60568. int endOfLastKey, kw;
  60569. getKeyPos (rangeEnd, endOfLastKey, kw);
  60570. endOfLastKey += kw;
  60571. float mousePositionVelocity;
  60572. const int spaceAvailable = w - scrollButtonW * 2;
  60573. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60574. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60575. {
  60576. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60577. sendChangeMessage (this);
  60578. }
  60579. int newOffset = 0;
  60580. getKeyPos (firstKey, newOffset, kw);
  60581. xOffset = newOffset - scrollButtonW;
  60582. }
  60583. else
  60584. {
  60585. firstKey = rangeStart;
  60586. }
  60587. timerCallback();
  60588. repaint();
  60589. }
  60590. }
  60591. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60592. {
  60593. triggerAsyncUpdate();
  60594. }
  60595. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60596. {
  60597. triggerAsyncUpdate();
  60598. }
  60599. void MidiKeyboardComponent::handleAsyncUpdate()
  60600. {
  60601. for (int i = rangeStart; i <= rangeEnd; ++i)
  60602. {
  60603. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60604. {
  60605. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60606. repaintNote (i);
  60607. }
  60608. }
  60609. }
  60610. void MidiKeyboardComponent::resetAnyKeysInUse()
  60611. {
  60612. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60613. {
  60614. state.allNotesOff (midiChannel);
  60615. keysPressed.clear();
  60616. mouseDownNote = -1;
  60617. }
  60618. }
  60619. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60620. {
  60621. float mousePositionVelocity = 0.0f;
  60622. const int newNote = (mouseDragging || isMouseOver())
  60623. ? xyToNote (pos, mousePositionVelocity) : -1;
  60624. if (noteUnderMouse != newNote)
  60625. {
  60626. if (mouseDownNote >= 0)
  60627. {
  60628. state.noteOff (midiChannel, mouseDownNote);
  60629. mouseDownNote = -1;
  60630. }
  60631. if (mouseDragging && newNote >= 0)
  60632. {
  60633. if (! useMousePositionForVelocity)
  60634. mousePositionVelocity = 1.0f;
  60635. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60636. mouseDownNote = newNote;
  60637. }
  60638. repaintNote (noteUnderMouse);
  60639. noteUnderMouse = newNote;
  60640. repaintNote (noteUnderMouse);
  60641. }
  60642. else if (mouseDownNote >= 0 && ! mouseDragging)
  60643. {
  60644. state.noteOff (midiChannel, mouseDownNote);
  60645. mouseDownNote = -1;
  60646. }
  60647. }
  60648. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60649. {
  60650. updateNoteUnderMouse (e.getPosition());
  60651. stopTimer();
  60652. }
  60653. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60654. {
  60655. float mousePositionVelocity;
  60656. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60657. if (newNote >= 0)
  60658. mouseDraggedToKey (newNote, e);
  60659. updateNoteUnderMouse (e.getPosition());
  60660. }
  60661. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60662. {
  60663. return true;
  60664. }
  60665. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60666. {
  60667. }
  60668. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60669. {
  60670. float mousePositionVelocity;
  60671. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60672. mouseDragging = false;
  60673. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60674. {
  60675. repaintNote (noteUnderMouse);
  60676. noteUnderMouse = -1;
  60677. mouseDragging = true;
  60678. updateNoteUnderMouse (e.getPosition());
  60679. startTimer (500);
  60680. }
  60681. }
  60682. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60683. {
  60684. mouseDragging = false;
  60685. updateNoteUnderMouse (e.getPosition());
  60686. stopTimer();
  60687. }
  60688. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60689. {
  60690. updateNoteUnderMouse (e.getPosition());
  60691. }
  60692. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60693. {
  60694. updateNoteUnderMouse (e.getPosition());
  60695. }
  60696. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60697. {
  60698. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60699. }
  60700. void MidiKeyboardComponent::timerCallback()
  60701. {
  60702. updateNoteUnderMouse (getMouseXYRelative());
  60703. }
  60704. void MidiKeyboardComponent::clearKeyMappings()
  60705. {
  60706. resetAnyKeysInUse();
  60707. keyPressNotes.clear();
  60708. keyPresses.clear();
  60709. }
  60710. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60711. const int midiNoteOffsetFromC)
  60712. {
  60713. removeKeyPressForNote (midiNoteOffsetFromC);
  60714. keyPressNotes.add (midiNoteOffsetFromC);
  60715. keyPresses.add (key);
  60716. }
  60717. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60718. {
  60719. for (int i = keyPressNotes.size(); --i >= 0;)
  60720. {
  60721. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60722. {
  60723. keyPressNotes.remove (i);
  60724. keyPresses.remove (i);
  60725. }
  60726. }
  60727. }
  60728. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60729. {
  60730. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60731. keyMappingOctave = newOctaveNumber;
  60732. }
  60733. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60734. {
  60735. bool keyPressUsed = false;
  60736. for (int i = keyPresses.size(); --i >= 0;)
  60737. {
  60738. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60739. if (keyPresses.getReference(i).isCurrentlyDown())
  60740. {
  60741. if (! keysPressed [note])
  60742. {
  60743. keysPressed.setBit (note);
  60744. state.noteOn (midiChannel, note, velocity);
  60745. keyPressUsed = true;
  60746. }
  60747. }
  60748. else
  60749. {
  60750. if (keysPressed [note])
  60751. {
  60752. keysPressed.clearBit (note);
  60753. state.noteOff (midiChannel, note);
  60754. keyPressUsed = true;
  60755. }
  60756. }
  60757. }
  60758. return keyPressUsed;
  60759. }
  60760. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60761. {
  60762. resetAnyKeysInUse();
  60763. }
  60764. END_JUCE_NAMESPACE
  60765. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60766. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60767. #if JUCE_OPENGL
  60768. BEGIN_JUCE_NAMESPACE
  60769. extern void juce_glViewport (const int w, const int h);
  60770. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60771. const int alphaBits_,
  60772. const int depthBufferBits_,
  60773. const int stencilBufferBits_)
  60774. : redBits (bitsPerRGBComponent),
  60775. greenBits (bitsPerRGBComponent),
  60776. blueBits (bitsPerRGBComponent),
  60777. alphaBits (alphaBits_),
  60778. depthBufferBits (depthBufferBits_),
  60779. stencilBufferBits (stencilBufferBits_),
  60780. accumulationBufferRedBits (0),
  60781. accumulationBufferGreenBits (0),
  60782. accumulationBufferBlueBits (0),
  60783. accumulationBufferAlphaBits (0),
  60784. fullSceneAntiAliasingNumSamples (0)
  60785. {
  60786. }
  60787. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60788. : redBits (other.redBits),
  60789. greenBits (other.greenBits),
  60790. blueBits (other.blueBits),
  60791. alphaBits (other.alphaBits),
  60792. depthBufferBits (other.depthBufferBits),
  60793. stencilBufferBits (other.stencilBufferBits),
  60794. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60795. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60796. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60797. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60798. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60799. {
  60800. }
  60801. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60802. {
  60803. redBits = other.redBits;
  60804. greenBits = other.greenBits;
  60805. blueBits = other.blueBits;
  60806. alphaBits = other.alphaBits;
  60807. depthBufferBits = other.depthBufferBits;
  60808. stencilBufferBits = other.stencilBufferBits;
  60809. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60810. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60811. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60812. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60813. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60814. return *this;
  60815. }
  60816. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60817. {
  60818. return redBits == other.redBits
  60819. && greenBits == other.greenBits
  60820. && blueBits == other.blueBits
  60821. && alphaBits == other.alphaBits
  60822. && depthBufferBits == other.depthBufferBits
  60823. && stencilBufferBits == other.stencilBufferBits
  60824. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60825. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60826. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60827. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60828. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60829. }
  60830. static Array<OpenGLContext*> knownContexts;
  60831. OpenGLContext::OpenGLContext() throw()
  60832. {
  60833. knownContexts.add (this);
  60834. }
  60835. OpenGLContext::~OpenGLContext()
  60836. {
  60837. knownContexts.removeValue (this);
  60838. }
  60839. OpenGLContext* OpenGLContext::getCurrentContext()
  60840. {
  60841. for (int i = knownContexts.size(); --i >= 0;)
  60842. {
  60843. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60844. if (oglc->isActive())
  60845. return oglc;
  60846. }
  60847. return 0;
  60848. }
  60849. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60850. {
  60851. public:
  60852. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60853. : ComponentMovementWatcher (owner_),
  60854. owner (owner_),
  60855. wasShowing (false)
  60856. {
  60857. }
  60858. ~OpenGLComponentWatcher() {}
  60859. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60860. {
  60861. owner->updateContextPosition();
  60862. }
  60863. void componentPeerChanged()
  60864. {
  60865. const ScopedLock sl (owner->getContextLock());
  60866. owner->deleteContext();
  60867. }
  60868. void componentVisibilityChanged (Component&)
  60869. {
  60870. const bool isShowingNow = owner->isShowing();
  60871. if (wasShowing != isShowingNow)
  60872. {
  60873. wasShowing = isShowingNow;
  60874. if (! isShowingNow)
  60875. {
  60876. const ScopedLock sl (owner->getContextLock());
  60877. owner->deleteContext();
  60878. }
  60879. }
  60880. }
  60881. juce_UseDebuggingNewOperator
  60882. private:
  60883. OpenGLComponent* const owner;
  60884. bool wasShowing;
  60885. };
  60886. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60887. : type (type_),
  60888. contextToShareListsWith (0),
  60889. needToUpdateViewport (true)
  60890. {
  60891. setOpaque (true);
  60892. componentWatcher = new OpenGLComponentWatcher (this);
  60893. }
  60894. OpenGLComponent::~OpenGLComponent()
  60895. {
  60896. deleteContext();
  60897. componentWatcher = 0;
  60898. }
  60899. void OpenGLComponent::deleteContext()
  60900. {
  60901. const ScopedLock sl (contextLock);
  60902. context = 0;
  60903. }
  60904. void OpenGLComponent::updateContextPosition()
  60905. {
  60906. needToUpdateViewport = true;
  60907. if (getWidth() > 0 && getHeight() > 0)
  60908. {
  60909. Component* const topComp = getTopLevelComponent();
  60910. if (topComp->getPeer() != 0)
  60911. {
  60912. const ScopedLock sl (contextLock);
  60913. if (context != 0)
  60914. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60915. getScreenY() - topComp->getScreenY(),
  60916. getWidth(),
  60917. getHeight(),
  60918. topComp->getHeight());
  60919. }
  60920. }
  60921. }
  60922. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60923. {
  60924. OpenGLPixelFormat pf;
  60925. const ScopedLock sl (contextLock);
  60926. if (context != 0)
  60927. pf = context->getPixelFormat();
  60928. return pf;
  60929. }
  60930. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60931. {
  60932. if (! (preferredPixelFormat == formatToUse))
  60933. {
  60934. const ScopedLock sl (contextLock);
  60935. deleteContext();
  60936. preferredPixelFormat = formatToUse;
  60937. }
  60938. }
  60939. void OpenGLComponent::shareWith (OpenGLContext* c)
  60940. {
  60941. if (contextToShareListsWith != c)
  60942. {
  60943. const ScopedLock sl (contextLock);
  60944. deleteContext();
  60945. contextToShareListsWith = c;
  60946. }
  60947. }
  60948. bool OpenGLComponent::makeCurrentContextActive()
  60949. {
  60950. if (context == 0)
  60951. {
  60952. const ScopedLock sl (contextLock);
  60953. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60954. {
  60955. context = createContext();
  60956. if (context != 0)
  60957. {
  60958. updateContextPosition();
  60959. if (context->makeActive())
  60960. newOpenGLContextCreated();
  60961. }
  60962. }
  60963. }
  60964. return context != 0 && context->makeActive();
  60965. }
  60966. void OpenGLComponent::makeCurrentContextInactive()
  60967. {
  60968. if (context != 0)
  60969. context->makeInactive();
  60970. }
  60971. bool OpenGLComponent::isActiveContext() const throw()
  60972. {
  60973. return context != 0 && context->isActive();
  60974. }
  60975. void OpenGLComponent::swapBuffers()
  60976. {
  60977. if (context != 0)
  60978. context->swapBuffers();
  60979. }
  60980. void OpenGLComponent::paint (Graphics&)
  60981. {
  60982. if (renderAndSwapBuffers())
  60983. {
  60984. ComponentPeer* const peer = getPeer();
  60985. if (peer != 0)
  60986. {
  60987. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60988. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60989. }
  60990. }
  60991. }
  60992. bool OpenGLComponent::renderAndSwapBuffers()
  60993. {
  60994. const ScopedLock sl (contextLock);
  60995. if (! makeCurrentContextActive())
  60996. return false;
  60997. if (needToUpdateViewport)
  60998. {
  60999. needToUpdateViewport = false;
  61000. juce_glViewport (getWidth(), getHeight());
  61001. }
  61002. renderOpenGL();
  61003. swapBuffers();
  61004. return true;
  61005. }
  61006. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61007. {
  61008. Component::internalRepaint (x, y, w, h);
  61009. if (context != 0)
  61010. context->repaint();
  61011. }
  61012. END_JUCE_NAMESPACE
  61013. #endif
  61014. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61015. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61016. BEGIN_JUCE_NAMESPACE
  61017. PreferencesPanel::PreferencesPanel()
  61018. : buttonSize (70)
  61019. {
  61020. }
  61021. PreferencesPanel::~PreferencesPanel()
  61022. {
  61023. currentPage = 0;
  61024. deleteAllChildren();
  61025. }
  61026. void PreferencesPanel::addSettingsPage (const String& title,
  61027. const Drawable* icon,
  61028. const Drawable* overIcon,
  61029. const Drawable* downIcon)
  61030. {
  61031. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61032. button->setImages (icon, overIcon, downIcon);
  61033. button->setRadioGroupId (1);
  61034. button->addButtonListener (this);
  61035. button->setClickingTogglesState (true);
  61036. button->setWantsKeyboardFocus (false);
  61037. addAndMakeVisible (button);
  61038. resized();
  61039. if (currentPage == 0)
  61040. setCurrentPage (title);
  61041. }
  61042. void PreferencesPanel::addSettingsPage (const String& title,
  61043. const void* imageData,
  61044. const int imageDataSize)
  61045. {
  61046. DrawableImage icon, iconOver, iconDown;
  61047. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61048. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61049. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61050. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61051. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61052. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61053. }
  61054. class PrefsDialogWindow : public DialogWindow
  61055. {
  61056. public:
  61057. PrefsDialogWindow (const String& dialogtitle,
  61058. const Colour& backgroundColour)
  61059. : DialogWindow (dialogtitle, backgroundColour, true)
  61060. {
  61061. }
  61062. ~PrefsDialogWindow()
  61063. {
  61064. }
  61065. void closeButtonPressed()
  61066. {
  61067. exitModalState (0);
  61068. }
  61069. private:
  61070. PrefsDialogWindow (const PrefsDialogWindow&);
  61071. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61072. };
  61073. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61074. int dialogWidth,
  61075. int dialogHeight,
  61076. const Colour& backgroundColour)
  61077. {
  61078. setSize (dialogWidth, dialogHeight);
  61079. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61080. dw.setContentComponent (this, true, true);
  61081. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61082. dw.runModalLoop();
  61083. dw.setContentComponent (0, false, false);
  61084. }
  61085. void PreferencesPanel::resized()
  61086. {
  61087. int x = 0;
  61088. for (int i = 0; i < getNumChildComponents(); ++i)
  61089. {
  61090. Component* c = getChildComponent (i);
  61091. if (dynamic_cast <DrawableButton*> (c) == 0)
  61092. {
  61093. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61094. }
  61095. else
  61096. {
  61097. c->setBounds (x, 0, buttonSize, buttonSize);
  61098. x += buttonSize;
  61099. }
  61100. }
  61101. }
  61102. void PreferencesPanel::paint (Graphics& g)
  61103. {
  61104. g.setColour (Colours::grey);
  61105. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61106. }
  61107. void PreferencesPanel::setCurrentPage (const String& pageName)
  61108. {
  61109. if (currentPageName != pageName)
  61110. {
  61111. currentPageName = pageName;
  61112. currentPage = 0;
  61113. currentPage = createComponentForPage (pageName);
  61114. if (currentPage != 0)
  61115. {
  61116. addAndMakeVisible (currentPage);
  61117. currentPage->toBack();
  61118. resized();
  61119. }
  61120. for (int i = 0; i < getNumChildComponents(); ++i)
  61121. {
  61122. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61123. if (db != 0 && db->getName() == pageName)
  61124. {
  61125. db->setToggleState (true, false);
  61126. break;
  61127. }
  61128. }
  61129. }
  61130. }
  61131. void PreferencesPanel::buttonClicked (Button*)
  61132. {
  61133. for (int i = 0; i < getNumChildComponents(); ++i)
  61134. {
  61135. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61136. if (db != 0 && db->getToggleState())
  61137. {
  61138. setCurrentPage (db->getName());
  61139. break;
  61140. }
  61141. }
  61142. }
  61143. END_JUCE_NAMESPACE
  61144. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61145. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61146. #if JUCE_WINDOWS || JUCE_LINUX
  61147. BEGIN_JUCE_NAMESPACE
  61148. SystemTrayIconComponent::SystemTrayIconComponent()
  61149. {
  61150. addToDesktop (0);
  61151. }
  61152. SystemTrayIconComponent::~SystemTrayIconComponent()
  61153. {
  61154. }
  61155. END_JUCE_NAMESPACE
  61156. #endif
  61157. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61158. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61159. BEGIN_JUCE_NAMESPACE
  61160. class AlertWindowTextEditor : public TextEditor
  61161. {
  61162. public:
  61163. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61164. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61165. {
  61166. setSelectAllWhenFocused (true);
  61167. }
  61168. ~AlertWindowTextEditor()
  61169. {
  61170. }
  61171. void returnPressed()
  61172. {
  61173. // pass these up the component hierarchy to be trigger the buttons
  61174. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61175. }
  61176. void escapePressed()
  61177. {
  61178. // pass these up the component hierarchy to be trigger the buttons
  61179. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61180. }
  61181. private:
  61182. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61183. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61184. static juce_wchar getDefaultPasswordChar() throw()
  61185. {
  61186. #if JUCE_LINUX
  61187. return 0x2022;
  61188. #else
  61189. return 0x25cf;
  61190. #endif
  61191. }
  61192. };
  61193. AlertWindow::AlertWindow (const String& title,
  61194. const String& message,
  61195. AlertIconType iconType,
  61196. Component* associatedComponent_)
  61197. : TopLevelWindow (title, true),
  61198. alertIconType (iconType),
  61199. associatedComponent (associatedComponent_)
  61200. {
  61201. if (message.isEmpty())
  61202. text = " "; // to force an update if the message is empty
  61203. setMessage (message);
  61204. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61205. {
  61206. Component* const c = Desktop::getInstance().getComponent (i);
  61207. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61208. {
  61209. setAlwaysOnTop (true);
  61210. break;
  61211. }
  61212. }
  61213. if (JUCEApplication::getInstance() == 0)
  61214. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61215. lookAndFeelChanged();
  61216. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61217. }
  61218. AlertWindow::~AlertWindow()
  61219. {
  61220. for (int i = customComps.size(); --i >= 0;)
  61221. removeChildComponent ((Component*) customComps[i]);
  61222. deleteAllChildren();
  61223. }
  61224. void AlertWindow::userTriedToCloseWindow()
  61225. {
  61226. exitModalState (0);
  61227. }
  61228. void AlertWindow::setMessage (const String& message)
  61229. {
  61230. const String newMessage (message.substring (0, 2048));
  61231. if (text != newMessage)
  61232. {
  61233. text = newMessage;
  61234. font.setHeight (15.0f);
  61235. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61236. textLayout.setText (getName() + "\n\n", titleFont);
  61237. textLayout.appendText (text, font);
  61238. updateLayout (true);
  61239. repaint();
  61240. }
  61241. }
  61242. void AlertWindow::buttonClicked (Button* button)
  61243. {
  61244. for (int i = 0; i < buttons.size(); i++)
  61245. {
  61246. TextButton* const c = (TextButton*) buttons[i];
  61247. if (button->getName() == c->getName())
  61248. {
  61249. if (c->getParentComponent() != 0)
  61250. c->getParentComponent()->exitModalState (c->getCommandID());
  61251. break;
  61252. }
  61253. }
  61254. }
  61255. void AlertWindow::addButton (const String& name,
  61256. const int returnValue,
  61257. const KeyPress& shortcutKey1,
  61258. const KeyPress& shortcutKey2)
  61259. {
  61260. TextButton* const b = new TextButton (name, String::empty);
  61261. b->setWantsKeyboardFocus (true);
  61262. b->setMouseClickGrabsKeyboardFocus (false);
  61263. b->setCommandToTrigger (0, returnValue, false);
  61264. b->addShortcut (shortcutKey1);
  61265. b->addShortcut (shortcutKey2);
  61266. b->addButtonListener (this);
  61267. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61268. addAndMakeVisible (b, 0);
  61269. buttons.add (b);
  61270. updateLayout (false);
  61271. }
  61272. int AlertWindow::getNumButtons() const
  61273. {
  61274. return buttons.size();
  61275. }
  61276. void AlertWindow::triggerButtonClick (const String& buttonName)
  61277. {
  61278. for (int i = buttons.size(); --i >= 0;)
  61279. {
  61280. TextButton* const b = (TextButton*) buttons[i];
  61281. if (buttonName == b->getName())
  61282. {
  61283. b->triggerClick();
  61284. break;
  61285. }
  61286. }
  61287. }
  61288. void AlertWindow::addTextEditor (const String& name,
  61289. const String& initialContents,
  61290. const String& onScreenLabel,
  61291. const bool isPasswordBox)
  61292. {
  61293. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61294. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61295. tc->setFont (font);
  61296. tc->setText (initialContents);
  61297. tc->setCaretPosition (initialContents.length());
  61298. addAndMakeVisible (tc);
  61299. textBoxes.add (tc);
  61300. allComps.add (tc);
  61301. textboxNames.add (onScreenLabel);
  61302. updateLayout (false);
  61303. }
  61304. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61305. {
  61306. for (int i = textBoxes.size(); --i >= 0;)
  61307. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61308. return ((TextEditor*)textBoxes[i])->getText();
  61309. return String::empty;
  61310. }
  61311. void AlertWindow::addComboBox (const String& name,
  61312. const StringArray& items,
  61313. const String& onScreenLabel)
  61314. {
  61315. ComboBox* const cb = new ComboBox (name);
  61316. for (int i = 0; i < items.size(); ++i)
  61317. cb->addItem (items[i], i + 1);
  61318. addAndMakeVisible (cb);
  61319. cb->setSelectedItemIndex (0);
  61320. comboBoxes.add (cb);
  61321. allComps.add (cb);
  61322. comboBoxNames.add (onScreenLabel);
  61323. updateLayout (false);
  61324. }
  61325. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61326. {
  61327. for (int i = comboBoxes.size(); --i >= 0;)
  61328. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61329. return (ComboBox*) comboBoxes[i];
  61330. return 0;
  61331. }
  61332. class AlertTextComp : public TextEditor
  61333. {
  61334. public:
  61335. AlertTextComp (const String& message,
  61336. const Font& font)
  61337. {
  61338. setReadOnly (true);
  61339. setMultiLine (true, true);
  61340. setCaretVisible (false);
  61341. setScrollbarsShown (true);
  61342. lookAndFeelChanged();
  61343. setWantsKeyboardFocus (false);
  61344. setFont (font);
  61345. setText (message, false);
  61346. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61347. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61348. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61349. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61350. }
  61351. ~AlertTextComp()
  61352. {
  61353. }
  61354. int getPreferredWidth() const throw() { return bestWidth; }
  61355. void updateLayout (const int width)
  61356. {
  61357. TextLayout text;
  61358. text.appendText (getText(), getFont());
  61359. text.layout (width - 8, Justification::topLeft, true);
  61360. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61361. }
  61362. private:
  61363. int bestWidth;
  61364. AlertTextComp (const AlertTextComp&);
  61365. AlertTextComp& operator= (const AlertTextComp&);
  61366. };
  61367. void AlertWindow::addTextBlock (const String& textBlock)
  61368. {
  61369. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61370. textBlocks.add (c);
  61371. allComps.add (c);
  61372. addAndMakeVisible (c);
  61373. updateLayout (false);
  61374. }
  61375. void AlertWindow::addProgressBarComponent (double& progressValue)
  61376. {
  61377. ProgressBar* const pb = new ProgressBar (progressValue);
  61378. progressBars.add (pb);
  61379. allComps.add (pb);
  61380. addAndMakeVisible (pb);
  61381. updateLayout (false);
  61382. }
  61383. void AlertWindow::addCustomComponent (Component* const component)
  61384. {
  61385. customComps.add (component);
  61386. allComps.add (component);
  61387. addAndMakeVisible (component);
  61388. updateLayout (false);
  61389. }
  61390. int AlertWindow::getNumCustomComponents() const
  61391. {
  61392. return customComps.size();
  61393. }
  61394. Component* AlertWindow::getCustomComponent (const int index) const
  61395. {
  61396. return (Component*) customComps [index];
  61397. }
  61398. Component* AlertWindow::removeCustomComponent (const int index)
  61399. {
  61400. Component* const c = getCustomComponent (index);
  61401. if (c != 0)
  61402. {
  61403. customComps.removeValue (c);
  61404. allComps.removeValue (c);
  61405. removeChildComponent (c);
  61406. updateLayout (false);
  61407. }
  61408. return c;
  61409. }
  61410. void AlertWindow::paint (Graphics& g)
  61411. {
  61412. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61413. g.setColour (findColour (textColourId));
  61414. g.setFont (getLookAndFeel().getAlertWindowFont());
  61415. int i;
  61416. for (i = textBoxes.size(); --i >= 0;)
  61417. {
  61418. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61419. g.drawFittedText (textboxNames[i],
  61420. te->getX(), te->getY() - 14,
  61421. te->getWidth(), 14,
  61422. Justification::centredLeft, 1);
  61423. }
  61424. for (i = comboBoxNames.size(); --i >= 0;)
  61425. {
  61426. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61427. g.drawFittedText (comboBoxNames[i],
  61428. cb->getX(), cb->getY() - 14,
  61429. cb->getWidth(), 14,
  61430. Justification::centredLeft, 1);
  61431. }
  61432. for (i = customComps.size(); --i >= 0;)
  61433. {
  61434. const Component* const c = (Component*) customComps[i];
  61435. g.drawFittedText (c->getName(),
  61436. c->getX(), c->getY() - 14,
  61437. c->getWidth(), 14,
  61438. Justification::centredLeft, 1);
  61439. }
  61440. }
  61441. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61442. {
  61443. const int titleH = 24;
  61444. const int iconWidth = 80;
  61445. const int wid = jmax (font.getStringWidth (text),
  61446. font.getStringWidth (getName()));
  61447. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61448. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61449. const int edgeGap = 10;
  61450. const int labelHeight = 18;
  61451. int iconSpace;
  61452. if (alertIconType == NoIcon)
  61453. {
  61454. textLayout.layout (w, Justification::horizontallyCentred, true);
  61455. iconSpace = 0;
  61456. }
  61457. else
  61458. {
  61459. textLayout.layout (w, Justification::left, true);
  61460. iconSpace = iconWidth;
  61461. }
  61462. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61463. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61464. const int textLayoutH = textLayout.getHeight();
  61465. const int textBottom = 16 + titleH + textLayoutH;
  61466. int h = textBottom;
  61467. int buttonW = 40;
  61468. int i;
  61469. for (i = 0; i < buttons.size(); ++i)
  61470. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61471. w = jmax (buttonW, w);
  61472. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61473. if (buttons.size() > 0)
  61474. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61475. for (i = customComps.size(); --i >= 0;)
  61476. {
  61477. Component* c = (Component*) customComps[i];
  61478. w = jmax (w, (c->getWidth() * 100) / 80);
  61479. h += 10 + c->getHeight();
  61480. if (c->getName().isNotEmpty())
  61481. h += labelHeight;
  61482. }
  61483. for (i = textBlocks.size(); --i >= 0;)
  61484. {
  61485. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61486. w = jmax (w, ac->getPreferredWidth());
  61487. }
  61488. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61489. for (i = textBlocks.size(); --i >= 0;)
  61490. {
  61491. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61492. ac->updateLayout ((int) (w * 0.8f));
  61493. h += ac->getHeight() + 10;
  61494. }
  61495. h = jmin (getParentHeight() - 50, h);
  61496. if (onlyIncreaseSize)
  61497. {
  61498. w = jmax (w, getWidth());
  61499. h = jmax (h, getHeight());
  61500. }
  61501. if (! isVisible())
  61502. {
  61503. centreAroundComponent (associatedComponent, w, h);
  61504. }
  61505. else
  61506. {
  61507. const int cx = getX() + getWidth() / 2;
  61508. const int cy = getY() + getHeight() / 2;
  61509. setBounds (cx - w / 2,
  61510. cy - h / 2,
  61511. w, h);
  61512. }
  61513. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61514. const int spacer = 16;
  61515. int totalWidth = -spacer;
  61516. for (i = buttons.size(); --i >= 0;)
  61517. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61518. int x = (w - totalWidth) / 2;
  61519. int y = (int) (getHeight() * 0.95f);
  61520. for (i = 0; i < buttons.size(); ++i)
  61521. {
  61522. TextButton* const c = (TextButton*) buttons[i];
  61523. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61524. c->setTopLeftPosition (x, ny);
  61525. if (ny < y)
  61526. y = ny;
  61527. x += c->getWidth() + spacer;
  61528. c->toFront (false);
  61529. }
  61530. y = textBottom;
  61531. for (i = 0; i < allComps.size(); ++i)
  61532. {
  61533. Component* const c = (Component*) allComps[i];
  61534. h = 22;
  61535. const int comboIndex = comboBoxes.indexOf (c);
  61536. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61537. y += labelHeight;
  61538. const int tbIndex = textBoxes.indexOf (c);
  61539. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61540. y += labelHeight;
  61541. if (customComps.contains (c))
  61542. {
  61543. if (c->getName().isNotEmpty())
  61544. y += labelHeight;
  61545. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61546. h = c->getHeight();
  61547. }
  61548. else if (textBlocks.contains (c))
  61549. {
  61550. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61551. h = c->getHeight();
  61552. }
  61553. else
  61554. {
  61555. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61556. }
  61557. y += h + 10;
  61558. }
  61559. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61560. }
  61561. bool AlertWindow::containsAnyExtraComponents() const
  61562. {
  61563. return textBoxes.size()
  61564. + comboBoxes.size()
  61565. + progressBars.size()
  61566. + customComps.size() > 0;
  61567. }
  61568. void AlertWindow::mouseDown (const MouseEvent&)
  61569. {
  61570. dragger.startDraggingComponent (this, &constrainer);
  61571. }
  61572. void AlertWindow::mouseDrag (const MouseEvent& e)
  61573. {
  61574. dragger.dragComponent (this, e);
  61575. }
  61576. bool AlertWindow::keyPressed (const KeyPress& key)
  61577. {
  61578. for (int i = buttons.size(); --i >= 0;)
  61579. {
  61580. TextButton* const b = (TextButton*) buttons[i];
  61581. if (b->isRegisteredForShortcut (key))
  61582. {
  61583. b->triggerClick();
  61584. return true;
  61585. }
  61586. }
  61587. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61588. {
  61589. exitModalState (0);
  61590. return true;
  61591. }
  61592. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61593. {
  61594. ((TextButton*) buttons.getFirst())->triggerClick();
  61595. return true;
  61596. }
  61597. return false;
  61598. }
  61599. void AlertWindow::lookAndFeelChanged()
  61600. {
  61601. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61602. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61603. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61604. }
  61605. int AlertWindow::getDesktopWindowStyleFlags() const
  61606. {
  61607. return getLookAndFeel().getAlertBoxWindowFlags();
  61608. }
  61609. struct AlertWindowInfo
  61610. {
  61611. String title, message, button1, button2, button3;
  61612. AlertWindow::AlertIconType iconType;
  61613. int numButtons;
  61614. Component::SafePointer<Component> associatedComponent;
  61615. int run() const
  61616. {
  61617. return (int) (pointer_sized_int)
  61618. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61619. }
  61620. private:
  61621. int show() const
  61622. {
  61623. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61624. : LookAndFeel::getDefaultLookAndFeel();
  61625. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61626. iconType, numButtons, associatedComponent));
  61627. jassert (alertBox != 0); // you have to return one of these!
  61628. return alertBox->runModalLoop();
  61629. }
  61630. static void* showCallback (void* userData)
  61631. {
  61632. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61633. }
  61634. };
  61635. void AlertWindow::showMessageBox (AlertIconType iconType,
  61636. const String& title,
  61637. const String& message,
  61638. const String& buttonText,
  61639. Component* associatedComponent)
  61640. {
  61641. AlertWindowInfo info;
  61642. info.title = title;
  61643. info.message = message;
  61644. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61645. info.iconType = iconType;
  61646. info.numButtons = 1;
  61647. info.associatedComponent = associatedComponent;
  61648. info.run();
  61649. }
  61650. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61651. const String& title,
  61652. const String& message,
  61653. const String& button1Text,
  61654. const String& button2Text,
  61655. Component* associatedComponent)
  61656. {
  61657. AlertWindowInfo info;
  61658. info.title = title;
  61659. info.message = message;
  61660. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61661. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61662. info.iconType = iconType;
  61663. info.numButtons = 2;
  61664. info.associatedComponent = associatedComponent;
  61665. return info.run() != 0;
  61666. }
  61667. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61668. const String& title,
  61669. const String& message,
  61670. const String& button1Text,
  61671. const String& button2Text,
  61672. const String& button3Text,
  61673. Component* associatedComponent)
  61674. {
  61675. AlertWindowInfo info;
  61676. info.title = title;
  61677. info.message = message;
  61678. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61679. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61680. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61681. info.iconType = iconType;
  61682. info.numButtons = 3;
  61683. info.associatedComponent = associatedComponent;
  61684. return info.run();
  61685. }
  61686. END_JUCE_NAMESPACE
  61687. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61688. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61689. BEGIN_JUCE_NAMESPACE
  61690. CallOutBox::CallOutBox (Component& contentComponent,
  61691. Component& componentToPointTo,
  61692. Component* const parentComponent)
  61693. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61694. {
  61695. addAndMakeVisible (&content);
  61696. if (parentComponent != 0)
  61697. {
  61698. updatePosition (parentComponent->getLocalBounds(),
  61699. componentToPointTo.getLocalBounds()
  61700. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61701. parentComponent->addAndMakeVisible (this);
  61702. }
  61703. else
  61704. {
  61705. updatePosition (componentToPointTo.getScreenBounds(),
  61706. componentToPointTo.getParentMonitorArea());
  61707. addToDesktop (ComponentPeer::windowIsTemporary);
  61708. }
  61709. }
  61710. CallOutBox::~CallOutBox()
  61711. {
  61712. }
  61713. void CallOutBox::setArrowSize (const float newSize)
  61714. {
  61715. arrowSize = newSize;
  61716. borderSpace = jmax (20, (int) arrowSize);
  61717. refreshPath();
  61718. }
  61719. void CallOutBox::paint (Graphics& g)
  61720. {
  61721. if (background.isNull())
  61722. {
  61723. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61724. Graphics g (background);
  61725. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61726. }
  61727. g.setColour (Colours::black);
  61728. g.drawImageAt (background, 0, 0);
  61729. }
  61730. void CallOutBox::resized()
  61731. {
  61732. content.setTopLeftPosition (borderSpace, borderSpace);
  61733. refreshPath();
  61734. }
  61735. void CallOutBox::moved()
  61736. {
  61737. refreshPath();
  61738. }
  61739. void CallOutBox::childBoundsChanged (Component*)
  61740. {
  61741. updatePosition (targetArea, availableArea);
  61742. }
  61743. bool CallOutBox::hitTest (int x, int y)
  61744. {
  61745. return outline.contains ((float) x, (float) y);
  61746. }
  61747. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61748. void CallOutBox::inputAttemptWhenModal()
  61749. {
  61750. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61751. if (targetArea.contains (mousePos))
  61752. {
  61753. // if you click on the area that originally popped-up the callout, you expect it
  61754. // to get rid of the box, but deleting the box here allows the click to pass through and
  61755. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61756. postCommandMessage (callOutBoxDismissCommandId);
  61757. }
  61758. else
  61759. {
  61760. exitModalState (0);
  61761. setVisible (false);
  61762. }
  61763. }
  61764. void CallOutBox::handleCommandMessage (int commandId)
  61765. {
  61766. Component::handleCommandMessage (commandId);
  61767. if (commandId == callOutBoxDismissCommandId)
  61768. {
  61769. exitModalState (0);
  61770. setVisible (false);
  61771. }
  61772. }
  61773. bool CallOutBox::keyPressed (const KeyPress& key)
  61774. {
  61775. if (key.isKeyCode (KeyPress::escapeKey))
  61776. {
  61777. inputAttemptWhenModal();
  61778. return true;
  61779. }
  61780. return false;
  61781. }
  61782. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61783. {
  61784. targetArea = newAreaToPointTo;
  61785. availableArea = newAreaToFitIn;
  61786. Rectangle<int> bounds (0, 0,
  61787. content.getWidth() + borderSpace * 2,
  61788. content.getHeight() + borderSpace * 2);
  61789. const int hw = bounds.getWidth() / 2;
  61790. const int hh = bounds.getHeight() / 2;
  61791. const float hwReduced = (float) (hw - borderSpace * 3);
  61792. const float hhReduced = (float) (hh - borderSpace * 3);
  61793. const float arrowIndent = borderSpace - arrowSize;
  61794. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61795. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61796. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61797. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61798. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61799. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61800. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61801. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61802. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61803. float nearest = 1.0e9f;
  61804. for (int i = 0; i < 4; ++i)
  61805. {
  61806. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61807. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61808. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61809. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61810. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61811. distanceFromCentre *= 2.0f;
  61812. if (distanceFromCentre < nearest)
  61813. {
  61814. nearest = distanceFromCentre;
  61815. targetPoint = targets[i];
  61816. bounds.setPosition ((int) (centre.getX() - hw),
  61817. (int) (centre.getY() - hh));
  61818. }
  61819. }
  61820. setBounds (bounds);
  61821. }
  61822. void CallOutBox::refreshPath()
  61823. {
  61824. repaint();
  61825. background = Image();
  61826. outline.clear();
  61827. const float gap = 4.5f;
  61828. const float cornerSize = 9.0f;
  61829. const float cornerSize2 = 2.0f * cornerSize;
  61830. const float arrowBaseWidth = arrowSize * 0.7f;
  61831. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61832. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61833. outline.startNewSubPath (left + cornerSize, top);
  61834. if (targetY <= top)
  61835. {
  61836. outline.lineTo (targetX - arrowBaseWidth, top);
  61837. outline.lineTo (targetX, targetY);
  61838. outline.lineTo (targetX + arrowBaseWidth, top);
  61839. }
  61840. outline.lineTo (right - cornerSize, top);
  61841. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61842. if (targetX >= right)
  61843. {
  61844. outline.lineTo (right, targetY - arrowBaseWidth);
  61845. outline.lineTo (targetX, targetY);
  61846. outline.lineTo (right, targetY + arrowBaseWidth);
  61847. }
  61848. outline.lineTo (right, bottom - cornerSize);
  61849. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61850. if (targetY >= bottom)
  61851. {
  61852. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61853. outline.lineTo (targetX, targetY);
  61854. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61855. }
  61856. outline.lineTo (left + cornerSize, bottom);
  61857. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61858. if (targetX <= left)
  61859. {
  61860. outline.lineTo (left, targetY + arrowBaseWidth);
  61861. outline.lineTo (targetX, targetY);
  61862. outline.lineTo (left, targetY - arrowBaseWidth);
  61863. }
  61864. outline.lineTo (left, top + cornerSize);
  61865. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61866. outline.closeSubPath();
  61867. }
  61868. END_JUCE_NAMESPACE
  61869. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61870. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61871. BEGIN_JUCE_NAMESPACE
  61872. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61873. static Array <ComponentPeer*> heavyweightPeers;
  61874. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61875. : component (component_),
  61876. styleFlags (styleFlags_),
  61877. lastPaintTime (0),
  61878. constrainer (0),
  61879. lastDragAndDropCompUnderMouse (0),
  61880. fakeMouseMessageSent (false),
  61881. isWindowMinimised (false)
  61882. {
  61883. heavyweightPeers.add (this);
  61884. }
  61885. ComponentPeer::~ComponentPeer()
  61886. {
  61887. heavyweightPeers.removeValue (this);
  61888. Desktop::getInstance().triggerFocusCallback();
  61889. }
  61890. int ComponentPeer::getNumPeers() throw()
  61891. {
  61892. return heavyweightPeers.size();
  61893. }
  61894. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61895. {
  61896. return heavyweightPeers [index];
  61897. }
  61898. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61899. {
  61900. for (int i = heavyweightPeers.size(); --i >= 0;)
  61901. {
  61902. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61903. if (peer->getComponent() == component)
  61904. return peer;
  61905. }
  61906. return 0;
  61907. }
  61908. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61909. {
  61910. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61911. }
  61912. void ComponentPeer::updateCurrentModifiers() throw()
  61913. {
  61914. ModifierKeys::updateCurrentModifiers();
  61915. }
  61916. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61917. {
  61918. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61919. jassert (mouse != 0); // not enough sources!
  61920. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61921. }
  61922. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61923. {
  61924. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61925. jassert (mouse != 0); // not enough sources!
  61926. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61927. }
  61928. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61929. {
  61930. Graphics g (&contextToPaintTo);
  61931. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61932. g.saveState();
  61933. #endif
  61934. JUCE_TRY
  61935. {
  61936. component->paintEntireComponent (g);
  61937. }
  61938. JUCE_CATCH_EXCEPTION
  61939. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61940. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61941. // clearly when things are being repainted.
  61942. {
  61943. g.restoreState();
  61944. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61945. (uint8) Random::getSystemRandom().nextInt (255),
  61946. (uint8) Random::getSystemRandom().nextInt (255),
  61947. (uint8) 0x50));
  61948. }
  61949. #endif
  61950. }
  61951. bool ComponentPeer::handleKeyPress (const int keyCode,
  61952. const juce_wchar textCharacter)
  61953. {
  61954. updateCurrentModifiers();
  61955. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61956. ? Component::getCurrentlyFocusedComponent()
  61957. : component;
  61958. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61959. {
  61960. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61961. if (currentModalComp != 0)
  61962. target = currentModalComp;
  61963. }
  61964. const KeyPress keyInfo (keyCode,
  61965. ModifierKeys::getCurrentModifiers().getRawFlags()
  61966. & ModifierKeys::allKeyboardModifiers,
  61967. textCharacter);
  61968. bool keyWasUsed = false;
  61969. while (target != 0)
  61970. {
  61971. const Component::SafePointer<Component> deletionChecker (target);
  61972. if (target->keyListeners_ != 0)
  61973. {
  61974. for (int i = target->keyListeners_->size(); --i >= 0;)
  61975. {
  61976. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61977. if (keyWasUsed || deletionChecker == 0)
  61978. return keyWasUsed;
  61979. i = jmin (i, target->keyListeners_->size());
  61980. }
  61981. }
  61982. keyWasUsed = target->keyPressed (keyInfo);
  61983. if (keyWasUsed || deletionChecker == 0)
  61984. break;
  61985. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61986. {
  61987. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61988. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61989. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61990. break;
  61991. }
  61992. target = target->parentComponent_;
  61993. }
  61994. return keyWasUsed;
  61995. }
  61996. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61997. {
  61998. updateCurrentModifiers();
  61999. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62000. ? Component::getCurrentlyFocusedComponent()
  62001. : component;
  62002. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62003. {
  62004. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62005. if (currentModalComp != 0)
  62006. target = currentModalComp;
  62007. }
  62008. bool keyWasUsed = false;
  62009. while (target != 0)
  62010. {
  62011. const Component::SafePointer<Component> deletionChecker (target);
  62012. keyWasUsed = target->keyStateChanged (isKeyDown);
  62013. if (keyWasUsed || deletionChecker == 0)
  62014. break;
  62015. if (target->keyListeners_ != 0)
  62016. {
  62017. for (int i = target->keyListeners_->size(); --i >= 0;)
  62018. {
  62019. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62020. if (keyWasUsed || deletionChecker == 0)
  62021. return keyWasUsed;
  62022. i = jmin (i, target->keyListeners_->size());
  62023. }
  62024. }
  62025. target = target->parentComponent_;
  62026. }
  62027. return keyWasUsed;
  62028. }
  62029. void ComponentPeer::handleModifierKeysChange()
  62030. {
  62031. updateCurrentModifiers();
  62032. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62033. if (target == 0)
  62034. target = Component::getCurrentlyFocusedComponent();
  62035. if (target == 0)
  62036. target = component;
  62037. if (target != 0)
  62038. target->internalModifierKeysChanged();
  62039. }
  62040. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62041. {
  62042. Component* const c = Component::getCurrentlyFocusedComponent();
  62043. if (component->isParentOf (c))
  62044. {
  62045. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62046. if (ti != 0 && ti->isTextInputActive())
  62047. return ti;
  62048. }
  62049. return 0;
  62050. }
  62051. void ComponentPeer::handleBroughtToFront()
  62052. {
  62053. updateCurrentModifiers();
  62054. if (component != 0)
  62055. component->internalBroughtToFront();
  62056. }
  62057. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62058. {
  62059. constrainer = newConstrainer;
  62060. }
  62061. void ComponentPeer::handleMovedOrResized()
  62062. {
  62063. jassert (component->isValidComponent());
  62064. updateCurrentModifiers();
  62065. const bool nowMinimised = isMinimised();
  62066. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62067. {
  62068. const Component::SafePointer<Component> deletionChecker (component);
  62069. const Rectangle<int> newBounds (getBounds());
  62070. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62071. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62072. if (wasMoved || wasResized)
  62073. {
  62074. component->bounds_ = newBounds;
  62075. if (wasResized)
  62076. component->repaint();
  62077. component->sendMovedResizedMessages (wasMoved, wasResized);
  62078. if (deletionChecker == 0)
  62079. return;
  62080. }
  62081. }
  62082. if (isWindowMinimised != nowMinimised)
  62083. {
  62084. isWindowMinimised = nowMinimised;
  62085. component->minimisationStateChanged (nowMinimised);
  62086. component->sendVisibilityChangeMessage();
  62087. }
  62088. if (! isFullScreen())
  62089. lastNonFullscreenBounds = component->getBounds();
  62090. }
  62091. void ComponentPeer::handleFocusGain()
  62092. {
  62093. updateCurrentModifiers();
  62094. if (component->isParentOf (lastFocusedComponent))
  62095. {
  62096. Component::currentlyFocusedComponent = lastFocusedComponent;
  62097. Desktop::getInstance().triggerFocusCallback();
  62098. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62099. }
  62100. else
  62101. {
  62102. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62103. component->grabKeyboardFocus();
  62104. else
  62105. Component::bringModalComponentToFront();
  62106. }
  62107. }
  62108. void ComponentPeer::handleFocusLoss()
  62109. {
  62110. updateCurrentModifiers();
  62111. if (component->hasKeyboardFocus (true))
  62112. {
  62113. lastFocusedComponent = Component::currentlyFocusedComponent;
  62114. if (lastFocusedComponent != 0)
  62115. {
  62116. Component::currentlyFocusedComponent = 0;
  62117. Desktop::getInstance().triggerFocusCallback();
  62118. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62119. }
  62120. }
  62121. }
  62122. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62123. {
  62124. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62125. ? static_cast <Component*> (lastFocusedComponent)
  62126. : component;
  62127. }
  62128. void ComponentPeer::handleScreenSizeChange()
  62129. {
  62130. updateCurrentModifiers();
  62131. component->parentSizeChanged();
  62132. handleMovedOrResized();
  62133. }
  62134. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62135. {
  62136. lastNonFullscreenBounds = newBounds;
  62137. }
  62138. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62139. {
  62140. return lastNonFullscreenBounds;
  62141. }
  62142. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62143. const StringArray& files,
  62144. FileDragAndDropTarget* const lastOne)
  62145. {
  62146. while (c != 0)
  62147. {
  62148. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62149. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62150. return t;
  62151. c = c->getParentComponent();
  62152. }
  62153. return 0;
  62154. }
  62155. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62156. {
  62157. updateCurrentModifiers();
  62158. FileDragAndDropTarget* lastTarget
  62159. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62160. FileDragAndDropTarget* newTarget = 0;
  62161. Component* const compUnderMouse = component->getComponentAt (position);
  62162. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62163. {
  62164. lastDragAndDropCompUnderMouse = compUnderMouse;
  62165. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62166. if (newTarget != lastTarget)
  62167. {
  62168. if (lastTarget != 0)
  62169. lastTarget->fileDragExit (files);
  62170. dragAndDropTargetComponent = 0;
  62171. if (newTarget != 0)
  62172. {
  62173. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62174. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62175. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62176. }
  62177. }
  62178. }
  62179. else
  62180. {
  62181. newTarget = lastTarget;
  62182. }
  62183. if (newTarget != 0)
  62184. {
  62185. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62186. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62187. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62188. }
  62189. }
  62190. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62191. {
  62192. handleFileDragMove (files, Point<int> (-1, -1));
  62193. jassert (dragAndDropTargetComponent == 0);
  62194. lastDragAndDropCompUnderMouse = 0;
  62195. }
  62196. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62197. {
  62198. handleFileDragMove (files, position);
  62199. if (dragAndDropTargetComponent != 0)
  62200. {
  62201. FileDragAndDropTarget* const target
  62202. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62203. dragAndDropTargetComponent = 0;
  62204. lastDragAndDropCompUnderMouse = 0;
  62205. if (target != 0)
  62206. {
  62207. Component* const targetComp = dynamic_cast <Component*> (target);
  62208. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62209. {
  62210. targetComp->internalModalInputAttempt();
  62211. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62212. return;
  62213. }
  62214. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62215. target->filesDropped (files, pos.getX(), pos.getY());
  62216. }
  62217. }
  62218. }
  62219. void ComponentPeer::handleUserClosingWindow()
  62220. {
  62221. updateCurrentModifiers();
  62222. component->userTriedToCloseWindow();
  62223. }
  62224. void ComponentPeer::bringModalComponentToFront()
  62225. {
  62226. Component::bringModalComponentToFront();
  62227. }
  62228. void ComponentPeer::clearMaskedRegion()
  62229. {
  62230. maskedRegion.clear();
  62231. }
  62232. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62233. {
  62234. maskedRegion.add (x, y, w, h);
  62235. }
  62236. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62237. {
  62238. StringArray s;
  62239. s.add ("Software Renderer");
  62240. return s;
  62241. }
  62242. int ComponentPeer::getCurrentRenderingEngine() throw()
  62243. {
  62244. return 0;
  62245. }
  62246. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62247. {
  62248. }
  62249. END_JUCE_NAMESPACE
  62250. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62251. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62252. BEGIN_JUCE_NAMESPACE
  62253. DialogWindow::DialogWindow (const String& name,
  62254. const Colour& backgroundColour_,
  62255. const bool escapeKeyTriggersCloseButton_,
  62256. const bool addToDesktop_)
  62257. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62258. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62259. {
  62260. }
  62261. DialogWindow::~DialogWindow()
  62262. {
  62263. }
  62264. void DialogWindow::resized()
  62265. {
  62266. DocumentWindow::resized();
  62267. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62268. if (escapeKeyTriggersCloseButton
  62269. && getCloseButton() != 0
  62270. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62271. {
  62272. getCloseButton()->addShortcut (esc);
  62273. }
  62274. }
  62275. class TempDialogWindow : public DialogWindow
  62276. {
  62277. public:
  62278. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62279. : DialogWindow (title, colour, escapeCloses, true)
  62280. {
  62281. if (JUCEApplication::getInstance() == 0)
  62282. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62283. }
  62284. ~TempDialogWindow()
  62285. {
  62286. }
  62287. void closeButtonPressed()
  62288. {
  62289. setVisible (false);
  62290. }
  62291. private:
  62292. TempDialogWindow (const TempDialogWindow&);
  62293. TempDialogWindow& operator= (const TempDialogWindow&);
  62294. };
  62295. int DialogWindow::showModalDialog (const String& dialogTitle,
  62296. Component* contentComponent,
  62297. Component* componentToCentreAround,
  62298. const Colour& colour,
  62299. const bool escapeKeyTriggersCloseButton,
  62300. const bool shouldBeResizable,
  62301. const bool useBottomRightCornerResizer)
  62302. {
  62303. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62304. dw.setContentComponent (contentComponent, true, true);
  62305. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62306. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62307. const int result = dw.runModalLoop();
  62308. dw.setContentComponent (0, false);
  62309. return result;
  62310. }
  62311. END_JUCE_NAMESPACE
  62312. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62313. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62314. BEGIN_JUCE_NAMESPACE
  62315. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  62316. {
  62317. public:
  62318. ButtonListenerProxy (DocumentWindow& owner_)
  62319. : owner (owner_)
  62320. {
  62321. }
  62322. void buttonClicked (Button* button)
  62323. {
  62324. if (button == owner.getMinimiseButton())
  62325. owner.minimiseButtonPressed();
  62326. else if (button == owner.getMaximiseButton())
  62327. owner.maximiseButtonPressed();
  62328. else if (button == owner.getCloseButton())
  62329. owner.closeButtonPressed();
  62330. }
  62331. juce_UseDebuggingNewOperator
  62332. private:
  62333. DocumentWindow& owner;
  62334. ButtonListenerProxy (const ButtonListenerProxy&);
  62335. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62336. };
  62337. DocumentWindow::DocumentWindow (const String& title,
  62338. const Colour& backgroundColour,
  62339. const int requiredButtons_,
  62340. const bool addToDesktop_)
  62341. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62342. titleBarHeight (26),
  62343. menuBarHeight (24),
  62344. requiredButtons (requiredButtons_),
  62345. #if JUCE_MAC
  62346. positionTitleBarButtonsOnLeft (true),
  62347. #else
  62348. positionTitleBarButtonsOnLeft (false),
  62349. #endif
  62350. drawTitleTextCentred (true),
  62351. menuBarModel (0)
  62352. {
  62353. setResizeLimits (128, 128, 32768, 32768);
  62354. lookAndFeelChanged();
  62355. }
  62356. DocumentWindow::~DocumentWindow()
  62357. {
  62358. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62359. titleBarButtons[i] = 0;
  62360. menuBar = 0;
  62361. }
  62362. void DocumentWindow::repaintTitleBar()
  62363. {
  62364. repaint (getTitleBarArea());
  62365. }
  62366. void DocumentWindow::setName (const String& newName)
  62367. {
  62368. if (newName != getName())
  62369. {
  62370. Component::setName (newName);
  62371. repaintTitleBar();
  62372. }
  62373. }
  62374. void DocumentWindow::setIcon (const Image& imageToUse)
  62375. {
  62376. titleBarIcon = imageToUse;
  62377. repaintTitleBar();
  62378. }
  62379. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62380. {
  62381. titleBarHeight = newHeight;
  62382. resized();
  62383. repaintTitleBar();
  62384. }
  62385. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62386. const bool positionTitleBarButtonsOnLeft_)
  62387. {
  62388. requiredButtons = requiredButtons_;
  62389. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62390. lookAndFeelChanged();
  62391. }
  62392. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62393. {
  62394. drawTitleTextCentred = textShouldBeCentred;
  62395. repaintTitleBar();
  62396. }
  62397. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62398. const int menuBarHeight_)
  62399. {
  62400. if (menuBarModel != menuBarModel_)
  62401. {
  62402. menuBar = 0;
  62403. menuBarModel = menuBarModel_;
  62404. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62405. : getLookAndFeel().getDefaultMenuBarHeight();
  62406. if (menuBarModel != 0)
  62407. {
  62408. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62409. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62410. menuBar->setEnabled (isActiveWindow());
  62411. }
  62412. resized();
  62413. }
  62414. }
  62415. void DocumentWindow::closeButtonPressed()
  62416. {
  62417. /* If you've got a close button, you have to override this method to get
  62418. rid of your window!
  62419. If the window is just a pop-up, you should override this method and make
  62420. it delete the window in whatever way is appropriate for your app. E.g. you
  62421. might just want to call "delete this".
  62422. If your app is centred around this window such that the whole app should quit when
  62423. the window is closed, then you will probably want to use this method as an opportunity
  62424. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62425. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62426. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62427. or closing it via the taskbar icon on Windows).
  62428. */
  62429. jassertfalse;
  62430. }
  62431. void DocumentWindow::minimiseButtonPressed()
  62432. {
  62433. setMinimised (true);
  62434. }
  62435. void DocumentWindow::maximiseButtonPressed()
  62436. {
  62437. setFullScreen (! isFullScreen());
  62438. }
  62439. void DocumentWindow::paint (Graphics& g)
  62440. {
  62441. ResizableWindow::paint (g);
  62442. if (resizableBorder == 0)
  62443. {
  62444. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62445. const BorderSize border (getBorderThickness());
  62446. g.fillRect (0, 0, getWidth(), border.getTop());
  62447. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62448. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62449. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62450. }
  62451. const Rectangle<int> titleBarArea (getTitleBarArea());
  62452. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62453. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62454. int titleSpaceX1 = 6;
  62455. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62456. for (int i = 0; i < 3; ++i)
  62457. {
  62458. if (titleBarButtons[i] != 0)
  62459. {
  62460. if (positionTitleBarButtonsOnLeft)
  62461. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62462. else
  62463. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62464. }
  62465. }
  62466. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62467. titleBarArea.getWidth(),
  62468. titleBarArea.getHeight(),
  62469. titleSpaceX1,
  62470. jmax (1, titleSpaceX2 - titleSpaceX1),
  62471. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62472. ! drawTitleTextCentred);
  62473. }
  62474. void DocumentWindow::resized()
  62475. {
  62476. ResizableWindow::resized();
  62477. if (titleBarButtons[1] != 0)
  62478. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62479. const Rectangle<int> titleBarArea (getTitleBarArea());
  62480. getLookAndFeel()
  62481. .positionDocumentWindowButtons (*this,
  62482. titleBarArea.getX(), titleBarArea.getY(),
  62483. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62484. titleBarButtons[0],
  62485. titleBarButtons[1],
  62486. titleBarButtons[2],
  62487. positionTitleBarButtonsOnLeft);
  62488. if (menuBar != 0)
  62489. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62490. titleBarArea.getWidth(), menuBarHeight);
  62491. }
  62492. const BorderSize DocumentWindow::getBorderThickness()
  62493. {
  62494. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62495. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62496. }
  62497. const BorderSize DocumentWindow::getContentComponentBorder()
  62498. {
  62499. BorderSize border (getBorderThickness());
  62500. border.setTop (border.getTop()
  62501. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62502. + (menuBar != 0 ? menuBarHeight : 0));
  62503. return border;
  62504. }
  62505. int DocumentWindow::getTitleBarHeight() const
  62506. {
  62507. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62508. }
  62509. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62510. {
  62511. const BorderSize border (getBorderThickness());
  62512. return Rectangle<int> (border.getLeft(), border.getTop(),
  62513. getWidth() - border.getLeftAndRight(),
  62514. getTitleBarHeight());
  62515. }
  62516. Button* DocumentWindow::getCloseButton() const throw()
  62517. {
  62518. return titleBarButtons[2];
  62519. }
  62520. Button* DocumentWindow::getMinimiseButton() const throw()
  62521. {
  62522. return titleBarButtons[0];
  62523. }
  62524. Button* DocumentWindow::getMaximiseButton() const throw()
  62525. {
  62526. return titleBarButtons[1];
  62527. }
  62528. int DocumentWindow::getDesktopWindowStyleFlags() const
  62529. {
  62530. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62531. if ((requiredButtons & minimiseButton) != 0)
  62532. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62533. if ((requiredButtons & maximiseButton) != 0)
  62534. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62535. if ((requiredButtons & closeButton) != 0)
  62536. styleFlags |= ComponentPeer::windowHasCloseButton;
  62537. return styleFlags;
  62538. }
  62539. void DocumentWindow::lookAndFeelChanged()
  62540. {
  62541. int i;
  62542. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62543. titleBarButtons[i] = 0;
  62544. if (! isUsingNativeTitleBar())
  62545. {
  62546. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62547. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62548. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62549. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62550. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62551. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62552. for (i = 0; i < 3; ++i)
  62553. {
  62554. if (titleBarButtons[i] != 0)
  62555. {
  62556. if (buttonListener == 0)
  62557. buttonListener = new ButtonListenerProxy (*this);
  62558. titleBarButtons[i]->addButtonListener (buttonListener);
  62559. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62560. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62561. Component::addAndMakeVisible (titleBarButtons[i]);
  62562. }
  62563. }
  62564. if (getCloseButton() != 0)
  62565. {
  62566. #if JUCE_MAC
  62567. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62568. #else
  62569. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62570. #endif
  62571. }
  62572. }
  62573. activeWindowStatusChanged();
  62574. ResizableWindow::lookAndFeelChanged();
  62575. }
  62576. void DocumentWindow::parentHierarchyChanged()
  62577. {
  62578. lookAndFeelChanged();
  62579. }
  62580. void DocumentWindow::activeWindowStatusChanged()
  62581. {
  62582. ResizableWindow::activeWindowStatusChanged();
  62583. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62584. if (titleBarButtons[i] != 0)
  62585. titleBarButtons[i]->setEnabled (isActiveWindow());
  62586. if (menuBar != 0)
  62587. menuBar->setEnabled (isActiveWindow());
  62588. }
  62589. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62590. {
  62591. if (getTitleBarArea().contains (e.x, e.y)
  62592. && getMaximiseButton() != 0)
  62593. {
  62594. getMaximiseButton()->triggerClick();
  62595. }
  62596. }
  62597. void DocumentWindow::userTriedToCloseWindow()
  62598. {
  62599. closeButtonPressed();
  62600. }
  62601. END_JUCE_NAMESPACE
  62602. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62603. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62604. BEGIN_JUCE_NAMESPACE
  62605. ResizableWindow::ResizableWindow (const String& name,
  62606. const bool addToDesktop_)
  62607. : TopLevelWindow (name, addToDesktop_),
  62608. resizeToFitContent (false),
  62609. fullscreen (false),
  62610. lastNonFullScreenPos (50, 50, 256, 256),
  62611. constrainer (0)
  62612. #if JUCE_DEBUG
  62613. , hasBeenResized (false)
  62614. #endif
  62615. {
  62616. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62617. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62618. if (addToDesktop_)
  62619. Component::addToDesktop (getDesktopWindowStyleFlags());
  62620. }
  62621. ResizableWindow::ResizableWindow (const String& name,
  62622. const Colour& backgroundColour_,
  62623. const bool addToDesktop_)
  62624. : TopLevelWindow (name, addToDesktop_),
  62625. resizeToFitContent (false),
  62626. fullscreen (false),
  62627. lastNonFullScreenPos (50, 50, 256, 256),
  62628. constrainer (0)
  62629. #if JUCE_DEBUG
  62630. , hasBeenResized (false)
  62631. #endif
  62632. {
  62633. setBackgroundColour (backgroundColour_);
  62634. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62635. if (addToDesktop_)
  62636. Component::addToDesktop (getDesktopWindowStyleFlags());
  62637. }
  62638. ResizableWindow::~ResizableWindow()
  62639. {
  62640. resizableCorner = 0;
  62641. resizableBorder = 0;
  62642. delete static_cast <Component*> (contentComponent);
  62643. contentComponent = 0;
  62644. // have you been adding your own components directly to this window..? tut tut tut.
  62645. // Read the instructions for using a ResizableWindow!
  62646. jassert (getNumChildComponents() == 0);
  62647. }
  62648. int ResizableWindow::getDesktopWindowStyleFlags() const
  62649. {
  62650. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62651. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62652. styleFlags |= ComponentPeer::windowIsResizable;
  62653. return styleFlags;
  62654. }
  62655. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62656. const bool deleteOldOne,
  62657. const bool resizeToFit)
  62658. {
  62659. resizeToFitContent = resizeToFit;
  62660. if (newContentComponent != static_cast <Component*> (contentComponent))
  62661. {
  62662. if (deleteOldOne)
  62663. delete static_cast <Component*> (contentComponent); // (avoid using a scoped pointer for this, so that it survives
  62664. // external deletion of the content comp)
  62665. else
  62666. removeChildComponent (contentComponent);
  62667. contentComponent = newContentComponent;
  62668. Component::addAndMakeVisible (contentComponent);
  62669. }
  62670. if (resizeToFit)
  62671. childBoundsChanged (contentComponent);
  62672. resized(); // must always be called to position the new content comp
  62673. }
  62674. void ResizableWindow::setContentComponentSize (int width, int height)
  62675. {
  62676. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62677. const BorderSize border (getContentComponentBorder());
  62678. setSize (width + border.getLeftAndRight(),
  62679. height + border.getTopAndBottom());
  62680. }
  62681. const BorderSize ResizableWindow::getBorderThickness()
  62682. {
  62683. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62684. }
  62685. const BorderSize ResizableWindow::getContentComponentBorder()
  62686. {
  62687. return getBorderThickness();
  62688. }
  62689. void ResizableWindow::moved()
  62690. {
  62691. updateLastPos();
  62692. }
  62693. void ResizableWindow::visibilityChanged()
  62694. {
  62695. TopLevelWindow::visibilityChanged();
  62696. updateLastPos();
  62697. }
  62698. void ResizableWindow::resized()
  62699. {
  62700. if (resizableBorder != 0)
  62701. {
  62702. resizableBorder->setVisible (! isFullScreen());
  62703. resizableBorder->setBorderThickness (getBorderThickness());
  62704. resizableBorder->setSize (getWidth(), getHeight());
  62705. resizableBorder->toBack();
  62706. }
  62707. if (resizableCorner != 0)
  62708. {
  62709. resizableCorner->setVisible (! isFullScreen());
  62710. const int resizerSize = 18;
  62711. resizableCorner->setBounds (getWidth() - resizerSize,
  62712. getHeight() - resizerSize,
  62713. resizerSize, resizerSize);
  62714. }
  62715. if (contentComponent != 0)
  62716. contentComponent->setBoundsInset (getContentComponentBorder());
  62717. updateLastPos();
  62718. #if JUCE_DEBUG
  62719. hasBeenResized = true;
  62720. #endif
  62721. }
  62722. void ResizableWindow::childBoundsChanged (Component* child)
  62723. {
  62724. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62725. {
  62726. // not going to look very good if this component has a zero size..
  62727. jassert (child->getWidth() > 0);
  62728. jassert (child->getHeight() > 0);
  62729. const BorderSize borders (getContentComponentBorder());
  62730. setSize (child->getWidth() + borders.getLeftAndRight(),
  62731. child->getHeight() + borders.getTopAndBottom());
  62732. }
  62733. }
  62734. void ResizableWindow::activeWindowStatusChanged()
  62735. {
  62736. const BorderSize border (getContentComponentBorder());
  62737. Rectangle<int> area (getLocalBounds());
  62738. repaint (area.removeFromTop (border.getTop()));
  62739. repaint (area.removeFromLeft (border.getLeft()));
  62740. repaint (area.removeFromRight (border.getRight()));
  62741. repaint (area.removeFromBottom (border.getBottom()));
  62742. }
  62743. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62744. const bool useBottomRightCornerResizer)
  62745. {
  62746. if (shouldBeResizable)
  62747. {
  62748. if (useBottomRightCornerResizer)
  62749. {
  62750. resizableBorder = 0;
  62751. if (resizableCorner == 0)
  62752. {
  62753. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62754. resizableCorner->setAlwaysOnTop (true);
  62755. }
  62756. }
  62757. else
  62758. {
  62759. resizableCorner = 0;
  62760. if (resizableBorder == 0)
  62761. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62762. }
  62763. }
  62764. else
  62765. {
  62766. resizableCorner = 0;
  62767. resizableBorder = 0;
  62768. }
  62769. if (isUsingNativeTitleBar())
  62770. recreateDesktopWindow();
  62771. childBoundsChanged (contentComponent);
  62772. resized();
  62773. }
  62774. bool ResizableWindow::isResizable() const throw()
  62775. {
  62776. return resizableCorner != 0
  62777. || resizableBorder != 0;
  62778. }
  62779. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62780. const int newMinimumHeight,
  62781. const int newMaximumWidth,
  62782. const int newMaximumHeight) throw()
  62783. {
  62784. // if you've set up a custom constrainer then these settings won't have any effect..
  62785. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62786. if (constrainer == 0)
  62787. setConstrainer (&defaultConstrainer);
  62788. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62789. newMaximumWidth, newMaximumHeight);
  62790. setBoundsConstrained (getBounds());
  62791. }
  62792. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62793. {
  62794. if (constrainer != newConstrainer)
  62795. {
  62796. constrainer = newConstrainer;
  62797. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62798. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62799. resizableCorner = 0;
  62800. resizableBorder = 0;
  62801. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62802. ComponentPeer* const peer = getPeer();
  62803. if (peer != 0)
  62804. peer->setConstrainer (newConstrainer);
  62805. }
  62806. }
  62807. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62808. {
  62809. if (constrainer != 0)
  62810. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62811. else
  62812. setBounds (bounds);
  62813. }
  62814. void ResizableWindow::paint (Graphics& g)
  62815. {
  62816. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62817. getBorderThickness(), *this);
  62818. if (! isFullScreen())
  62819. {
  62820. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62821. getBorderThickness(), *this);
  62822. }
  62823. #if JUCE_DEBUG
  62824. /* If this fails, then you've probably written a subclass with a resized()
  62825. callback but forgotten to make it call its parent class's resized() method.
  62826. It's important when you override methods like resized(), moved(),
  62827. etc., that you make sure the base class methods also get called.
  62828. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62829. because your content should all be inside the content component - and it's the
  62830. content component's resized() method that you should be using to do your
  62831. layout.
  62832. */
  62833. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62834. #endif
  62835. }
  62836. void ResizableWindow::lookAndFeelChanged()
  62837. {
  62838. resized();
  62839. if (isOnDesktop())
  62840. {
  62841. Component::addToDesktop (getDesktopWindowStyleFlags());
  62842. ComponentPeer* const peer = getPeer();
  62843. if (peer != 0)
  62844. peer->setConstrainer (constrainer);
  62845. }
  62846. }
  62847. const Colour ResizableWindow::getBackgroundColour() const throw()
  62848. {
  62849. return findColour (backgroundColourId, false);
  62850. }
  62851. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62852. {
  62853. Colour backgroundColour (newColour);
  62854. if (! Desktop::canUseSemiTransparentWindows())
  62855. backgroundColour = newColour.withAlpha (1.0f);
  62856. setColour (backgroundColourId, backgroundColour);
  62857. setOpaque (backgroundColour.isOpaque());
  62858. repaint();
  62859. }
  62860. bool ResizableWindow::isFullScreen() const
  62861. {
  62862. if (isOnDesktop())
  62863. {
  62864. ComponentPeer* const peer = getPeer();
  62865. return peer != 0 && peer->isFullScreen();
  62866. }
  62867. return fullscreen;
  62868. }
  62869. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62870. {
  62871. if (shouldBeFullScreen != isFullScreen())
  62872. {
  62873. updateLastPos();
  62874. fullscreen = shouldBeFullScreen;
  62875. if (isOnDesktop())
  62876. {
  62877. ComponentPeer* const peer = getPeer();
  62878. if (peer != 0)
  62879. {
  62880. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62881. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62882. peer->setFullScreen (shouldBeFullScreen);
  62883. if (! shouldBeFullScreen)
  62884. setBounds (lastPos);
  62885. }
  62886. else
  62887. {
  62888. jassertfalse;
  62889. }
  62890. }
  62891. else
  62892. {
  62893. if (shouldBeFullScreen)
  62894. setBounds (0, 0, getParentWidth(), getParentHeight());
  62895. else
  62896. setBounds (lastNonFullScreenPos);
  62897. }
  62898. resized();
  62899. }
  62900. }
  62901. bool ResizableWindow::isMinimised() const
  62902. {
  62903. ComponentPeer* const peer = getPeer();
  62904. return (peer != 0) && peer->isMinimised();
  62905. }
  62906. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62907. {
  62908. if (shouldMinimise != isMinimised())
  62909. {
  62910. ComponentPeer* const peer = getPeer();
  62911. if (peer != 0)
  62912. {
  62913. updateLastPos();
  62914. peer->setMinimised (shouldMinimise);
  62915. }
  62916. else
  62917. {
  62918. jassertfalse;
  62919. }
  62920. }
  62921. }
  62922. void ResizableWindow::updateLastPos()
  62923. {
  62924. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62925. {
  62926. lastNonFullScreenPos = getBounds();
  62927. }
  62928. }
  62929. void ResizableWindow::parentSizeChanged()
  62930. {
  62931. if (isFullScreen() && getParentComponent() != 0)
  62932. {
  62933. setBounds (0, 0, getParentWidth(), getParentHeight());
  62934. }
  62935. }
  62936. const String ResizableWindow::getWindowStateAsString()
  62937. {
  62938. updateLastPos();
  62939. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62940. }
  62941. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62942. {
  62943. StringArray tokens;
  62944. tokens.addTokens (s, false);
  62945. tokens.removeEmptyStrings();
  62946. tokens.trim();
  62947. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62948. const int firstCoord = fs ? 1 : 0;
  62949. if (tokens.size() != firstCoord + 4)
  62950. return false;
  62951. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62952. tokens[firstCoord + 1].getIntValue(),
  62953. tokens[firstCoord + 2].getIntValue(),
  62954. tokens[firstCoord + 3].getIntValue());
  62955. if (newPos.isEmpty())
  62956. return false;
  62957. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62958. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62959. if (peer != 0)
  62960. peer->getFrameSize().addTo (newPos);
  62961. if (! screen.contains (newPos))
  62962. {
  62963. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62964. jmin (newPos.getHeight(), screen.getHeight()));
  62965. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62966. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62967. }
  62968. if (peer != 0)
  62969. {
  62970. peer->getFrameSize().subtractFrom (newPos);
  62971. peer->setNonFullScreenBounds (newPos);
  62972. }
  62973. lastNonFullScreenPos = newPos;
  62974. setFullScreen (fs);
  62975. if (! fs)
  62976. setBoundsConstrained (newPos);
  62977. return true;
  62978. }
  62979. void ResizableWindow::mouseDown (const MouseEvent&)
  62980. {
  62981. if (! isFullScreen())
  62982. dragger.startDraggingComponent (this, constrainer);
  62983. }
  62984. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62985. {
  62986. if (! isFullScreen())
  62987. dragger.dragComponent (this, e);
  62988. }
  62989. #if JUCE_DEBUG
  62990. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62991. {
  62992. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62993. manages its child components automatically, and if you add your own it'll cause
  62994. trouble. Instead, use setContentComponent() to give it a component which
  62995. will be automatically resized and kept in the right place - then you can add
  62996. subcomponents to the content comp. See the notes for the ResizableWindow class
  62997. for more info.
  62998. If you really know what you're doing and want to avoid this assertion, just call
  62999. Component::addChildComponent directly.
  63000. */
  63001. jassertfalse;
  63002. Component::addChildComponent (child, zOrder);
  63003. }
  63004. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63005. {
  63006. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63007. manages its child components automatically, and if you add your own it'll cause
  63008. trouble. Instead, use setContentComponent() to give it a component which
  63009. will be automatically resized and kept in the right place - then you can add
  63010. subcomponents to the content comp. See the notes for the ResizableWindow class
  63011. for more info.
  63012. If you really know what you're doing and want to avoid this assertion, just call
  63013. Component::addAndMakeVisible directly.
  63014. */
  63015. jassertfalse;
  63016. Component::addAndMakeVisible (child, zOrder);
  63017. }
  63018. #endif
  63019. END_JUCE_NAMESPACE
  63020. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63021. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63022. BEGIN_JUCE_NAMESPACE
  63023. SplashScreen::SplashScreen()
  63024. {
  63025. setOpaque (true);
  63026. }
  63027. SplashScreen::~SplashScreen()
  63028. {
  63029. }
  63030. void SplashScreen::show (const String& title,
  63031. const Image& backgroundImage_,
  63032. const int minimumTimeToDisplayFor,
  63033. const bool useDropShadow,
  63034. const bool removeOnMouseClick)
  63035. {
  63036. backgroundImage = backgroundImage_;
  63037. jassert (backgroundImage_.isValid());
  63038. if (backgroundImage_.isValid())
  63039. {
  63040. setOpaque (! backgroundImage_.hasAlphaChannel());
  63041. show (title,
  63042. backgroundImage_.getWidth(),
  63043. backgroundImage_.getHeight(),
  63044. minimumTimeToDisplayFor,
  63045. useDropShadow,
  63046. removeOnMouseClick);
  63047. }
  63048. }
  63049. void SplashScreen::show (const String& title,
  63050. const int width,
  63051. const int height,
  63052. const int minimumTimeToDisplayFor,
  63053. const bool useDropShadow,
  63054. const bool removeOnMouseClick)
  63055. {
  63056. setName (title);
  63057. setAlwaysOnTop (true);
  63058. setVisible (true);
  63059. centreWithSize (width, height);
  63060. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63061. toFront (false);
  63062. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63063. repaint();
  63064. originalClickCounter = removeOnMouseClick
  63065. ? Desktop::getMouseButtonClickCounter()
  63066. : std::numeric_limits<int>::max();
  63067. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63068. startTimer (50);
  63069. }
  63070. void SplashScreen::paint (Graphics& g)
  63071. {
  63072. g.setOpacity (1.0f);
  63073. g.drawImage (backgroundImage,
  63074. 0, 0, getWidth(), getHeight(),
  63075. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63076. }
  63077. void SplashScreen::timerCallback()
  63078. {
  63079. if (Time::getCurrentTime() > earliestTimeToDelete
  63080. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63081. {
  63082. delete this;
  63083. }
  63084. }
  63085. END_JUCE_NAMESPACE
  63086. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63087. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63088. BEGIN_JUCE_NAMESPACE
  63089. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63090. const bool hasProgressBar,
  63091. const bool hasCancelButton,
  63092. const int timeOutMsWhenCancelling_,
  63093. const String& cancelButtonText)
  63094. : Thread ("Juce Progress Window"),
  63095. progress (0.0),
  63096. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63097. {
  63098. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63099. .createAlertWindow (title, String::empty, cancelButtonText,
  63100. String::empty, String::empty,
  63101. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63102. if (hasProgressBar)
  63103. alertWindow->addProgressBarComponent (progress);
  63104. }
  63105. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63106. {
  63107. stopThread (timeOutMsWhenCancelling);
  63108. }
  63109. bool ThreadWithProgressWindow::runThread (const int priority)
  63110. {
  63111. startThread (priority);
  63112. startTimer (100);
  63113. {
  63114. const ScopedLock sl (messageLock);
  63115. alertWindow->setMessage (message);
  63116. }
  63117. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63118. stopThread (timeOutMsWhenCancelling);
  63119. alertWindow->setVisible (false);
  63120. return finishedNaturally;
  63121. }
  63122. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63123. {
  63124. progress = newProgress;
  63125. }
  63126. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63127. {
  63128. const ScopedLock sl (messageLock);
  63129. message = newStatusMessage;
  63130. }
  63131. void ThreadWithProgressWindow::timerCallback()
  63132. {
  63133. if (! isThreadRunning())
  63134. {
  63135. // thread has finished normally..
  63136. alertWindow->exitModalState (1);
  63137. alertWindow->setVisible (false);
  63138. }
  63139. else
  63140. {
  63141. const ScopedLock sl (messageLock);
  63142. alertWindow->setMessage (message);
  63143. }
  63144. }
  63145. END_JUCE_NAMESPACE
  63146. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63147. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63148. BEGIN_JUCE_NAMESPACE
  63149. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63150. const int millisecondsBeforeTipAppears_)
  63151. : Component ("tooltip"),
  63152. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63153. mouseClicks (0),
  63154. lastHideTime (0),
  63155. lastComponentUnderMouse (0),
  63156. changedCompsSinceShown (true)
  63157. {
  63158. if (Desktop::getInstance().getMainMouseSource().canHover())
  63159. startTimer (123);
  63160. setAlwaysOnTop (true);
  63161. setOpaque (true);
  63162. if (parentComponent != 0)
  63163. parentComponent->addChildComponent (this);
  63164. }
  63165. TooltipWindow::~TooltipWindow()
  63166. {
  63167. hide();
  63168. }
  63169. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63170. {
  63171. millisecondsBeforeTipAppears = newTimeMs;
  63172. }
  63173. void TooltipWindow::paint (Graphics& g)
  63174. {
  63175. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63176. }
  63177. void TooltipWindow::mouseEnter (const MouseEvent&)
  63178. {
  63179. hide();
  63180. }
  63181. void TooltipWindow::showFor (const String& tip)
  63182. {
  63183. jassert (tip.isNotEmpty());
  63184. tipShowing = tip;
  63185. Point<int> mousePos (Desktop::getMousePosition());
  63186. if (getParentComponent() != 0)
  63187. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63188. int x, y, w, h;
  63189. getLookAndFeel().getTooltipSize (tip, w, h);
  63190. if (mousePos.getX() > getParentWidth() / 2)
  63191. x = mousePos.getX() - (w + 12);
  63192. else
  63193. x = mousePos.getX() + 24;
  63194. if (mousePos.getY() > getParentHeight() / 2)
  63195. y = mousePos.getY() - (h + 6);
  63196. else
  63197. y = mousePos.getY() + 6;
  63198. setBounds (x, y, w, h);
  63199. setVisible (true);
  63200. if (getParentComponent() == 0)
  63201. {
  63202. addToDesktop (ComponentPeer::windowHasDropShadow
  63203. | ComponentPeer::windowIsTemporary
  63204. | ComponentPeer::windowIgnoresKeyPresses);
  63205. }
  63206. toFront (false);
  63207. }
  63208. const String TooltipWindow::getTipFor (Component* const c)
  63209. {
  63210. if (c != 0
  63211. && Process::isForegroundProcess()
  63212. && ! Component::isMouseButtonDownAnywhere())
  63213. {
  63214. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63215. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63216. return ttc->getTooltip();
  63217. }
  63218. return String::empty;
  63219. }
  63220. void TooltipWindow::hide()
  63221. {
  63222. tipShowing = String::empty;
  63223. removeFromDesktop();
  63224. setVisible (false);
  63225. }
  63226. void TooltipWindow::timerCallback()
  63227. {
  63228. const unsigned int now = Time::getApproximateMillisecondCounter();
  63229. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63230. const String newTip (getTipFor (newComp));
  63231. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63232. lastComponentUnderMouse = newComp;
  63233. lastTipUnderMouse = newTip;
  63234. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63235. const bool mouseWasClicked = clickCount > mouseClicks;
  63236. mouseClicks = clickCount;
  63237. const Point<int> mousePos (Desktop::getMousePosition());
  63238. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63239. lastMousePos = mousePos;
  63240. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63241. lastCompChangeTime = now;
  63242. if (isVisible() || now < lastHideTime + 500)
  63243. {
  63244. // if a tip is currently visible (or has just disappeared), update to a new one
  63245. // immediately if needed..
  63246. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63247. {
  63248. if (isVisible())
  63249. {
  63250. lastHideTime = now;
  63251. hide();
  63252. }
  63253. }
  63254. else if (tipChanged)
  63255. {
  63256. showFor (newTip);
  63257. }
  63258. }
  63259. else
  63260. {
  63261. // if there isn't currently a tip, but one is needed, only let it
  63262. // appear after a timeout..
  63263. if (newTip.isNotEmpty()
  63264. && newTip != tipShowing
  63265. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63266. {
  63267. showFor (newTip);
  63268. }
  63269. }
  63270. }
  63271. END_JUCE_NAMESPACE
  63272. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63273. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63274. BEGIN_JUCE_NAMESPACE
  63275. /** Keeps track of the active top level window.
  63276. */
  63277. class TopLevelWindowManager : public Timer,
  63278. public DeletedAtShutdown
  63279. {
  63280. public:
  63281. TopLevelWindowManager()
  63282. : currentActive (0)
  63283. {
  63284. }
  63285. ~TopLevelWindowManager()
  63286. {
  63287. clearSingletonInstance();
  63288. }
  63289. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63290. void timerCallback()
  63291. {
  63292. startTimer (jmin (1731, getTimerInterval() * 2));
  63293. TopLevelWindow* active = 0;
  63294. if (Process::isForegroundProcess())
  63295. {
  63296. active = currentActive;
  63297. Component* const c = Component::getCurrentlyFocusedComponent();
  63298. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63299. if (tlw == 0 && c != 0)
  63300. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63301. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63302. if (tlw != 0)
  63303. active = tlw;
  63304. }
  63305. if (active != currentActive)
  63306. {
  63307. currentActive = active;
  63308. for (int i = windows.size(); --i >= 0;)
  63309. {
  63310. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63311. tlw->setWindowActive (isWindowActive (tlw));
  63312. i = jmin (i, windows.size() - 1);
  63313. }
  63314. Desktop::getInstance().triggerFocusCallback();
  63315. }
  63316. }
  63317. bool addWindow (TopLevelWindow* const w)
  63318. {
  63319. windows.add (w);
  63320. startTimer (10);
  63321. return isWindowActive (w);
  63322. }
  63323. void removeWindow (TopLevelWindow* const w)
  63324. {
  63325. startTimer (10);
  63326. if (currentActive == w)
  63327. currentActive = 0;
  63328. windows.removeValue (w);
  63329. if (windows.size() == 0)
  63330. deleteInstance();
  63331. }
  63332. Array <TopLevelWindow*> windows;
  63333. private:
  63334. TopLevelWindow* currentActive;
  63335. bool isWindowActive (TopLevelWindow* const tlw) const
  63336. {
  63337. return (tlw == currentActive
  63338. || tlw->isParentOf (currentActive)
  63339. || tlw->hasKeyboardFocus (true))
  63340. && tlw->isShowing();
  63341. }
  63342. TopLevelWindowManager (const TopLevelWindowManager&);
  63343. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63344. };
  63345. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63346. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63347. {
  63348. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63349. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63350. }
  63351. TopLevelWindow::TopLevelWindow (const String& name,
  63352. const bool addToDesktop_)
  63353. : Component (name),
  63354. useDropShadow (true),
  63355. useNativeTitleBar (false),
  63356. windowIsActive_ (false)
  63357. {
  63358. setOpaque (true);
  63359. if (addToDesktop_)
  63360. Component::addToDesktop (getDesktopWindowStyleFlags());
  63361. else
  63362. setDropShadowEnabled (true);
  63363. setWantsKeyboardFocus (true);
  63364. setBroughtToFrontOnMouseClick (true);
  63365. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63366. }
  63367. TopLevelWindow::~TopLevelWindow()
  63368. {
  63369. shadower = 0;
  63370. TopLevelWindowManager::getInstance()->removeWindow (this);
  63371. }
  63372. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63373. {
  63374. if (hasKeyboardFocus (true))
  63375. TopLevelWindowManager::getInstance()->timerCallback();
  63376. else
  63377. TopLevelWindowManager::getInstance()->startTimer (10);
  63378. }
  63379. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63380. {
  63381. if (windowIsActive_ != isNowActive)
  63382. {
  63383. windowIsActive_ = isNowActive;
  63384. activeWindowStatusChanged();
  63385. }
  63386. }
  63387. void TopLevelWindow::activeWindowStatusChanged()
  63388. {
  63389. }
  63390. void TopLevelWindow::parentHierarchyChanged()
  63391. {
  63392. setDropShadowEnabled (useDropShadow);
  63393. }
  63394. void TopLevelWindow::visibilityChanged()
  63395. {
  63396. if (isShowing())
  63397. toFront (true);
  63398. }
  63399. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63400. {
  63401. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63402. if (useDropShadow)
  63403. styleFlags |= ComponentPeer::windowHasDropShadow;
  63404. if (useNativeTitleBar)
  63405. styleFlags |= ComponentPeer::windowHasTitleBar;
  63406. return styleFlags;
  63407. }
  63408. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63409. {
  63410. useDropShadow = useShadow;
  63411. if (isOnDesktop())
  63412. {
  63413. shadower = 0;
  63414. Component::addToDesktop (getDesktopWindowStyleFlags());
  63415. }
  63416. else
  63417. {
  63418. if (useShadow && isOpaque())
  63419. {
  63420. if (shadower == 0)
  63421. {
  63422. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63423. if (shadower != 0)
  63424. shadower->setOwner (this);
  63425. }
  63426. }
  63427. else
  63428. {
  63429. shadower = 0;
  63430. }
  63431. }
  63432. }
  63433. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63434. {
  63435. if (useNativeTitleBar != useNativeTitleBar_)
  63436. {
  63437. useNativeTitleBar = useNativeTitleBar_;
  63438. recreateDesktopWindow();
  63439. sendLookAndFeelChange();
  63440. }
  63441. }
  63442. void TopLevelWindow::recreateDesktopWindow()
  63443. {
  63444. if (isOnDesktop())
  63445. {
  63446. Component::addToDesktop (getDesktopWindowStyleFlags());
  63447. toFront (true);
  63448. }
  63449. }
  63450. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63451. {
  63452. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63453. because this class needs to make sure its layout corresponds with settings like whether
  63454. it's got a native title bar or not.
  63455. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63456. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63457. method, then add or remove whatever flags are necessary from this value before returning it.
  63458. */
  63459. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63460. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63461. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63462. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63463. sendLookAndFeelChange();
  63464. }
  63465. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63466. {
  63467. if (c == 0)
  63468. c = TopLevelWindow::getActiveTopLevelWindow();
  63469. if (c == 0)
  63470. {
  63471. centreWithSize (width, height);
  63472. }
  63473. else
  63474. {
  63475. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63476. (c->getHeight() - height) / 2)));
  63477. Rectangle<int> parentArea (c->getParentMonitorArea());
  63478. if (getParentComponent() != 0)
  63479. {
  63480. p = getParentComponent()->globalPositionToRelative (p);
  63481. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63482. }
  63483. parentArea.reduce (12, 12);
  63484. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63485. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63486. width, height);
  63487. }
  63488. }
  63489. int TopLevelWindow::getNumTopLevelWindows() throw()
  63490. {
  63491. return TopLevelWindowManager::getInstance()->windows.size();
  63492. }
  63493. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63494. {
  63495. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63496. }
  63497. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63498. {
  63499. TopLevelWindow* best = 0;
  63500. int bestNumTWLParents = -1;
  63501. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63502. {
  63503. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63504. if (tlw->isActiveWindow())
  63505. {
  63506. int numTWLParents = 0;
  63507. const Component* c = tlw->getParentComponent();
  63508. while (c != 0)
  63509. {
  63510. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63511. ++numTWLParents;
  63512. c = c->getParentComponent();
  63513. }
  63514. if (bestNumTWLParents < numTWLParents)
  63515. {
  63516. best = tlw;
  63517. bestNumTWLParents = numTWLParents;
  63518. }
  63519. }
  63520. }
  63521. return best;
  63522. }
  63523. END_JUCE_NAMESPACE
  63524. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63525. #endif
  63526. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63527. /*** Start of inlined file: juce_Colour.cpp ***/
  63528. BEGIN_JUCE_NAMESPACE
  63529. namespace ColourHelpers
  63530. {
  63531. static uint8 floatAlphaToInt (const float alpha) throw()
  63532. {
  63533. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63534. }
  63535. static void convertHSBtoRGB (float h, float s, float v,
  63536. uint8& r, uint8& g, uint8& b) throw()
  63537. {
  63538. v = jlimit (0.0f, 1.0f, v);
  63539. v *= 255.0f;
  63540. const uint8 intV = (uint8) roundToInt (v);
  63541. if (s <= 0)
  63542. {
  63543. r = intV;
  63544. g = intV;
  63545. b = intV;
  63546. }
  63547. else
  63548. {
  63549. s = jmin (1.0f, s);
  63550. h = jlimit (0.0f, 1.0f, h);
  63551. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63552. const float f = h - std::floor (h);
  63553. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63554. const float y = v * (1.0f - s * f);
  63555. const float z = v * (1.0f - (s * (1.0f - f)));
  63556. if (h < 1.0f)
  63557. {
  63558. r = intV;
  63559. g = (uint8) roundToInt (z);
  63560. b = x;
  63561. }
  63562. else if (h < 2.0f)
  63563. {
  63564. r = (uint8) roundToInt (y);
  63565. g = intV;
  63566. b = x;
  63567. }
  63568. else if (h < 3.0f)
  63569. {
  63570. r = x;
  63571. g = intV;
  63572. b = (uint8) roundToInt (z);
  63573. }
  63574. else if (h < 4.0f)
  63575. {
  63576. r = x;
  63577. g = (uint8) roundToInt (y);
  63578. b = intV;
  63579. }
  63580. else if (h < 5.0f)
  63581. {
  63582. r = (uint8) roundToInt (z);
  63583. g = x;
  63584. b = intV;
  63585. }
  63586. else if (h < 6.0f)
  63587. {
  63588. r = intV;
  63589. g = x;
  63590. b = (uint8) roundToInt (y);
  63591. }
  63592. else
  63593. {
  63594. r = 0;
  63595. g = 0;
  63596. b = 0;
  63597. }
  63598. }
  63599. }
  63600. }
  63601. Colour::Colour() throw()
  63602. : argb (0)
  63603. {
  63604. }
  63605. Colour::Colour (const Colour& other) throw()
  63606. : argb (other.argb)
  63607. {
  63608. }
  63609. Colour& Colour::operator= (const Colour& other) throw()
  63610. {
  63611. argb = other.argb;
  63612. return *this;
  63613. }
  63614. bool Colour::operator== (const Colour& other) const throw()
  63615. {
  63616. return argb.getARGB() == other.argb.getARGB();
  63617. }
  63618. bool Colour::operator!= (const Colour& other) const throw()
  63619. {
  63620. return argb.getARGB() != other.argb.getARGB();
  63621. }
  63622. Colour::Colour (const uint32 argb_) throw()
  63623. : argb (argb_)
  63624. {
  63625. }
  63626. Colour::Colour (const uint8 red,
  63627. const uint8 green,
  63628. const uint8 blue) throw()
  63629. {
  63630. argb.setARGB (0xff, red, green, blue);
  63631. }
  63632. const Colour Colour::fromRGB (const uint8 red,
  63633. const uint8 green,
  63634. const uint8 blue) throw()
  63635. {
  63636. return Colour (red, green, blue);
  63637. }
  63638. Colour::Colour (const uint8 red,
  63639. const uint8 green,
  63640. const uint8 blue,
  63641. const uint8 alpha) throw()
  63642. {
  63643. argb.setARGB (alpha, red, green, blue);
  63644. }
  63645. const Colour Colour::fromRGBA (const uint8 red,
  63646. const uint8 green,
  63647. const uint8 blue,
  63648. const uint8 alpha) throw()
  63649. {
  63650. return Colour (red, green, blue, alpha);
  63651. }
  63652. Colour::Colour (const uint8 red,
  63653. const uint8 green,
  63654. const uint8 blue,
  63655. const float alpha) throw()
  63656. {
  63657. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63658. }
  63659. const Colour Colour::fromRGBAFloat (const uint8 red,
  63660. const uint8 green,
  63661. const uint8 blue,
  63662. const float alpha) throw()
  63663. {
  63664. return Colour (red, green, blue, alpha);
  63665. }
  63666. Colour::Colour (const float hue,
  63667. const float saturation,
  63668. const float brightness,
  63669. const float alpha) throw()
  63670. {
  63671. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63672. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63673. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63674. }
  63675. const Colour Colour::fromHSV (const float hue,
  63676. const float saturation,
  63677. const float brightness,
  63678. const float alpha) throw()
  63679. {
  63680. return Colour (hue, saturation, brightness, alpha);
  63681. }
  63682. Colour::Colour (const float hue,
  63683. const float saturation,
  63684. const float brightness,
  63685. const uint8 alpha) throw()
  63686. {
  63687. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63688. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63689. argb.setARGB (alpha, r, g, b);
  63690. }
  63691. Colour::~Colour() throw()
  63692. {
  63693. }
  63694. const PixelARGB Colour::getPixelARGB() const throw()
  63695. {
  63696. PixelARGB p (argb);
  63697. p.premultiply();
  63698. return p;
  63699. }
  63700. uint32 Colour::getARGB() const throw()
  63701. {
  63702. return argb.getARGB();
  63703. }
  63704. bool Colour::isTransparent() const throw()
  63705. {
  63706. return getAlpha() == 0;
  63707. }
  63708. bool Colour::isOpaque() const throw()
  63709. {
  63710. return getAlpha() == 0xff;
  63711. }
  63712. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63713. {
  63714. PixelARGB newCol (argb);
  63715. newCol.setAlpha (newAlpha);
  63716. return Colour (newCol.getARGB());
  63717. }
  63718. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63719. {
  63720. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63721. PixelARGB newCol (argb);
  63722. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63723. return Colour (newCol.getARGB());
  63724. }
  63725. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63726. {
  63727. jassert (alphaMultiplier >= 0);
  63728. PixelARGB newCol (argb);
  63729. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63730. return Colour (newCol.getARGB());
  63731. }
  63732. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63733. {
  63734. const int destAlpha = getAlpha();
  63735. if (destAlpha > 0)
  63736. {
  63737. const int invA = 0xff - (int) src.getAlpha();
  63738. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63739. if (resA > 0)
  63740. {
  63741. const int da = (invA * destAlpha) / resA;
  63742. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63743. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63744. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63745. (uint8) resA);
  63746. }
  63747. return *this;
  63748. }
  63749. else
  63750. {
  63751. return src;
  63752. }
  63753. }
  63754. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63755. {
  63756. if (proportionOfOther <= 0)
  63757. return *this;
  63758. if (proportionOfOther >= 1.0f)
  63759. return other;
  63760. PixelARGB c1 (getPixelARGB());
  63761. const PixelARGB c2 (other.getPixelARGB());
  63762. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63763. c1.unpremultiply();
  63764. return Colour (c1.getARGB());
  63765. }
  63766. float Colour::getFloatRed() const throw()
  63767. {
  63768. return getRed() / 255.0f;
  63769. }
  63770. float Colour::getFloatGreen() const throw()
  63771. {
  63772. return getGreen() / 255.0f;
  63773. }
  63774. float Colour::getFloatBlue() const throw()
  63775. {
  63776. return getBlue() / 255.0f;
  63777. }
  63778. float Colour::getFloatAlpha() const throw()
  63779. {
  63780. return getAlpha() / 255.0f;
  63781. }
  63782. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63783. {
  63784. const int r = getRed();
  63785. const int g = getGreen();
  63786. const int b = getBlue();
  63787. const int hi = jmax (r, g, b);
  63788. const int lo = jmin (r, g, b);
  63789. if (hi != 0)
  63790. {
  63791. s = (hi - lo) / (float) hi;
  63792. if (s != 0)
  63793. {
  63794. const float invDiff = 1.0f / (hi - lo);
  63795. const float red = (hi - r) * invDiff;
  63796. const float green = (hi - g) * invDiff;
  63797. const float blue = (hi - b) * invDiff;
  63798. if (r == hi)
  63799. h = blue - green;
  63800. else if (g == hi)
  63801. h = 2.0f + red - blue;
  63802. else
  63803. h = 4.0f + green - red;
  63804. h *= 1.0f / 6.0f;
  63805. if (h < 0)
  63806. ++h;
  63807. }
  63808. else
  63809. {
  63810. h = 0;
  63811. }
  63812. }
  63813. else
  63814. {
  63815. s = 0;
  63816. h = 0;
  63817. }
  63818. v = hi / 255.0f;
  63819. }
  63820. float Colour::getHue() const throw()
  63821. {
  63822. float h, s, b;
  63823. getHSB (h, s, b);
  63824. return h;
  63825. }
  63826. const Colour Colour::withHue (const float hue) const throw()
  63827. {
  63828. float h, s, b;
  63829. getHSB (h, s, b);
  63830. return Colour (hue, s, b, getAlpha());
  63831. }
  63832. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63833. {
  63834. float h, s, b;
  63835. getHSB (h, s, b);
  63836. h += amountToRotate;
  63837. h -= std::floor (h);
  63838. return Colour (h, s, b, getAlpha());
  63839. }
  63840. float Colour::getSaturation() const throw()
  63841. {
  63842. float h, s, b;
  63843. getHSB (h, s, b);
  63844. return s;
  63845. }
  63846. const Colour Colour::withSaturation (const float saturation) const throw()
  63847. {
  63848. float h, s, b;
  63849. getHSB (h, s, b);
  63850. return Colour (h, saturation, b, getAlpha());
  63851. }
  63852. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63853. {
  63854. float h, s, b;
  63855. getHSB (h, s, b);
  63856. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63857. }
  63858. float Colour::getBrightness() const throw()
  63859. {
  63860. float h, s, b;
  63861. getHSB (h, s, b);
  63862. return b;
  63863. }
  63864. const Colour Colour::withBrightness (const float brightness) const throw()
  63865. {
  63866. float h, s, b;
  63867. getHSB (h, s, b);
  63868. return Colour (h, s, brightness, getAlpha());
  63869. }
  63870. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63871. {
  63872. float h, s, b;
  63873. getHSB (h, s, b);
  63874. b *= amount;
  63875. if (b > 1.0f)
  63876. b = 1.0f;
  63877. return Colour (h, s, b, getAlpha());
  63878. }
  63879. const Colour Colour::brighter (float amount) const throw()
  63880. {
  63881. amount = 1.0f / (1.0f + amount);
  63882. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63883. (uint8) (255 - (amount * (255 - getGreen()))),
  63884. (uint8) (255 - (amount * (255 - getBlue()))),
  63885. getAlpha());
  63886. }
  63887. const Colour Colour::darker (float amount) const throw()
  63888. {
  63889. amount = 1.0f / (1.0f + amount);
  63890. return Colour ((uint8) (amount * getRed()),
  63891. (uint8) (amount * getGreen()),
  63892. (uint8) (amount * getBlue()),
  63893. getAlpha());
  63894. }
  63895. const Colour Colour::greyLevel (const float brightness) throw()
  63896. {
  63897. const uint8 level
  63898. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63899. return Colour (level, level, level);
  63900. }
  63901. const Colour Colour::contrasting (const float amount) const throw()
  63902. {
  63903. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63904. ? Colours::black
  63905. : Colours::white).withAlpha (amount));
  63906. }
  63907. const Colour Colour::contrasting (const Colour& colour1,
  63908. const Colour& colour2) throw()
  63909. {
  63910. const float b1 = colour1.getBrightness();
  63911. const float b2 = colour2.getBrightness();
  63912. float best = 0.0f;
  63913. float bestDist = 0.0f;
  63914. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63915. {
  63916. const float d1 = std::abs (i - b1);
  63917. const float d2 = std::abs (i - b2);
  63918. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63919. if (dist > bestDist)
  63920. {
  63921. best = i;
  63922. bestDist = dist;
  63923. }
  63924. }
  63925. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63926. .withBrightness (best);
  63927. }
  63928. const String Colour::toString() const
  63929. {
  63930. return String::toHexString ((int) argb.getARGB());
  63931. }
  63932. const Colour Colour::fromString (const String& encodedColourString)
  63933. {
  63934. return Colour ((uint32) encodedColourString.getHexValue32());
  63935. }
  63936. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63937. {
  63938. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63939. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63940. .toUpperCase();
  63941. }
  63942. END_JUCE_NAMESPACE
  63943. /*** End of inlined file: juce_Colour.cpp ***/
  63944. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63945. BEGIN_JUCE_NAMESPACE
  63946. ColourGradient::ColourGradient() throw()
  63947. {
  63948. #if JUCE_DEBUG
  63949. point1.setX (987654.0f);
  63950. #endif
  63951. }
  63952. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  63953. const Colour& colour2, const float x2_, const float y2_,
  63954. const bool isRadial_)
  63955. : point1 (x1_, y1_),
  63956. point2 (x2_, y2_),
  63957. isRadial (isRadial_)
  63958. {
  63959. colours.add (ColourPoint (0.0, colour1));
  63960. colours.add (ColourPoint (1.0, colour2));
  63961. }
  63962. ColourGradient::~ColourGradient()
  63963. {
  63964. }
  63965. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  63966. {
  63967. return point1 == other.point1 && point2 == other.point2
  63968. && isRadial == other.isRadial
  63969. && colours == other.colours;
  63970. }
  63971. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  63972. {
  63973. return ! operator== (other);
  63974. }
  63975. void ColourGradient::clearColours()
  63976. {
  63977. colours.clear();
  63978. }
  63979. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  63980. {
  63981. // must be within the two end-points
  63982. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63983. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  63984. int i;
  63985. for (i = 0; i < colours.size(); ++i)
  63986. if (colours.getReference(i).position > pos)
  63987. break;
  63988. colours.insert (i, ColourPoint (pos, colour));
  63989. return i;
  63990. }
  63991. void ColourGradient::removeColour (int index)
  63992. {
  63993. jassert (index > 0 && index < colours.size() - 1);
  63994. colours.remove (index);
  63995. }
  63996. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63997. {
  63998. for (int i = 0; i < colours.size(); ++i)
  63999. {
  64000. Colour& c = colours.getReference(i).colour;
  64001. c = c.withMultipliedAlpha (multiplier);
  64002. }
  64003. }
  64004. int ColourGradient::getNumColours() const throw()
  64005. {
  64006. return colours.size();
  64007. }
  64008. double ColourGradient::getColourPosition (const int index) const throw()
  64009. {
  64010. if (((unsigned int) index) < (unsigned int) colours.size())
  64011. return colours.getReference (index).position;
  64012. return 0;
  64013. }
  64014. const Colour ColourGradient::getColour (const int index) const throw()
  64015. {
  64016. if (((unsigned int) index) < (unsigned int) colours.size())
  64017. return colours.getReference (index).colour;
  64018. return Colour();
  64019. }
  64020. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64021. {
  64022. if (((unsigned int) index) < (unsigned int) colours.size())
  64023. colours.getReference (index).colour = newColour;
  64024. }
  64025. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64026. {
  64027. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64028. if (position <= 0 || colours.size() <= 1)
  64029. return colours.getReference(0).colour;
  64030. int i = colours.size() - 1;
  64031. while (position < colours.getReference(i).position)
  64032. --i;
  64033. const ColourPoint& p1 = colours.getReference (i);
  64034. if (i >= colours.size() - 1)
  64035. return p1.colour;
  64036. const ColourPoint& p2 = colours.getReference (i + 1);
  64037. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64038. }
  64039. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64040. {
  64041. #if JUCE_DEBUG
  64042. // trying to use the object without setting its co-ordinates? Have a careful read of
  64043. // the comments for the constructors.
  64044. jassert (point1.getX() != 987654.0f);
  64045. #endif
  64046. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64047. 3 * (int) point1.transformedBy (transform)
  64048. .getDistanceFrom (point2.transformedBy (transform)));
  64049. lookupTable.malloc (numEntries);
  64050. if (colours.size() >= 2)
  64051. {
  64052. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64053. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64054. int index = 0;
  64055. for (int j = 1; j < colours.size(); ++j)
  64056. {
  64057. const ColourPoint& p = colours.getReference (j);
  64058. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64059. const PixelARGB pix2 (p.colour.getPixelARGB());
  64060. for (int i = 0; i < numToDo; ++i)
  64061. {
  64062. jassert (index >= 0 && index < numEntries);
  64063. lookupTable[index] = pix1;
  64064. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64065. ++index;
  64066. }
  64067. pix1 = pix2;
  64068. }
  64069. while (index < numEntries)
  64070. lookupTable [index++] = pix1;
  64071. }
  64072. else
  64073. {
  64074. jassertfalse; // no colours specified!
  64075. }
  64076. return numEntries;
  64077. }
  64078. bool ColourGradient::isOpaque() const throw()
  64079. {
  64080. for (int i = 0; i < colours.size(); ++i)
  64081. if (! colours.getReference(i).colour.isOpaque())
  64082. return false;
  64083. return true;
  64084. }
  64085. bool ColourGradient::isInvisible() const throw()
  64086. {
  64087. for (int i = 0; i < colours.size(); ++i)
  64088. if (! colours.getReference(i).colour.isTransparent())
  64089. return false;
  64090. return true;
  64091. }
  64092. END_JUCE_NAMESPACE
  64093. /*** End of inlined file: juce_ColourGradient.cpp ***/
  64094. /*** Start of inlined file: juce_Colours.cpp ***/
  64095. BEGIN_JUCE_NAMESPACE
  64096. const Colour Colours::transparentBlack (0);
  64097. const Colour Colours::transparentWhite (0x00ffffff);
  64098. const Colour Colours::aliceblue (0xfff0f8ff);
  64099. const Colour Colours::antiquewhite (0xfffaebd7);
  64100. const Colour Colours::aqua (0xff00ffff);
  64101. const Colour Colours::aquamarine (0xff7fffd4);
  64102. const Colour Colours::azure (0xfff0ffff);
  64103. const Colour Colours::beige (0xfff5f5dc);
  64104. const Colour Colours::bisque (0xffffe4c4);
  64105. const Colour Colours::black (0xff000000);
  64106. const Colour Colours::blanchedalmond (0xffffebcd);
  64107. const Colour Colours::blue (0xff0000ff);
  64108. const Colour Colours::blueviolet (0xff8a2be2);
  64109. const Colour Colours::brown (0xffa52a2a);
  64110. const Colour Colours::burlywood (0xffdeb887);
  64111. const Colour Colours::cadetblue (0xff5f9ea0);
  64112. const Colour Colours::chartreuse (0xff7fff00);
  64113. const Colour Colours::chocolate (0xffd2691e);
  64114. const Colour Colours::coral (0xffff7f50);
  64115. const Colour Colours::cornflowerblue (0xff6495ed);
  64116. const Colour Colours::cornsilk (0xfffff8dc);
  64117. const Colour Colours::crimson (0xffdc143c);
  64118. const Colour Colours::cyan (0xff00ffff);
  64119. const Colour Colours::darkblue (0xff00008b);
  64120. const Colour Colours::darkcyan (0xff008b8b);
  64121. const Colour Colours::darkgoldenrod (0xffb8860b);
  64122. const Colour Colours::darkgrey (0xff555555);
  64123. const Colour Colours::darkgreen (0xff006400);
  64124. const Colour Colours::darkkhaki (0xffbdb76b);
  64125. const Colour Colours::darkmagenta (0xff8b008b);
  64126. const Colour Colours::darkolivegreen (0xff556b2f);
  64127. const Colour Colours::darkorange (0xffff8c00);
  64128. const Colour Colours::darkorchid (0xff9932cc);
  64129. const Colour Colours::darkred (0xff8b0000);
  64130. const Colour Colours::darksalmon (0xffe9967a);
  64131. const Colour Colours::darkseagreen (0xff8fbc8f);
  64132. const Colour Colours::darkslateblue (0xff483d8b);
  64133. const Colour Colours::darkslategrey (0xff2f4f4f);
  64134. const Colour Colours::darkturquoise (0xff00ced1);
  64135. const Colour Colours::darkviolet (0xff9400d3);
  64136. const Colour Colours::deeppink (0xffff1493);
  64137. const Colour Colours::deepskyblue (0xff00bfff);
  64138. const Colour Colours::dimgrey (0xff696969);
  64139. const Colour Colours::dodgerblue (0xff1e90ff);
  64140. const Colour Colours::firebrick (0xffb22222);
  64141. const Colour Colours::floralwhite (0xfffffaf0);
  64142. const Colour Colours::forestgreen (0xff228b22);
  64143. const Colour Colours::fuchsia (0xffff00ff);
  64144. const Colour Colours::gainsboro (0xffdcdcdc);
  64145. const Colour Colours::gold (0xffffd700);
  64146. const Colour Colours::goldenrod (0xffdaa520);
  64147. const Colour Colours::grey (0xff808080);
  64148. const Colour Colours::green (0xff008000);
  64149. const Colour Colours::greenyellow (0xffadff2f);
  64150. const Colour Colours::honeydew (0xfff0fff0);
  64151. const Colour Colours::hotpink (0xffff69b4);
  64152. const Colour Colours::indianred (0xffcd5c5c);
  64153. const Colour Colours::indigo (0xff4b0082);
  64154. const Colour Colours::ivory (0xfffffff0);
  64155. const Colour Colours::khaki (0xfff0e68c);
  64156. const Colour Colours::lavender (0xffe6e6fa);
  64157. const Colour Colours::lavenderblush (0xfffff0f5);
  64158. const Colour Colours::lemonchiffon (0xfffffacd);
  64159. const Colour Colours::lightblue (0xffadd8e6);
  64160. const Colour Colours::lightcoral (0xfff08080);
  64161. const Colour Colours::lightcyan (0xffe0ffff);
  64162. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  64163. const Colour Colours::lightgreen (0xff90ee90);
  64164. const Colour Colours::lightgrey (0xffd3d3d3);
  64165. const Colour Colours::lightpink (0xffffb6c1);
  64166. const Colour Colours::lightsalmon (0xffffa07a);
  64167. const Colour Colours::lightseagreen (0xff20b2aa);
  64168. const Colour Colours::lightskyblue (0xff87cefa);
  64169. const Colour Colours::lightslategrey (0xff778899);
  64170. const Colour Colours::lightsteelblue (0xffb0c4de);
  64171. const Colour Colours::lightyellow (0xffffffe0);
  64172. const Colour Colours::lime (0xff00ff00);
  64173. const Colour Colours::limegreen (0xff32cd32);
  64174. const Colour Colours::linen (0xfffaf0e6);
  64175. const Colour Colours::magenta (0xffff00ff);
  64176. const Colour Colours::maroon (0xff800000);
  64177. const Colour Colours::mediumaquamarine (0xff66cdaa);
  64178. const Colour Colours::mediumblue (0xff0000cd);
  64179. const Colour Colours::mediumorchid (0xffba55d3);
  64180. const Colour Colours::mediumpurple (0xff9370db);
  64181. const Colour Colours::mediumseagreen (0xff3cb371);
  64182. const Colour Colours::mediumslateblue (0xff7b68ee);
  64183. const Colour Colours::mediumspringgreen (0xff00fa9a);
  64184. const Colour Colours::mediumturquoise (0xff48d1cc);
  64185. const Colour Colours::mediumvioletred (0xffc71585);
  64186. const Colour Colours::midnightblue (0xff191970);
  64187. const Colour Colours::mintcream (0xfff5fffa);
  64188. const Colour Colours::mistyrose (0xffffe4e1);
  64189. const Colour Colours::navajowhite (0xffffdead);
  64190. const Colour Colours::navy (0xff000080);
  64191. const Colour Colours::oldlace (0xfffdf5e6);
  64192. const Colour Colours::olive (0xff808000);
  64193. const Colour Colours::olivedrab (0xff6b8e23);
  64194. const Colour Colours::orange (0xffffa500);
  64195. const Colour Colours::orangered (0xffff4500);
  64196. const Colour Colours::orchid (0xffda70d6);
  64197. const Colour Colours::palegoldenrod (0xffeee8aa);
  64198. const Colour Colours::palegreen (0xff98fb98);
  64199. const Colour Colours::paleturquoise (0xffafeeee);
  64200. const Colour Colours::palevioletred (0xffdb7093);
  64201. const Colour Colours::papayawhip (0xffffefd5);
  64202. const Colour Colours::peachpuff (0xffffdab9);
  64203. const Colour Colours::peru (0xffcd853f);
  64204. const Colour Colours::pink (0xffffc0cb);
  64205. const Colour Colours::plum (0xffdda0dd);
  64206. const Colour Colours::powderblue (0xffb0e0e6);
  64207. const Colour Colours::purple (0xff800080);
  64208. const Colour Colours::red (0xffff0000);
  64209. const Colour Colours::rosybrown (0xffbc8f8f);
  64210. const Colour Colours::royalblue (0xff4169e1);
  64211. const Colour Colours::saddlebrown (0xff8b4513);
  64212. const Colour Colours::salmon (0xfffa8072);
  64213. const Colour Colours::sandybrown (0xfff4a460);
  64214. const Colour Colours::seagreen (0xff2e8b57);
  64215. const Colour Colours::seashell (0xfffff5ee);
  64216. const Colour Colours::sienna (0xffa0522d);
  64217. const Colour Colours::silver (0xffc0c0c0);
  64218. const Colour Colours::skyblue (0xff87ceeb);
  64219. const Colour Colours::slateblue (0xff6a5acd);
  64220. const Colour Colours::slategrey (0xff708090);
  64221. const Colour Colours::snow (0xfffffafa);
  64222. const Colour Colours::springgreen (0xff00ff7f);
  64223. const Colour Colours::steelblue (0xff4682b4);
  64224. const Colour Colours::tan (0xffd2b48c);
  64225. const Colour Colours::teal (0xff008080);
  64226. const Colour Colours::thistle (0xffd8bfd8);
  64227. const Colour Colours::tomato (0xffff6347);
  64228. const Colour Colours::turquoise (0xff40e0d0);
  64229. const Colour Colours::violet (0xffee82ee);
  64230. const Colour Colours::wheat (0xfff5deb3);
  64231. const Colour Colours::white (0xffffffff);
  64232. const Colour Colours::whitesmoke (0xfff5f5f5);
  64233. const Colour Colours::yellow (0xffffff00);
  64234. const Colour Colours::yellowgreen (0xff9acd32);
  64235. const Colour Colours::findColourForName (const String& colourName,
  64236. const Colour& defaultColour)
  64237. {
  64238. static const int presets[] =
  64239. {
  64240. // (first value is the string's hashcode, second is ARGB)
  64241. 0x05978fff, 0xff000000, /* black */
  64242. 0x06bdcc29, 0xffffffff, /* white */
  64243. 0x002e305a, 0xff0000ff, /* blue */
  64244. 0x00308adf, 0xff808080, /* grey */
  64245. 0x05e0cf03, 0xff008000, /* green */
  64246. 0x0001b891, 0xffff0000, /* red */
  64247. 0xd43c6474, 0xffffff00, /* yellow */
  64248. 0x620886da, 0xfff0f8ff, /* aliceblue */
  64249. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  64250. 0x002dcebc, 0xff00ffff, /* aqua */
  64251. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  64252. 0x0590228f, 0xfff0ffff, /* azure */
  64253. 0x05947fe4, 0xfff5f5dc, /* beige */
  64254. 0xad388e35, 0xffffe4c4, /* bisque */
  64255. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  64256. 0x39129959, 0xff8a2be2, /* blueviolet */
  64257. 0x059a8136, 0xffa52a2a, /* brown */
  64258. 0x89cea8f9, 0xffdeb887, /* burlywood */
  64259. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  64260. 0x6b748956, 0xff7fff00, /* chartreuse */
  64261. 0x2903623c, 0xffd2691e, /* chocolate */
  64262. 0x05a74431, 0xffff7f50, /* coral */
  64263. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  64264. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  64265. 0x3d8c4edf, 0xffdc143c, /* crimson */
  64266. 0x002ed323, 0xff00ffff, /* cyan */
  64267. 0x67cc74d0, 0xff00008b, /* darkblue */
  64268. 0x67cd1799, 0xff008b8b, /* darkcyan */
  64269. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  64270. 0x67cecf55, 0xff555555, /* darkgrey */
  64271. 0x920b194d, 0xff006400, /* darkgreen */
  64272. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  64273. 0x5c293873, 0xff8b008b, /* darkmagenta */
  64274. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  64275. 0xbcfd2524, 0xffff8c00, /* darkorange */
  64276. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  64277. 0x55ee0d5b, 0xff8b0000, /* darkred */
  64278. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  64279. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  64280. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  64281. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  64282. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  64283. 0xc8769375, 0xff9400d3, /* darkviolet */
  64284. 0x25832862, 0xffff1493, /* deeppink */
  64285. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  64286. 0x634c8b67, 0xff696969, /* dimgrey */
  64287. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  64288. 0xef19e3cb, 0xffb22222, /* firebrick */
  64289. 0xb852b195, 0xfffffaf0, /* floralwhite */
  64290. 0xd086fd06, 0xff228b22, /* forestgreen */
  64291. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  64292. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  64293. 0x00308060, 0xffffd700, /* gold */
  64294. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  64295. 0xbab8a537, 0xffadff2f, /* greenyellow */
  64296. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  64297. 0x41892743, 0xffff69b4, /* hotpink */
  64298. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  64299. 0xb969fed2, 0xff4b0082, /* indigo */
  64300. 0x05fef6a9, 0xfffffff0, /* ivory */
  64301. 0x06149302, 0xfff0e68c, /* khaki */
  64302. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  64303. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  64304. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  64305. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  64306. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  64307. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  64308. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  64309. 0xf40157ad, 0xff90ee90, /* lightgreen */
  64310. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  64311. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  64312. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  64313. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  64314. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  64315. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  64316. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  64317. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  64318. 0x0032afd5, 0xff00ff00, /* lime */
  64319. 0x607bbc4e, 0xff32cd32, /* limegreen */
  64320. 0x06234efa, 0xfffaf0e6, /* linen */
  64321. 0x316858a9, 0xffff00ff, /* magenta */
  64322. 0xbf8ca470, 0xff800000, /* maroon */
  64323. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  64324. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  64325. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  64326. 0x07556b71, 0xff9370db, /* mediumpurple */
  64327. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  64328. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  64329. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  64330. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  64331. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  64332. 0x168eb32a, 0xff191970, /* midnightblue */
  64333. 0x4306b960, 0xfff5fffa, /* mintcream */
  64334. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  64335. 0xe97218a6, 0xffffdead, /* navajowhite */
  64336. 0x00337bb6, 0xff000080, /* navy */
  64337. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  64338. 0x064ee1db, 0xff808000, /* olive */
  64339. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  64340. 0xc3de262e, 0xffffa500, /* orange */
  64341. 0x58bebba3, 0xffff4500, /* orangered */
  64342. 0xc3def8a3, 0xffda70d6, /* orchid */
  64343. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  64344. 0x3d9dd619, 0xff98fb98, /* palegreen */
  64345. 0x74022737, 0xffafeeee, /* paleturquoise */
  64346. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  64347. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  64348. 0x93e1b776, 0xffffdab9, /* peachpuff */
  64349. 0x003472f8, 0xffcd853f, /* peru */
  64350. 0x00348176, 0xffffc0cb, /* pink */
  64351. 0x00348d94, 0xffdda0dd, /* plum */
  64352. 0xd036be93, 0xffb0e0e6, /* powderblue */
  64353. 0xc5c507bc, 0xff800080, /* purple */
  64354. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  64355. 0xbd9413e1, 0xff4169e1, /* royalblue */
  64356. 0xf456044f, 0xff8b4513, /* saddlebrown */
  64357. 0xc9c6f66e, 0xfffa8072, /* salmon */
  64358. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  64359. 0x34636c14, 0xff2e8b57, /* seagreen */
  64360. 0x3507fb41, 0xfffff5ee, /* seashell */
  64361. 0xca348772, 0xffa0522d, /* sienna */
  64362. 0xca37d30d, 0xffc0c0c0, /* silver */
  64363. 0x80da74fb, 0xff87ceeb, /* skyblue */
  64364. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  64365. 0x44ab37f8, 0xff708090, /* slategrey */
  64366. 0x0035f183, 0xfffffafa, /* snow */
  64367. 0xd5440d16, 0xff00ff7f, /* springgreen */
  64368. 0x3e1524a5, 0xff4682b4, /* steelblue */
  64369. 0x0001bfa1, 0xffd2b48c, /* tan */
  64370. 0x0036425c, 0xff008080, /* teal */
  64371. 0xafc8858f, 0xffd8bfd8, /* thistle */
  64372. 0xcc41600a, 0xffff6347, /* tomato */
  64373. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  64374. 0xcf57947f, 0xffee82ee, /* violet */
  64375. 0x06bdbae7, 0xfff5deb3, /* wheat */
  64376. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  64377. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  64378. };
  64379. const int hash = colourName.trim().toLowerCase().hashCode();
  64380. for (int i = 0; i < numElementsInArray (presets); i += 2)
  64381. if (presets [i] == hash)
  64382. return Colour (presets [i + 1]);
  64383. return defaultColour;
  64384. }
  64385. END_JUCE_NAMESPACE
  64386. /*** End of inlined file: juce_Colours.cpp ***/
  64387. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  64388. BEGIN_JUCE_NAMESPACE
  64389. const int juce_edgeTableDefaultEdgesPerLine = 32;
  64390. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  64391. const Path& path, const AffineTransform& transform)
  64392. : bounds (bounds_),
  64393. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64394. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64395. needToCheckEmptinesss (true)
  64396. {
  64397. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64398. int* t = table;
  64399. for (int i = bounds.getHeight(); --i >= 0;)
  64400. {
  64401. *t = 0;
  64402. t += lineStrideElements;
  64403. }
  64404. const int topLimit = bounds.getY() << 8;
  64405. const int heightLimit = bounds.getHeight() << 8;
  64406. const int leftLimit = bounds.getX() << 8;
  64407. const int rightLimit = bounds.getRight() << 8;
  64408. PathFlatteningIterator iter (path, transform);
  64409. while (iter.next())
  64410. {
  64411. int y1 = roundToInt (iter.y1 * 256.0f);
  64412. int y2 = roundToInt (iter.y2 * 256.0f);
  64413. if (y1 != y2)
  64414. {
  64415. y1 -= topLimit;
  64416. y2 -= topLimit;
  64417. const int startY = y1;
  64418. int direction = -1;
  64419. if (y1 > y2)
  64420. {
  64421. swapVariables (y1, y2);
  64422. direction = 1;
  64423. }
  64424. if (y1 < 0)
  64425. y1 = 0;
  64426. if (y2 > heightLimit)
  64427. y2 = heightLimit;
  64428. if (y1 < y2)
  64429. {
  64430. const double startX = 256.0f * iter.x1;
  64431. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64432. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64433. do
  64434. {
  64435. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64436. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64437. if (x < leftLimit)
  64438. x = leftLimit;
  64439. else if (x >= rightLimit)
  64440. x = rightLimit - 1;
  64441. addEdgePoint (x, y1 >> 8, direction * step);
  64442. y1 += step;
  64443. }
  64444. while (y1 < y2);
  64445. }
  64446. }
  64447. }
  64448. sanitiseLevels (path.isUsingNonZeroWinding());
  64449. }
  64450. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64451. : bounds (rectangleToAdd),
  64452. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64453. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64454. needToCheckEmptinesss (true)
  64455. {
  64456. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64457. table[0] = 0;
  64458. const int x1 = rectangleToAdd.getX() << 8;
  64459. const int x2 = rectangleToAdd.getRight() << 8;
  64460. int* t = table;
  64461. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64462. {
  64463. t[0] = 2;
  64464. t[1] = x1;
  64465. t[2] = 255;
  64466. t[3] = x2;
  64467. t[4] = 0;
  64468. t += lineStrideElements;
  64469. }
  64470. }
  64471. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64472. : bounds (rectanglesToAdd.getBounds()),
  64473. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64474. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64475. needToCheckEmptinesss (true)
  64476. {
  64477. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64478. int* t = table;
  64479. for (int i = bounds.getHeight(); --i >= 0;)
  64480. {
  64481. *t = 0;
  64482. t += lineStrideElements;
  64483. }
  64484. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64485. {
  64486. const Rectangle<int>* const r = iter.getRectangle();
  64487. const int x1 = r->getX() << 8;
  64488. const int x2 = r->getRight() << 8;
  64489. int y = r->getY() - bounds.getY();
  64490. for (int j = r->getHeight(); --j >= 0;)
  64491. {
  64492. addEdgePoint (x1, y, 255);
  64493. addEdgePoint (x2, y, -255);
  64494. ++y;
  64495. }
  64496. }
  64497. sanitiseLevels (true);
  64498. }
  64499. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64500. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64501. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64502. 2 + (int) rectangleToAdd.getWidth(),
  64503. 2 + (int) rectangleToAdd.getHeight())),
  64504. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64505. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64506. needToCheckEmptinesss (true)
  64507. {
  64508. jassert (! rectangleToAdd.isEmpty());
  64509. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64510. table[0] = 0;
  64511. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64512. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64513. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64514. jassert (y1 < 256);
  64515. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64516. if (x2 <= x1 || y2 <= y1)
  64517. {
  64518. bounds.setHeight (0);
  64519. return;
  64520. }
  64521. int lineY = 0;
  64522. int* t = table;
  64523. if ((y1 >> 8) == (y2 >> 8))
  64524. {
  64525. t[0] = 2;
  64526. t[1] = x1;
  64527. t[2] = y2 - y1;
  64528. t[3] = x2;
  64529. t[4] = 0;
  64530. ++lineY;
  64531. t += lineStrideElements;
  64532. }
  64533. else
  64534. {
  64535. t[0] = 2;
  64536. t[1] = x1;
  64537. t[2] = 255 - (y1 & 255);
  64538. t[3] = x2;
  64539. t[4] = 0;
  64540. ++lineY;
  64541. t += lineStrideElements;
  64542. while (lineY < (y2 >> 8))
  64543. {
  64544. t[0] = 2;
  64545. t[1] = x1;
  64546. t[2] = 255;
  64547. t[3] = x2;
  64548. t[4] = 0;
  64549. ++lineY;
  64550. t += lineStrideElements;
  64551. }
  64552. jassert (lineY < bounds.getHeight());
  64553. t[0] = 2;
  64554. t[1] = x1;
  64555. t[2] = y2 & 255;
  64556. t[3] = x2;
  64557. t[4] = 0;
  64558. ++lineY;
  64559. t += lineStrideElements;
  64560. }
  64561. while (lineY < bounds.getHeight())
  64562. {
  64563. t[0] = 0;
  64564. t += lineStrideElements;
  64565. ++lineY;
  64566. }
  64567. }
  64568. EdgeTable::EdgeTable (const EdgeTable& other)
  64569. {
  64570. operator= (other);
  64571. }
  64572. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64573. {
  64574. bounds = other.bounds;
  64575. maxEdgesPerLine = other.maxEdgesPerLine;
  64576. lineStrideElements = other.lineStrideElements;
  64577. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64578. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64579. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64580. return *this;
  64581. }
  64582. EdgeTable::~EdgeTable()
  64583. {
  64584. }
  64585. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64586. {
  64587. while (--numLines >= 0)
  64588. {
  64589. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64590. src += srcLineStride;
  64591. dest += destLineStride;
  64592. }
  64593. }
  64594. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64595. {
  64596. // Convert the table from relative windings to absolute levels..
  64597. int* lineStart = table;
  64598. for (int i = bounds.getHeight(); --i >= 0;)
  64599. {
  64600. int* line = lineStart;
  64601. lineStart += lineStrideElements;
  64602. int num = *line;
  64603. if (num == 0)
  64604. continue;
  64605. int level = 0;
  64606. if (useNonZeroWinding)
  64607. {
  64608. while (--num > 0)
  64609. {
  64610. line += 2;
  64611. level += *line;
  64612. int corrected = abs (level);
  64613. if (corrected >> 8)
  64614. corrected = 255;
  64615. *line = corrected;
  64616. }
  64617. }
  64618. else
  64619. {
  64620. while (--num > 0)
  64621. {
  64622. line += 2;
  64623. level += *line;
  64624. int corrected = abs (level);
  64625. if (corrected >> 8)
  64626. {
  64627. corrected &= 511;
  64628. if (corrected >> 8)
  64629. corrected = 511 - corrected;
  64630. }
  64631. *line = corrected;
  64632. }
  64633. }
  64634. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64635. }
  64636. }
  64637. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64638. {
  64639. if (newNumEdgesPerLine != maxEdgesPerLine)
  64640. {
  64641. maxEdgesPerLine = newNumEdgesPerLine;
  64642. jassert (bounds.getHeight() > 0);
  64643. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64644. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64645. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64646. table.swapWith (newTable);
  64647. lineStrideElements = newLineStrideElements;
  64648. }
  64649. }
  64650. void EdgeTable::optimiseTable() throw()
  64651. {
  64652. int maxLineElements = 0;
  64653. for (int i = bounds.getHeight(); --i >= 0;)
  64654. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64655. remapTableForNumEdges (maxLineElements);
  64656. }
  64657. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64658. {
  64659. jassert (y >= 0 && y < bounds.getHeight());
  64660. int* line = table + lineStrideElements * y;
  64661. const int numPoints = line[0];
  64662. int n = numPoints << 1;
  64663. if (n > 0)
  64664. {
  64665. while (n > 0)
  64666. {
  64667. const int cx = line [n - 1];
  64668. if (cx <= x)
  64669. {
  64670. if (cx == x)
  64671. {
  64672. line [n] += winding;
  64673. return;
  64674. }
  64675. break;
  64676. }
  64677. n -= 2;
  64678. }
  64679. if (numPoints >= maxEdgesPerLine)
  64680. {
  64681. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64682. jassert (numPoints < maxEdgesPerLine);
  64683. line = table + lineStrideElements * y;
  64684. }
  64685. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64686. }
  64687. line [n + 1] = x;
  64688. line [n + 2] = winding;
  64689. line[0]++;
  64690. }
  64691. void EdgeTable::translate (float dx, const int dy) throw()
  64692. {
  64693. bounds.translate ((int) std::floor (dx), dy);
  64694. int* lineStart = table;
  64695. const int intDx = (int) (dx * 256.0f);
  64696. for (int i = bounds.getHeight(); --i >= 0;)
  64697. {
  64698. int* line = lineStart;
  64699. lineStart += lineStrideElements;
  64700. int num = *line++;
  64701. while (--num >= 0)
  64702. {
  64703. *line += intDx;
  64704. line += 2;
  64705. }
  64706. }
  64707. }
  64708. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64709. {
  64710. jassert (y >= 0 && y < bounds.getHeight());
  64711. int* dest = table + lineStrideElements * y;
  64712. if (dest[0] == 0)
  64713. return;
  64714. int otherNumPoints = *otherLine;
  64715. if (otherNumPoints == 0)
  64716. {
  64717. *dest = 0;
  64718. return;
  64719. }
  64720. const int right = bounds.getRight() << 8;
  64721. // optimise for the common case where our line lies entirely within a
  64722. // single pair of points, as happens when clipping to a simple rect.
  64723. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64724. {
  64725. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64726. return;
  64727. }
  64728. ++otherLine;
  64729. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64730. int* temp = (int*) alloca (lineSizeBytes);
  64731. memcpy (temp, dest, lineSizeBytes);
  64732. const int* src1 = temp;
  64733. int srcNum1 = *src1++;
  64734. int x1 = *src1++;
  64735. const int* src2 = otherLine;
  64736. int srcNum2 = otherNumPoints;
  64737. int x2 = *src2++;
  64738. int destIndex = 0, destTotal = 0;
  64739. int level1 = 0, level2 = 0;
  64740. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64741. while (srcNum1 > 0 && srcNum2 > 0)
  64742. {
  64743. int nextX;
  64744. if (x1 < x2)
  64745. {
  64746. nextX = x1;
  64747. level1 = *src1++;
  64748. x1 = *src1++;
  64749. --srcNum1;
  64750. }
  64751. else if (x1 == x2)
  64752. {
  64753. nextX = x1;
  64754. level1 = *src1++;
  64755. level2 = *src2++;
  64756. x1 = *src1++;
  64757. x2 = *src2++;
  64758. --srcNum1;
  64759. --srcNum2;
  64760. }
  64761. else
  64762. {
  64763. nextX = x2;
  64764. level2 = *src2++;
  64765. x2 = *src2++;
  64766. --srcNum2;
  64767. }
  64768. if (nextX > lastX)
  64769. {
  64770. if (nextX >= right)
  64771. break;
  64772. lastX = nextX;
  64773. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64774. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64775. if (nextLevel != lastLevel)
  64776. {
  64777. if (destTotal >= maxEdgesPerLine)
  64778. {
  64779. dest[0] = destTotal;
  64780. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64781. dest = table + lineStrideElements * y;
  64782. }
  64783. ++destTotal;
  64784. lastLevel = nextLevel;
  64785. dest[++destIndex] = nextX;
  64786. dest[++destIndex] = nextLevel;
  64787. }
  64788. }
  64789. }
  64790. if (lastLevel > 0)
  64791. {
  64792. if (destTotal >= maxEdgesPerLine)
  64793. {
  64794. dest[0] = destTotal;
  64795. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64796. dest = table + lineStrideElements * y;
  64797. }
  64798. ++destTotal;
  64799. dest[++destIndex] = right;
  64800. dest[++destIndex] = 0;
  64801. }
  64802. dest[0] = destTotal;
  64803. #if JUCE_DEBUG
  64804. int last = std::numeric_limits<int>::min();
  64805. for (int i = 0; i < dest[0]; ++i)
  64806. {
  64807. jassert (dest[i * 2 + 1] > last);
  64808. last = dest[i * 2 + 1];
  64809. }
  64810. jassert (dest [dest[0] * 2] == 0);
  64811. #endif
  64812. }
  64813. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64814. {
  64815. int* lastItem = dest + (dest[0] * 2 - 1);
  64816. if (x2 < lastItem[0])
  64817. {
  64818. if (x2 <= dest[1])
  64819. {
  64820. dest[0] = 0;
  64821. return;
  64822. }
  64823. while (x2 < lastItem[-2])
  64824. {
  64825. --(dest[0]);
  64826. lastItem -= 2;
  64827. }
  64828. lastItem[0] = x2;
  64829. lastItem[1] = 0;
  64830. }
  64831. if (x1 > dest[1])
  64832. {
  64833. while (lastItem[0] > x1)
  64834. lastItem -= 2;
  64835. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64836. if (itemsRemoved > 0)
  64837. {
  64838. dest[0] -= itemsRemoved;
  64839. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64840. }
  64841. dest[1] = x1;
  64842. }
  64843. }
  64844. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64845. {
  64846. const Rectangle<int> clipped (r.getIntersection (bounds));
  64847. if (clipped.isEmpty())
  64848. {
  64849. needToCheckEmptinesss = false;
  64850. bounds.setHeight (0);
  64851. }
  64852. else
  64853. {
  64854. const int top = clipped.getY() - bounds.getY();
  64855. const int bottom = clipped.getBottom() - bounds.getY();
  64856. if (bottom < bounds.getHeight())
  64857. bounds.setHeight (bottom);
  64858. if (clipped.getRight() < bounds.getRight())
  64859. bounds.setRight (clipped.getRight());
  64860. for (int i = top; --i >= 0;)
  64861. table [lineStrideElements * i] = 0;
  64862. if (clipped.getX() > bounds.getX())
  64863. {
  64864. const int x1 = clipped.getX() << 8;
  64865. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64866. int* line = table + lineStrideElements * top;
  64867. for (int i = bottom - top; --i >= 0;)
  64868. {
  64869. if (line[0] != 0)
  64870. clipEdgeTableLineToRange (line, x1, x2);
  64871. line += lineStrideElements;
  64872. }
  64873. }
  64874. needToCheckEmptinesss = true;
  64875. }
  64876. }
  64877. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64878. {
  64879. const Rectangle<int> clipped (r.getIntersection (bounds));
  64880. if (! clipped.isEmpty())
  64881. {
  64882. const int top = clipped.getY() - bounds.getY();
  64883. const int bottom = clipped.getBottom() - bounds.getY();
  64884. //XXX optimise here by shortening the table if it fills top or bottom
  64885. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64886. clipped.getX() << 8, 0,
  64887. clipped.getRight() << 8, 255,
  64888. std::numeric_limits<int>::max(), 0 };
  64889. for (int i = top; i < bottom; ++i)
  64890. intersectWithEdgeTableLine (i, rectLine);
  64891. needToCheckEmptinesss = true;
  64892. }
  64893. }
  64894. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64895. {
  64896. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64897. if (clipped.isEmpty())
  64898. {
  64899. needToCheckEmptinesss = false;
  64900. bounds.setHeight (0);
  64901. }
  64902. else
  64903. {
  64904. const int top = clipped.getY() - bounds.getY();
  64905. const int bottom = clipped.getBottom() - bounds.getY();
  64906. if (bottom < bounds.getHeight())
  64907. bounds.setHeight (bottom);
  64908. if (clipped.getRight() < bounds.getRight())
  64909. bounds.setRight (clipped.getRight());
  64910. int i = 0;
  64911. for (i = top; --i >= 0;)
  64912. table [lineStrideElements * i] = 0;
  64913. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64914. for (i = top; i < bottom; ++i)
  64915. {
  64916. intersectWithEdgeTableLine (i, otherLine);
  64917. otherLine += other.lineStrideElements;
  64918. }
  64919. needToCheckEmptinesss = true;
  64920. }
  64921. }
  64922. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64923. {
  64924. y -= bounds.getY();
  64925. if (y < 0 || y >= bounds.getHeight())
  64926. return;
  64927. needToCheckEmptinesss = true;
  64928. if (numPixels <= 0)
  64929. {
  64930. table [lineStrideElements * y] = 0;
  64931. return;
  64932. }
  64933. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64934. int destIndex = 0, lastLevel = 0;
  64935. while (--numPixels >= 0)
  64936. {
  64937. const int alpha = *mask;
  64938. mask += maskStride;
  64939. if (alpha != lastLevel)
  64940. {
  64941. tempLine[++destIndex] = (x << 8);
  64942. tempLine[++destIndex] = alpha;
  64943. lastLevel = alpha;
  64944. }
  64945. ++x;
  64946. }
  64947. if (lastLevel > 0)
  64948. {
  64949. tempLine[++destIndex] = (x << 8);
  64950. tempLine[++destIndex] = 0;
  64951. }
  64952. tempLine[0] = destIndex >> 1;
  64953. intersectWithEdgeTableLine (y, tempLine);
  64954. }
  64955. bool EdgeTable::isEmpty() throw()
  64956. {
  64957. if (needToCheckEmptinesss)
  64958. {
  64959. needToCheckEmptinesss = false;
  64960. int* t = table;
  64961. for (int i = bounds.getHeight(); --i >= 0;)
  64962. {
  64963. if (t[0] > 1)
  64964. return false;
  64965. t += lineStrideElements;
  64966. }
  64967. bounds.setHeight (0);
  64968. }
  64969. return bounds.getHeight() == 0;
  64970. }
  64971. END_JUCE_NAMESPACE
  64972. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64973. /*** Start of inlined file: juce_FillType.cpp ***/
  64974. BEGIN_JUCE_NAMESPACE
  64975. FillType::FillType() throw()
  64976. : colour (0xff000000), image (0)
  64977. {
  64978. }
  64979. FillType::FillType (const Colour& colour_) throw()
  64980. : colour (colour_), image (0)
  64981. {
  64982. }
  64983. FillType::FillType (const ColourGradient& gradient_)
  64984. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64985. {
  64986. }
  64987. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64988. : colour (0xff000000), image (image_), transform (transform_)
  64989. {
  64990. }
  64991. FillType::FillType (const FillType& other)
  64992. : colour (other.colour),
  64993. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64994. image (other.image), transform (other.transform)
  64995. {
  64996. }
  64997. FillType& FillType::operator= (const FillType& other)
  64998. {
  64999. if (this != &other)
  65000. {
  65001. colour = other.colour;
  65002. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65003. image = other.image;
  65004. transform = other.transform;
  65005. }
  65006. return *this;
  65007. }
  65008. FillType::~FillType() throw()
  65009. {
  65010. }
  65011. bool FillType::operator== (const FillType& other) const
  65012. {
  65013. return colour == other.colour && image == other.image
  65014. && transform == other.transform
  65015. && (gradient == other.gradient
  65016. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65017. }
  65018. bool FillType::operator!= (const FillType& other) const
  65019. {
  65020. return ! operator== (other);
  65021. }
  65022. void FillType::setColour (const Colour& newColour) throw()
  65023. {
  65024. gradient = 0;
  65025. image = Image();
  65026. colour = newColour;
  65027. }
  65028. void FillType::setGradient (const ColourGradient& newGradient)
  65029. {
  65030. if (gradient != 0)
  65031. {
  65032. *gradient = newGradient;
  65033. }
  65034. else
  65035. {
  65036. image = Image();
  65037. gradient = new ColourGradient (newGradient);
  65038. colour = Colours::black;
  65039. }
  65040. }
  65041. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65042. {
  65043. gradient = 0;
  65044. image = image_;
  65045. transform = transform_;
  65046. colour = Colours::black;
  65047. }
  65048. void FillType::setOpacity (const float newOpacity) throw()
  65049. {
  65050. colour = colour.withAlpha (newOpacity);
  65051. }
  65052. bool FillType::isInvisible() const throw()
  65053. {
  65054. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65055. }
  65056. END_JUCE_NAMESPACE
  65057. /*** End of inlined file: juce_FillType.cpp ***/
  65058. /*** Start of inlined file: juce_Graphics.cpp ***/
  65059. BEGIN_JUCE_NAMESPACE
  65060. template <typename Type>
  65061. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65062. {
  65063. const int maxVal = 0x3fffffff;
  65064. return (int) x >= -maxVal && (int) x <= maxVal
  65065. && (int) y >= -maxVal && (int) y <= maxVal
  65066. && (int) w >= -maxVal && (int) w <= maxVal
  65067. && (int) h >= -maxVal && (int) h <= maxVal;
  65068. }
  65069. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65070. {
  65071. }
  65072. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65073. {
  65074. }
  65075. Graphics::Graphics (const Image& imageToDrawOnto)
  65076. : context (imageToDrawOnto.createLowLevelContext()),
  65077. contextToDelete (context),
  65078. saveStatePending (false)
  65079. {
  65080. }
  65081. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  65082. : context (internalContext),
  65083. saveStatePending (false)
  65084. {
  65085. }
  65086. Graphics::~Graphics()
  65087. {
  65088. }
  65089. void Graphics::resetToDefaultState()
  65090. {
  65091. saveStateIfPending();
  65092. context->setFill (FillType());
  65093. context->setFont (Font());
  65094. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  65095. }
  65096. bool Graphics::isVectorDevice() const
  65097. {
  65098. return context->isVectorDevice();
  65099. }
  65100. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  65101. {
  65102. saveStateIfPending();
  65103. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  65104. }
  65105. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  65106. {
  65107. saveStateIfPending();
  65108. return context->clipToRectangleList (clipRegion);
  65109. }
  65110. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  65111. {
  65112. saveStateIfPending();
  65113. context->clipToPath (path, transform);
  65114. return ! context->isClipEmpty();
  65115. }
  65116. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  65117. {
  65118. saveStateIfPending();
  65119. context->clipToImageAlpha (image, sourceClipRegion, transform);
  65120. return ! context->isClipEmpty();
  65121. }
  65122. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  65123. {
  65124. saveStateIfPending();
  65125. context->excludeClipRectangle (rectangleToExclude);
  65126. }
  65127. bool Graphics::isClipEmpty() const
  65128. {
  65129. return context->isClipEmpty();
  65130. }
  65131. const Rectangle<int> Graphics::getClipBounds() const
  65132. {
  65133. return context->getClipBounds();
  65134. }
  65135. void Graphics::saveState()
  65136. {
  65137. saveStateIfPending();
  65138. saveStatePending = true;
  65139. }
  65140. void Graphics::restoreState()
  65141. {
  65142. if (saveStatePending)
  65143. saveStatePending = false;
  65144. else
  65145. context->restoreState();
  65146. }
  65147. void Graphics::saveStateIfPending()
  65148. {
  65149. if (saveStatePending)
  65150. {
  65151. saveStatePending = false;
  65152. context->saveState();
  65153. }
  65154. }
  65155. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  65156. {
  65157. saveStateIfPending();
  65158. context->setOrigin (newOriginX, newOriginY);
  65159. }
  65160. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  65161. {
  65162. return context->clipRegionIntersects (area);
  65163. }
  65164. void Graphics::setColour (const Colour& newColour)
  65165. {
  65166. saveStateIfPending();
  65167. context->setFill (newColour);
  65168. }
  65169. void Graphics::setOpacity (const float newOpacity)
  65170. {
  65171. saveStateIfPending();
  65172. context->setOpacity (newOpacity);
  65173. }
  65174. void Graphics::setGradientFill (const ColourGradient& gradient)
  65175. {
  65176. setFillType (gradient);
  65177. }
  65178. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  65179. {
  65180. saveStateIfPending();
  65181. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  65182. context->setOpacity (opacity);
  65183. }
  65184. void Graphics::setFillType (const FillType& newFill)
  65185. {
  65186. saveStateIfPending();
  65187. context->setFill (newFill);
  65188. }
  65189. void Graphics::setFont (const Font& newFont)
  65190. {
  65191. saveStateIfPending();
  65192. context->setFont (newFont);
  65193. }
  65194. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65195. {
  65196. saveStateIfPending();
  65197. Font f (context->getFont());
  65198. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65199. context->setFont (f);
  65200. }
  65201. const Font Graphics::getCurrentFont() const
  65202. {
  65203. return context->getFont();
  65204. }
  65205. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65206. {
  65207. if (text.isNotEmpty()
  65208. && startX < context->getClipBounds().getRight())
  65209. {
  65210. GlyphArrangement arr;
  65211. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65212. arr.draw (*this);
  65213. }
  65214. }
  65215. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65216. {
  65217. if (text.isNotEmpty())
  65218. {
  65219. GlyphArrangement arr;
  65220. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65221. arr.draw (*this, transform);
  65222. }
  65223. }
  65224. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65225. {
  65226. if (text.isNotEmpty()
  65227. && startX < context->getClipBounds().getRight())
  65228. {
  65229. GlyphArrangement arr;
  65230. arr.addJustifiedText (context->getFont(), text,
  65231. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65232. Justification::left);
  65233. arr.draw (*this);
  65234. }
  65235. }
  65236. void Graphics::drawText (const String& text,
  65237. const int x, const int y, const int width, const int height,
  65238. const Justification& justificationType,
  65239. const bool useEllipsesIfTooBig) const
  65240. {
  65241. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65242. {
  65243. GlyphArrangement arr;
  65244. arr.addCurtailedLineOfText (context->getFont(), text,
  65245. 0.0f, 0.0f, (float) width,
  65246. useEllipsesIfTooBig);
  65247. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  65248. (float) x, (float) y, (float) width, (float) height,
  65249. justificationType);
  65250. arr.draw (*this);
  65251. }
  65252. }
  65253. void Graphics::drawFittedText (const String& text,
  65254. const int x, const int y, const int width, const int height,
  65255. const Justification& justification,
  65256. const int maximumNumberOfLines,
  65257. const float minimumHorizontalScale) const
  65258. {
  65259. if (text.isNotEmpty()
  65260. && width > 0 && height > 0
  65261. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65262. {
  65263. GlyphArrangement arr;
  65264. arr.addFittedText (context->getFont(), text,
  65265. (float) x, (float) y, (float) width, (float) height,
  65266. justification,
  65267. maximumNumberOfLines,
  65268. minimumHorizontalScale);
  65269. arr.draw (*this);
  65270. }
  65271. }
  65272. void Graphics::fillRect (int x, int y, int width, int height) const
  65273. {
  65274. // passing in a silly number can cause maths problems in rendering!
  65275. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65276. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65277. }
  65278. void Graphics::fillRect (const Rectangle<int>& r) const
  65279. {
  65280. context->fillRect (r, false);
  65281. }
  65282. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  65283. {
  65284. // passing in a silly number can cause maths problems in rendering!
  65285. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65286. Path p;
  65287. p.addRectangle (x, y, width, height);
  65288. fillPath (p);
  65289. }
  65290. void Graphics::setPixel (int x, int y) const
  65291. {
  65292. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  65293. }
  65294. void Graphics::fillAll() const
  65295. {
  65296. fillRect (context->getClipBounds());
  65297. }
  65298. void Graphics::fillAll (const Colour& colourToUse) const
  65299. {
  65300. if (! colourToUse.isTransparent())
  65301. {
  65302. const Rectangle<int> clip (context->getClipBounds());
  65303. context->saveState();
  65304. context->setFill (colourToUse);
  65305. context->fillRect (clip, false);
  65306. context->restoreState();
  65307. }
  65308. }
  65309. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  65310. {
  65311. if ((! context->isClipEmpty()) && ! path.isEmpty())
  65312. context->fillPath (path, transform);
  65313. }
  65314. void Graphics::strokePath (const Path& path,
  65315. const PathStrokeType& strokeType,
  65316. const AffineTransform& transform) const
  65317. {
  65318. Path stroke;
  65319. strokeType.createStrokedPath (stroke, path, transform);
  65320. fillPath (stroke);
  65321. }
  65322. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  65323. const int lineThickness) const
  65324. {
  65325. // passing in a silly number can cause maths problems in rendering!
  65326. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65327. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  65328. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65329. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65330. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  65331. }
  65332. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  65333. {
  65334. // passing in a silly number can cause maths problems in rendering!
  65335. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65336. Path p;
  65337. p.addRectangle (x, y, width, lineThickness);
  65338. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65339. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65340. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  65341. fillPath (p);
  65342. }
  65343. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  65344. {
  65345. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  65346. }
  65347. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  65348. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  65349. const bool useGradient, const bool sharpEdgeOnOutside) const
  65350. {
  65351. // passing in a silly number can cause maths problems in rendering!
  65352. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65353. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65354. {
  65355. context->saveState();
  65356. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  65357. const float ramp = oldOpacity / bevelThickness;
  65358. for (int i = bevelThickness; --i >= 0;)
  65359. {
  65360. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  65361. : oldOpacity;
  65362. context->setFill (topLeftColour.withMultipliedAlpha (op));
  65363. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  65364. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  65365. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  65366. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  65367. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  65368. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  65369. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  65370. }
  65371. context->restoreState();
  65372. }
  65373. }
  65374. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  65375. {
  65376. // passing in a silly number can cause maths problems in rendering!
  65377. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65378. Path p;
  65379. p.addEllipse (x, y, width, height);
  65380. fillPath (p);
  65381. }
  65382. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  65383. const float lineThickness) const
  65384. {
  65385. // passing in a silly number can cause maths problems in rendering!
  65386. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65387. Path p;
  65388. p.addEllipse (x, y, width, height);
  65389. strokePath (p, PathStrokeType (lineThickness));
  65390. }
  65391. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  65392. {
  65393. // passing in a silly number can cause maths problems in rendering!
  65394. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65395. Path p;
  65396. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65397. fillPath (p);
  65398. }
  65399. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  65400. {
  65401. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  65402. }
  65403. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  65404. const float cornerSize, const float lineThickness) const
  65405. {
  65406. // passing in a silly number can cause maths problems in rendering!
  65407. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65408. Path p;
  65409. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65410. strokePath (p, PathStrokeType (lineThickness));
  65411. }
  65412. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  65413. {
  65414. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  65415. }
  65416. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65417. {
  65418. Path p;
  65419. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  65420. fillPath (p);
  65421. }
  65422. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  65423. const int checkWidth, const int checkHeight,
  65424. const Colour& colour1, const Colour& colour2) const
  65425. {
  65426. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65427. if (checkWidth > 0 && checkHeight > 0)
  65428. {
  65429. context->saveState();
  65430. if (colour1 == colour2)
  65431. {
  65432. context->setFill (colour1);
  65433. context->fillRect (area, false);
  65434. }
  65435. else
  65436. {
  65437. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  65438. if (! clipped.isEmpty())
  65439. {
  65440. context->clipToRectangle (clipped);
  65441. const int startX = area.getX() + ((clipped.getX() - area.getX()) / checkWidth) * checkWidth;
  65442. const int startY = area.getY() + ((clipped.getY() - area.getY()) / checkHeight) * checkHeight;
  65443. const int right = clipped.getRight();
  65444. const int bottom = clipped.getBottom();
  65445. for (int i = 0; i < 2; ++i)
  65446. {
  65447. context->setFill (i == 0 ? colour1 : colour2);
  65448. int cy = i;
  65449. for (int y = startY; y < bottom; y += checkHeight)
  65450. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  65451. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  65452. }
  65453. }
  65454. }
  65455. context->restoreState();
  65456. }
  65457. }
  65458. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65459. {
  65460. context->drawVerticalLine (x, top, bottom);
  65461. }
  65462. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65463. {
  65464. context->drawHorizontalLine (y, left, right);
  65465. }
  65466. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65467. {
  65468. context->drawLine (Line<float> (x1, y1, x2, y2));
  65469. }
  65470. void Graphics::drawLine (const float startX, const float startY,
  65471. const float endX, const float endY,
  65472. const float lineThickness) const
  65473. {
  65474. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  65475. }
  65476. void Graphics::drawLine (const Line<float>& line) const
  65477. {
  65478. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65479. }
  65480. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65481. {
  65482. Path p;
  65483. p.addLineSegment (line, lineThickness);
  65484. fillPath (p);
  65485. }
  65486. void Graphics::drawDashedLine (const float startX, const float startY,
  65487. const float endX, const float endY,
  65488. const float* const dashLengths,
  65489. const int numDashLengths,
  65490. const float lineThickness) const
  65491. {
  65492. const double dx = endX - startX;
  65493. const double dy = endY - startY;
  65494. const double totalLen = juce_hypot (dx, dy);
  65495. if (totalLen >= 0.5)
  65496. {
  65497. const double onePixAlpha = 1.0 / totalLen;
  65498. double alpha = 0.0;
  65499. float x = startX;
  65500. float y = startY;
  65501. int n = 0;
  65502. while (alpha < 1.0f)
  65503. {
  65504. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65505. n = n % numDashLengths;
  65506. const float oldX = x;
  65507. const float oldY = y;
  65508. x = (float) (startX + dx * alpha);
  65509. y = (float) (startY + dy * alpha);
  65510. if ((n & 1) != 0)
  65511. {
  65512. if (lineThickness != 1.0f)
  65513. drawLine (oldX, oldY, x, y, lineThickness);
  65514. else
  65515. drawLine (oldX, oldY, x, y);
  65516. }
  65517. }
  65518. }
  65519. }
  65520. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65521. {
  65522. saveStateIfPending();
  65523. context->setInterpolationQuality (newQuality);
  65524. }
  65525. void Graphics::drawImageAt (const Image& imageToDraw,
  65526. const int topLeftX, const int topLeftY,
  65527. const bool fillAlphaChannelWithCurrentBrush) const
  65528. {
  65529. const int imageW = imageToDraw.getWidth();
  65530. const int imageH = imageToDraw.getHeight();
  65531. drawImage (imageToDraw,
  65532. topLeftX, topLeftY, imageW, imageH,
  65533. 0, 0, imageW, imageH,
  65534. fillAlphaChannelWithCurrentBrush);
  65535. }
  65536. void Graphics::drawImageWithin (const Image& imageToDraw,
  65537. const int destX, const int destY,
  65538. const int destW, const int destH,
  65539. const RectanglePlacement& placementWithinTarget,
  65540. const bool fillAlphaChannelWithCurrentBrush) const
  65541. {
  65542. // passing in a silly number can cause maths problems in rendering!
  65543. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65544. if (imageToDraw.isValid())
  65545. {
  65546. const int imageW = imageToDraw.getWidth();
  65547. const int imageH = imageToDraw.getHeight();
  65548. if (imageW > 0 && imageH > 0)
  65549. {
  65550. double newX = 0.0, newY = 0.0;
  65551. double newW = imageW;
  65552. double newH = imageH;
  65553. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65554. destX, destY, destW, destH);
  65555. if (newW > 0 && newH > 0)
  65556. {
  65557. drawImage (imageToDraw,
  65558. roundToInt (newX), roundToInt (newY),
  65559. roundToInt (newW), roundToInt (newH),
  65560. 0, 0, imageW, imageH,
  65561. fillAlphaChannelWithCurrentBrush);
  65562. }
  65563. }
  65564. }
  65565. }
  65566. void Graphics::drawImage (const Image& imageToDraw,
  65567. int dx, int dy, int dw, int dh,
  65568. int sx, int sy, int sw, int sh,
  65569. const bool fillAlphaChannelWithCurrentBrush) const
  65570. {
  65571. // passing in a silly number can cause maths problems in rendering!
  65572. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65573. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65574. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65575. {
  65576. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65577. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65578. .translated ((float) dx, (float) dy),
  65579. fillAlphaChannelWithCurrentBrush);
  65580. }
  65581. }
  65582. void Graphics::drawImageTransformed (const Image& imageToDraw,
  65583. const Rectangle<int>& imageSubRegion,
  65584. const AffineTransform& transform,
  65585. const bool fillAlphaChannelWithCurrentBrush) const
  65586. {
  65587. if (imageToDraw.isValid() && ! context->isClipEmpty())
  65588. {
  65589. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw.getBounds()));
  65590. if (fillAlphaChannelWithCurrentBrush)
  65591. {
  65592. context->saveState();
  65593. context->clipToImageAlpha (imageToDraw, srcClip, transform);
  65594. fillAll();
  65595. context->restoreState();
  65596. }
  65597. else
  65598. {
  65599. context->drawImage (imageToDraw, srcClip, transform, false);
  65600. }
  65601. }
  65602. }
  65603. END_JUCE_NAMESPACE
  65604. /*** End of inlined file: juce_Graphics.cpp ***/
  65605. /*** Start of inlined file: juce_Justification.cpp ***/
  65606. BEGIN_JUCE_NAMESPACE
  65607. Justification::Justification (const Justification& other) throw()
  65608. : flags (other.flags)
  65609. {
  65610. }
  65611. Justification& Justification::operator= (const Justification& other) throw()
  65612. {
  65613. flags = other.flags;
  65614. return *this;
  65615. }
  65616. int Justification::getOnlyVerticalFlags() const throw()
  65617. {
  65618. return flags & (top | bottom | verticallyCentred);
  65619. }
  65620. int Justification::getOnlyHorizontalFlags() const throw()
  65621. {
  65622. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65623. }
  65624. void Justification::applyToRectangle (int& x, int& y,
  65625. const int w, const int h,
  65626. const int spaceX, const int spaceY,
  65627. const int spaceW, const int spaceH) const throw()
  65628. {
  65629. if ((flags & horizontallyCentred) != 0)
  65630. x = spaceX + ((spaceW - w) >> 1);
  65631. else if ((flags & right) != 0)
  65632. x = spaceX + spaceW - w;
  65633. else
  65634. x = spaceX;
  65635. if ((flags & verticallyCentred) != 0)
  65636. y = spaceY + ((spaceH - h) >> 1);
  65637. else if ((flags & bottom) != 0)
  65638. y = spaceY + spaceH - h;
  65639. else
  65640. y = spaceY;
  65641. }
  65642. END_JUCE_NAMESPACE
  65643. /*** End of inlined file: juce_Justification.cpp ***/
  65644. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65645. BEGIN_JUCE_NAMESPACE
  65646. // this will throw an assertion if you try to draw something that's not
  65647. // possible in postscript
  65648. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65649. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65650. #define notPossibleInPostscriptAssert jassertfalse
  65651. #else
  65652. #define notPossibleInPostscriptAssert
  65653. #endif
  65654. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65655. const String& documentTitle,
  65656. const int totalWidth_,
  65657. const int totalHeight_)
  65658. : out (resultingPostScript),
  65659. totalWidth (totalWidth_),
  65660. totalHeight (totalHeight_),
  65661. needToClip (true)
  65662. {
  65663. stateStack.add (new SavedState());
  65664. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  65665. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65666. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65667. "\n%%BoundingBox: 0 0 600 824"
  65668. "\n%%Pages: 0"
  65669. "\n%%Creator: Raw Material Software JUCE"
  65670. "\n%%Title: " << documentTitle <<
  65671. "\n%%CreationDate: none"
  65672. "\n%%LanguageLevel: 2"
  65673. "\n%%EndComments"
  65674. "\n%%BeginProlog"
  65675. "\n%%BeginResource: JRes"
  65676. "\n/bd {bind def} bind def"
  65677. "\n/c {setrgbcolor} bd"
  65678. "\n/m {moveto} bd"
  65679. "\n/l {lineto} bd"
  65680. "\n/rl {rlineto} bd"
  65681. "\n/ct {curveto} bd"
  65682. "\n/cp {closepath} bd"
  65683. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65684. "\n/doclip {initclip newpath} bd"
  65685. "\n/endclip {clip newpath} bd"
  65686. "\n%%EndResource"
  65687. "\n%%EndProlog"
  65688. "\n%%BeginSetup"
  65689. "\n%%EndSetup"
  65690. "\n%%Page: 1 1"
  65691. "\n%%BeginPageSetup"
  65692. "\n%%EndPageSetup\n\n"
  65693. << "40 800 translate\n"
  65694. << scale << ' ' << scale << " scale\n\n";
  65695. }
  65696. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65697. {
  65698. }
  65699. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65700. {
  65701. return true;
  65702. }
  65703. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65704. {
  65705. if (x != 0 || y != 0)
  65706. {
  65707. stateStack.getLast()->xOffset += x;
  65708. stateStack.getLast()->yOffset += y;
  65709. needToClip = true;
  65710. }
  65711. }
  65712. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65713. {
  65714. needToClip = true;
  65715. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65716. }
  65717. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65718. {
  65719. needToClip = true;
  65720. return stateStack.getLast()->clip.clipTo (clipRegion);
  65721. }
  65722. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65723. {
  65724. needToClip = true;
  65725. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65726. }
  65727. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65728. {
  65729. writeClip();
  65730. Path p (path);
  65731. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65732. writePath (p);
  65733. out << "clip\n";
  65734. }
  65735. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65736. {
  65737. needToClip = true;
  65738. jassertfalse; // xxx
  65739. }
  65740. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65741. {
  65742. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65743. }
  65744. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65745. {
  65746. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65747. -stateStack.getLast()->yOffset);
  65748. }
  65749. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65750. {
  65751. return stateStack.getLast()->clip.isEmpty();
  65752. }
  65753. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65754. : xOffset (0),
  65755. yOffset (0)
  65756. {
  65757. }
  65758. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65759. {
  65760. }
  65761. void LowLevelGraphicsPostScriptRenderer::saveState()
  65762. {
  65763. stateStack.add (new SavedState (*stateStack.getLast()));
  65764. }
  65765. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65766. {
  65767. jassert (stateStack.size() > 0);
  65768. if (stateStack.size() > 0)
  65769. stateStack.removeLast();
  65770. }
  65771. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65772. {
  65773. if (needToClip)
  65774. {
  65775. needToClip = false;
  65776. out << "doclip ";
  65777. int itemsOnLine = 0;
  65778. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65779. {
  65780. if (++itemsOnLine == 6)
  65781. {
  65782. itemsOnLine = 0;
  65783. out << '\n';
  65784. }
  65785. const Rectangle<int>& r = *i.getRectangle();
  65786. out << r.getX() << ' ' << -r.getY() << ' '
  65787. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65788. }
  65789. out << "endclip\n";
  65790. }
  65791. }
  65792. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65793. {
  65794. Colour c (Colours::white.overlaidWith (colour));
  65795. if (lastColour != c)
  65796. {
  65797. lastColour = c;
  65798. out << String (c.getFloatRed(), 3) << ' '
  65799. << String (c.getFloatGreen(), 3) << ' '
  65800. << String (c.getFloatBlue(), 3) << " c\n";
  65801. }
  65802. }
  65803. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65804. {
  65805. out << String (x, 2) << ' '
  65806. << String (-y, 2) << ' ';
  65807. }
  65808. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65809. {
  65810. out << "newpath ";
  65811. float lastX = 0.0f;
  65812. float lastY = 0.0f;
  65813. int itemsOnLine = 0;
  65814. Path::Iterator i (path);
  65815. while (i.next())
  65816. {
  65817. if (++itemsOnLine == 4)
  65818. {
  65819. itemsOnLine = 0;
  65820. out << '\n';
  65821. }
  65822. switch (i.elementType)
  65823. {
  65824. case Path::Iterator::startNewSubPath:
  65825. writeXY (i.x1, i.y1);
  65826. lastX = i.x1;
  65827. lastY = i.y1;
  65828. out << "m ";
  65829. break;
  65830. case Path::Iterator::lineTo:
  65831. writeXY (i.x1, i.y1);
  65832. lastX = i.x1;
  65833. lastY = i.y1;
  65834. out << "l ";
  65835. break;
  65836. case Path::Iterator::quadraticTo:
  65837. {
  65838. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65839. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65840. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65841. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65842. writeXY (cp1x, cp1y);
  65843. writeXY (cp2x, cp2y);
  65844. writeXY (i.x2, i.y2);
  65845. out << "ct ";
  65846. lastX = i.x2;
  65847. lastY = i.y2;
  65848. }
  65849. break;
  65850. case Path::Iterator::cubicTo:
  65851. writeXY (i.x1, i.y1);
  65852. writeXY (i.x2, i.y2);
  65853. writeXY (i.x3, i.y3);
  65854. out << "ct ";
  65855. lastX = i.x3;
  65856. lastY = i.y3;
  65857. break;
  65858. case Path::Iterator::closePath:
  65859. out << "cp ";
  65860. break;
  65861. default:
  65862. jassertfalse;
  65863. break;
  65864. }
  65865. }
  65866. out << '\n';
  65867. }
  65868. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65869. {
  65870. out << "[ "
  65871. << trans.mat00 << ' '
  65872. << trans.mat10 << ' '
  65873. << trans.mat01 << ' '
  65874. << trans.mat11 << ' '
  65875. << trans.mat02 << ' '
  65876. << trans.mat12 << " ] concat ";
  65877. }
  65878. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65879. {
  65880. stateStack.getLast()->fillType = fillType;
  65881. }
  65882. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65883. {
  65884. }
  65885. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65886. {
  65887. }
  65888. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65889. {
  65890. if (stateStack.getLast()->fillType.isColour())
  65891. {
  65892. writeClip();
  65893. writeColour (stateStack.getLast()->fillType.colour);
  65894. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65895. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65896. }
  65897. else
  65898. {
  65899. Path p;
  65900. p.addRectangle (r);
  65901. fillPath (p, AffineTransform::identity);
  65902. }
  65903. }
  65904. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65905. {
  65906. if (stateStack.getLast()->fillType.isColour())
  65907. {
  65908. writeClip();
  65909. Path p (path);
  65910. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65911. (float) stateStack.getLast()->yOffset));
  65912. writePath (p);
  65913. writeColour (stateStack.getLast()->fillType.colour);
  65914. out << "fill\n";
  65915. }
  65916. else if (stateStack.getLast()->fillType.isGradient())
  65917. {
  65918. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65919. // postscript can't do semi-transparent ones.
  65920. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65921. writeClip();
  65922. out << "gsave ";
  65923. {
  65924. Path p (path);
  65925. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65926. writePath (p);
  65927. out << "clip\n";
  65928. }
  65929. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65930. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65931. // time-being, this just fills it with the average colour..
  65932. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65933. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65934. out << "grestore\n";
  65935. }
  65936. }
  65937. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65938. const int sx, const int sy,
  65939. const int maxW, const int maxH) const
  65940. {
  65941. out << "{<\n";
  65942. const int w = jmin (maxW, im.getWidth());
  65943. const int h = jmin (maxH, im.getHeight());
  65944. int charsOnLine = 0;
  65945. const Image::BitmapData srcData (im, 0, 0, w, h);
  65946. Colour pixel;
  65947. for (int y = h; --y >= 0;)
  65948. {
  65949. for (int x = 0; x < w; ++x)
  65950. {
  65951. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65952. if (x >= sx && y >= sy)
  65953. {
  65954. if (im.isARGB())
  65955. {
  65956. PixelARGB p (*(const PixelARGB*) pixelData);
  65957. p.unpremultiply();
  65958. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65959. }
  65960. else if (im.isRGB())
  65961. {
  65962. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65963. }
  65964. else
  65965. {
  65966. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65967. }
  65968. }
  65969. else
  65970. {
  65971. pixel = Colours::transparentWhite;
  65972. }
  65973. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65974. out << String::toHexString (pixelValues, 3, 0);
  65975. charsOnLine += 3;
  65976. if (charsOnLine > 100)
  65977. {
  65978. out << '\n';
  65979. charsOnLine = 0;
  65980. }
  65981. }
  65982. }
  65983. out << "\n>}\n";
  65984. }
  65985. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65986. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65987. {
  65988. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65989. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65990. writeClip();
  65991. out << "gsave ";
  65992. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65993. .scaled (1.0f, -1.0f));
  65994. RectangleList imageClip;
  65995. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65996. imageClip.clipTo (srcClip);
  65997. out << "newpath ";
  65998. int itemsOnLine = 0;
  65999. for (RectangleList::Iterator i (imageClip); i.next();)
  66000. {
  66001. if (++itemsOnLine == 6)
  66002. {
  66003. out << '\n';
  66004. itemsOnLine = 0;
  66005. }
  66006. const Rectangle<int>& r = *i.getRectangle();
  66007. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66008. }
  66009. out << " clip newpath\n";
  66010. out << w << ' ' << h << " scale\n";
  66011. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66012. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66013. out << "false 3 colorimage grestore\n";
  66014. needToClip = true;
  66015. }
  66016. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66017. {
  66018. Path p;
  66019. p.addLineSegment (line, 1.0f);
  66020. fillPath (p, AffineTransform::identity);
  66021. }
  66022. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66023. {
  66024. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66025. }
  66026. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66027. {
  66028. drawLine (Line<float> (left, (float) y, right, (float) y));
  66029. }
  66030. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66031. {
  66032. stateStack.getLast()->font = newFont;
  66033. }
  66034. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66035. {
  66036. return stateStack.getLast()->font;
  66037. }
  66038. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66039. {
  66040. Path p;
  66041. Font& font = stateStack.getLast()->font;
  66042. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66043. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66044. }
  66045. END_JUCE_NAMESPACE
  66046. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66047. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66048. BEGIN_JUCE_NAMESPACE
  66049. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  66050. #define JUCE_USE_SSE_INSTRUCTIONS 1
  66051. #endif
  66052. #if JUCE_MSVC
  66053. #pragma warning (push)
  66054. #pragma warning (disable: 4127) // "expression is constant" warning
  66055. #if JUCE_DEBUG
  66056. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  66057. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  66058. #endif
  66059. #endif
  66060. namespace SoftwareRendererClasses
  66061. {
  66062. template <class PixelType, bool replaceExisting = false>
  66063. class SolidColourEdgeTableRenderer
  66064. {
  66065. public:
  66066. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  66067. : data (data_),
  66068. sourceColour (colour)
  66069. {
  66070. if (sizeof (PixelType) == 3)
  66071. {
  66072. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  66073. && sourceColour.getGreen() == sourceColour.getBlue();
  66074. filler[0].set (sourceColour);
  66075. filler[1].set (sourceColour);
  66076. filler[2].set (sourceColour);
  66077. filler[3].set (sourceColour);
  66078. }
  66079. }
  66080. forcedinline void setEdgeTableYPos (const int y) throw()
  66081. {
  66082. linePixels = (PixelType*) data.getLinePointer (y);
  66083. }
  66084. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66085. {
  66086. if (replaceExisting)
  66087. linePixels[x].set (sourceColour);
  66088. else
  66089. linePixels[x].blend (sourceColour, alphaLevel);
  66090. }
  66091. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66092. {
  66093. if (replaceExisting)
  66094. linePixels[x].set (sourceColour);
  66095. else
  66096. linePixels[x].blend (sourceColour);
  66097. }
  66098. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  66099. {
  66100. PixelARGB p (sourceColour);
  66101. p.multiplyAlpha (alphaLevel);
  66102. PixelType* dest = linePixels + x;
  66103. if (replaceExisting || p.getAlpha() >= 0xff)
  66104. replaceLine (dest, p, width);
  66105. else
  66106. blendLine (dest, p, width);
  66107. }
  66108. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  66109. {
  66110. PixelType* dest = linePixels + x;
  66111. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  66112. replaceLine (dest, sourceColour, width);
  66113. else
  66114. blendLine (dest, sourceColour, width);
  66115. }
  66116. private:
  66117. const Image::BitmapData& data;
  66118. PixelType* linePixels;
  66119. PixelARGB sourceColour;
  66120. PixelRGB filler [4];
  66121. bool areRGBComponentsEqual;
  66122. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  66123. {
  66124. do
  66125. {
  66126. dest->blend (colour);
  66127. ++dest;
  66128. } while (--width > 0);
  66129. }
  66130. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  66131. {
  66132. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  66133. {
  66134. memset (dest, colour.getRed(), width * 3);
  66135. }
  66136. else
  66137. {
  66138. if (width >> 5)
  66139. {
  66140. const int* const intFiller = (const int*) filler;
  66141. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  66142. {
  66143. dest->set (colour);
  66144. ++dest;
  66145. --width;
  66146. }
  66147. while (width > 4)
  66148. {
  66149. ((int*) dest) [0] = intFiller[0];
  66150. ((int*) dest) [1] = intFiller[1];
  66151. ((int*) dest) [2] = intFiller[2];
  66152. dest = (PixelRGB*) (((uint8*) dest) + 12);
  66153. width -= 4;
  66154. }
  66155. }
  66156. while (--width >= 0)
  66157. {
  66158. dest->set (colour);
  66159. ++dest;
  66160. }
  66161. }
  66162. }
  66163. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  66164. {
  66165. memset (dest, colour.getAlpha(), width);
  66166. }
  66167. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  66168. {
  66169. do
  66170. {
  66171. dest->set (colour);
  66172. ++dest;
  66173. } while (--width > 0);
  66174. }
  66175. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  66176. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  66177. };
  66178. class LinearGradientPixelGenerator
  66179. {
  66180. public:
  66181. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  66182. : lookupTable (lookupTable_), numEntries (numEntries_)
  66183. {
  66184. jassert (numEntries_ >= 0);
  66185. Point<float> p1 (gradient.point1);
  66186. Point<float> p2 (gradient.point2);
  66187. if (! transform.isIdentity())
  66188. {
  66189. const Line<float> l (p2, p1);
  66190. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  66191. p1.applyTransform (transform);
  66192. p2.applyTransform (transform);
  66193. p3.applyTransform (transform);
  66194. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  66195. }
  66196. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66197. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66198. if (vertical)
  66199. {
  66200. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66201. start = roundToInt (p1.getY() * scale);
  66202. }
  66203. else if (horizontal)
  66204. {
  66205. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66206. start = roundToInt (p1.getX() * scale);
  66207. }
  66208. else
  66209. {
  66210. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66211. yTerm = p1.getY() - p1.getX() / grad;
  66212. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66213. grad *= scale;
  66214. }
  66215. }
  66216. forcedinline void setY (const int y) throw()
  66217. {
  66218. if (vertical)
  66219. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66220. else if (! horizontal)
  66221. start = roundToInt ((y - yTerm) * grad);
  66222. }
  66223. inline const PixelARGB getPixel (const int x) const throw()
  66224. {
  66225. return vertical ? linePix
  66226. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66227. }
  66228. private:
  66229. const PixelARGB* const lookupTable;
  66230. const int numEntries;
  66231. PixelARGB linePix;
  66232. int start, scale;
  66233. double grad, yTerm;
  66234. bool vertical, horizontal;
  66235. enum { numScaleBits = 12 };
  66236. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  66237. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  66238. };
  66239. class RadialGradientPixelGenerator
  66240. {
  66241. public:
  66242. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  66243. const PixelARGB* const lookupTable_, const int numEntries_)
  66244. : lookupTable (lookupTable_),
  66245. numEntries (numEntries_),
  66246. gx1 (gradient.point1.getX()),
  66247. gy1 (gradient.point1.getY())
  66248. {
  66249. jassert (numEntries_ >= 0);
  66250. const Point<float> diff (gradient.point1 - gradient.point2);
  66251. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  66252. invScale = numEntries / std::sqrt (maxDist);
  66253. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  66254. }
  66255. forcedinline void setY (const int y) throw()
  66256. {
  66257. dy = y - gy1;
  66258. dy *= dy;
  66259. }
  66260. inline const PixelARGB getPixel (const int px) const throw()
  66261. {
  66262. double x = px - gx1;
  66263. x *= x;
  66264. x += dy;
  66265. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  66266. }
  66267. protected:
  66268. const PixelARGB* const lookupTable;
  66269. const int numEntries;
  66270. const double gx1, gy1;
  66271. double maxDist, invScale, dy;
  66272. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  66273. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  66274. };
  66275. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  66276. {
  66277. public:
  66278. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  66279. const PixelARGB* const lookupTable_, const int numEntries_)
  66280. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  66281. inverseTransform (transform.inverted())
  66282. {
  66283. tM10 = inverseTransform.mat10;
  66284. tM00 = inverseTransform.mat00;
  66285. }
  66286. forcedinline void setY (const int y) throw()
  66287. {
  66288. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  66289. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  66290. }
  66291. inline const PixelARGB getPixel (const int px) const throw()
  66292. {
  66293. double x = px;
  66294. const double y = tM10 * x + lineYM11;
  66295. x = tM00 * x + lineYM01;
  66296. x *= x;
  66297. x += y * y;
  66298. if (x >= maxDist)
  66299. return lookupTable [numEntries];
  66300. else
  66301. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  66302. }
  66303. private:
  66304. double tM10, tM00, lineYM01, lineYM11;
  66305. const AffineTransform inverseTransform;
  66306. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  66307. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  66308. };
  66309. template <class PixelType, class GradientType>
  66310. class GradientEdgeTableRenderer : public GradientType
  66311. {
  66312. public:
  66313. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  66314. const PixelARGB* const lookupTable_, const int numEntries_)
  66315. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  66316. destData (destData_)
  66317. {
  66318. }
  66319. forcedinline void setEdgeTableYPos (const int y) throw()
  66320. {
  66321. linePixels = (PixelType*) destData.getLinePointer (y);
  66322. GradientType::setY (y);
  66323. }
  66324. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66325. {
  66326. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  66327. }
  66328. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66329. {
  66330. linePixels[x].blend (GradientType::getPixel (x));
  66331. }
  66332. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  66333. {
  66334. PixelType* dest = linePixels + x;
  66335. if (alphaLevel < 0xff)
  66336. {
  66337. do
  66338. {
  66339. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  66340. } while (--width > 0);
  66341. }
  66342. else
  66343. {
  66344. do
  66345. {
  66346. (dest++)->blend (GradientType::getPixel (x++));
  66347. } while (--width > 0);
  66348. }
  66349. }
  66350. void handleEdgeTableLineFull (int x, int width) const throw()
  66351. {
  66352. PixelType* dest = linePixels + x;
  66353. do
  66354. {
  66355. (dest++)->blend (GradientType::getPixel (x++));
  66356. } while (--width > 0);
  66357. }
  66358. private:
  66359. const Image::BitmapData& destData;
  66360. PixelType* linePixels;
  66361. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  66362. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  66363. };
  66364. static forcedinline int safeModulo (int n, const int divisor) throw()
  66365. {
  66366. jassert (divisor > 0);
  66367. n %= divisor;
  66368. return (n < 0) ? (n + divisor) : n;
  66369. }
  66370. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66371. class ImageFillEdgeTableRenderer
  66372. {
  66373. public:
  66374. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66375. const Image::BitmapData& srcData_,
  66376. const int extraAlpha_,
  66377. const int x, const int y)
  66378. : destData (destData_),
  66379. srcData (srcData_),
  66380. extraAlpha (extraAlpha_ + 1),
  66381. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  66382. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  66383. {
  66384. }
  66385. forcedinline void setEdgeTableYPos (int y) throw()
  66386. {
  66387. linePixels = (DestPixelType*) destData.getLinePointer (y);
  66388. y -= yOffset;
  66389. if (repeatPattern)
  66390. {
  66391. jassert (y >= 0);
  66392. y %= srcData.height;
  66393. }
  66394. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  66395. }
  66396. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  66397. {
  66398. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66399. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  66400. }
  66401. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66402. {
  66403. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  66404. }
  66405. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  66406. {
  66407. DestPixelType* dest = linePixels + x;
  66408. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66409. x -= xOffset;
  66410. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66411. if (alphaLevel < 0xfe)
  66412. {
  66413. do
  66414. {
  66415. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  66416. } while (--width > 0);
  66417. }
  66418. else
  66419. {
  66420. if (repeatPattern)
  66421. {
  66422. do
  66423. {
  66424. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66425. } while (--width > 0);
  66426. }
  66427. else
  66428. {
  66429. copyRow (dest, sourceLineStart + x, width);
  66430. }
  66431. }
  66432. }
  66433. void handleEdgeTableLineFull (int x, int width) const throw()
  66434. {
  66435. DestPixelType* dest = linePixels + x;
  66436. x -= xOffset;
  66437. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66438. if (extraAlpha < 0xfe)
  66439. {
  66440. do
  66441. {
  66442. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  66443. } while (--width > 0);
  66444. }
  66445. else
  66446. {
  66447. if (repeatPattern)
  66448. {
  66449. do
  66450. {
  66451. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66452. } while (--width > 0);
  66453. }
  66454. else
  66455. {
  66456. copyRow (dest, sourceLineStart + x, width);
  66457. }
  66458. }
  66459. }
  66460. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66461. {
  66462. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66463. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66464. uint8* mask = (uint8*) (s + x - xOffset);
  66465. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66466. mask += PixelARGB::indexA;
  66467. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66468. }
  66469. private:
  66470. const Image::BitmapData& destData;
  66471. const Image::BitmapData& srcData;
  66472. const int extraAlpha, xOffset, yOffset;
  66473. DestPixelType* linePixels;
  66474. SrcPixelType* sourceLineStart;
  66475. template <class PixelType1, class PixelType2>
  66476. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66477. {
  66478. do
  66479. {
  66480. dest++ ->blend (*src++);
  66481. } while (--width > 0);
  66482. }
  66483. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66484. {
  66485. memcpy (dest, src, width * sizeof (PixelRGB));
  66486. }
  66487. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66488. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66489. };
  66490. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66491. class TransformedImageFillEdgeTableRenderer
  66492. {
  66493. public:
  66494. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66495. const Image::BitmapData& srcData_,
  66496. const AffineTransform& transform,
  66497. const int extraAlpha_,
  66498. const bool betterQuality_)
  66499. : interpolator (transform),
  66500. destData (destData_),
  66501. srcData (srcData_),
  66502. extraAlpha (extraAlpha_ + 1),
  66503. betterQuality (betterQuality_),
  66504. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66505. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66506. maxX (srcData_.width - 1),
  66507. maxY (srcData_.height - 1),
  66508. scratchSize (2048)
  66509. {
  66510. scratchBuffer.malloc (scratchSize);
  66511. }
  66512. ~TransformedImageFillEdgeTableRenderer()
  66513. {
  66514. }
  66515. forcedinline void setEdgeTableYPos (const int newY) throw()
  66516. {
  66517. y = newY;
  66518. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66519. }
  66520. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66521. {
  66522. alphaLevel *= extraAlpha;
  66523. alphaLevel >>= 8;
  66524. SrcPixelType p;
  66525. generate (&p, x, 1);
  66526. linePixels[x].blend (p, alphaLevel);
  66527. }
  66528. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  66529. {
  66530. SrcPixelType p;
  66531. generate (&p, x, 1);
  66532. linePixels[x].blend (p, extraAlpha);
  66533. }
  66534. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66535. {
  66536. if (width > scratchSize)
  66537. {
  66538. scratchSize = width;
  66539. scratchBuffer.malloc (scratchSize);
  66540. }
  66541. SrcPixelType* span = scratchBuffer;
  66542. generate (span, x, width);
  66543. DestPixelType* dest = linePixels + x;
  66544. alphaLevel *= extraAlpha;
  66545. alphaLevel >>= 8;
  66546. if (alphaLevel < 0xfe)
  66547. {
  66548. do
  66549. {
  66550. dest++ ->blend (*span++, alphaLevel);
  66551. } while (--width > 0);
  66552. }
  66553. else
  66554. {
  66555. do
  66556. {
  66557. dest++ ->blend (*span++);
  66558. } while (--width > 0);
  66559. }
  66560. }
  66561. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  66562. {
  66563. handleEdgeTableLine (x, width, 255);
  66564. }
  66565. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66566. {
  66567. if (width > scratchSize)
  66568. {
  66569. scratchSize = width;
  66570. scratchBuffer.malloc (scratchSize);
  66571. }
  66572. y = y_;
  66573. generate (scratchBuffer, x, width);
  66574. et.clipLineToMask (x, y_,
  66575. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66576. sizeof (SrcPixelType), width);
  66577. }
  66578. private:
  66579. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66580. {
  66581. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66582. do
  66583. {
  66584. int hiResX, hiResY;
  66585. this->interpolator.next (hiResX, hiResY);
  66586. hiResX += pixelOffsetInt;
  66587. hiResY += pixelOffsetInt;
  66588. int loResX = hiResX >> 8;
  66589. int loResY = hiResY >> 8;
  66590. if (repeatPattern)
  66591. {
  66592. loResX = safeModulo (loResX, srcData.width);
  66593. loResY = safeModulo (loResY, srcData.height);
  66594. }
  66595. if (betterQuality
  66596. && ((unsigned int) loResX) < (unsigned int) maxX
  66597. && ((unsigned int) loResY) < (unsigned int) maxY)
  66598. {
  66599. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66600. hiResX &= 255;
  66601. hiResY &= 255;
  66602. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66603. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66604. c[0] += weight * src[0];
  66605. c[1] += weight * src[1];
  66606. c[2] += weight * src[2];
  66607. c[3] += weight * src[3];
  66608. weight = hiResX * (256 - hiResY);
  66609. c[0] += weight * src[4];
  66610. c[1] += weight * src[5];
  66611. c[2] += weight * src[6];
  66612. c[3] += weight * src[7];
  66613. src += this->srcData.lineStride;
  66614. weight = (256 - hiResX) * hiResY;
  66615. c[0] += weight * src[0];
  66616. c[1] += weight * src[1];
  66617. c[2] += weight * src[2];
  66618. c[3] += weight * src[3];
  66619. weight = hiResX * hiResY;
  66620. c[0] += weight * src[4];
  66621. c[1] += weight * src[5];
  66622. c[2] += weight * src[6];
  66623. c[3] += weight * src[7];
  66624. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66625. (uint8) (c[PixelARGB::indexR] >> 16),
  66626. (uint8) (c[PixelARGB::indexG] >> 16),
  66627. (uint8) (c[PixelARGB::indexB] >> 16));
  66628. }
  66629. else
  66630. {
  66631. if (! repeatPattern)
  66632. {
  66633. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66634. if (loResX < 0) loResX = 0;
  66635. if (loResY < 0) loResY = 0;
  66636. if (loResX > maxX) loResX = maxX;
  66637. if (loResY > maxY) loResY = maxY;
  66638. }
  66639. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66640. }
  66641. ++dest;
  66642. } while (--numPixels > 0);
  66643. }
  66644. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66645. {
  66646. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66647. do
  66648. {
  66649. int hiResX, hiResY;
  66650. this->interpolator.next (hiResX, hiResY);
  66651. hiResX += pixelOffsetInt;
  66652. hiResY += pixelOffsetInt;
  66653. int loResX = hiResX >> 8;
  66654. int loResY = hiResY >> 8;
  66655. if (repeatPattern)
  66656. {
  66657. loResX = safeModulo (loResX, srcData.width);
  66658. loResY = safeModulo (loResY, srcData.height);
  66659. }
  66660. if (betterQuality
  66661. && ((unsigned int) loResX) < (unsigned int) maxX
  66662. && ((unsigned int) loResY) < (unsigned int) maxY)
  66663. {
  66664. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66665. hiResX &= 255;
  66666. hiResY &= 255;
  66667. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66668. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66669. c[0] += weight * src[0];
  66670. c[1] += weight * src[1];
  66671. c[2] += weight * src[2];
  66672. weight = hiResX * (256 - hiResY);
  66673. c[0] += weight * src[3];
  66674. c[1] += weight * src[4];
  66675. c[2] += weight * src[5];
  66676. src += this->srcData.lineStride;
  66677. weight = (256 - hiResX) * hiResY;
  66678. c[0] += weight * src[0];
  66679. c[1] += weight * src[1];
  66680. c[2] += weight * src[2];
  66681. weight = hiResX * hiResY;
  66682. c[0] += weight * src[3];
  66683. c[1] += weight * src[4];
  66684. c[2] += weight * src[5];
  66685. dest->setARGB ((uint8) 255,
  66686. (uint8) (c[PixelRGB::indexR] >> 16),
  66687. (uint8) (c[PixelRGB::indexG] >> 16),
  66688. (uint8) (c[PixelRGB::indexB] >> 16));
  66689. }
  66690. else
  66691. {
  66692. if (! repeatPattern)
  66693. {
  66694. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66695. if (loResX < 0) loResX = 0;
  66696. if (loResY < 0) loResY = 0;
  66697. if (loResX > maxX) loResX = maxX;
  66698. if (loResY > maxY) loResY = maxY;
  66699. }
  66700. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66701. }
  66702. ++dest;
  66703. } while (--numPixels > 0);
  66704. }
  66705. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66706. {
  66707. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66708. do
  66709. {
  66710. int hiResX, hiResY;
  66711. this->interpolator.next (hiResX, hiResY);
  66712. hiResX += pixelOffsetInt;
  66713. hiResY += pixelOffsetInt;
  66714. int loResX = hiResX >> 8;
  66715. int loResY = hiResY >> 8;
  66716. if (repeatPattern)
  66717. {
  66718. loResX = safeModulo (loResX, srcData.width);
  66719. loResY = safeModulo (loResY, srcData.height);
  66720. }
  66721. if (betterQuality
  66722. && ((unsigned int) loResX) < (unsigned int) maxX
  66723. && ((unsigned int) loResY) < (unsigned int) maxY)
  66724. {
  66725. hiResX &= 255;
  66726. hiResY &= 255;
  66727. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66728. uint32 c = 256 * 128;
  66729. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66730. c += src[1] * (hiResX * (256 - hiResY));
  66731. src += this->srcData.lineStride;
  66732. c += src[0] * ((256 - hiResX) * hiResY);
  66733. c += src[1] * (hiResX * hiResY);
  66734. *((uint8*) dest) = (uint8) c;
  66735. }
  66736. else
  66737. {
  66738. if (! repeatPattern)
  66739. {
  66740. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66741. if (loResX < 0) loResX = 0;
  66742. if (loResY < 0) loResY = 0;
  66743. if (loResX > maxX) loResX = maxX;
  66744. if (loResY > maxY) loResY = maxY;
  66745. }
  66746. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66747. }
  66748. ++dest;
  66749. } while (--numPixels > 0);
  66750. }
  66751. class TransformedImageSpanInterpolator
  66752. {
  66753. public:
  66754. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66755. : inverseTransform (transform.inverted())
  66756. {}
  66757. void setStartOfLine (float x, float y, const int numPixels) throw()
  66758. {
  66759. float x1 = x, y1 = y;
  66760. x += numPixels;
  66761. inverseTransform.transformPoints (x1, y1, x, y);
  66762. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66763. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66764. }
  66765. void next (int& x, int& y) throw()
  66766. {
  66767. x = xBresenham.n;
  66768. xBresenham.stepToNext();
  66769. y = yBresenham.n;
  66770. yBresenham.stepToNext();
  66771. }
  66772. private:
  66773. class BresenhamInterpolator
  66774. {
  66775. public:
  66776. BresenhamInterpolator() throw() {}
  66777. void set (const int n1, const int n2, const int numSteps_) throw()
  66778. {
  66779. numSteps = jmax (1, numSteps_);
  66780. step = (n2 - n1) / numSteps;
  66781. remainder = modulo = (n2 - n1) % numSteps;
  66782. n = n1;
  66783. if (modulo <= 0)
  66784. {
  66785. modulo += numSteps;
  66786. remainder += numSteps;
  66787. --step;
  66788. }
  66789. modulo -= numSteps;
  66790. }
  66791. forcedinline void stepToNext() throw()
  66792. {
  66793. modulo += remainder;
  66794. n += step;
  66795. if (modulo > 0)
  66796. {
  66797. modulo -= numSteps;
  66798. ++n;
  66799. }
  66800. }
  66801. int n;
  66802. private:
  66803. int numSteps, step, modulo, remainder;
  66804. };
  66805. const AffineTransform inverseTransform;
  66806. BresenhamInterpolator xBresenham, yBresenham;
  66807. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66808. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66809. };
  66810. TransformedImageSpanInterpolator interpolator;
  66811. const Image::BitmapData& destData;
  66812. const Image::BitmapData& srcData;
  66813. const int extraAlpha;
  66814. const bool betterQuality;
  66815. const float pixelOffset;
  66816. const int pixelOffsetInt, maxX, maxY;
  66817. int y;
  66818. DestPixelType* linePixels;
  66819. HeapBlock <SrcPixelType> scratchBuffer;
  66820. int scratchSize;
  66821. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66822. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66823. };
  66824. class ClipRegionBase : public ReferenceCountedObject
  66825. {
  66826. public:
  66827. ClipRegionBase() {}
  66828. virtual ~ClipRegionBase() {}
  66829. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66830. virtual const Ptr clone() const = 0;
  66831. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  66832. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66833. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66834. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66835. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66836. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66837. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66838. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66839. virtual const Rectangle<int> getClipBounds() const = 0;
  66840. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66841. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66842. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66843. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66844. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66845. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  66846. protected:
  66847. template <class Iterator>
  66848. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66849. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66850. {
  66851. switch (destData.pixelFormat)
  66852. {
  66853. case Image::ARGB:
  66854. switch (srcData.pixelFormat)
  66855. {
  66856. case Image::ARGB:
  66857. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66858. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66859. break;
  66860. case Image::RGB:
  66861. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66862. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66863. break;
  66864. default:
  66865. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66866. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66867. break;
  66868. }
  66869. break;
  66870. case Image::RGB:
  66871. switch (srcData.pixelFormat)
  66872. {
  66873. case Image::ARGB:
  66874. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66875. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66876. break;
  66877. case Image::RGB:
  66878. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66879. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66880. break;
  66881. default:
  66882. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66883. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66884. break;
  66885. }
  66886. break;
  66887. default:
  66888. switch (srcData.pixelFormat)
  66889. {
  66890. case Image::ARGB:
  66891. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66892. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66893. break;
  66894. case Image::RGB:
  66895. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66896. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66897. break;
  66898. default:
  66899. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66900. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66901. break;
  66902. }
  66903. break;
  66904. }
  66905. }
  66906. template <class Iterator>
  66907. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  66908. {
  66909. switch (destData.pixelFormat)
  66910. {
  66911. case Image::ARGB:
  66912. switch (srcData.pixelFormat)
  66913. {
  66914. case Image::ARGB:
  66915. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66916. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66917. break;
  66918. case Image::RGB:
  66919. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66920. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66921. break;
  66922. default:
  66923. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66924. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66925. break;
  66926. }
  66927. break;
  66928. case Image::RGB:
  66929. switch (srcData.pixelFormat)
  66930. {
  66931. case Image::ARGB:
  66932. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66933. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66934. break;
  66935. case Image::RGB:
  66936. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66937. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66938. break;
  66939. default:
  66940. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66941. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66942. break;
  66943. }
  66944. break;
  66945. default:
  66946. switch (srcData.pixelFormat)
  66947. {
  66948. case Image::ARGB:
  66949. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66950. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66951. break;
  66952. case Image::RGB:
  66953. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66954. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66955. break;
  66956. default:
  66957. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66958. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66959. break;
  66960. }
  66961. break;
  66962. }
  66963. }
  66964. template <class Iterator, class DestPixelType>
  66965. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66966. {
  66967. jassert (destData.pixelStride == sizeof (DestPixelType));
  66968. if (replaceContents)
  66969. {
  66970. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66971. iter.iterate (r);
  66972. }
  66973. else
  66974. {
  66975. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66976. iter.iterate (r);
  66977. }
  66978. }
  66979. template <class Iterator, class DestPixelType>
  66980. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66981. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66982. {
  66983. jassert (destData.pixelStride == sizeof (DestPixelType));
  66984. if (g.isRadial)
  66985. {
  66986. if (isIdentity)
  66987. {
  66988. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66989. iter.iterate (renderer);
  66990. }
  66991. else
  66992. {
  66993. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66994. iter.iterate (renderer);
  66995. }
  66996. }
  66997. else
  66998. {
  66999. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67000. iter.iterate (renderer);
  67001. }
  67002. }
  67003. };
  67004. class ClipRegion_EdgeTable : public ClipRegionBase
  67005. {
  67006. public:
  67007. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67008. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  67009. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  67010. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  67011. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  67012. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  67013. ~ClipRegion_EdgeTable() {}
  67014. const Ptr clone() const
  67015. {
  67016. return new ClipRegion_EdgeTable (*this);
  67017. }
  67018. const Ptr applyClipTo (const Ptr& target) const
  67019. {
  67020. return target->clipToEdgeTable (edgeTable);
  67021. }
  67022. const Ptr clipToRectangle (const Rectangle<int>& r)
  67023. {
  67024. edgeTable.clipToRectangle (r);
  67025. return edgeTable.isEmpty() ? 0 : this;
  67026. }
  67027. const Ptr clipToRectangleList (const RectangleList& r)
  67028. {
  67029. RectangleList inverse (edgeTable.getMaximumBounds());
  67030. if (inverse.subtract (r))
  67031. for (RectangleList::Iterator iter (inverse); iter.next();)
  67032. edgeTable.excludeRectangle (*iter.getRectangle());
  67033. return edgeTable.isEmpty() ? 0 : this;
  67034. }
  67035. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67036. {
  67037. edgeTable.excludeRectangle (r);
  67038. return edgeTable.isEmpty() ? 0 : this;
  67039. }
  67040. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67041. {
  67042. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  67043. edgeTable.clipToEdgeTable (et);
  67044. return edgeTable.isEmpty() ? 0 : this;
  67045. }
  67046. const Ptr clipToEdgeTable (const EdgeTable& et)
  67047. {
  67048. edgeTable.clipToEdgeTable (et);
  67049. return edgeTable.isEmpty() ? 0 : this;
  67050. }
  67051. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67052. {
  67053. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67054. if (transform.isOnlyTranslation())
  67055. {
  67056. // If our translation doesn't involve any distortion, just use a simple blit..
  67057. const int tx = (int) (transform.getTranslationX() * 256.0f);
  67058. const int ty = (int) (transform.getTranslationY() * 256.0f);
  67059. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67060. {
  67061. const int imageX = ((tx + 128) >> 8);
  67062. const int imageY = ((ty + 128) >> 8);
  67063. if (image.getFormat() == Image::ARGB)
  67064. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  67065. else
  67066. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  67067. return edgeTable.isEmpty() ? 0 : this;
  67068. }
  67069. }
  67070. if (transform.isSingularity())
  67071. return 0;
  67072. {
  67073. Path p;
  67074. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  67075. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  67076. edgeTable.clipToEdgeTable (et2);
  67077. }
  67078. if (! edgeTable.isEmpty())
  67079. {
  67080. if (image.getFormat() == Image::ARGB)
  67081. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  67082. else
  67083. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  67084. }
  67085. return edgeTable.isEmpty() ? 0 : this;
  67086. }
  67087. bool clipRegionIntersects (const Rectangle<int>& r) const
  67088. {
  67089. return edgeTable.getMaximumBounds().intersects (r);
  67090. }
  67091. const Rectangle<int> getClipBounds() const
  67092. {
  67093. return edgeTable.getMaximumBounds();
  67094. }
  67095. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67096. {
  67097. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  67098. const Rectangle<int> clipped (totalClip.getIntersection (area));
  67099. if (! clipped.isEmpty())
  67100. {
  67101. ClipRegion_EdgeTable et (clipped);
  67102. et.edgeTable.clipToEdgeTable (edgeTable);
  67103. et.fillAllWithColour (destData, colour, replaceContents);
  67104. }
  67105. }
  67106. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67107. {
  67108. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  67109. const Rectangle<float> clipped (totalClip.getIntersection (area));
  67110. if (! clipped.isEmpty())
  67111. {
  67112. ClipRegion_EdgeTable et (clipped);
  67113. et.edgeTable.clipToEdgeTable (edgeTable);
  67114. et.fillAllWithColour (destData, colour, false);
  67115. }
  67116. }
  67117. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67118. {
  67119. switch (destData.pixelFormat)
  67120. {
  67121. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67122. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67123. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67124. }
  67125. }
  67126. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67127. {
  67128. HeapBlock <PixelARGB> lookupTable;
  67129. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67130. jassert (numLookupEntries > 0);
  67131. switch (destData.pixelFormat)
  67132. {
  67133. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67134. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67135. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67136. }
  67137. }
  67138. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67139. {
  67140. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67141. }
  67142. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67143. {
  67144. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  67145. }
  67146. EdgeTable edgeTable;
  67147. private:
  67148. template <class SrcPixelType>
  67149. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  67150. {
  67151. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  67152. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  67153. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  67154. edgeTable.getMaximumBounds().getWidth());
  67155. }
  67156. template <class SrcPixelType>
  67157. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  67158. {
  67159. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  67160. edgeTable.clipToRectangle (r);
  67161. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  67162. for (int y = 0; y < r.getHeight(); ++y)
  67163. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  67164. }
  67165. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  67166. };
  67167. class ClipRegion_RectangleList : public ClipRegionBase
  67168. {
  67169. public:
  67170. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  67171. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  67172. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  67173. ~ClipRegion_RectangleList() {}
  67174. const Ptr clone() const
  67175. {
  67176. return new ClipRegion_RectangleList (*this);
  67177. }
  67178. const Ptr applyClipTo (const Ptr& target) const
  67179. {
  67180. return target->clipToRectangleList (clip);
  67181. }
  67182. const Ptr clipToRectangle (const Rectangle<int>& r)
  67183. {
  67184. clip.clipTo (r);
  67185. return clip.isEmpty() ? 0 : this;
  67186. }
  67187. const Ptr clipToRectangleList (const RectangleList& r)
  67188. {
  67189. clip.clipTo (r);
  67190. return clip.isEmpty() ? 0 : this;
  67191. }
  67192. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67193. {
  67194. clip.subtract (r);
  67195. return clip.isEmpty() ? 0 : this;
  67196. }
  67197. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67198. {
  67199. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67200. }
  67201. const Ptr clipToEdgeTable (const EdgeTable& et)
  67202. {
  67203. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67204. }
  67205. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67206. {
  67207. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  67208. }
  67209. bool clipRegionIntersects (const Rectangle<int>& r) const
  67210. {
  67211. return clip.intersects (r);
  67212. }
  67213. const Rectangle<int> getClipBounds() const
  67214. {
  67215. return clip.getBounds();
  67216. }
  67217. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67218. {
  67219. SubRectangleIterator iter (clip, area);
  67220. switch (destData.pixelFormat)
  67221. {
  67222. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67223. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67224. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67225. }
  67226. }
  67227. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67228. {
  67229. SubRectangleIteratorFloat iter (clip, area);
  67230. switch (destData.pixelFormat)
  67231. {
  67232. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67233. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67234. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  67235. }
  67236. }
  67237. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67238. {
  67239. switch (destData.pixelFormat)
  67240. {
  67241. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67242. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67243. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67244. }
  67245. }
  67246. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67247. {
  67248. HeapBlock <PixelARGB> lookupTable;
  67249. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67250. jassert (numLookupEntries > 0);
  67251. switch (destData.pixelFormat)
  67252. {
  67253. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67254. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67255. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67256. }
  67257. }
  67258. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67259. {
  67260. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67261. }
  67262. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67263. {
  67264. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  67265. }
  67266. RectangleList clip;
  67267. template <class Renderer>
  67268. void iterate (Renderer& r) const throw()
  67269. {
  67270. RectangleList::Iterator iter (clip);
  67271. while (iter.next())
  67272. {
  67273. const Rectangle<int> rect (*iter.getRectangle());
  67274. const int x = rect.getX();
  67275. const int w = rect.getWidth();
  67276. jassert (w > 0);
  67277. const int bottom = rect.getBottom();
  67278. for (int y = rect.getY(); y < bottom; ++y)
  67279. {
  67280. r.setEdgeTableYPos (y);
  67281. r.handleEdgeTableLineFull (x, w);
  67282. }
  67283. }
  67284. }
  67285. private:
  67286. class SubRectangleIterator
  67287. {
  67288. public:
  67289. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  67290. : clip (clip_), area (area_)
  67291. {
  67292. }
  67293. template <class Renderer>
  67294. void iterate (Renderer& r) const throw()
  67295. {
  67296. RectangleList::Iterator iter (clip);
  67297. while (iter.next())
  67298. {
  67299. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  67300. if (! rect.isEmpty())
  67301. {
  67302. const int x = rect.getX();
  67303. const int w = rect.getWidth();
  67304. const int bottom = rect.getBottom();
  67305. for (int y = rect.getY(); y < bottom; ++y)
  67306. {
  67307. r.setEdgeTableYPos (y);
  67308. r.handleEdgeTableLineFull (x, w);
  67309. }
  67310. }
  67311. }
  67312. }
  67313. private:
  67314. const RectangleList& clip;
  67315. const Rectangle<int> area;
  67316. SubRectangleIterator (const SubRectangleIterator&);
  67317. SubRectangleIterator& operator= (const SubRectangleIterator&);
  67318. };
  67319. class SubRectangleIteratorFloat
  67320. {
  67321. public:
  67322. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  67323. : clip (clip_), area (area_)
  67324. {
  67325. }
  67326. template <class Renderer>
  67327. void iterate (Renderer& r) const throw()
  67328. {
  67329. int left = roundToInt (area.getX() * 256.0f);
  67330. int top = roundToInt (area.getY() * 256.0f);
  67331. int right = roundToInt (area.getRight() * 256.0f);
  67332. int bottom = roundToInt (area.getBottom() * 256.0f);
  67333. int totalTop, totalLeft, totalBottom, totalRight;
  67334. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  67335. if ((top >> 8) == (bottom >> 8))
  67336. {
  67337. topAlpha = bottom - top;
  67338. bottomAlpha = 0;
  67339. totalTop = top >> 8;
  67340. totalBottom = bottom = top = totalTop + 1;
  67341. }
  67342. else
  67343. {
  67344. if ((top & 255) == 0)
  67345. {
  67346. topAlpha = 0;
  67347. top = totalTop = (top >> 8);
  67348. }
  67349. else
  67350. {
  67351. topAlpha = 255 - (top & 255);
  67352. totalTop = (top >> 8);
  67353. top = totalTop + 1;
  67354. }
  67355. bottomAlpha = bottom & 255;
  67356. bottom >>= 8;
  67357. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  67358. }
  67359. if ((left >> 8) == (right >> 8))
  67360. {
  67361. leftAlpha = right - left;
  67362. rightAlpha = 0;
  67363. totalLeft = (left >> 8);
  67364. totalRight = right = left = totalLeft + 1;
  67365. }
  67366. else
  67367. {
  67368. if ((left & 255) == 0)
  67369. {
  67370. leftAlpha = 0;
  67371. left = totalLeft = (left >> 8);
  67372. }
  67373. else
  67374. {
  67375. leftAlpha = 255 - (left & 255);
  67376. totalLeft = (left >> 8);
  67377. left = totalLeft + 1;
  67378. }
  67379. rightAlpha = right & 255;
  67380. right >>= 8;
  67381. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  67382. }
  67383. RectangleList::Iterator iter (clip);
  67384. while (iter.next())
  67385. {
  67386. const int clipLeft = iter.getRectangle()->getX();
  67387. const int clipRight = iter.getRectangle()->getRight();
  67388. const int clipTop = iter.getRectangle()->getY();
  67389. const int clipBottom = iter.getRectangle()->getBottom();
  67390. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  67391. {
  67392. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  67393. {
  67394. if (topAlpha != 0 && totalTop >= clipTop)
  67395. {
  67396. r.setEdgeTableYPos (totalTop);
  67397. r.handleEdgeTablePixel (left, topAlpha);
  67398. }
  67399. const int endY = jmin (bottom, clipBottom);
  67400. for (int y = jmax (clipTop, top); y < endY; ++y)
  67401. {
  67402. r.setEdgeTableYPos (y);
  67403. r.handleEdgeTablePixelFull (left);
  67404. }
  67405. if (bottomAlpha != 0 && bottom < clipBottom)
  67406. {
  67407. r.setEdgeTableYPos (bottom);
  67408. r.handleEdgeTablePixel (left, bottomAlpha);
  67409. }
  67410. }
  67411. else
  67412. {
  67413. const int clippedLeft = jmax (left, clipLeft);
  67414. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  67415. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  67416. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  67417. if (topAlpha != 0 && totalTop >= clipTop)
  67418. {
  67419. r.setEdgeTableYPos (totalTop);
  67420. if (doLeftAlpha)
  67421. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  67422. if (clippedWidth > 0)
  67423. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  67424. if (doRightAlpha)
  67425. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  67426. }
  67427. const int endY = jmin (bottom, clipBottom);
  67428. for (int y = jmax (clipTop, top); y < endY; ++y)
  67429. {
  67430. r.setEdgeTableYPos (y);
  67431. if (doLeftAlpha)
  67432. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  67433. if (clippedWidth > 0)
  67434. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  67435. if (doRightAlpha)
  67436. r.handleEdgeTablePixel (right, rightAlpha);
  67437. }
  67438. if (bottomAlpha != 0 && bottom < clipBottom)
  67439. {
  67440. r.setEdgeTableYPos (bottom);
  67441. if (doLeftAlpha)
  67442. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  67443. if (clippedWidth > 0)
  67444. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  67445. if (doRightAlpha)
  67446. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  67447. }
  67448. }
  67449. }
  67450. }
  67451. }
  67452. private:
  67453. const RectangleList& clip;
  67454. const Rectangle<float>& area;
  67455. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  67456. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  67457. };
  67458. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  67459. };
  67460. }
  67461. class LowLevelGraphicsSoftwareRenderer::SavedState
  67462. {
  67463. public:
  67464. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  67465. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67466. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67467. {
  67468. }
  67469. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67470. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67471. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67472. {
  67473. }
  67474. SavedState (const SavedState& other)
  67475. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  67476. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67477. {
  67478. }
  67479. ~SavedState()
  67480. {
  67481. }
  67482. void setOrigin (const int x, const int y) throw()
  67483. {
  67484. xOffset += x;
  67485. yOffset += y;
  67486. }
  67487. bool clipToRectangle (const Rectangle<int>& r)
  67488. {
  67489. if (clip != 0)
  67490. {
  67491. cloneClipIfMultiplyReferenced();
  67492. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67493. }
  67494. return clip != 0;
  67495. }
  67496. bool clipToRectangleList (const RectangleList& r)
  67497. {
  67498. if (clip != 0)
  67499. {
  67500. cloneClipIfMultiplyReferenced();
  67501. RectangleList offsetList (r);
  67502. offsetList.offsetAll (xOffset, yOffset);
  67503. clip = clip->clipToRectangleList (offsetList);
  67504. }
  67505. return clip != 0;
  67506. }
  67507. bool excludeClipRectangle (const Rectangle<int>& r)
  67508. {
  67509. if (clip != 0)
  67510. {
  67511. cloneClipIfMultiplyReferenced();
  67512. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67513. }
  67514. return clip != 0;
  67515. }
  67516. void clipToPath (const Path& p, const AffineTransform& transform)
  67517. {
  67518. if (clip != 0)
  67519. {
  67520. cloneClipIfMultiplyReferenced();
  67521. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67522. }
  67523. }
  67524. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67525. {
  67526. if (clip != 0)
  67527. {
  67528. if (image.hasAlphaChannel())
  67529. {
  67530. cloneClipIfMultiplyReferenced();
  67531. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67532. interpolationQuality != Graphics::lowResamplingQuality);
  67533. }
  67534. else
  67535. {
  67536. Path p;
  67537. p.addRectangle (srcClip);
  67538. clipToPath (p, t);
  67539. }
  67540. }
  67541. }
  67542. bool clipRegionIntersects (const Rectangle<int>& r) const
  67543. {
  67544. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67545. }
  67546. const Rectangle<int> getClipBounds() const
  67547. {
  67548. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67549. }
  67550. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67551. {
  67552. if (clip != 0)
  67553. {
  67554. if (fillType.isColour())
  67555. {
  67556. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67557. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67558. }
  67559. else
  67560. {
  67561. const Rectangle<int> totalClip (clip->getClipBounds());
  67562. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67563. if (! clipped.isEmpty())
  67564. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  67565. }
  67566. }
  67567. }
  67568. void fillRect (Image& image, const Rectangle<float>& r)
  67569. {
  67570. if (clip != 0)
  67571. {
  67572. if (fillType.isColour())
  67573. {
  67574. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67575. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67576. }
  67577. else
  67578. {
  67579. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67580. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67581. if (! clipped.isEmpty())
  67582. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  67583. }
  67584. }
  67585. }
  67586. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67587. {
  67588. if (clip != 0)
  67589. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67590. }
  67591. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67592. {
  67593. if (clip != 0)
  67594. {
  67595. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  67596. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67597. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67598. fillShape (image, shapeToFill, false);
  67599. }
  67600. }
  67601. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67602. {
  67603. jassert (clip != 0);
  67604. shapeToFill = clip->applyClipTo (shapeToFill);
  67605. if (shapeToFill != 0)
  67606. {
  67607. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67608. if (fillType.isGradient())
  67609. {
  67610. jassert (! replaceContents); // that option is just for solid colours
  67611. ColourGradient g2 (*(fillType.gradient));
  67612. g2.multiplyOpacity (fillType.getOpacity());
  67613. g2.point1.addXY (-0.5f, -0.5f);
  67614. g2.point2.addXY (-0.5f, -0.5f);
  67615. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67616. const bool isIdentity = transform.isOnlyTranslation();
  67617. if (isIdentity)
  67618. {
  67619. // If our translation doesn't involve any distortion, we can speed it up..
  67620. g2.point1.applyTransform (transform);
  67621. g2.point2.applyTransform (transform);
  67622. transform = AffineTransform::identity;
  67623. }
  67624. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67625. }
  67626. else if (fillType.isTiledImage())
  67627. {
  67628. renderImage (image, fillType.image, fillType.image.getBounds(), fillType.transform, shapeToFill);
  67629. }
  67630. else
  67631. {
  67632. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67633. }
  67634. }
  67635. }
  67636. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67637. const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  67638. {
  67639. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67640. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67641. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67642. const int alpha = fillType.colour.getAlpha();
  67643. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67644. if (transform.isOnlyTranslation())
  67645. {
  67646. // If our translation doesn't involve any distortion, just use a simple blit..
  67647. int tx = (int) (transform.getTranslationX() * 256.0f);
  67648. int ty = (int) (transform.getTranslationY() * 256.0f);
  67649. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67650. {
  67651. tx = ((tx + 128) >> 8);
  67652. ty = ((ty + 128) >> 8);
  67653. if (tiledFillClipRegion != 0)
  67654. {
  67655. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  67656. }
  67657. else
  67658. {
  67659. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67660. c = clip->applyClipTo (c);
  67661. if (c != 0)
  67662. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  67663. }
  67664. return;
  67665. }
  67666. }
  67667. if (transform.isSingularity())
  67668. return;
  67669. if (tiledFillClipRegion != 0)
  67670. {
  67671. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67672. }
  67673. else
  67674. {
  67675. Path p;
  67676. p.addRectangle (srcClip);
  67677. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  67678. c = c->clipToPath (p, transform);
  67679. if (c != 0)
  67680. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  67681. }
  67682. }
  67683. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  67684. int xOffset, yOffset;
  67685. Font font;
  67686. FillType fillType;
  67687. Graphics::ResamplingQuality interpolationQuality;
  67688. private:
  67689. void cloneClipIfMultiplyReferenced()
  67690. {
  67691. if (clip->getReferenceCount() > 1)
  67692. clip = clip->clone();
  67693. }
  67694. SavedState& operator= (const SavedState&);
  67695. };
  67696. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  67697. : image (image_)
  67698. {
  67699. currentState = new SavedState (image_.getBounds(), 0, 0);
  67700. }
  67701. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  67702. const RectangleList& initialClip)
  67703. : image (image_)
  67704. {
  67705. currentState = new SavedState (initialClip, xOffset, yOffset);
  67706. }
  67707. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67708. {
  67709. }
  67710. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67711. {
  67712. return false;
  67713. }
  67714. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67715. {
  67716. currentState->setOrigin (x, y);
  67717. }
  67718. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67719. {
  67720. return currentState->clipToRectangle (r);
  67721. }
  67722. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67723. {
  67724. return currentState->clipToRectangleList (clipRegion);
  67725. }
  67726. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67727. {
  67728. currentState->excludeClipRectangle (r);
  67729. }
  67730. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67731. {
  67732. currentState->clipToPath (path, transform);
  67733. }
  67734. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67735. {
  67736. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67737. }
  67738. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67739. {
  67740. return currentState->clipRegionIntersects (r);
  67741. }
  67742. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67743. {
  67744. return currentState->getClipBounds();
  67745. }
  67746. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67747. {
  67748. return currentState->clip == 0;
  67749. }
  67750. void LowLevelGraphicsSoftwareRenderer::saveState()
  67751. {
  67752. stateStack.add (new SavedState (*currentState));
  67753. }
  67754. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67755. {
  67756. SavedState* const top = stateStack.getLast();
  67757. if (top != 0)
  67758. {
  67759. currentState = top;
  67760. stateStack.removeLast (1, false);
  67761. }
  67762. else
  67763. {
  67764. jassertfalse; // trying to pop with an empty stack!
  67765. }
  67766. }
  67767. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67768. {
  67769. currentState->fillType = fillType;
  67770. }
  67771. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67772. {
  67773. currentState->fillType.setOpacity (newOpacity);
  67774. }
  67775. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67776. {
  67777. currentState->interpolationQuality = quality;
  67778. }
  67779. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67780. {
  67781. currentState->fillRect (image, r, replaceExistingContents);
  67782. }
  67783. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67784. {
  67785. currentState->fillPath (image, path, transform);
  67786. }
  67787. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67788. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67789. {
  67790. jassert (sourceImage.getBounds().contains (srcClip));
  67791. currentState->renderImage (image, sourceImage, srcClip, transform,
  67792. fillEntireClipAsTiles ? currentState->clip : 0);
  67793. }
  67794. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  67795. {
  67796. Path p;
  67797. p.addLineSegment (line, 1.0f);
  67798. fillPath (p, AffineTransform::identity);
  67799. }
  67800. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  67801. {
  67802. if (bottom > top)
  67803. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  67804. }
  67805. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  67806. {
  67807. if (right > left)
  67808. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  67809. }
  67810. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  67811. {
  67812. public:
  67813. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67814. ~CachedGlyph() {}
  67815. void draw (SavedState& state, Image& image, const float x, const float y) const
  67816. {
  67817. if (edgeTable != 0)
  67818. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67819. }
  67820. void generate (const Font& newFont, const int glyphNumber)
  67821. {
  67822. font = newFont;
  67823. glyph = glyphNumber;
  67824. edgeTable = 0;
  67825. Path glyphPath;
  67826. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67827. if (! glyphPath.isEmpty())
  67828. {
  67829. const float fontHeight = font.getHeight();
  67830. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67831. .translated (0.0f, -0.5f));
  67832. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67833. glyphPath, transform);
  67834. }
  67835. }
  67836. int glyph, lastAccessCount;
  67837. Font font;
  67838. juce_UseDebuggingNewOperator
  67839. private:
  67840. ScopedPointer <EdgeTable> edgeTable;
  67841. CachedGlyph (const CachedGlyph&);
  67842. CachedGlyph& operator= (const CachedGlyph&);
  67843. };
  67844. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  67845. {
  67846. public:
  67847. GlyphCache()
  67848. : accessCounter (0), hits (0), misses (0)
  67849. {
  67850. for (int i = 120; --i >= 0;)
  67851. glyphs.add (new CachedGlyph());
  67852. }
  67853. ~GlyphCache()
  67854. {
  67855. clearSingletonInstance();
  67856. }
  67857. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67858. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67859. {
  67860. ++accessCounter;
  67861. int oldestCounter = std::numeric_limits<int>::max();
  67862. CachedGlyph* oldest = 0;
  67863. for (int i = glyphs.size(); --i >= 0;)
  67864. {
  67865. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67866. if (glyph->glyph == glyphNumber && glyph->font == font)
  67867. {
  67868. ++hits;
  67869. glyph->lastAccessCount = accessCounter;
  67870. glyph->draw (state, image, x, y);
  67871. return;
  67872. }
  67873. if (glyph->lastAccessCount <= oldestCounter)
  67874. {
  67875. oldestCounter = glyph->lastAccessCount;
  67876. oldest = glyph;
  67877. }
  67878. }
  67879. if (hits + ++misses > (glyphs.size() << 4))
  67880. {
  67881. if (misses * 2 > hits)
  67882. {
  67883. for (int i = 32; --i >= 0;)
  67884. glyphs.add (new CachedGlyph());
  67885. }
  67886. hits = misses = 0;
  67887. oldest = glyphs.getLast();
  67888. }
  67889. jassert (oldest != 0);
  67890. oldest->lastAccessCount = accessCounter;
  67891. oldest->generate (font, glyphNumber);
  67892. oldest->draw (state, image, x, y);
  67893. }
  67894. juce_UseDebuggingNewOperator
  67895. private:
  67896. friend class OwnedArray <CachedGlyph>;
  67897. OwnedArray <CachedGlyph> glyphs;
  67898. int accessCounter, hits, misses;
  67899. GlyphCache (const GlyphCache&);
  67900. GlyphCache& operator= (const GlyphCache&);
  67901. };
  67902. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  67903. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67904. {
  67905. currentState->font = newFont;
  67906. }
  67907. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67908. {
  67909. return currentState->font;
  67910. }
  67911. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67912. {
  67913. Font& f = currentState->font;
  67914. if (transform.isOnlyTranslation())
  67915. {
  67916. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67917. transform.getTranslationX(),
  67918. transform.getTranslationY());
  67919. }
  67920. else
  67921. {
  67922. Path p;
  67923. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67924. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67925. }
  67926. }
  67927. #if JUCE_MSVC
  67928. #pragma warning (pop)
  67929. #if JUCE_DEBUG
  67930. #pragma optimize ("", on) // resets optimisations to the project defaults
  67931. #endif
  67932. #endif
  67933. END_JUCE_NAMESPACE
  67934. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67935. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67936. BEGIN_JUCE_NAMESPACE
  67937. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67938. : flags (other.flags)
  67939. {
  67940. }
  67941. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67942. {
  67943. flags = other.flags;
  67944. return *this;
  67945. }
  67946. void RectanglePlacement::applyTo (double& x, double& y,
  67947. double& w, double& h,
  67948. const double dx, const double dy,
  67949. const double dw, const double dh) const throw()
  67950. {
  67951. if (w == 0 || h == 0)
  67952. return;
  67953. if ((flags & stretchToFit) != 0)
  67954. {
  67955. x = dx;
  67956. y = dy;
  67957. w = dw;
  67958. h = dh;
  67959. }
  67960. else
  67961. {
  67962. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67963. : jmin (dw / w, dh / h);
  67964. if ((flags & onlyReduceInSize) != 0)
  67965. scale = jmin (scale, 1.0);
  67966. if ((flags & onlyIncreaseInSize) != 0)
  67967. scale = jmax (scale, 1.0);
  67968. w *= scale;
  67969. h *= scale;
  67970. if ((flags & xLeft) != 0)
  67971. x = dx;
  67972. else if ((flags & xRight) != 0)
  67973. x = dx + dw - w;
  67974. else
  67975. x = dx + (dw - w) * 0.5;
  67976. if ((flags & yTop) != 0)
  67977. y = dy;
  67978. else if ((flags & yBottom) != 0)
  67979. y = dy + dh - h;
  67980. else
  67981. y = dy + (dh - h) * 0.5;
  67982. }
  67983. }
  67984. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67985. float w, float h,
  67986. const float dx, const float dy,
  67987. const float dw, const float dh) const throw()
  67988. {
  67989. if (w == 0 || h == 0)
  67990. return AffineTransform::identity;
  67991. const float scaleX = dw / w;
  67992. const float scaleY = dh / h;
  67993. if ((flags & stretchToFit) != 0)
  67994. return AffineTransform::translation (-x, -y)
  67995. .scaled (scaleX, scaleY)
  67996. .translated (dx, dy);
  67997. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67998. : jmin (scaleX, scaleY);
  67999. if ((flags & onlyReduceInSize) != 0)
  68000. scale = jmin (scale, 1.0f);
  68001. if ((flags & onlyIncreaseInSize) != 0)
  68002. scale = jmax (scale, 1.0f);
  68003. w *= scale;
  68004. h *= scale;
  68005. float newX = dx;
  68006. if ((flags & xRight) != 0)
  68007. newX += dw - w; // right
  68008. else if ((flags & xLeft) == 0)
  68009. newX += (dw - w) / 2.0f; // centre
  68010. float newY = dy;
  68011. if ((flags & yBottom) != 0)
  68012. newY += dh - h; // bottom
  68013. else if ((flags & yTop) == 0)
  68014. newY += (dh - h) / 2.0f; // centre
  68015. return AffineTransform::translation (-x, -y)
  68016. .scaled (scale, scale)
  68017. .translated (newX, newY);
  68018. }
  68019. END_JUCE_NAMESPACE
  68020. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  68021. /*** Start of inlined file: juce_Drawable.cpp ***/
  68022. BEGIN_JUCE_NAMESPACE
  68023. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  68024. const AffineTransform& transform_,
  68025. const float opacity_) throw()
  68026. : g (g_),
  68027. transform (transform_),
  68028. opacity (opacity_)
  68029. {
  68030. }
  68031. Drawable::Drawable()
  68032. : parent (0)
  68033. {
  68034. }
  68035. Drawable::~Drawable()
  68036. {
  68037. }
  68038. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  68039. {
  68040. render (RenderingContext (g, transform, opacity));
  68041. }
  68042. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  68043. {
  68044. draw (g, opacity, AffineTransform::translation (x, y));
  68045. }
  68046. void Drawable::drawWithin (Graphics& g,
  68047. const int destX,
  68048. const int destY,
  68049. const int destW,
  68050. const int destH,
  68051. const RectanglePlacement& placement,
  68052. const float opacity) const
  68053. {
  68054. if (destW > 0 && destH > 0)
  68055. {
  68056. Rectangle<float> bounds (getBounds());
  68057. draw (g, opacity,
  68058. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  68059. (float) destX, (float) destY,
  68060. (float) destW, (float) destH));
  68061. }
  68062. }
  68063. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  68064. {
  68065. Drawable* result = 0;
  68066. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  68067. if (image.isValid())
  68068. {
  68069. DrawableImage* const di = new DrawableImage();
  68070. di->setImage (image);
  68071. result = di;
  68072. }
  68073. else
  68074. {
  68075. const String asString (String::createStringFromData (data, (int) numBytes));
  68076. XmlDocument doc (asString);
  68077. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  68078. if (outer != 0 && outer->hasTagName ("svg"))
  68079. {
  68080. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  68081. if (svg != 0)
  68082. result = Drawable::createFromSVG (*svg);
  68083. }
  68084. }
  68085. return result;
  68086. }
  68087. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  68088. {
  68089. MemoryBlock mb;
  68090. dataSource.readIntoMemoryBlock (mb);
  68091. return createFromImageData (mb.getData(), mb.getSize());
  68092. }
  68093. Drawable* Drawable::createFromImageFile (const File& file)
  68094. {
  68095. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  68096. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  68097. }
  68098. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68099. {
  68100. return createChildFromValueTree (0, tree, imageProvider);
  68101. }
  68102. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  68103. {
  68104. const Identifier type (tree.getType());
  68105. Drawable* d = 0;
  68106. if (type == DrawablePath::valueTreeType)
  68107. d = new DrawablePath();
  68108. else if (type == DrawableComposite::valueTreeType)
  68109. d = new DrawableComposite();
  68110. else if (type == DrawableImage::valueTreeType)
  68111. d = new DrawableImage();
  68112. else if (type == DrawableText::valueTreeType)
  68113. d = new DrawableText();
  68114. if (d != 0)
  68115. {
  68116. d->parent = parent;
  68117. d->refreshFromValueTree (tree, imageProvider);
  68118. }
  68119. return d;
  68120. }
  68121. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  68122. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  68123. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  68124. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  68125. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  68126. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  68127. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  68128. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  68129. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  68130. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  68131. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  68132. : state (state_)
  68133. {
  68134. }
  68135. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  68136. {
  68137. }
  68138. const String Drawable::ValueTreeWrapperBase::getID() const
  68139. {
  68140. return state [idProperty];
  68141. }
  68142. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  68143. {
  68144. if (newID.isEmpty())
  68145. state.removeProperty (idProperty, undoManager);
  68146. else
  68147. state.setProperty (idProperty, newID, undoManager);
  68148. }
  68149. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  68150. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  68151. {
  68152. const String newType (v[type].toString());
  68153. if (newType == "solid")
  68154. {
  68155. const String colourString (v [colour].toString());
  68156. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  68157. : (uint32) colourString.getHexValue32()));
  68158. }
  68159. else if (newType == "gradient")
  68160. {
  68161. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  68162. ColourGradient g;
  68163. if (gp1 != 0) *gp1 = p1;
  68164. if (gp2 != 0) *gp2 = p2;
  68165. if (gp3 != 0) *gp3 = p3;
  68166. g.point1 = p1.resolve (nameFinder);
  68167. g.point2 = p2.resolve (nameFinder);
  68168. g.isRadial = v[radial];
  68169. StringArray colourSteps;
  68170. colourSteps.addTokens (v[colours].toString(), false);
  68171. for (int i = 0; i < colourSteps.size() / 2; ++i)
  68172. g.addColour (colourSteps[i * 2].getDoubleValue(),
  68173. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  68174. FillType fillType (g);
  68175. if (g.isRadial)
  68176. {
  68177. const Point<float> point3 (p3.resolve (nameFinder));
  68178. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68179. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68180. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  68181. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  68182. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  68183. }
  68184. return fillType;
  68185. }
  68186. else if (newType == "image")
  68187. {
  68188. Image im;
  68189. if (imageProvider != 0)
  68190. im = imageProvider->getImageForIdentifier (v[imageId]);
  68191. FillType f (im, AffineTransform::identity);
  68192. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  68193. return f;
  68194. }
  68195. jassertfalse;
  68196. return FillType();
  68197. }
  68198. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  68199. {
  68200. const ColourGradient& g = *fillType.gradient;
  68201. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68202. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68203. return point3Source.transformedBy (fillType.transform);
  68204. }
  68205. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  68206. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  68207. ImageProvider* imageProvider, UndoManager* const undoManager)
  68208. {
  68209. if (fillType.isColour())
  68210. {
  68211. v.setProperty (type, "solid", undoManager);
  68212. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68213. }
  68214. else if (fillType.isGradient())
  68215. {
  68216. v.setProperty (type, "gradient", undoManager);
  68217. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68218. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68219. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  68220. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68221. String s;
  68222. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68223. s << ' ' << fillType.gradient->getColourPosition (i)
  68224. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68225. v.setProperty (colours, s.trimStart(), undoManager);
  68226. }
  68227. else if (fillType.isTiledImage())
  68228. {
  68229. v.setProperty (type, "image", undoManager);
  68230. if (imageProvider != 0)
  68231. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68232. if (fillType.getOpacity() < 1.0f)
  68233. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68234. else
  68235. v.removeProperty (imageOpacity, undoManager);
  68236. }
  68237. else
  68238. {
  68239. jassertfalse;
  68240. }
  68241. }
  68242. END_JUCE_NAMESPACE
  68243. /*** End of inlined file: juce_Drawable.cpp ***/
  68244. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  68245. BEGIN_JUCE_NAMESPACE
  68246. DrawableComposite::DrawableComposite()
  68247. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  68248. {
  68249. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  68250. RelativeCoordinate (100.0),
  68251. RelativeCoordinate (0.0),
  68252. RelativeCoordinate (100.0)));
  68253. }
  68254. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  68255. {
  68256. bounds = other.bounds;
  68257. for (int i = 0; i < other.drawables.size(); ++i)
  68258. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  68259. markersX.addCopiesOf (other.markersX);
  68260. markersY.addCopiesOf (other.markersY);
  68261. }
  68262. DrawableComposite::~DrawableComposite()
  68263. {
  68264. }
  68265. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  68266. {
  68267. if (drawable != 0)
  68268. {
  68269. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  68270. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  68271. drawables.insert (index, drawable);
  68272. drawable->parent = this;
  68273. }
  68274. }
  68275. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  68276. {
  68277. insertDrawable (drawable.createCopy(), index);
  68278. }
  68279. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  68280. {
  68281. drawables.remove (index, deleteDrawable);
  68282. }
  68283. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  68284. {
  68285. for (int i = drawables.size(); --i >= 0;)
  68286. if (drawables.getUnchecked(i)->getName() == name)
  68287. return drawables.getUnchecked(i);
  68288. return 0;
  68289. }
  68290. void DrawableComposite::bringToFront (const int index)
  68291. {
  68292. if (index >= 0 && index < drawables.size() - 1)
  68293. drawables.move (index, -1);
  68294. }
  68295. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  68296. {
  68297. bounds = newBoundingBox;
  68298. }
  68299. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  68300. : name (other.name), position (other.position)
  68301. {
  68302. }
  68303. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  68304. : name (name_), position (position_)
  68305. {
  68306. }
  68307. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  68308. {
  68309. return name != other.name || position != other.position;
  68310. }
  68311. const char* const DrawableComposite::contentLeftMarkerName ("left");
  68312. const char* const DrawableComposite::contentRightMarkerName ("right");
  68313. const char* const DrawableComposite::contentTopMarkerName ("top");
  68314. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  68315. const RelativeRectangle DrawableComposite::getContentArea() const
  68316. {
  68317. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  68318. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  68319. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  68320. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  68321. }
  68322. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  68323. {
  68324. setMarker (contentLeftMarkerName, true, newArea.left);
  68325. setMarker (contentRightMarkerName, true, newArea.right);
  68326. setMarker (contentTopMarkerName, false, newArea.top);
  68327. setMarker (contentBottomMarkerName, false, newArea.bottom);
  68328. }
  68329. void DrawableComposite::resetBoundingBoxToContentArea()
  68330. {
  68331. const RelativeRectangle content (getContentArea());
  68332. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68333. RelativePoint (content.right, content.top),
  68334. RelativePoint (content.left, content.bottom)));
  68335. }
  68336. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  68337. {
  68338. const Rectangle<float> bounds (getUntransformedBounds (false));
  68339. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  68340. RelativeCoordinate (bounds.getRight()),
  68341. RelativeCoordinate (bounds.getY()),
  68342. RelativeCoordinate (bounds.getBottom())));
  68343. resetBoundingBoxToContentArea();
  68344. }
  68345. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  68346. {
  68347. return (xAxis ? markersX : markersY).size();
  68348. }
  68349. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  68350. {
  68351. return (xAxis ? markersX : markersY) [index];
  68352. }
  68353. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  68354. {
  68355. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  68356. for (int i = 0; i < markers.size(); ++i)
  68357. {
  68358. Marker* const m = markers.getUnchecked(i);
  68359. if (m->name == name)
  68360. {
  68361. if (m->position != position)
  68362. {
  68363. m->position = position;
  68364. invalidatePoints();
  68365. }
  68366. return;
  68367. }
  68368. }
  68369. (xAxis ? markersX : markersY).add (new Marker (name, position));
  68370. invalidatePoints();
  68371. }
  68372. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  68373. {
  68374. jassert (index >= 2);
  68375. if (index >= 2)
  68376. (xAxis ? markersX : markersY).remove (index);
  68377. }
  68378. const AffineTransform DrawableComposite::calculateTransform() const
  68379. {
  68380. Point<float> resolved[3];
  68381. bounds.resolveThreePoints (resolved, parent);
  68382. const Rectangle<float> content (getContentArea().resolve (parent));
  68383. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  68384. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  68385. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  68386. }
  68387. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  68388. {
  68389. if (drawables.size() > 0 && context.opacity > 0)
  68390. {
  68391. if (context.opacity >= 1.0f || drawables.size() == 1)
  68392. {
  68393. Drawable::RenderingContext contextCopy (context);
  68394. contextCopy.transform = calculateTransform().followedBy (context.transform);
  68395. for (int i = 0; i < drawables.size(); ++i)
  68396. drawables.getUnchecked(i)->render (contextCopy);
  68397. }
  68398. else
  68399. {
  68400. // To correctly render a whole composite layer with an overall transparency,
  68401. // we need to render everything opaquely into a temp buffer, then blend that
  68402. // with the target opacity...
  68403. const Rectangle<int> clipBounds (context.g.getClipBounds());
  68404. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  68405. {
  68406. Graphics tempG (tempImage);
  68407. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  68408. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  68409. render (tempContext);
  68410. }
  68411. context.g.setOpacity (context.opacity);
  68412. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  68413. }
  68414. }
  68415. }
  68416. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  68417. {
  68418. if (objectName == RelativeCoordinate::Strings::parent)
  68419. {
  68420. if (edge == RelativeCoordinate::Strings::right || edge == RelativeCoordinate::Strings::bottom)
  68421. {
  68422. jassertfalse; // a Drawable doesn't have a fixed right-hand or bottom edge - use a marker instead if you need a point of reference.
  68423. return RelativeCoordinate (100.0);
  68424. }
  68425. }
  68426. int i;
  68427. for (i = 0; i < markersX.size(); ++i)
  68428. {
  68429. Marker* const m = markersX.getUnchecked(i);
  68430. if (m->name == objectName)
  68431. return m->position;
  68432. }
  68433. for (i = 0; i < markersY.size(); ++i)
  68434. {
  68435. Marker* const m = markersY.getUnchecked(i);
  68436. if (m->name == objectName)
  68437. return m->position;
  68438. }
  68439. return RelativeCoordinate();
  68440. }
  68441. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  68442. {
  68443. Rectangle<float> bounds;
  68444. int i;
  68445. for (i = 0; i < drawables.size(); ++i)
  68446. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  68447. if (includeMarkers)
  68448. {
  68449. if (markersX.size() > 0)
  68450. {
  68451. float minX = std::numeric_limits<float>::max();
  68452. float maxX = std::numeric_limits<float>::min();
  68453. for (i = markersX.size(); --i >= 0;)
  68454. {
  68455. const Marker* m = markersX.getUnchecked(i);
  68456. const float pos = (float) m->position.resolve (this);
  68457. minX = jmin (minX, pos);
  68458. maxX = jmax (maxX, pos);
  68459. }
  68460. if (minX <= maxX)
  68461. {
  68462. if (bounds.getHeight() > 0)
  68463. {
  68464. minX = jmin (minX, bounds.getX());
  68465. maxX = jmax (maxX, bounds.getRight());
  68466. }
  68467. bounds.setLeft (minX);
  68468. bounds.setWidth (maxX - minX);
  68469. }
  68470. }
  68471. if (markersY.size() > 0)
  68472. {
  68473. float minY = std::numeric_limits<float>::max();
  68474. float maxY = std::numeric_limits<float>::min();
  68475. for (i = markersY.size(); --i >= 0;)
  68476. {
  68477. const Marker* m = markersY.getUnchecked(i);
  68478. const float pos = (float) m->position.resolve (this);
  68479. minY = jmin (minY, pos);
  68480. maxY = jmax (maxY, pos);
  68481. }
  68482. if (minY <= maxY)
  68483. {
  68484. if (bounds.getHeight() > 0)
  68485. {
  68486. minY = jmin (minY, bounds.getY());
  68487. maxY = jmax (maxY, bounds.getBottom());
  68488. }
  68489. bounds.setTop (minY);
  68490. bounds.setHeight (maxY - minY);
  68491. }
  68492. }
  68493. }
  68494. return bounds;
  68495. }
  68496. const Rectangle<float> DrawableComposite::getBounds() const
  68497. {
  68498. return getUntransformedBounds (true).transformed (calculateTransform());
  68499. }
  68500. bool DrawableComposite::hitTest (float x, float y) const
  68501. {
  68502. calculateTransform().inverted().transformPoint (x, y);
  68503. for (int i = 0; i < drawables.size(); ++i)
  68504. if (drawables.getUnchecked(i)->hitTest (x, y))
  68505. return true;
  68506. return false;
  68507. }
  68508. Drawable* DrawableComposite::createCopy() const
  68509. {
  68510. return new DrawableComposite (*this);
  68511. }
  68512. void DrawableComposite::invalidatePoints()
  68513. {
  68514. for (int i = 0; i < drawables.size(); ++i)
  68515. drawables.getUnchecked(i)->invalidatePoints();
  68516. }
  68517. const Identifier DrawableComposite::valueTreeType ("Group");
  68518. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  68519. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  68520. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68521. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  68522. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  68523. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  68524. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  68525. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  68526. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  68527. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68528. : ValueTreeWrapperBase (state_)
  68529. {
  68530. jassert (state.hasType (valueTreeType));
  68531. }
  68532. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  68533. {
  68534. return state.getChildWithName (childGroupTag);
  68535. }
  68536. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  68537. {
  68538. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  68539. }
  68540. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  68541. {
  68542. return getChildList().getNumChildren();
  68543. }
  68544. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  68545. {
  68546. return getChildList().getChild (index);
  68547. }
  68548. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  68549. {
  68550. if (getID() == objectId)
  68551. return state;
  68552. if (! recursive)
  68553. {
  68554. return getChildList().getChildWithProperty (idProperty, objectId);
  68555. }
  68556. else
  68557. {
  68558. const ValueTree childList (getChildList());
  68559. for (int i = getNumDrawables(); --i >= 0;)
  68560. {
  68561. const ValueTree& child = childList.getChild (i);
  68562. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  68563. return child;
  68564. if (child.hasType (DrawableComposite::valueTreeType))
  68565. {
  68566. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  68567. if (v.isValid())
  68568. return v;
  68569. }
  68570. }
  68571. return ValueTree::invalid;
  68572. }
  68573. }
  68574. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  68575. {
  68576. return getChildList().indexOf (item);
  68577. }
  68578. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  68579. {
  68580. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  68581. }
  68582. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  68583. {
  68584. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  68585. }
  68586. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  68587. {
  68588. getChildList().removeChild (child, undoManager);
  68589. }
  68590. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  68591. {
  68592. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68593. state.getProperty (topRight, "100, 0"),
  68594. state.getProperty (bottomLeft, "0, 100"));
  68595. }
  68596. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68597. {
  68598. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68599. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68600. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68601. }
  68602. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  68603. {
  68604. const RelativeRectangle content (getContentArea());
  68605. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68606. RelativePoint (content.right, content.top),
  68607. RelativePoint (content.left, content.bottom)), undoManager);
  68608. }
  68609. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  68610. {
  68611. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  68612. getMarker (true, getMarkerState (true, 1)).position,
  68613. getMarker (false, getMarkerState (false, 0)).position,
  68614. getMarker (false, getMarkerState (false, 1)).position);
  68615. }
  68616. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  68617. {
  68618. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  68619. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  68620. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  68621. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  68622. }
  68623. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  68624. {
  68625. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  68626. }
  68627. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  68628. {
  68629. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  68630. }
  68631. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  68632. {
  68633. return getMarkerList (xAxis).getNumChildren();
  68634. }
  68635. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  68636. {
  68637. return getMarkerList (xAxis).getChild (index);
  68638. }
  68639. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  68640. {
  68641. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  68642. }
  68643. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  68644. {
  68645. return state.isAChildOf (getMarkerList (xAxis));
  68646. }
  68647. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  68648. {
  68649. jassert (containsMarker (xAxis, state));
  68650. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  68651. }
  68652. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  68653. {
  68654. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  68655. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  68656. if (marker.isValid())
  68657. {
  68658. marker.setProperty (posProperty, m.position.toString(), undoManager);
  68659. }
  68660. else
  68661. {
  68662. marker = ValueTree (markerTag);
  68663. marker.setProperty (nameProperty, m.name, 0);
  68664. marker.setProperty (posProperty, m.position.toString(), 0);
  68665. markerList.addChild (marker, -1, undoManager);
  68666. }
  68667. }
  68668. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  68669. {
  68670. if (state [nameProperty].toString() != contentLeftMarkerName
  68671. && state [nameProperty].toString() != contentRightMarkerName
  68672. && state [nameProperty].toString() != contentTopMarkerName
  68673. && state [nameProperty].toString() != contentBottomMarkerName)
  68674. return getMarkerList (xAxis).removeChild (state, undoManager);
  68675. }
  68676. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68677. {
  68678. const ValueTreeWrapper wrapper (tree);
  68679. setName (wrapper.getID());
  68680. Rectangle<float> damage;
  68681. bool redrawAll = false;
  68682. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  68683. if (bounds != newBounds)
  68684. {
  68685. redrawAll = true;
  68686. damage = getBounds();
  68687. bounds = newBounds;
  68688. }
  68689. const int numMarkersX = wrapper.getNumMarkers (true);
  68690. const int numMarkersY = wrapper.getNumMarkers (false);
  68691. // Remove deleted markers...
  68692. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  68693. {
  68694. if (! redrawAll)
  68695. {
  68696. redrawAll = true;
  68697. damage = getBounds();
  68698. }
  68699. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  68700. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  68701. }
  68702. // Update markers and add new ones..
  68703. int i;
  68704. for (i = 0; i < numMarkersX; ++i)
  68705. {
  68706. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  68707. Marker* m = markersX[i];
  68708. if (m == 0 || newMarker != *m)
  68709. {
  68710. if (! redrawAll)
  68711. {
  68712. redrawAll = true;
  68713. damage = getBounds();
  68714. }
  68715. if (m == 0)
  68716. markersX.add (new Marker (newMarker));
  68717. else
  68718. *m = newMarker;
  68719. }
  68720. }
  68721. for (i = 0; i < numMarkersY; ++i)
  68722. {
  68723. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  68724. Marker* m = markersY[i];
  68725. if (m == 0 || newMarker != *m)
  68726. {
  68727. if (! redrawAll)
  68728. {
  68729. redrawAll = true;
  68730. damage = getBounds();
  68731. }
  68732. if (m == 0)
  68733. markersY.add (new Marker (newMarker));
  68734. else
  68735. *m = newMarker;
  68736. }
  68737. }
  68738. // Remove deleted drawables..
  68739. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  68740. {
  68741. Drawable* const d = drawables.getUnchecked(i);
  68742. if (! redrawAll)
  68743. damage = damage.getUnion (d->getBounds());
  68744. d->parent = 0;
  68745. drawables.remove (i);
  68746. }
  68747. // Update drawables and add new ones..
  68748. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  68749. {
  68750. const ValueTree newDrawable (wrapper.getDrawableState (i));
  68751. Drawable* d = drawables[i];
  68752. if (d != 0)
  68753. {
  68754. if (newDrawable.hasType (d->getValueTreeType()))
  68755. {
  68756. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  68757. if (! redrawAll)
  68758. damage = damage.getUnion (area);
  68759. }
  68760. else
  68761. {
  68762. if (! redrawAll)
  68763. damage = damage.getUnion (d->getBounds());
  68764. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68765. drawables.set (i, d);
  68766. if (! redrawAll)
  68767. damage = damage.getUnion (d->getBounds());
  68768. }
  68769. }
  68770. else
  68771. {
  68772. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68773. drawables.set (i, d);
  68774. if (! redrawAll)
  68775. damage = damage.getUnion (d->getBounds());
  68776. }
  68777. }
  68778. if (redrawAll)
  68779. damage = damage.getUnion (getBounds());
  68780. else if (! damage.isEmpty())
  68781. damage = damage.transformed (calculateTransform());
  68782. return damage;
  68783. }
  68784. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  68785. {
  68786. ValueTree tree (valueTreeType);
  68787. ValueTreeWrapper v (tree);
  68788. v.setID (getName(), 0);
  68789. v.setBoundingBox (bounds, 0);
  68790. int i;
  68791. for (i = 0; i < drawables.size(); ++i)
  68792. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  68793. for (i = 0; i < markersX.size(); ++i)
  68794. v.setMarker (true, *markersX.getUnchecked(i), 0);
  68795. for (i = 0; i < markersY.size(); ++i)
  68796. v.setMarker (false, *markersY.getUnchecked(i), 0);
  68797. return tree;
  68798. }
  68799. END_JUCE_NAMESPACE
  68800. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  68801. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  68802. BEGIN_JUCE_NAMESPACE
  68803. DrawableImage::DrawableImage()
  68804. : image (0),
  68805. opacity (1.0f),
  68806. overlayColour (0x00000000)
  68807. {
  68808. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  68809. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  68810. }
  68811. DrawableImage::DrawableImage (const DrawableImage& other)
  68812. : image (other.image),
  68813. opacity (other.opacity),
  68814. overlayColour (other.overlayColour),
  68815. bounds (other.bounds)
  68816. {
  68817. }
  68818. DrawableImage::~DrawableImage()
  68819. {
  68820. }
  68821. void DrawableImage::setImage (const Image& imageToUse)
  68822. {
  68823. image = imageToUse;
  68824. if (image.isValid())
  68825. {
  68826. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  68827. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  68828. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  68829. }
  68830. }
  68831. void DrawableImage::setOpacity (const float newOpacity)
  68832. {
  68833. opacity = newOpacity;
  68834. }
  68835. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  68836. {
  68837. overlayColour = newOverlayColour;
  68838. }
  68839. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  68840. {
  68841. bounds = newBounds;
  68842. }
  68843. const AffineTransform DrawableImage::calculateTransform() const
  68844. {
  68845. if (image.isNull())
  68846. return AffineTransform::identity;
  68847. Point<float> resolved[3];
  68848. bounds.resolveThreePoints (resolved, parent);
  68849. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  68850. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  68851. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  68852. tr.getX(), tr.getY(),
  68853. bl.getX(), bl.getY());
  68854. }
  68855. void DrawableImage::render (const Drawable::RenderingContext& context) const
  68856. {
  68857. if (image.isValid())
  68858. {
  68859. const AffineTransform t (calculateTransform().followedBy (context.transform));
  68860. if (opacity > 0.0f && ! overlayColour.isOpaque())
  68861. {
  68862. context.g.setOpacity (context.opacity * opacity);
  68863. context.g.drawImageTransformed (image, image.getBounds(), t, false);
  68864. }
  68865. if (! overlayColour.isTransparent())
  68866. {
  68867. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  68868. context.g.drawImageTransformed (image, image.getBounds(), t, true);
  68869. }
  68870. }
  68871. }
  68872. const Rectangle<float> DrawableImage::getBounds() const
  68873. {
  68874. if (image.isNull())
  68875. return Rectangle<float>();
  68876. return bounds.getBounds (parent);
  68877. }
  68878. bool DrawableImage::hitTest (float x, float y) const
  68879. {
  68880. if (image.isNull())
  68881. return false;
  68882. calculateTransform().inverted().transformPoint (x, y);
  68883. const int ix = roundToInt (x);
  68884. const int iy = roundToInt (y);
  68885. return ix >= 0
  68886. && iy >= 0
  68887. && ix < image.getWidth()
  68888. && iy < image.getHeight()
  68889. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  68890. }
  68891. Drawable* DrawableImage::createCopy() const
  68892. {
  68893. return new DrawableImage (*this);
  68894. }
  68895. void DrawableImage::invalidatePoints()
  68896. {
  68897. }
  68898. const Identifier DrawableImage::valueTreeType ("Image");
  68899. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  68900. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  68901. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  68902. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  68903. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  68904. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68905. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68906. : ValueTreeWrapperBase (state_)
  68907. {
  68908. jassert (state.hasType (valueTreeType));
  68909. }
  68910. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  68911. {
  68912. return state [image];
  68913. }
  68914. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  68915. {
  68916. return state.getPropertyAsValue (image, undoManager);
  68917. }
  68918. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  68919. {
  68920. state.setProperty (image, newIdentifier, undoManager);
  68921. }
  68922. float DrawableImage::ValueTreeWrapper::getOpacity() const
  68923. {
  68924. return (float) state.getProperty (opacity, 1.0);
  68925. }
  68926. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  68927. {
  68928. if (! state.hasProperty (opacity))
  68929. state.setProperty (opacity, 1.0, undoManager);
  68930. return state.getPropertyAsValue (opacity, undoManager);
  68931. }
  68932. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  68933. {
  68934. state.setProperty (opacity, newOpacity, undoManager);
  68935. }
  68936. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  68937. {
  68938. return Colour (state [overlay].toString().getHexValue32());
  68939. }
  68940. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  68941. {
  68942. if (newColour.isTransparent())
  68943. state.removeProperty (overlay, undoManager);
  68944. else
  68945. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  68946. }
  68947. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  68948. {
  68949. return state.getPropertyAsValue (overlay, undoManager);
  68950. }
  68951. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  68952. {
  68953. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68954. state.getProperty (topRight, "100, 0"),
  68955. state.getProperty (bottomLeft, "0, 100"));
  68956. }
  68957. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68958. {
  68959. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68960. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68961. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68962. }
  68963. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68964. {
  68965. const ValueTreeWrapper controller (tree);
  68966. setName (controller.getID());
  68967. const float newOpacity = controller.getOpacity();
  68968. const Colour newOverlayColour (controller.getOverlayColour());
  68969. Image newImage;
  68970. const var imageIdentifier (controller.getImageIdentifier());
  68971. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  68972. if (imageProvider != 0)
  68973. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  68974. const RelativeParallelogram newBounds (controller.getBoundingBox());
  68975. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  68976. {
  68977. const Rectangle<float> damage (getBounds());
  68978. opacity = newOpacity;
  68979. overlayColour = newOverlayColour;
  68980. bounds = newBounds;
  68981. image = newImage;
  68982. return damage.getUnion (getBounds());
  68983. }
  68984. return Rectangle<float>();
  68985. }
  68986. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  68987. {
  68988. ValueTree tree (valueTreeType);
  68989. ValueTreeWrapper v (tree);
  68990. v.setID (getName(), 0);
  68991. v.setOpacity (opacity, 0);
  68992. v.setOverlayColour (overlayColour, 0);
  68993. v.setBoundingBox (bounds, 0);
  68994. if (image.isValid())
  68995. {
  68996. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  68997. if (imageProvider != 0)
  68998. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  68999. }
  69000. return tree;
  69001. }
  69002. END_JUCE_NAMESPACE
  69003. /*** End of inlined file: juce_DrawableImage.cpp ***/
  69004. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  69005. BEGIN_JUCE_NAMESPACE
  69006. DrawablePath::DrawablePath()
  69007. : mainFill (Colours::black),
  69008. strokeFill (Colours::black),
  69009. strokeType (0.0f),
  69010. pathNeedsUpdating (true),
  69011. strokeNeedsUpdating (true)
  69012. {
  69013. }
  69014. DrawablePath::DrawablePath (const DrawablePath& other)
  69015. : mainFill (other.mainFill),
  69016. strokeFill (other.strokeFill),
  69017. strokeType (other.strokeType),
  69018. pathNeedsUpdating (true),
  69019. strokeNeedsUpdating (true)
  69020. {
  69021. if (other.relativePath != 0)
  69022. relativePath = new RelativePointPath (*other.relativePath);
  69023. else
  69024. path = other.path;
  69025. }
  69026. DrawablePath::~DrawablePath()
  69027. {
  69028. }
  69029. void DrawablePath::setPath (const Path& newPath)
  69030. {
  69031. path = newPath;
  69032. strokeNeedsUpdating = true;
  69033. }
  69034. void DrawablePath::setFill (const FillType& newFill)
  69035. {
  69036. mainFill = newFill;
  69037. }
  69038. void DrawablePath::setStrokeFill (const FillType& newFill)
  69039. {
  69040. strokeFill = newFill;
  69041. }
  69042. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  69043. {
  69044. strokeType = newStrokeType;
  69045. strokeNeedsUpdating = true;
  69046. }
  69047. void DrawablePath::setStrokeThickness (const float newThickness)
  69048. {
  69049. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69050. }
  69051. void DrawablePath::updatePath() const
  69052. {
  69053. if (pathNeedsUpdating)
  69054. {
  69055. pathNeedsUpdating = false;
  69056. if (relativePath != 0)
  69057. {
  69058. path.clear();
  69059. relativePath->createPath (path, parent);
  69060. strokeNeedsUpdating = true;
  69061. }
  69062. }
  69063. }
  69064. void DrawablePath::updateStroke() const
  69065. {
  69066. if (strokeNeedsUpdating)
  69067. {
  69068. strokeNeedsUpdating = false;
  69069. updatePath();
  69070. stroke.clear();
  69071. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  69072. }
  69073. }
  69074. const Path& DrawablePath::getPath() const
  69075. {
  69076. updatePath();
  69077. return path;
  69078. }
  69079. const Path& DrawablePath::getStrokePath() const
  69080. {
  69081. updateStroke();
  69082. return stroke;
  69083. }
  69084. bool DrawablePath::isStrokeVisible() const throw()
  69085. {
  69086. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69087. }
  69088. void DrawablePath::invalidatePoints()
  69089. {
  69090. pathNeedsUpdating = true;
  69091. strokeNeedsUpdating = true;
  69092. }
  69093. void DrawablePath::render (const Drawable::RenderingContext& context) const
  69094. {
  69095. {
  69096. FillType f (mainFill);
  69097. if (f.isGradient())
  69098. f.gradient->multiplyOpacity (context.opacity);
  69099. f.transform = f.transform.followedBy (context.transform);
  69100. context.g.setFillType (f);
  69101. context.g.fillPath (getPath(), context.transform);
  69102. }
  69103. if (isStrokeVisible())
  69104. {
  69105. FillType f (strokeFill);
  69106. if (f.isGradient())
  69107. f.gradient->multiplyOpacity (context.opacity);
  69108. f.transform = f.transform.followedBy (context.transform);
  69109. context.g.setFillType (f);
  69110. context.g.fillPath (getStrokePath(), context.transform);
  69111. }
  69112. }
  69113. const Rectangle<float> DrawablePath::getBounds() const
  69114. {
  69115. if (isStrokeVisible())
  69116. return getStrokePath().getBounds();
  69117. else
  69118. return getPath().getBounds();
  69119. }
  69120. bool DrawablePath::hitTest (float x, float y) const
  69121. {
  69122. return getPath().contains (x, y)
  69123. || (isStrokeVisible() && getStrokePath().contains (x, y));
  69124. }
  69125. Drawable* DrawablePath::createCopy() const
  69126. {
  69127. return new DrawablePath (*this);
  69128. }
  69129. const Identifier DrawablePath::valueTreeType ("Path");
  69130. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  69131. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  69132. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  69133. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  69134. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  69135. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  69136. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  69137. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  69138. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  69139. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  69140. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69141. : ValueTreeWrapperBase (state_)
  69142. {
  69143. jassert (state.hasType (valueTreeType));
  69144. }
  69145. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  69146. {
  69147. return state.getOrCreateChildWithName (path, 0);
  69148. }
  69149. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  69150. {
  69151. ValueTree v (state.getChildWithName (fill));
  69152. if (v.isValid())
  69153. return v;
  69154. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69155. return getMainFillState();
  69156. }
  69157. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  69158. {
  69159. ValueTree v (state.getChildWithName (stroke));
  69160. if (v.isValid())
  69161. return v;
  69162. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69163. return getStrokeFillState();
  69164. }
  69165. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69166. ImageProvider* imageProvider) const
  69167. {
  69168. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69169. }
  69170. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  69171. const RelativePoint* gp2, const RelativePoint* gp3,
  69172. ImageProvider* imageProvider, UndoManager* undoManager)
  69173. {
  69174. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69175. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69176. }
  69177. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69178. ImageProvider* imageProvider) const
  69179. {
  69180. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69181. }
  69182. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  69183. const RelativePoint* gp2, const RelativePoint* gp3,
  69184. ImageProvider* imageProvider, UndoManager* undoManager)
  69185. {
  69186. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69187. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69188. }
  69189. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  69190. {
  69191. const String jointStyleString (state [jointStyle].toString());
  69192. const String capStyleString (state [capStyle].toString());
  69193. return PathStrokeType (state [strokeWidth],
  69194. jointStyleString == "curved" ? PathStrokeType::curved
  69195. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69196. : PathStrokeType::mitered),
  69197. capStyleString == "square" ? PathStrokeType::square
  69198. : (capStyleString == "round" ? PathStrokeType::rounded
  69199. : PathStrokeType::butt));
  69200. }
  69201. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69202. {
  69203. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69204. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69205. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69206. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69207. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69208. }
  69209. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69210. {
  69211. return state [nonZeroWinding];
  69212. }
  69213. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69214. {
  69215. state.setProperty (nonZeroWinding, b, undoManager);
  69216. }
  69217. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  69218. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69219. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69220. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69221. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69222. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69223. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69224. : state (state_)
  69225. {
  69226. }
  69227. DrawablePath::ValueTreeWrapper::Element::~Element()
  69228. {
  69229. }
  69230. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69231. {
  69232. return ValueTreeWrapper (state.getParent().getParent());
  69233. }
  69234. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  69235. {
  69236. return Element (state.getSibling (-1));
  69237. }
  69238. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  69239. {
  69240. const Identifier i (state.getType());
  69241. if (i == startSubPathElement || i == lineToElement) return 1;
  69242. if (i == quadraticToElement) return 2;
  69243. if (i == cubicToElement) return 3;
  69244. return 0;
  69245. }
  69246. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  69247. {
  69248. jassert (index >= 0 && index < getNumControlPoints());
  69249. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  69250. }
  69251. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  69252. {
  69253. jassert (index >= 0 && index < getNumControlPoints());
  69254. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  69255. }
  69256. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  69257. {
  69258. jassert (index >= 0 && index < getNumControlPoints());
  69259. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  69260. }
  69261. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  69262. {
  69263. const Identifier i (state.getType());
  69264. if (i == startSubPathElement)
  69265. return getControlPoint (0);
  69266. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  69267. return getPreviousElement().getEndPoint();
  69268. }
  69269. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  69270. {
  69271. const Identifier i (state.getType());
  69272. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  69273. if (i == quadraticToElement) return getControlPoint (1);
  69274. if (i == cubicToElement) return getControlPoint (2);
  69275. jassert (i == closeSubPathElement);
  69276. return RelativePoint();
  69277. }
  69278. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  69279. {
  69280. return state [mode].toString();
  69281. }
  69282. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  69283. {
  69284. if (state.hasType (cubicToElement))
  69285. state.setProperty (mode, newMode, undoManager);
  69286. }
  69287. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  69288. {
  69289. const Identifier i (state.getType());
  69290. if (i == quadraticToElement || i == cubicToElement)
  69291. {
  69292. ValueTree newState (lineToElement);
  69293. Element e (newState);
  69294. e.setControlPoint (0, getEndPoint(), undoManager);
  69295. state = newState;
  69296. }
  69297. }
  69298. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  69299. {
  69300. const Identifier i (state.getType());
  69301. if (i == lineToElement || i == quadraticToElement)
  69302. {
  69303. ValueTree newState (cubicToElement);
  69304. Element e (newState);
  69305. const RelativePoint start (getStartPoint());
  69306. const RelativePoint end (getEndPoint());
  69307. const Point<float> startResolved (start.resolve (nameFinder));
  69308. const Point<float> endResolved (end.resolve (nameFinder));
  69309. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  69310. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  69311. e.setControlPoint (2, end, undoManager);
  69312. state = newState;
  69313. }
  69314. }
  69315. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  69316. {
  69317. const Identifier i (state.getType());
  69318. if (i != startSubPathElement)
  69319. {
  69320. ValueTree newState (startSubPathElement);
  69321. Element e (newState);
  69322. e.setControlPoint (0, getEndPoint(), undoManager);
  69323. state = newState;
  69324. }
  69325. }
  69326. void DrawablePath::ValueTreeWrapper::Element::insertPoint (double, RelativeCoordinate::NamedCoordinateFinder*, UndoManager*)
  69327. {
  69328. }
  69329. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  69330. {
  69331. state.getParent().removeChild (state, undoManager);
  69332. }
  69333. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69334. {
  69335. Rectangle<float> damageRect;
  69336. ValueTreeWrapper v (tree);
  69337. setName (v.getID());
  69338. bool needsRedraw = false;
  69339. const FillType newFill (v.getMainFill (parent, imageProvider));
  69340. if (mainFill != newFill)
  69341. {
  69342. needsRedraw = true;
  69343. mainFill = newFill;
  69344. }
  69345. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  69346. if (strokeFill != newStrokeFill)
  69347. {
  69348. needsRedraw = true;
  69349. strokeFill = newStrokeFill;
  69350. }
  69351. const PathStrokeType newStroke (v.getStrokeType());
  69352. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  69353. Path newPath;
  69354. newRelativePath->createPath (newPath, parent);
  69355. if (! newRelativePath->containsAnyDynamicPoints())
  69356. newRelativePath = 0;
  69357. if (strokeType != newStroke || path != newPath)
  69358. {
  69359. damageRect = getBounds();
  69360. path.swapWithPath (newPath);
  69361. strokeNeedsUpdating = true;
  69362. strokeType = newStroke;
  69363. needsRedraw = true;
  69364. }
  69365. relativePath = newRelativePath;
  69366. if (needsRedraw)
  69367. damageRect = damageRect.getUnion (getBounds());
  69368. return damageRect;
  69369. }
  69370. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  69371. {
  69372. ValueTree tree (valueTreeType);
  69373. ValueTreeWrapper v (tree);
  69374. v.setID (getName(), 0);
  69375. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  69376. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  69377. v.setStrokeType (strokeType, 0);
  69378. if (relativePath != 0)
  69379. {
  69380. relativePath->writeTo (tree, 0);
  69381. }
  69382. else
  69383. {
  69384. RelativePointPath rp (path);
  69385. rp.writeTo (tree, 0);
  69386. }
  69387. return tree;
  69388. }
  69389. END_JUCE_NAMESPACE
  69390. /*** End of inlined file: juce_DrawablePath.cpp ***/
  69391. /*** Start of inlined file: juce_DrawableText.cpp ***/
  69392. BEGIN_JUCE_NAMESPACE
  69393. DrawableText::DrawableText()
  69394. : colour (Colours::black),
  69395. justification (Justification::centredLeft)
  69396. {
  69397. setFont (Font (15.0f), true);
  69398. }
  69399. DrawableText::DrawableText (const DrawableText& other)
  69400. : text (other.text),
  69401. font (other.font),
  69402. colour (other.colour),
  69403. justification (other.justification),
  69404. bounds (other.bounds),
  69405. fontSizeControlPoint (other.fontSizeControlPoint)
  69406. {
  69407. }
  69408. DrawableText::~DrawableText()
  69409. {
  69410. }
  69411. void DrawableText::setText (const String& newText)
  69412. {
  69413. text = newText;
  69414. }
  69415. void DrawableText::setColour (const Colour& newColour)
  69416. {
  69417. colour = newColour;
  69418. }
  69419. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  69420. {
  69421. font = newFont;
  69422. if (applySizeAndScale)
  69423. {
  69424. Point<float> corners[3];
  69425. bounds.resolveThreePoints (corners, parent);
  69426. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  69427. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  69428. }
  69429. }
  69430. void DrawableText::setJustification (const Justification& newJustification)
  69431. {
  69432. justification = newJustification;
  69433. }
  69434. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  69435. {
  69436. bounds = newBounds;
  69437. }
  69438. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  69439. {
  69440. fontSizeControlPoint = newPoint;
  69441. }
  69442. void DrawableText::render (const Drawable::RenderingContext& context) const
  69443. {
  69444. Point<float> points[3];
  69445. bounds.resolveThreePoints (points, parent);
  69446. const float w = Line<float> (points[0], points[1]).getLength();
  69447. const float h = Line<float> (points[0], points[2]).getLength();
  69448. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  69449. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  69450. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  69451. Font f (font);
  69452. f.setHeight (fontHeight);
  69453. f.setHorizontalScale (fontWidth / fontHeight);
  69454. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  69455. GlyphArrangement ga;
  69456. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  69457. ga.draw (context.g,
  69458. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  69459. w, 0, points[1].getX(), points[1].getY(),
  69460. 0, h, points[2].getX(), points[2].getY())
  69461. .followedBy (context.transform));
  69462. }
  69463. const Rectangle<float> DrawableText::getBounds() const
  69464. {
  69465. return bounds.getBounds (parent);
  69466. }
  69467. bool DrawableText::hitTest (float x, float y) const
  69468. {
  69469. Path p;
  69470. bounds.getPath (p, parent);
  69471. return p.contains (x, y);
  69472. }
  69473. Drawable* DrawableText::createCopy() const
  69474. {
  69475. return new DrawableText (*this);
  69476. }
  69477. void DrawableText::invalidatePoints()
  69478. {
  69479. }
  69480. const Identifier DrawableText::valueTreeType ("Text");
  69481. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  69482. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  69483. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  69484. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  69485. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  69486. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  69487. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69488. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  69489. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69490. : ValueTreeWrapperBase (state_)
  69491. {
  69492. jassert (state.hasType (valueTreeType));
  69493. }
  69494. const String DrawableText::ValueTreeWrapper::getText() const
  69495. {
  69496. return state [text].toString();
  69497. }
  69498. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  69499. {
  69500. state.setProperty (text, newText, undoManager);
  69501. }
  69502. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  69503. {
  69504. return state.getPropertyAsValue (text, undoManager);
  69505. }
  69506. const Colour DrawableText::ValueTreeWrapper::getColour() const
  69507. {
  69508. return Colour::fromString (state [colour].toString());
  69509. }
  69510. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  69511. {
  69512. state.setProperty (colour, newColour.toString(), undoManager);
  69513. }
  69514. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  69515. {
  69516. return Justification ((int) state [justification]);
  69517. }
  69518. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  69519. {
  69520. state.setProperty (justification, newJustification.getFlags(), undoManager);
  69521. }
  69522. const Font DrawableText::ValueTreeWrapper::getFont() const
  69523. {
  69524. return Font::fromString (state [font]);
  69525. }
  69526. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  69527. {
  69528. state.setProperty (font, newFont.toString(), undoManager);
  69529. }
  69530. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  69531. {
  69532. return state.getPropertyAsValue (font, undoManager);
  69533. }
  69534. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  69535. {
  69536. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  69537. }
  69538. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69539. {
  69540. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69541. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69542. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69543. }
  69544. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  69545. {
  69546. return state [fontSizeAnchor].toString();
  69547. }
  69548. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  69549. {
  69550. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  69551. }
  69552. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  69553. {
  69554. ValueTreeWrapper v (tree);
  69555. setName (v.getID());
  69556. const RelativeParallelogram newBounds (v.getBoundingBox());
  69557. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  69558. const Colour newColour (v.getColour());
  69559. const Justification newJustification (v.getJustification());
  69560. const String newText (v.getText());
  69561. const Font newFont (v.getFont());
  69562. if (text != newText || font != newFont || justification != newJustification
  69563. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  69564. {
  69565. const Rectangle<float> damage (getBounds());
  69566. setBoundingBox (newBounds);
  69567. setFontSizeControlPoint (newFontPoint);
  69568. setColour (newColour);
  69569. setFont (newFont, false);
  69570. setJustification (newJustification);
  69571. setText (newText);
  69572. return damage.getUnion (getBounds());
  69573. }
  69574. return Rectangle<float>();
  69575. }
  69576. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  69577. {
  69578. ValueTree tree (valueTreeType);
  69579. ValueTreeWrapper v (tree);
  69580. v.setID (getName(), 0);
  69581. v.setText (text, 0);
  69582. v.setFont (font, 0);
  69583. v.setJustification (justification, 0);
  69584. v.setColour (colour, 0);
  69585. v.setBoundingBox (bounds, 0);
  69586. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  69587. return tree;
  69588. }
  69589. END_JUCE_NAMESPACE
  69590. /*** End of inlined file: juce_DrawableText.cpp ***/
  69591. /*** Start of inlined file: juce_SVGParser.cpp ***/
  69592. BEGIN_JUCE_NAMESPACE
  69593. class SVGState
  69594. {
  69595. public:
  69596. SVGState (const XmlElement* const topLevel)
  69597. : topLevelXml (topLevel),
  69598. elementX (0), elementY (0),
  69599. width (512), height (512),
  69600. viewBoxW (0), viewBoxH (0)
  69601. {
  69602. }
  69603. ~SVGState()
  69604. {
  69605. }
  69606. Drawable* parseSVGElement (const XmlElement& xml)
  69607. {
  69608. if (! xml.hasTagName ("svg"))
  69609. return 0;
  69610. DrawableComposite* const drawable = new DrawableComposite();
  69611. drawable->setName (xml.getStringAttribute ("id"));
  69612. SVGState newState (*this);
  69613. if (xml.hasAttribute ("transform"))
  69614. newState.addTransform (xml);
  69615. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  69616. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  69617. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  69618. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  69619. if (xml.hasAttribute ("viewBox"))
  69620. {
  69621. const String viewParams (xml.getStringAttribute ("viewBox"));
  69622. int i = 0;
  69623. float vx, vy, vw, vh;
  69624. if (parseCoords (viewParams, vx, vy, i, true)
  69625. && parseCoords (viewParams, vw, vh, i, true)
  69626. && vw > 0
  69627. && vh > 0)
  69628. {
  69629. newState.viewBoxW = vw;
  69630. newState.viewBoxH = vh;
  69631. int placementFlags = 0;
  69632. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  69633. if (aspect.containsIgnoreCase ("none"))
  69634. {
  69635. placementFlags = RectanglePlacement::stretchToFit;
  69636. }
  69637. else
  69638. {
  69639. if (aspect.containsIgnoreCase ("slice"))
  69640. placementFlags |= RectanglePlacement::fillDestination;
  69641. if (aspect.containsIgnoreCase ("xMin"))
  69642. placementFlags |= RectanglePlacement::xLeft;
  69643. else if (aspect.containsIgnoreCase ("xMax"))
  69644. placementFlags |= RectanglePlacement::xRight;
  69645. else
  69646. placementFlags |= RectanglePlacement::xMid;
  69647. if (aspect.containsIgnoreCase ("yMin"))
  69648. placementFlags |= RectanglePlacement::yTop;
  69649. else if (aspect.containsIgnoreCase ("yMax"))
  69650. placementFlags |= RectanglePlacement::yBottom;
  69651. else
  69652. placementFlags |= RectanglePlacement::yMid;
  69653. }
  69654. const RectanglePlacement placement (placementFlags);
  69655. newState.transform
  69656. = placement.getTransformToFit (vx, vy, vw, vh,
  69657. 0.0f, 0.0f, newState.width, newState.height)
  69658. .followedBy (newState.transform);
  69659. }
  69660. }
  69661. else
  69662. {
  69663. if (viewBoxW == 0)
  69664. newState.viewBoxW = newState.width;
  69665. if (viewBoxH == 0)
  69666. newState.viewBoxH = newState.height;
  69667. }
  69668. newState.parseSubElements (xml, drawable);
  69669. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69670. return drawable;
  69671. }
  69672. private:
  69673. const XmlElement* const topLevelXml;
  69674. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  69675. AffineTransform transform;
  69676. String cssStyleText;
  69677. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  69678. {
  69679. forEachXmlChildElement (xml, e)
  69680. {
  69681. Drawable* d = 0;
  69682. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  69683. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  69684. else if (e->hasTagName ("path")) d = parsePath (*e);
  69685. else if (e->hasTagName ("rect")) d = parseRect (*e);
  69686. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  69687. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  69688. else if (e->hasTagName ("line")) d = parseLine (*e);
  69689. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  69690. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  69691. else if (e->hasTagName ("text")) d = parseText (*e);
  69692. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  69693. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  69694. parentDrawable->insertDrawable (d);
  69695. }
  69696. }
  69697. DrawableComposite* parseSwitch (const XmlElement& xml)
  69698. {
  69699. const XmlElement* const group = xml.getChildByName ("g");
  69700. if (group != 0)
  69701. return parseGroupElement (*group);
  69702. return 0;
  69703. }
  69704. DrawableComposite* parseGroupElement (const XmlElement& xml)
  69705. {
  69706. DrawableComposite* const drawable = new DrawableComposite();
  69707. drawable->setName (xml.getStringAttribute ("id"));
  69708. if (xml.hasAttribute ("transform"))
  69709. {
  69710. SVGState newState (*this);
  69711. newState.addTransform (xml);
  69712. newState.parseSubElements (xml, drawable);
  69713. }
  69714. else
  69715. {
  69716. parseSubElements (xml, drawable);
  69717. }
  69718. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69719. return drawable;
  69720. }
  69721. Drawable* parsePath (const XmlElement& xml) const
  69722. {
  69723. const String d (xml.getStringAttribute ("d").trimStart());
  69724. Path path;
  69725. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  69726. path.setUsingNonZeroWinding (false);
  69727. int index = 0;
  69728. float lastX = 0, lastY = 0;
  69729. float lastX2 = 0, lastY2 = 0;
  69730. juce_wchar lastCommandChar = 0;
  69731. bool isRelative = true;
  69732. bool carryOn = true;
  69733. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  69734. while (d[index] != 0)
  69735. {
  69736. float x, y, x2, y2, x3, y3;
  69737. if (validCommandChars.containsChar (d[index]))
  69738. {
  69739. lastCommandChar = d [index++];
  69740. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  69741. }
  69742. switch (lastCommandChar)
  69743. {
  69744. case 'M':
  69745. case 'm':
  69746. case 'L':
  69747. case 'l':
  69748. if (parseCoords (d, x, y, index, false))
  69749. {
  69750. if (isRelative)
  69751. {
  69752. x += lastX;
  69753. y += lastY;
  69754. }
  69755. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  69756. {
  69757. path.startNewSubPath (x, y);
  69758. lastCommandChar = 'l';
  69759. }
  69760. else
  69761. path.lineTo (x, y);
  69762. lastX2 = lastX;
  69763. lastY2 = lastY;
  69764. lastX = x;
  69765. lastY = y;
  69766. }
  69767. else
  69768. {
  69769. ++index;
  69770. }
  69771. break;
  69772. case 'H':
  69773. case 'h':
  69774. if (parseCoord (d, x, index, false, true))
  69775. {
  69776. if (isRelative)
  69777. x += lastX;
  69778. path.lineTo (x, lastY);
  69779. lastX2 = lastX;
  69780. lastX = x;
  69781. }
  69782. else
  69783. {
  69784. ++index;
  69785. }
  69786. break;
  69787. case 'V':
  69788. case 'v':
  69789. if (parseCoord (d, y, index, false, false))
  69790. {
  69791. if (isRelative)
  69792. y += lastY;
  69793. path.lineTo (lastX, y);
  69794. lastY2 = lastY;
  69795. lastY = y;
  69796. }
  69797. else
  69798. {
  69799. ++index;
  69800. }
  69801. break;
  69802. case 'C':
  69803. case 'c':
  69804. if (parseCoords (d, x, y, index, false)
  69805. && parseCoords (d, x2, y2, index, false)
  69806. && parseCoords (d, x3, y3, index, false))
  69807. {
  69808. if (isRelative)
  69809. {
  69810. x += lastX;
  69811. y += lastY;
  69812. x2 += lastX;
  69813. y2 += lastY;
  69814. x3 += lastX;
  69815. y3 += lastY;
  69816. }
  69817. path.cubicTo (x, y, x2, y2, x3, y3);
  69818. lastX2 = x2;
  69819. lastY2 = y2;
  69820. lastX = x3;
  69821. lastY = y3;
  69822. }
  69823. else
  69824. {
  69825. ++index;
  69826. }
  69827. break;
  69828. case 'S':
  69829. case 's':
  69830. if (parseCoords (d, x, y, index, false)
  69831. && parseCoords (d, x3, y3, index, false))
  69832. {
  69833. if (isRelative)
  69834. {
  69835. x += lastX;
  69836. y += lastY;
  69837. x3 += lastX;
  69838. y3 += lastY;
  69839. }
  69840. x2 = lastX + (lastX - lastX2);
  69841. y2 = lastY + (lastY - lastY2);
  69842. path.cubicTo (x2, y2, x, y, x3, y3);
  69843. lastX2 = x;
  69844. lastY2 = y;
  69845. lastX = x3;
  69846. lastY = y3;
  69847. }
  69848. else
  69849. {
  69850. ++index;
  69851. }
  69852. break;
  69853. case 'Q':
  69854. case 'q':
  69855. if (parseCoords (d, x, y, index, false)
  69856. && parseCoords (d, x2, y2, index, false))
  69857. {
  69858. if (isRelative)
  69859. {
  69860. x += lastX;
  69861. y += lastY;
  69862. x2 += lastX;
  69863. y2 += lastY;
  69864. }
  69865. path.quadraticTo (x, y, x2, y2);
  69866. lastX2 = x;
  69867. lastY2 = y;
  69868. lastX = x2;
  69869. lastY = y2;
  69870. }
  69871. else
  69872. {
  69873. ++index;
  69874. }
  69875. break;
  69876. case 'T':
  69877. case 't':
  69878. if (parseCoords (d, x, y, index, false))
  69879. {
  69880. if (isRelative)
  69881. {
  69882. x += lastX;
  69883. y += lastY;
  69884. }
  69885. x2 = lastX + (lastX - lastX2);
  69886. y2 = lastY + (lastY - lastY2);
  69887. path.quadraticTo (x2, y2, x, y);
  69888. lastX2 = x2;
  69889. lastY2 = y2;
  69890. lastX = x;
  69891. lastY = y;
  69892. }
  69893. else
  69894. {
  69895. ++index;
  69896. }
  69897. break;
  69898. case 'A':
  69899. case 'a':
  69900. if (parseCoords (d, x, y, index, false))
  69901. {
  69902. String num;
  69903. if (parseNextNumber (d, num, index, false))
  69904. {
  69905. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  69906. if (parseNextNumber (d, num, index, false))
  69907. {
  69908. const bool largeArc = num.getIntValue() != 0;
  69909. if (parseNextNumber (d, num, index, false))
  69910. {
  69911. const bool sweep = num.getIntValue() != 0;
  69912. if (parseCoords (d, x2, y2, index, false))
  69913. {
  69914. if (isRelative)
  69915. {
  69916. x2 += lastX;
  69917. y2 += lastY;
  69918. }
  69919. if (lastX != x2 || lastY != y2)
  69920. {
  69921. double centreX, centreY, startAngle, deltaAngle;
  69922. double rx = x, ry = y;
  69923. endpointToCentreParameters (lastX, lastY, x2, y2,
  69924. angle, largeArc, sweep,
  69925. rx, ry, centreX, centreY,
  69926. startAngle, deltaAngle);
  69927. path.addCentredArc ((float) centreX, (float) centreY,
  69928. (float) rx, (float) ry,
  69929. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  69930. false);
  69931. path.lineTo (x2, y2);
  69932. }
  69933. lastX2 = lastX;
  69934. lastY2 = lastY;
  69935. lastX = x2;
  69936. lastY = y2;
  69937. }
  69938. }
  69939. }
  69940. }
  69941. }
  69942. else
  69943. {
  69944. ++index;
  69945. }
  69946. break;
  69947. case 'Z':
  69948. case 'z':
  69949. path.closeSubPath();
  69950. while (CharacterFunctions::isWhitespace (d [index]))
  69951. ++index;
  69952. break;
  69953. default:
  69954. carryOn = false;
  69955. break;
  69956. }
  69957. if (! carryOn)
  69958. break;
  69959. }
  69960. return parseShape (xml, path);
  69961. }
  69962. Drawable* parseRect (const XmlElement& xml) const
  69963. {
  69964. Path rect;
  69965. const bool hasRX = xml.hasAttribute ("rx");
  69966. const bool hasRY = xml.hasAttribute ("ry");
  69967. if (hasRX || hasRY)
  69968. {
  69969. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69970. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69971. if (! hasRX)
  69972. rx = ry;
  69973. else if (! hasRY)
  69974. ry = rx;
  69975. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69976. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69977. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69978. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  69979. rx, ry);
  69980. }
  69981. else
  69982. {
  69983. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69984. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69985. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69986. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  69987. }
  69988. return parseShape (xml, rect);
  69989. }
  69990. Drawable* parseCircle (const XmlElement& xml) const
  69991. {
  69992. Path circle;
  69993. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69994. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69995. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  69996. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  69997. return parseShape (xml, circle);
  69998. }
  69999. Drawable* parseEllipse (const XmlElement& xml) const
  70000. {
  70001. Path ellipse;
  70002. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70003. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70004. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70005. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70006. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  70007. return parseShape (xml, ellipse);
  70008. }
  70009. Drawable* parseLine (const XmlElement& xml) const
  70010. {
  70011. Path line;
  70012. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  70013. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  70014. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  70015. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  70016. line.startNewSubPath (x1, y1);
  70017. line.lineTo (x2, y2);
  70018. return parseShape (xml, line);
  70019. }
  70020. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  70021. {
  70022. const String points (xml.getStringAttribute ("points"));
  70023. Path path;
  70024. int index = 0;
  70025. float x, y;
  70026. if (parseCoords (points, x, y, index, true))
  70027. {
  70028. float firstX = x;
  70029. float firstY = y;
  70030. float lastX = 0, lastY = 0;
  70031. path.startNewSubPath (x, y);
  70032. while (parseCoords (points, x, y, index, true))
  70033. {
  70034. lastX = x;
  70035. lastY = y;
  70036. path.lineTo (x, y);
  70037. }
  70038. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  70039. path.closeSubPath();
  70040. }
  70041. return parseShape (xml, path);
  70042. }
  70043. Drawable* parseShape (const XmlElement& xml, Path& path,
  70044. const bool shouldParseTransform = true) const
  70045. {
  70046. if (shouldParseTransform && xml.hasAttribute ("transform"))
  70047. {
  70048. SVGState newState (*this);
  70049. newState.addTransform (xml);
  70050. return newState.parseShape (xml, path, false);
  70051. }
  70052. DrawablePath* dp = new DrawablePath();
  70053. dp->setName (xml.getStringAttribute ("id"));
  70054. dp->setFill (Colours::transparentBlack);
  70055. path.applyTransform (transform);
  70056. dp->setPath (path);
  70057. Path::Iterator iter (path);
  70058. bool containsClosedSubPath = false;
  70059. while (iter.next())
  70060. {
  70061. if (iter.elementType == Path::Iterator::closePath)
  70062. {
  70063. containsClosedSubPath = true;
  70064. break;
  70065. }
  70066. }
  70067. dp->setFill (getPathFillType (path,
  70068. getStyleAttribute (&xml, "fill"),
  70069. getStyleAttribute (&xml, "fill-opacity"),
  70070. getStyleAttribute (&xml, "opacity"),
  70071. containsClosedSubPath ? Colours::black
  70072. : Colours::transparentBlack));
  70073. const String strokeType (getStyleAttribute (&xml, "stroke"));
  70074. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  70075. {
  70076. dp->setStrokeFill (getPathFillType (path, strokeType,
  70077. getStyleAttribute (&xml, "stroke-opacity"),
  70078. getStyleAttribute (&xml, "opacity"),
  70079. Colours::transparentBlack));
  70080. dp->setStrokeType (getStrokeFor (&xml));
  70081. }
  70082. return dp;
  70083. }
  70084. const XmlElement* findLinkedElement (const XmlElement* e) const
  70085. {
  70086. const String id (e->getStringAttribute ("xlink:href"));
  70087. if (! id.startsWithChar ('#'))
  70088. return 0;
  70089. return findElementForId (topLevelXml, id.substring (1));
  70090. }
  70091. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  70092. {
  70093. if (fillXml == 0)
  70094. return;
  70095. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  70096. {
  70097. int index = 0;
  70098. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  70099. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  70100. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  70101. double offset = e->getDoubleAttribute ("offset");
  70102. if (e->getStringAttribute ("offset").containsChar ('%'))
  70103. offset *= 0.01;
  70104. cg.addColour (jlimit (0.0, 1.0, offset), col);
  70105. }
  70106. }
  70107. const FillType getPathFillType (const Path& path,
  70108. const String& fill,
  70109. const String& fillOpacity,
  70110. const String& overallOpacity,
  70111. const Colour& defaultColour) const
  70112. {
  70113. float opacity = 1.0f;
  70114. if (overallOpacity.isNotEmpty())
  70115. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  70116. if (fillOpacity.isNotEmpty())
  70117. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  70118. if (fill.startsWithIgnoreCase ("url"))
  70119. {
  70120. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  70121. .upToLastOccurrenceOf (")", false, false).trim());
  70122. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  70123. if (fillXml != 0
  70124. && (fillXml->hasTagName ("linearGradient")
  70125. || fillXml->hasTagName ("radialGradient")))
  70126. {
  70127. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  70128. ColourGradient gradient;
  70129. addGradientStopsIn (gradient, inheritedFrom);
  70130. addGradientStopsIn (gradient, fillXml);
  70131. if (gradient.getNumColours() > 0)
  70132. {
  70133. gradient.addColour (0.0, gradient.getColour (0));
  70134. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  70135. }
  70136. else
  70137. {
  70138. gradient.addColour (0.0, Colours::black);
  70139. gradient.addColour (1.0, Colours::black);
  70140. }
  70141. if (overallOpacity.isNotEmpty())
  70142. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  70143. jassert (gradient.getNumColours() > 0);
  70144. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  70145. float gradientWidth = viewBoxW;
  70146. float gradientHeight = viewBoxH;
  70147. float dx = 0.0f;
  70148. float dy = 0.0f;
  70149. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  70150. if (! userSpace)
  70151. {
  70152. const Rectangle<float> bounds (path.getBounds());
  70153. dx = bounds.getX();
  70154. dy = bounds.getY();
  70155. gradientWidth = bounds.getWidth();
  70156. gradientHeight = bounds.getHeight();
  70157. }
  70158. if (gradient.isRadial)
  70159. {
  70160. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  70161. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  70162. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  70163. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  70164. //xxx (the fx, fy focal point isn't handled properly here..)
  70165. }
  70166. else
  70167. {
  70168. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  70169. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  70170. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  70171. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  70172. if (gradient.point1 == gradient.point2)
  70173. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  70174. }
  70175. FillType type (gradient);
  70176. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  70177. .followedBy (transform);
  70178. return type;
  70179. }
  70180. }
  70181. if (fill.equalsIgnoreCase ("none"))
  70182. return Colours::transparentBlack;
  70183. int i = 0;
  70184. const Colour colour (parseColour (fill, i, defaultColour));
  70185. return colour.withMultipliedAlpha (opacity);
  70186. }
  70187. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  70188. {
  70189. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  70190. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  70191. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  70192. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  70193. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  70194. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  70195. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  70196. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  70197. if (join.equalsIgnoreCase ("round"))
  70198. joinStyle = PathStrokeType::curved;
  70199. else if (join.equalsIgnoreCase ("bevel"))
  70200. joinStyle = PathStrokeType::beveled;
  70201. if (cap.equalsIgnoreCase ("round"))
  70202. capStyle = PathStrokeType::rounded;
  70203. else if (cap.equalsIgnoreCase ("square"))
  70204. capStyle = PathStrokeType::square;
  70205. float ox = 0.0f, oy = 0.0f;
  70206. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  70207. transform.transformPoints (ox, oy, x, y);
  70208. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  70209. joinStyle, capStyle);
  70210. }
  70211. Drawable* parseText (const XmlElement& xml)
  70212. {
  70213. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  70214. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  70215. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  70216. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  70217. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  70218. //xxx not done text yet!
  70219. forEachXmlChildElement (xml, e)
  70220. {
  70221. if (e->isTextElement())
  70222. {
  70223. const String text (e->getText());
  70224. Path path;
  70225. Drawable* s = parseShape (*e, path);
  70226. delete s;
  70227. }
  70228. else if (e->hasTagName ("tspan"))
  70229. {
  70230. Drawable* s = parseText (*e);
  70231. delete s;
  70232. }
  70233. }
  70234. return 0;
  70235. }
  70236. void addTransform (const XmlElement& xml)
  70237. {
  70238. transform = parseTransform (xml.getStringAttribute ("transform"))
  70239. .followedBy (transform);
  70240. }
  70241. bool parseCoord (const String& s, float& value, int& index,
  70242. const bool allowUnits, const bool isX) const
  70243. {
  70244. String number;
  70245. if (! parseNextNumber (s, number, index, allowUnits))
  70246. {
  70247. value = 0;
  70248. return false;
  70249. }
  70250. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  70251. return true;
  70252. }
  70253. bool parseCoords (const String& s, float& x, float& y,
  70254. int& index, const bool allowUnits) const
  70255. {
  70256. return parseCoord (s, x, index, allowUnits, true)
  70257. && parseCoord (s, y, index, allowUnits, false);
  70258. }
  70259. float getCoordLength (const String& s, const float sizeForProportions) const
  70260. {
  70261. float n = s.getFloatValue();
  70262. const int len = s.length();
  70263. if (len > 2)
  70264. {
  70265. const float dpi = 96.0f;
  70266. const juce_wchar n1 = s [len - 2];
  70267. const juce_wchar n2 = s [len - 1];
  70268. if (n1 == 'i' && n2 == 'n')
  70269. n *= dpi;
  70270. else if (n1 == 'm' && n2 == 'm')
  70271. n *= dpi / 25.4f;
  70272. else if (n1 == 'c' && n2 == 'm')
  70273. n *= dpi / 2.54f;
  70274. else if (n1 == 'p' && n2 == 'c')
  70275. n *= 15.0f;
  70276. else if (n2 == '%')
  70277. n *= 0.01f * sizeForProportions;
  70278. }
  70279. return n;
  70280. }
  70281. void getCoordList (Array <float>& coords, const String& list,
  70282. const bool allowUnits, const bool isX) const
  70283. {
  70284. int index = 0;
  70285. float value;
  70286. while (parseCoord (list, value, index, allowUnits, isX))
  70287. coords.add (value);
  70288. }
  70289. void parseCSSStyle (const XmlElement& xml)
  70290. {
  70291. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  70292. }
  70293. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  70294. const String& defaultValue = String::empty) const
  70295. {
  70296. if (xml->hasAttribute (attributeName))
  70297. return xml->getStringAttribute (attributeName, defaultValue);
  70298. const String styleAtt (xml->getStringAttribute ("style"));
  70299. if (styleAtt.isNotEmpty())
  70300. {
  70301. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  70302. if (value.isNotEmpty())
  70303. return value;
  70304. }
  70305. else if (xml->hasAttribute ("class"))
  70306. {
  70307. const String className ("." + xml->getStringAttribute ("class"));
  70308. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  70309. if (index < 0)
  70310. index = cssStyleText.indexOfIgnoreCase (className + "{");
  70311. if (index >= 0)
  70312. {
  70313. const int openBracket = cssStyleText.indexOfChar (index, '{');
  70314. if (openBracket > index)
  70315. {
  70316. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  70317. if (closeBracket > openBracket)
  70318. {
  70319. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  70320. if (value.isNotEmpty())
  70321. return value;
  70322. }
  70323. }
  70324. }
  70325. }
  70326. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70327. if (xml != 0)
  70328. return getStyleAttribute (xml, attributeName, defaultValue);
  70329. return defaultValue;
  70330. }
  70331. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  70332. {
  70333. if (xml->hasAttribute (attributeName))
  70334. return xml->getStringAttribute (attributeName);
  70335. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70336. if (xml != 0)
  70337. return getInheritedAttribute (xml, attributeName);
  70338. return String::empty;
  70339. }
  70340. static bool isIdentifierChar (const juce_wchar c)
  70341. {
  70342. return CharacterFunctions::isLetter (c) || c == '-';
  70343. }
  70344. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  70345. {
  70346. int i = 0;
  70347. for (;;)
  70348. {
  70349. i = list.indexOf (i, attributeName);
  70350. if (i < 0)
  70351. break;
  70352. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  70353. && ! isIdentifierChar (list [i + attributeName.length()]))
  70354. {
  70355. i = list.indexOfChar (i, ':');
  70356. if (i < 0)
  70357. break;
  70358. int end = list.indexOfChar (i, ';');
  70359. if (end < 0)
  70360. end = 0x7ffff;
  70361. return list.substring (i + 1, end).trim();
  70362. }
  70363. ++i;
  70364. }
  70365. return defaultValue;
  70366. }
  70367. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  70368. {
  70369. const juce_wchar* const s = source;
  70370. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70371. ++index;
  70372. int start = index;
  70373. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  70374. ++index;
  70375. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  70376. ++index;
  70377. if ((s[index] == 'e' || s[index] == 'E')
  70378. && (CharacterFunctions::isDigit (s[index + 1])
  70379. || s[index + 1] == '-'
  70380. || s[index + 1] == '+'))
  70381. {
  70382. index += 2;
  70383. while (CharacterFunctions::isDigit (s[index]))
  70384. ++index;
  70385. }
  70386. if (allowUnits)
  70387. {
  70388. while (CharacterFunctions::isLetter (s[index]))
  70389. ++index;
  70390. }
  70391. if (index == start)
  70392. return false;
  70393. value = String (s + start, index - start);
  70394. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70395. ++index;
  70396. return true;
  70397. }
  70398. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  70399. {
  70400. if (s [index] == '#')
  70401. {
  70402. uint32 hex [6];
  70403. zeromem (hex, sizeof (hex));
  70404. int numChars = 0;
  70405. for (int i = 6; --i >= 0;)
  70406. {
  70407. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  70408. if (hexValue >= 0)
  70409. hex [numChars++] = hexValue;
  70410. else
  70411. break;
  70412. }
  70413. if (numChars <= 3)
  70414. return Colour ((uint8) (hex [0] * 0x11),
  70415. (uint8) (hex [1] * 0x11),
  70416. (uint8) (hex [2] * 0x11));
  70417. else
  70418. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  70419. (uint8) ((hex [2] << 4) + hex [3]),
  70420. (uint8) ((hex [4] << 4) + hex [5]));
  70421. }
  70422. else if (s [index] == 'r'
  70423. && s [index + 1] == 'g'
  70424. && s [index + 2] == 'b')
  70425. {
  70426. const int openBracket = s.indexOfChar (index, '(');
  70427. const int closeBracket = s.indexOfChar (openBracket, ')');
  70428. if (openBracket >= 3 && closeBracket > openBracket)
  70429. {
  70430. index = closeBracket;
  70431. StringArray tokens;
  70432. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  70433. tokens.trim();
  70434. tokens.removeEmptyStrings();
  70435. if (tokens[0].containsChar ('%'))
  70436. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  70437. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  70438. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  70439. else
  70440. return Colour ((uint8) tokens[0].getIntValue(),
  70441. (uint8) tokens[1].getIntValue(),
  70442. (uint8) tokens[2].getIntValue());
  70443. }
  70444. }
  70445. return Colours::findColourForName (s, defaultColour);
  70446. }
  70447. static const AffineTransform parseTransform (String t)
  70448. {
  70449. AffineTransform result;
  70450. while (t.isNotEmpty())
  70451. {
  70452. StringArray tokens;
  70453. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  70454. .upToFirstOccurrenceOf (")", false, false),
  70455. ", ", String::empty);
  70456. tokens.removeEmptyStrings (true);
  70457. float numbers [6];
  70458. for (int i = 0; i < 6; ++i)
  70459. numbers[i] = tokens[i].getFloatValue();
  70460. AffineTransform trans;
  70461. if (t.startsWithIgnoreCase ("matrix"))
  70462. {
  70463. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  70464. numbers[1], numbers[3], numbers[5]);
  70465. }
  70466. else if (t.startsWithIgnoreCase ("translate"))
  70467. {
  70468. jassert (tokens.size() == 2);
  70469. trans = AffineTransform::translation (numbers[0], numbers[1]);
  70470. }
  70471. else if (t.startsWithIgnoreCase ("scale"))
  70472. {
  70473. if (tokens.size() == 1)
  70474. trans = AffineTransform::scale (numbers[0], numbers[0]);
  70475. else
  70476. trans = AffineTransform::scale (numbers[0], numbers[1]);
  70477. }
  70478. else if (t.startsWithIgnoreCase ("rotate"))
  70479. {
  70480. if (tokens.size() != 3)
  70481. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  70482. else
  70483. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  70484. numbers[1], numbers[2]);
  70485. }
  70486. else if (t.startsWithIgnoreCase ("skewX"))
  70487. {
  70488. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  70489. 0.0f, 1.0f, 0.0f);
  70490. }
  70491. else if (t.startsWithIgnoreCase ("skewY"))
  70492. {
  70493. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  70494. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  70495. }
  70496. result = trans.followedBy (result);
  70497. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  70498. }
  70499. return result;
  70500. }
  70501. static void endpointToCentreParameters (const double x1, const double y1,
  70502. const double x2, const double y2,
  70503. const double angle,
  70504. const bool largeArc, const bool sweep,
  70505. double& rx, double& ry,
  70506. double& centreX, double& centreY,
  70507. double& startAngle, double& deltaAngle)
  70508. {
  70509. const double midX = (x1 - x2) * 0.5;
  70510. const double midY = (y1 - y2) * 0.5;
  70511. const double cosAngle = cos (angle);
  70512. const double sinAngle = sin (angle);
  70513. const double xp = cosAngle * midX + sinAngle * midY;
  70514. const double yp = cosAngle * midY - sinAngle * midX;
  70515. const double xp2 = xp * xp;
  70516. const double yp2 = yp * yp;
  70517. double rx2 = rx * rx;
  70518. double ry2 = ry * ry;
  70519. const double s = (xp2 / rx2) + (yp2 / ry2);
  70520. double c;
  70521. if (s <= 1.0)
  70522. {
  70523. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  70524. / (( rx2 * yp2) + (ry2 * xp2))));
  70525. if (largeArc == sweep)
  70526. c = -c;
  70527. }
  70528. else
  70529. {
  70530. const double s2 = std::sqrt (s);
  70531. rx *= s2;
  70532. ry *= s2;
  70533. rx2 = rx * rx;
  70534. ry2 = ry * ry;
  70535. c = 0;
  70536. }
  70537. const double cpx = ((rx * yp) / ry) * c;
  70538. const double cpy = ((-ry * xp) / rx) * c;
  70539. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  70540. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  70541. const double ux = (xp - cpx) / rx;
  70542. const double uy = (yp - cpy) / ry;
  70543. const double vx = (-xp - cpx) / rx;
  70544. const double vy = (-yp - cpy) / ry;
  70545. const double length = juce_hypot (ux, uy);
  70546. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  70547. if (uy < 0)
  70548. startAngle = -startAngle;
  70549. startAngle += double_Pi * 0.5;
  70550. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  70551. / (length * juce_hypot (vx, vy))));
  70552. if ((ux * vy) - (uy * vx) < 0)
  70553. deltaAngle = -deltaAngle;
  70554. if (sweep)
  70555. {
  70556. if (deltaAngle < 0)
  70557. deltaAngle += double_Pi * 2.0;
  70558. }
  70559. else
  70560. {
  70561. if (deltaAngle > 0)
  70562. deltaAngle -= double_Pi * 2.0;
  70563. }
  70564. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  70565. }
  70566. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  70567. {
  70568. forEachXmlChildElement (*parent, e)
  70569. {
  70570. if (e->compareAttribute ("id", id))
  70571. return e;
  70572. const XmlElement* const found = findElementForId (e, id);
  70573. if (found != 0)
  70574. return found;
  70575. }
  70576. return 0;
  70577. }
  70578. SVGState& operator= (const SVGState&);
  70579. };
  70580. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  70581. {
  70582. SVGState state (&svgDocument);
  70583. return state.parseSVGElement (svgDocument);
  70584. }
  70585. END_JUCE_NAMESPACE
  70586. /*** End of inlined file: juce_SVGParser.cpp ***/
  70587. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  70588. BEGIN_JUCE_NAMESPACE
  70589. #if JUCE_MSVC && JUCE_DEBUG
  70590. #pragma optimize ("t", on)
  70591. #endif
  70592. DropShadowEffect::DropShadowEffect()
  70593. : offsetX (0),
  70594. offsetY (0),
  70595. radius (4),
  70596. opacity (0.6f)
  70597. {
  70598. }
  70599. DropShadowEffect::~DropShadowEffect()
  70600. {
  70601. }
  70602. void DropShadowEffect::setShadowProperties (const float newRadius,
  70603. const float newOpacity,
  70604. const int newShadowOffsetX,
  70605. const int newShadowOffsetY)
  70606. {
  70607. radius = jmax (1.1f, newRadius);
  70608. offsetX = newShadowOffsetX;
  70609. offsetY = newShadowOffsetY;
  70610. opacity = newOpacity;
  70611. }
  70612. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  70613. {
  70614. const int w = image.getWidth();
  70615. const int h = image.getHeight();
  70616. Image shadowImage (Image::SingleChannel, w, h, false);
  70617. const Image::BitmapData srcData (image, 0, 0, w, h);
  70618. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  70619. const int filter = roundToInt (63.0f / radius);
  70620. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  70621. for (int x = w; --x >= 0;)
  70622. {
  70623. int shadowAlpha = 0;
  70624. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  70625. uint8* shadowPix = destData.data + x;
  70626. for (int y = h; --y >= 0;)
  70627. {
  70628. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  70629. *shadowPix = (uint8) shadowAlpha;
  70630. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  70631. shadowPix += destData.lineStride;
  70632. }
  70633. }
  70634. for (int y = h; --y >= 0;)
  70635. {
  70636. int shadowAlpha = 0;
  70637. uint8* shadowPix = destData.getLinePointer (y);
  70638. for (int x = w; --x >= 0;)
  70639. {
  70640. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  70641. *shadowPix++ = (uint8) shadowAlpha;
  70642. }
  70643. }
  70644. g.setColour (Colours::black.withAlpha (opacity));
  70645. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  70646. g.setOpacity (1.0f);
  70647. g.drawImageAt (image, 0, 0);
  70648. }
  70649. #if JUCE_MSVC && JUCE_DEBUG
  70650. #pragma optimize ("", on) // resets optimisations to the project defaults
  70651. #endif
  70652. END_JUCE_NAMESPACE
  70653. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  70654. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  70655. BEGIN_JUCE_NAMESPACE
  70656. GlowEffect::GlowEffect()
  70657. : radius (2.0f),
  70658. colour (Colours::white)
  70659. {
  70660. }
  70661. GlowEffect::~GlowEffect()
  70662. {
  70663. }
  70664. void GlowEffect::setGlowProperties (const float newRadius,
  70665. const Colour& newColour)
  70666. {
  70667. radius = newRadius;
  70668. colour = newColour;
  70669. }
  70670. void GlowEffect::applyEffect (Image& image, Graphics& g)
  70671. {
  70672. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  70673. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  70674. blurKernel.createGaussianBlur (radius);
  70675. blurKernel.rescaleAllValues (radius);
  70676. blurKernel.applyToImage (temp, image, image.getBounds());
  70677. g.setColour (colour);
  70678. g.drawImageAt (temp, 0, 0, true);
  70679. g.setOpacity (1.0f);
  70680. g.drawImageAt (image, 0, 0, false);
  70681. }
  70682. END_JUCE_NAMESPACE
  70683. /*** End of inlined file: juce_GlowEffect.cpp ***/
  70684. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70685. BEGIN_JUCE_NAMESPACE
  70686. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  70687. : opacity (opacity_)
  70688. {
  70689. }
  70690. ReduceOpacityEffect::~ReduceOpacityEffect()
  70691. {
  70692. }
  70693. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  70694. {
  70695. opacity = jlimit (0.0f, 1.0f, newOpacity);
  70696. }
  70697. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  70698. {
  70699. g.setOpacity (opacity);
  70700. g.drawImageAt (image, 0, 0);
  70701. }
  70702. END_JUCE_NAMESPACE
  70703. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70704. /*** Start of inlined file: juce_Font.cpp ***/
  70705. BEGIN_JUCE_NAMESPACE
  70706. namespace FontValues
  70707. {
  70708. static float limitFontHeight (const float height) throw()
  70709. {
  70710. return jlimit (0.1f, 10000.0f, height);
  70711. }
  70712. static const float defaultFontHeight = 14.0f;
  70713. static String fallbackFont;
  70714. }
  70715. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  70716. const float kerning_, const float ascent_, const int styleFlags_,
  70717. Typeface* const typeface_) throw()
  70718. : typefaceName (typefaceName_),
  70719. height (height_),
  70720. horizontalScale (horizontalScale_),
  70721. kerning (kerning_),
  70722. ascent (ascent_),
  70723. styleFlags (styleFlags_),
  70724. typeface (typeface_)
  70725. {
  70726. }
  70727. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  70728. : typefaceName (other.typefaceName),
  70729. height (other.height),
  70730. horizontalScale (other.horizontalScale),
  70731. kerning (other.kerning),
  70732. ascent (other.ascent),
  70733. styleFlags (other.styleFlags),
  70734. typeface (other.typeface)
  70735. {
  70736. }
  70737. Font::Font() throw()
  70738. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  70739. 1.0f, 0, 0, Font::plain, 0))
  70740. {
  70741. }
  70742. Font::Font (const float fontHeight, const int styleFlags_) throw()
  70743. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  70744. 1.0f, 0, 0, styleFlags_, 0))
  70745. {
  70746. }
  70747. Font::Font (const String& typefaceName_,
  70748. const float fontHeight,
  70749. const int styleFlags_) throw()
  70750. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  70751. 1.0f, 0, 0, styleFlags_, 0))
  70752. {
  70753. }
  70754. Font::Font (const Font& other) throw()
  70755. : font (other.font)
  70756. {
  70757. }
  70758. Font& Font::operator= (const Font& other) throw()
  70759. {
  70760. font = other.font;
  70761. return *this;
  70762. }
  70763. Font::~Font() throw()
  70764. {
  70765. }
  70766. Font::Font (const Typeface::Ptr& typeface) throw()
  70767. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  70768. 1.0f, 0, 0, Font::plain, typeface))
  70769. {
  70770. }
  70771. bool Font::operator== (const Font& other) const throw()
  70772. {
  70773. return font == other.font
  70774. || (font->height == other.font->height
  70775. && font->styleFlags == other.font->styleFlags
  70776. && font->horizontalScale == other.font->horizontalScale
  70777. && font->kerning == other.font->kerning
  70778. && font->typefaceName == other.font->typefaceName);
  70779. }
  70780. bool Font::operator!= (const Font& other) const throw()
  70781. {
  70782. return ! operator== (other);
  70783. }
  70784. void Font::dupeInternalIfShared() throw()
  70785. {
  70786. if (font->getReferenceCount() > 1)
  70787. font = new SharedFontInternal (*font);
  70788. }
  70789. const String Font::getDefaultSansSerifFontName() throw()
  70790. {
  70791. static const String name ("<Sans-Serif>");
  70792. return name;
  70793. }
  70794. const String Font::getDefaultSerifFontName() throw()
  70795. {
  70796. static const String name ("<Serif>");
  70797. return name;
  70798. }
  70799. const String Font::getDefaultMonospacedFontName() throw()
  70800. {
  70801. static const String name ("<Monospaced>");
  70802. return name;
  70803. }
  70804. void Font::setTypefaceName (const String& faceName) throw()
  70805. {
  70806. if (faceName != font->typefaceName)
  70807. {
  70808. dupeInternalIfShared();
  70809. font->typefaceName = faceName;
  70810. font->typeface = 0;
  70811. font->ascent = 0;
  70812. }
  70813. }
  70814. const String Font::getFallbackFontName() throw()
  70815. {
  70816. return FontValues::fallbackFont;
  70817. }
  70818. void Font::setFallbackFontName (const String& name) throw()
  70819. {
  70820. FontValues::fallbackFont = name;
  70821. }
  70822. void Font::setHeight (float newHeight) throw()
  70823. {
  70824. newHeight = FontValues::limitFontHeight (newHeight);
  70825. if (font->height != newHeight)
  70826. {
  70827. dupeInternalIfShared();
  70828. font->height = newHeight;
  70829. }
  70830. }
  70831. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  70832. {
  70833. newHeight = FontValues::limitFontHeight (newHeight);
  70834. if (font->height != newHeight)
  70835. {
  70836. dupeInternalIfShared();
  70837. font->horizontalScale *= (font->height / newHeight);
  70838. font->height = newHeight;
  70839. }
  70840. }
  70841. void Font::setStyleFlags (const int newFlags) throw()
  70842. {
  70843. if (font->styleFlags != newFlags)
  70844. {
  70845. dupeInternalIfShared();
  70846. font->styleFlags = newFlags;
  70847. font->typeface = 0;
  70848. font->ascent = 0;
  70849. }
  70850. }
  70851. void Font::setSizeAndStyle (float newHeight,
  70852. const int newStyleFlags,
  70853. const float newHorizontalScale,
  70854. const float newKerningAmount) throw()
  70855. {
  70856. newHeight = FontValues::limitFontHeight (newHeight);
  70857. if (font->height != newHeight
  70858. || font->horizontalScale != newHorizontalScale
  70859. || font->kerning != newKerningAmount)
  70860. {
  70861. dupeInternalIfShared();
  70862. font->height = newHeight;
  70863. font->horizontalScale = newHorizontalScale;
  70864. font->kerning = newKerningAmount;
  70865. }
  70866. setStyleFlags (newStyleFlags);
  70867. }
  70868. void Font::setHorizontalScale (const float scaleFactor) throw()
  70869. {
  70870. dupeInternalIfShared();
  70871. font->horizontalScale = scaleFactor;
  70872. }
  70873. void Font::setExtraKerningFactor (const float extraKerning) throw()
  70874. {
  70875. dupeInternalIfShared();
  70876. font->kerning = extraKerning;
  70877. }
  70878. void Font::setBold (const bool shouldBeBold) throw()
  70879. {
  70880. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  70881. : (font->styleFlags & ~bold));
  70882. }
  70883. bool Font::isBold() const throw()
  70884. {
  70885. return (font->styleFlags & bold) != 0;
  70886. }
  70887. void Font::setItalic (const bool shouldBeItalic) throw()
  70888. {
  70889. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  70890. : (font->styleFlags & ~italic));
  70891. }
  70892. bool Font::isItalic() const throw()
  70893. {
  70894. return (font->styleFlags & italic) != 0;
  70895. }
  70896. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  70897. {
  70898. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  70899. : (font->styleFlags & ~underlined));
  70900. }
  70901. bool Font::isUnderlined() const throw()
  70902. {
  70903. return (font->styleFlags & underlined) != 0;
  70904. }
  70905. float Font::getAscent() const throw()
  70906. {
  70907. if (font->ascent == 0)
  70908. font->ascent = getTypeface()->getAscent();
  70909. return font->height * font->ascent;
  70910. }
  70911. float Font::getDescent() const throw()
  70912. {
  70913. return font->height - getAscent();
  70914. }
  70915. int Font::getStringWidth (const String& text) const throw()
  70916. {
  70917. return roundToInt (getStringWidthFloat (text));
  70918. }
  70919. float Font::getStringWidthFloat (const String& text) const throw()
  70920. {
  70921. float w = getTypeface()->getStringWidth (text);
  70922. if (font->kerning != 0)
  70923. w += font->kerning * text.length();
  70924. return w * font->height * font->horizontalScale;
  70925. }
  70926. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  70927. {
  70928. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  70929. const float scale = font->height * font->horizontalScale;
  70930. const int num = xOffsets.size();
  70931. if (num > 0)
  70932. {
  70933. float* const x = &(xOffsets.getReference(0));
  70934. if (font->kerning != 0)
  70935. {
  70936. for (int i = 0; i < num; ++i)
  70937. x[i] = (x[i] + i * font->kerning) * scale;
  70938. }
  70939. else
  70940. {
  70941. for (int i = 0; i < num; ++i)
  70942. x[i] *= scale;
  70943. }
  70944. }
  70945. }
  70946. void Font::findFonts (Array<Font>& destArray) throw()
  70947. {
  70948. const StringArray names (findAllTypefaceNames());
  70949. for (int i = 0; i < names.size(); ++i)
  70950. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  70951. }
  70952. const String Font::toString() const
  70953. {
  70954. String s (getTypefaceName());
  70955. if (s == getDefaultSansSerifFontName())
  70956. s = String::empty;
  70957. else
  70958. s += "; ";
  70959. s += String (getHeight(), 1);
  70960. if (isBold())
  70961. s += " bold";
  70962. if (isItalic())
  70963. s += " italic";
  70964. return s;
  70965. }
  70966. const Font Font::fromString (const String& fontDescription)
  70967. {
  70968. String name;
  70969. const int separator = fontDescription.indexOfChar (';');
  70970. if (separator > 0)
  70971. name = fontDescription.substring (0, separator).trim();
  70972. if (name.isEmpty())
  70973. name = getDefaultSansSerifFontName();
  70974. String sizeAndStyle (fontDescription.substring (separator + 1));
  70975. float height = sizeAndStyle.getFloatValue();
  70976. if (height <= 0)
  70977. height = 10.0f;
  70978. int flags = Font::plain;
  70979. if (sizeAndStyle.containsIgnoreCase ("bold"))
  70980. flags |= Font::bold;
  70981. if (sizeAndStyle.containsIgnoreCase ("italic"))
  70982. flags |= Font::italic;
  70983. return Font (name, height, flags);
  70984. }
  70985. class TypefaceCache : public DeletedAtShutdown
  70986. {
  70987. public:
  70988. TypefaceCache (int numToCache = 10) throw()
  70989. : counter (1)
  70990. {
  70991. while (--numToCache >= 0)
  70992. faces.add (new CachedFace());
  70993. }
  70994. ~TypefaceCache()
  70995. {
  70996. clearSingletonInstance();
  70997. }
  70998. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  70999. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  71000. {
  71001. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  71002. const String faceName (font.getTypefaceName());
  71003. int i;
  71004. for (i = faces.size(); --i >= 0;)
  71005. {
  71006. CachedFace* const face = faces.getUnchecked(i);
  71007. if (face->flags == flags
  71008. && face->typefaceName == faceName)
  71009. {
  71010. face->lastUsageCount = ++counter;
  71011. return face->typeFace;
  71012. }
  71013. }
  71014. int replaceIndex = 0;
  71015. int bestLastUsageCount = std::numeric_limits<int>::max();
  71016. for (i = faces.size(); --i >= 0;)
  71017. {
  71018. const int lu = faces.getUnchecked(i)->lastUsageCount;
  71019. if (bestLastUsageCount > lu)
  71020. {
  71021. bestLastUsageCount = lu;
  71022. replaceIndex = i;
  71023. }
  71024. }
  71025. CachedFace* const face = faces.getUnchecked (replaceIndex);
  71026. face->typefaceName = faceName;
  71027. face->flags = flags;
  71028. face->lastUsageCount = ++counter;
  71029. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  71030. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  71031. return face->typeFace;
  71032. }
  71033. juce_UseDebuggingNewOperator
  71034. private:
  71035. struct CachedFace
  71036. {
  71037. CachedFace() throw()
  71038. : lastUsageCount (0), flags (-1)
  71039. {
  71040. }
  71041. String typefaceName;
  71042. int lastUsageCount;
  71043. int flags;
  71044. Typeface::Ptr typeFace;
  71045. };
  71046. int counter;
  71047. OwnedArray <CachedFace> faces;
  71048. TypefaceCache (const TypefaceCache&);
  71049. TypefaceCache& operator= (const TypefaceCache&);
  71050. };
  71051. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  71052. Typeface* Font::getTypeface() const throw()
  71053. {
  71054. if (font->typeface == 0)
  71055. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  71056. return font->typeface;
  71057. }
  71058. END_JUCE_NAMESPACE
  71059. /*** End of inlined file: juce_Font.cpp ***/
  71060. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  71061. BEGIN_JUCE_NAMESPACE
  71062. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  71063. const juce_wchar character_, const int glyph_)
  71064. : x (x_),
  71065. y (y_),
  71066. w (w_),
  71067. font (font_),
  71068. character (character_),
  71069. glyph (glyph_)
  71070. {
  71071. }
  71072. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  71073. : x (other.x),
  71074. y (other.y),
  71075. w (other.w),
  71076. font (other.font),
  71077. character (other.character),
  71078. glyph (other.glyph)
  71079. {
  71080. }
  71081. void PositionedGlyph::draw (const Graphics& g) const
  71082. {
  71083. if (! isWhitespace())
  71084. {
  71085. g.getInternalContext()->setFont (font);
  71086. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  71087. }
  71088. }
  71089. void PositionedGlyph::draw (const Graphics& g,
  71090. const AffineTransform& transform) const
  71091. {
  71092. if (! isWhitespace())
  71093. {
  71094. g.getInternalContext()->setFont (font);
  71095. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  71096. .followedBy (transform));
  71097. }
  71098. }
  71099. void PositionedGlyph::createPath (Path& path) const
  71100. {
  71101. if (! isWhitespace())
  71102. {
  71103. Typeface* const t = font.getTypeface();
  71104. if (t != 0)
  71105. {
  71106. Path p;
  71107. t->getOutlineForGlyph (glyph, p);
  71108. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  71109. .translated (x, y));
  71110. }
  71111. }
  71112. }
  71113. bool PositionedGlyph::hitTest (float px, float py) const
  71114. {
  71115. if (getBounds().contains (px, py) && ! isWhitespace())
  71116. {
  71117. Typeface* const t = font.getTypeface();
  71118. if (t != 0)
  71119. {
  71120. Path p;
  71121. t->getOutlineForGlyph (glyph, p);
  71122. AffineTransform::translation (-x, -y)
  71123. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  71124. .transformPoint (px, py);
  71125. return p.contains (px, py);
  71126. }
  71127. }
  71128. return false;
  71129. }
  71130. void PositionedGlyph::moveBy (const float deltaX,
  71131. const float deltaY)
  71132. {
  71133. x += deltaX;
  71134. y += deltaY;
  71135. }
  71136. GlyphArrangement::GlyphArrangement()
  71137. {
  71138. glyphs.ensureStorageAllocated (128);
  71139. }
  71140. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  71141. {
  71142. addGlyphArrangement (other);
  71143. }
  71144. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  71145. {
  71146. if (this != &other)
  71147. {
  71148. clear();
  71149. addGlyphArrangement (other);
  71150. }
  71151. return *this;
  71152. }
  71153. GlyphArrangement::~GlyphArrangement()
  71154. {
  71155. }
  71156. void GlyphArrangement::clear()
  71157. {
  71158. glyphs.clear();
  71159. }
  71160. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  71161. {
  71162. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  71163. return *glyphs [index];
  71164. }
  71165. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  71166. {
  71167. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  71168. glyphs.addCopiesOf (other.glyphs);
  71169. }
  71170. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  71171. {
  71172. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  71173. }
  71174. void GlyphArrangement::addLineOfText (const Font& font,
  71175. const String& text,
  71176. const float xOffset,
  71177. const float yOffset)
  71178. {
  71179. addCurtailedLineOfText (font, text,
  71180. xOffset, yOffset,
  71181. 1.0e10f, false);
  71182. }
  71183. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  71184. const String& text,
  71185. float xOffset,
  71186. const float yOffset,
  71187. const float maxWidthPixels,
  71188. const bool useEllipsis)
  71189. {
  71190. if (text.isNotEmpty())
  71191. {
  71192. Array <int> newGlyphs;
  71193. Array <float> xOffsets;
  71194. font.getGlyphPositions (text, newGlyphs, xOffsets);
  71195. const int textLen = newGlyphs.size();
  71196. const juce_wchar* const unicodeText = text;
  71197. for (int i = 0; i < textLen; ++i)
  71198. {
  71199. const float thisX = xOffsets.getUnchecked (i);
  71200. const float nextX = xOffsets.getUnchecked (i + 1);
  71201. if (nextX > maxWidthPixels + 1.0f)
  71202. {
  71203. // curtail the string if it's too wide..
  71204. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  71205. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  71206. break;
  71207. }
  71208. else
  71209. {
  71210. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  71211. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  71212. }
  71213. }
  71214. }
  71215. }
  71216. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  71217. const int startIndex, int endIndex)
  71218. {
  71219. int numDeleted = 0;
  71220. if (glyphs.size() > 0)
  71221. {
  71222. Array<int> dotGlyphs;
  71223. Array<float> dotXs;
  71224. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  71225. const float dx = dotXs[1];
  71226. float xOffset = 0.0f, yOffset = 0.0f;
  71227. while (endIndex > startIndex)
  71228. {
  71229. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  71230. xOffset = pg->x;
  71231. yOffset = pg->y;
  71232. glyphs.remove (endIndex);
  71233. ++numDeleted;
  71234. if (xOffset + dx * 3 <= maxXPos)
  71235. break;
  71236. }
  71237. for (int i = 3; --i >= 0;)
  71238. {
  71239. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  71240. font, '.', dotGlyphs.getFirst()));
  71241. --numDeleted;
  71242. xOffset += dx;
  71243. if (xOffset > maxXPos)
  71244. break;
  71245. }
  71246. }
  71247. return numDeleted;
  71248. }
  71249. void GlyphArrangement::addJustifiedText (const Font& font,
  71250. const String& text,
  71251. float x, float y,
  71252. const float maxLineWidth,
  71253. const Justification& horizontalLayout)
  71254. {
  71255. int lineStartIndex = glyphs.size();
  71256. addLineOfText (font, text, x, y);
  71257. const float originalY = y;
  71258. while (lineStartIndex < glyphs.size())
  71259. {
  71260. int i = lineStartIndex;
  71261. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  71262. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  71263. ++i;
  71264. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  71265. int lastWordBreakIndex = -1;
  71266. while (i < glyphs.size())
  71267. {
  71268. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  71269. const juce_wchar c = pg->getCharacter();
  71270. if (c == '\r' || c == '\n')
  71271. {
  71272. ++i;
  71273. if (c == '\r' && i < glyphs.size()
  71274. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  71275. ++i;
  71276. break;
  71277. }
  71278. else if (pg->isWhitespace())
  71279. {
  71280. lastWordBreakIndex = i + 1;
  71281. }
  71282. else if (pg->getRight() - 0.0001f >= lineMaxX)
  71283. {
  71284. if (lastWordBreakIndex >= 0)
  71285. i = lastWordBreakIndex;
  71286. break;
  71287. }
  71288. ++i;
  71289. }
  71290. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  71291. float currentLineEndX = currentLineStartX;
  71292. for (int j = i; --j >= lineStartIndex;)
  71293. {
  71294. if (! glyphs.getUnchecked (j)->isWhitespace())
  71295. {
  71296. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  71297. break;
  71298. }
  71299. }
  71300. float deltaX = 0.0f;
  71301. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  71302. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  71303. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  71304. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  71305. else if (horizontalLayout.testFlags (Justification::right))
  71306. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  71307. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  71308. x + deltaX - currentLineStartX, y - originalY);
  71309. lineStartIndex = i;
  71310. y += font.getHeight();
  71311. }
  71312. }
  71313. void GlyphArrangement::addFittedText (const Font& f,
  71314. const String& text,
  71315. const float x, const float y,
  71316. const float width, const float height,
  71317. const Justification& layout,
  71318. int maximumLines,
  71319. const float minimumHorizontalScale)
  71320. {
  71321. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  71322. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  71323. if (text.containsAnyOf ("\r\n"))
  71324. {
  71325. GlyphArrangement ga;
  71326. ga.addJustifiedText (f, text, x, y, width, layout);
  71327. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  71328. float dy = y - bb.getY();
  71329. if (layout.testFlags (Justification::verticallyCentred))
  71330. dy += (height - bb.getHeight()) * 0.5f;
  71331. else if (layout.testFlags (Justification::bottom))
  71332. dy += height - bb.getHeight();
  71333. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  71334. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  71335. for (int i = 0; i < ga.glyphs.size(); ++i)
  71336. glyphs.add (ga.glyphs.getUnchecked (i));
  71337. ga.glyphs.clear (false);
  71338. return;
  71339. }
  71340. int startIndex = glyphs.size();
  71341. addLineOfText (f, text.trim(), x, y);
  71342. if (glyphs.size() > startIndex)
  71343. {
  71344. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71345. - glyphs.getUnchecked (startIndex)->getLeft();
  71346. if (lineWidth <= 0)
  71347. return;
  71348. if (lineWidth * minimumHorizontalScale < width)
  71349. {
  71350. if (lineWidth > width)
  71351. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  71352. width / lineWidth);
  71353. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  71354. x, y, width, height, layout);
  71355. }
  71356. else if (maximumLines <= 1)
  71357. {
  71358. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  71359. x, y, width, height, f, layout, minimumHorizontalScale);
  71360. }
  71361. else
  71362. {
  71363. Font font (f);
  71364. String txt (text.trim());
  71365. const int length = txt.length();
  71366. const int originalStartIndex = startIndex;
  71367. int numLines = 1;
  71368. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  71369. maximumLines = 1;
  71370. maximumLines = jmin (maximumLines, length);
  71371. while (numLines < maximumLines)
  71372. {
  71373. ++numLines;
  71374. const float newFontHeight = height / (float) numLines;
  71375. if (newFontHeight < font.getHeight())
  71376. {
  71377. font.setHeight (jmax (8.0f, newFontHeight));
  71378. removeRangeOfGlyphs (startIndex, -1);
  71379. addLineOfText (font, txt, x, y);
  71380. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71381. - glyphs.getUnchecked (startIndex)->getLeft();
  71382. }
  71383. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  71384. break;
  71385. }
  71386. if (numLines < 1)
  71387. numLines = 1;
  71388. float lineY = y;
  71389. float widthPerLine = lineWidth / numLines;
  71390. int lastLineStartIndex = 0;
  71391. for (int line = 0; line < numLines; ++line)
  71392. {
  71393. int i = startIndex;
  71394. lastLineStartIndex = i;
  71395. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  71396. if (line == numLines - 1)
  71397. {
  71398. widthPerLine = width;
  71399. i = glyphs.size();
  71400. }
  71401. else
  71402. {
  71403. while (i < glyphs.size())
  71404. {
  71405. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  71406. if (lineWidth > widthPerLine)
  71407. {
  71408. // got to a point where the line's too long, so skip forward to find a
  71409. // good place to break it..
  71410. const int searchStartIndex = i;
  71411. while (i < glyphs.size())
  71412. {
  71413. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  71414. {
  71415. if (glyphs.getUnchecked (i)->isWhitespace()
  71416. || glyphs.getUnchecked (i)->getCharacter() == '-')
  71417. {
  71418. ++i;
  71419. break;
  71420. }
  71421. }
  71422. else
  71423. {
  71424. // can't find a suitable break, so try looking backwards..
  71425. i = searchStartIndex;
  71426. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  71427. {
  71428. if (glyphs.getUnchecked (i - back)->isWhitespace()
  71429. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  71430. {
  71431. i -= back - 1;
  71432. break;
  71433. }
  71434. }
  71435. break;
  71436. }
  71437. ++i;
  71438. }
  71439. break;
  71440. }
  71441. ++i;
  71442. }
  71443. int wsStart = i;
  71444. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  71445. --wsStart;
  71446. int wsEnd = i;
  71447. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  71448. ++wsEnd;
  71449. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  71450. i = jmax (wsStart, startIndex + 1);
  71451. }
  71452. i -= fitLineIntoSpace (startIndex, i - startIndex,
  71453. x, lineY, width, font.getHeight(), font,
  71454. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  71455. minimumHorizontalScale);
  71456. startIndex = i;
  71457. lineY += font.getHeight();
  71458. if (startIndex >= glyphs.size())
  71459. break;
  71460. }
  71461. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  71462. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  71463. }
  71464. }
  71465. }
  71466. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  71467. const float dx, const float dy)
  71468. {
  71469. jassert (startIndex >= 0);
  71470. if (dx != 0.0f || dy != 0.0f)
  71471. {
  71472. if (num < 0 || startIndex + num > glyphs.size())
  71473. num = glyphs.size() - startIndex;
  71474. while (--num >= 0)
  71475. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  71476. }
  71477. }
  71478. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  71479. const Justification& justification, float minimumHorizontalScale)
  71480. {
  71481. int numDeleted = 0;
  71482. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  71483. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  71484. if (lineWidth > w)
  71485. {
  71486. if (minimumHorizontalScale < 1.0f)
  71487. {
  71488. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  71489. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  71490. }
  71491. if (lineWidth > w)
  71492. {
  71493. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  71494. numGlyphs -= numDeleted;
  71495. }
  71496. }
  71497. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  71498. return numDeleted;
  71499. }
  71500. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  71501. const float horizontalScaleFactor)
  71502. {
  71503. jassert (startIndex >= 0);
  71504. if (num < 0 || startIndex + num > glyphs.size())
  71505. num = glyphs.size() - startIndex;
  71506. if (num > 0)
  71507. {
  71508. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  71509. while (--num >= 0)
  71510. {
  71511. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71512. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  71513. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  71514. pg->w *= horizontalScaleFactor;
  71515. }
  71516. }
  71517. }
  71518. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  71519. {
  71520. jassert (startIndex >= 0);
  71521. if (num < 0 || startIndex + num > glyphs.size())
  71522. num = glyphs.size() - startIndex;
  71523. Rectangle<float> result;
  71524. while (--num >= 0)
  71525. {
  71526. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71527. if (includeWhitespace || ! pg->isWhitespace())
  71528. result = result.getUnion (pg->getBounds());
  71529. }
  71530. return result;
  71531. }
  71532. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  71533. const float x, const float y, const float width, const float height,
  71534. const Justification& justification)
  71535. {
  71536. jassert (num >= 0 && startIndex >= 0);
  71537. if (glyphs.size() > 0 && num > 0)
  71538. {
  71539. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  71540. | Justification::horizontallyCentred)));
  71541. float deltaX = 0.0f;
  71542. if (justification.testFlags (Justification::horizontallyJustified))
  71543. deltaX = x - bb.getX();
  71544. else if (justification.testFlags (Justification::horizontallyCentred))
  71545. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  71546. else if (justification.testFlags (Justification::right))
  71547. deltaX = (x + width) - bb.getRight();
  71548. else
  71549. deltaX = x - bb.getX();
  71550. float deltaY = 0.0f;
  71551. if (justification.testFlags (Justification::top))
  71552. deltaY = y - bb.getY();
  71553. else if (justification.testFlags (Justification::bottom))
  71554. deltaY = (y + height) - bb.getBottom();
  71555. else
  71556. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  71557. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  71558. if (justification.testFlags (Justification::horizontallyJustified))
  71559. {
  71560. int lineStart = 0;
  71561. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  71562. int i;
  71563. for (i = 0; i < num; ++i)
  71564. {
  71565. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  71566. if (glyphY != baseY)
  71567. {
  71568. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71569. lineStart = i;
  71570. baseY = glyphY;
  71571. }
  71572. }
  71573. if (i > lineStart)
  71574. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71575. }
  71576. }
  71577. }
  71578. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  71579. {
  71580. if (start + num < glyphs.size()
  71581. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  71582. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  71583. {
  71584. int numSpaces = 0;
  71585. int spacesAtEnd = 0;
  71586. for (int i = 0; i < num; ++i)
  71587. {
  71588. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71589. {
  71590. ++spacesAtEnd;
  71591. ++numSpaces;
  71592. }
  71593. else
  71594. {
  71595. spacesAtEnd = 0;
  71596. }
  71597. }
  71598. numSpaces -= spacesAtEnd;
  71599. if (numSpaces > 0)
  71600. {
  71601. const float startX = glyphs.getUnchecked (start)->getLeft();
  71602. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  71603. const float extraPaddingBetweenWords
  71604. = (targetWidth - (endX - startX)) / (float) numSpaces;
  71605. float deltaX = 0.0f;
  71606. for (int i = 0; i < num; ++i)
  71607. {
  71608. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  71609. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71610. deltaX += extraPaddingBetweenWords;
  71611. }
  71612. }
  71613. }
  71614. }
  71615. void GlyphArrangement::draw (const Graphics& g) const
  71616. {
  71617. for (int i = 0; i < glyphs.size(); ++i)
  71618. {
  71619. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71620. if (pg->font.isUnderlined())
  71621. {
  71622. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71623. float nextX = pg->x + pg->w;
  71624. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71625. nextX = glyphs.getUnchecked (i + 1)->x;
  71626. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  71627. nextX - pg->x, lineThickness);
  71628. }
  71629. pg->draw (g);
  71630. }
  71631. }
  71632. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  71633. {
  71634. for (int i = 0; i < glyphs.size(); ++i)
  71635. {
  71636. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71637. if (pg->font.isUnderlined())
  71638. {
  71639. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71640. float nextX = pg->x + pg->w;
  71641. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71642. nextX = glyphs.getUnchecked (i + 1)->x;
  71643. Path p;
  71644. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  71645. nextX, pg->y + lineThickness * 2.0f),
  71646. lineThickness);
  71647. g.fillPath (p, transform);
  71648. }
  71649. pg->draw (g, transform);
  71650. }
  71651. }
  71652. void GlyphArrangement::createPath (Path& path) const
  71653. {
  71654. for (int i = 0; i < glyphs.size(); ++i)
  71655. glyphs.getUnchecked (i)->createPath (path);
  71656. }
  71657. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  71658. {
  71659. for (int i = 0; i < glyphs.size(); ++i)
  71660. if (glyphs.getUnchecked (i)->hitTest (x, y))
  71661. return i;
  71662. return -1;
  71663. }
  71664. END_JUCE_NAMESPACE
  71665. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  71666. /*** Start of inlined file: juce_TextLayout.cpp ***/
  71667. BEGIN_JUCE_NAMESPACE
  71668. class TextLayout::Token
  71669. {
  71670. public:
  71671. String text;
  71672. Font font;
  71673. int x, y, w, h;
  71674. int line, lineHeight;
  71675. bool isWhitespace, isNewLine;
  71676. Token (const String& t,
  71677. const Font& f,
  71678. const bool isWhitespace_)
  71679. : text (t),
  71680. font (f),
  71681. x(0),
  71682. y(0),
  71683. isWhitespace (isWhitespace_)
  71684. {
  71685. w = font.getStringWidth (t);
  71686. h = roundToInt (f.getHeight());
  71687. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  71688. }
  71689. Token (const Token& other)
  71690. : text (other.text),
  71691. font (other.font),
  71692. x (other.x),
  71693. y (other.y),
  71694. w (other.w),
  71695. h (other.h),
  71696. line (other.line),
  71697. lineHeight (other.lineHeight),
  71698. isWhitespace (other.isWhitespace),
  71699. isNewLine (other.isNewLine)
  71700. {
  71701. }
  71702. ~Token()
  71703. {
  71704. }
  71705. void draw (Graphics& g,
  71706. const int xOffset,
  71707. const int yOffset)
  71708. {
  71709. if (! isWhitespace)
  71710. {
  71711. g.setFont (font);
  71712. g.drawSingleLineText (text.trimEnd(),
  71713. xOffset + x,
  71714. yOffset + y + (lineHeight - h)
  71715. + roundToInt (font.getAscent()));
  71716. }
  71717. }
  71718. juce_UseDebuggingNewOperator
  71719. };
  71720. TextLayout::TextLayout()
  71721. : totalLines (0)
  71722. {
  71723. tokens.ensureStorageAllocated (64);
  71724. }
  71725. TextLayout::TextLayout (const String& text, const Font& font)
  71726. : totalLines (0)
  71727. {
  71728. tokens.ensureStorageAllocated (64);
  71729. appendText (text, font);
  71730. }
  71731. TextLayout::TextLayout (const TextLayout& other)
  71732. : totalLines (0)
  71733. {
  71734. *this = other;
  71735. }
  71736. TextLayout& TextLayout::operator= (const TextLayout& other)
  71737. {
  71738. if (this != &other)
  71739. {
  71740. clear();
  71741. totalLines = other.totalLines;
  71742. tokens.addCopiesOf (other.tokens);
  71743. }
  71744. return *this;
  71745. }
  71746. TextLayout::~TextLayout()
  71747. {
  71748. clear();
  71749. }
  71750. void TextLayout::clear()
  71751. {
  71752. tokens.clear();
  71753. totalLines = 0;
  71754. }
  71755. void TextLayout::appendText (const String& text, const Font& font)
  71756. {
  71757. const juce_wchar* t = text;
  71758. String currentString;
  71759. int lastCharType = 0;
  71760. for (;;)
  71761. {
  71762. const juce_wchar c = *t++;
  71763. if (c == 0)
  71764. break;
  71765. int charType;
  71766. if (c == '\r' || c == '\n')
  71767. {
  71768. charType = 0;
  71769. }
  71770. else if (CharacterFunctions::isWhitespace (c))
  71771. {
  71772. charType = 2;
  71773. }
  71774. else
  71775. {
  71776. charType = 1;
  71777. }
  71778. if (charType == 0 || charType != lastCharType)
  71779. {
  71780. if (currentString.isNotEmpty())
  71781. {
  71782. tokens.add (new Token (currentString, font,
  71783. lastCharType == 2 || lastCharType == 0));
  71784. }
  71785. currentString = String::charToString (c);
  71786. if (c == '\r' && *t == '\n')
  71787. currentString += *t++;
  71788. }
  71789. else
  71790. {
  71791. currentString += c;
  71792. }
  71793. lastCharType = charType;
  71794. }
  71795. if (currentString.isNotEmpty())
  71796. tokens.add (new Token (currentString, font, lastCharType == 2));
  71797. }
  71798. void TextLayout::setText (const String& text, const Font& font)
  71799. {
  71800. clear();
  71801. appendText (text, font);
  71802. }
  71803. void TextLayout::layout (int maxWidth,
  71804. const Justification& justification,
  71805. const bool attemptToBalanceLineLengths)
  71806. {
  71807. if (attemptToBalanceLineLengths)
  71808. {
  71809. const int originalW = maxWidth;
  71810. int bestWidth = maxWidth;
  71811. float bestLineProportion = 0.0f;
  71812. while (maxWidth > originalW / 2)
  71813. {
  71814. layout (maxWidth, justification, false);
  71815. if (getNumLines() <= 1)
  71816. return;
  71817. const int lastLineW = getLineWidth (getNumLines() - 1);
  71818. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  71819. const float prop = lastLineW / (float) lastButOneLineW;
  71820. if (prop > 0.9f)
  71821. return;
  71822. if (prop > bestLineProportion)
  71823. {
  71824. bestLineProportion = prop;
  71825. bestWidth = maxWidth;
  71826. }
  71827. maxWidth -= 10;
  71828. }
  71829. layout (bestWidth, justification, false);
  71830. }
  71831. else
  71832. {
  71833. int x = 0;
  71834. int y = 0;
  71835. int h = 0;
  71836. totalLines = 0;
  71837. int i;
  71838. for (i = 0; i < tokens.size(); ++i)
  71839. {
  71840. Token* const t = tokens.getUnchecked(i);
  71841. t->x = x;
  71842. t->y = y;
  71843. t->line = totalLines;
  71844. x += t->w;
  71845. h = jmax (h, t->h);
  71846. const Token* nextTok = tokens [i + 1];
  71847. if (nextTok == 0)
  71848. break;
  71849. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  71850. {
  71851. // finished a line, so go back and update the heights of the things on it
  71852. for (int j = i; j >= 0; --j)
  71853. {
  71854. Token* const tok = tokens.getUnchecked(j);
  71855. if (tok->line == totalLines)
  71856. tok->lineHeight = h;
  71857. else
  71858. break;
  71859. }
  71860. x = 0;
  71861. y += h;
  71862. h = 0;
  71863. ++totalLines;
  71864. }
  71865. }
  71866. // finished a line, so go back and update the heights of the things on it
  71867. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  71868. {
  71869. Token* const t = tokens.getUnchecked(j);
  71870. if (t->line == totalLines)
  71871. t->lineHeight = h;
  71872. else
  71873. break;
  71874. }
  71875. ++totalLines;
  71876. if (! justification.testFlags (Justification::left))
  71877. {
  71878. int totalW = getWidth();
  71879. for (i = totalLines; --i >= 0;)
  71880. {
  71881. const int lineW = getLineWidth (i);
  71882. int dx = 0;
  71883. if (justification.testFlags (Justification::horizontallyCentred))
  71884. dx = (totalW - lineW) / 2;
  71885. else if (justification.testFlags (Justification::right))
  71886. dx = totalW - lineW;
  71887. for (int j = tokens.size(); --j >= 0;)
  71888. {
  71889. Token* const t = tokens.getUnchecked(j);
  71890. if (t->line == i)
  71891. t->x += dx;
  71892. }
  71893. }
  71894. }
  71895. }
  71896. }
  71897. int TextLayout::getLineWidth (const int lineNumber) const
  71898. {
  71899. int maxW = 0;
  71900. for (int i = tokens.size(); --i >= 0;)
  71901. {
  71902. const Token* const t = tokens.getUnchecked(i);
  71903. if (t->line == lineNumber && ! t->isWhitespace)
  71904. maxW = jmax (maxW, t->x + t->w);
  71905. }
  71906. return maxW;
  71907. }
  71908. int TextLayout::getWidth() const
  71909. {
  71910. int maxW = 0;
  71911. for (int i = tokens.size(); --i >= 0;)
  71912. {
  71913. const Token* const t = tokens.getUnchecked(i);
  71914. if (! t->isWhitespace)
  71915. maxW = jmax (maxW, t->x + t->w);
  71916. }
  71917. return maxW;
  71918. }
  71919. int TextLayout::getHeight() const
  71920. {
  71921. int maxH = 0;
  71922. for (int i = tokens.size(); --i >= 0;)
  71923. {
  71924. const Token* const t = tokens.getUnchecked(i);
  71925. if (! t->isWhitespace)
  71926. maxH = jmax (maxH, t->y + t->h);
  71927. }
  71928. return maxH;
  71929. }
  71930. void TextLayout::draw (Graphics& g,
  71931. const int xOffset,
  71932. const int yOffset) const
  71933. {
  71934. for (int i = tokens.size(); --i >= 0;)
  71935. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  71936. }
  71937. void TextLayout::drawWithin (Graphics& g,
  71938. int x, int y, int w, int h,
  71939. const Justification& justification) const
  71940. {
  71941. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  71942. x, y, w, h);
  71943. draw (g, x, y);
  71944. }
  71945. END_JUCE_NAMESPACE
  71946. /*** End of inlined file: juce_TextLayout.cpp ***/
  71947. /*** Start of inlined file: juce_Typeface.cpp ***/
  71948. BEGIN_JUCE_NAMESPACE
  71949. Typeface::Typeface (const String& name_) throw()
  71950. : name (name_)
  71951. {
  71952. }
  71953. Typeface::~Typeface()
  71954. {
  71955. }
  71956. class CustomTypeface::GlyphInfo
  71957. {
  71958. public:
  71959. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  71960. : character (character_), path (path_), width (width_)
  71961. {
  71962. }
  71963. ~GlyphInfo() throw()
  71964. {
  71965. }
  71966. struct KerningPair
  71967. {
  71968. juce_wchar character2;
  71969. float kerningAmount;
  71970. };
  71971. void addKerningPair (const juce_wchar subsequentCharacter,
  71972. const float extraKerningAmount) throw()
  71973. {
  71974. KerningPair kp;
  71975. kp.character2 = subsequentCharacter;
  71976. kp.kerningAmount = extraKerningAmount;
  71977. kerningPairs.add (kp);
  71978. }
  71979. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  71980. {
  71981. if (subsequentCharacter != 0)
  71982. {
  71983. for (int i = kerningPairs.size(); --i >= 0;)
  71984. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  71985. return width + kerningPairs.getReference(i).kerningAmount;
  71986. }
  71987. return width;
  71988. }
  71989. const juce_wchar character;
  71990. const Path path;
  71991. float width;
  71992. Array <KerningPair> kerningPairs;
  71993. juce_UseDebuggingNewOperator
  71994. private:
  71995. GlyphInfo (const GlyphInfo&);
  71996. GlyphInfo& operator= (const GlyphInfo&);
  71997. };
  71998. CustomTypeface::CustomTypeface()
  71999. : Typeface (String::empty)
  72000. {
  72001. clear();
  72002. }
  72003. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  72004. : Typeface (String::empty)
  72005. {
  72006. clear();
  72007. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  72008. BufferedInputStream in (&gzin, 32768, false);
  72009. name = in.readString();
  72010. isBold = in.readBool();
  72011. isItalic = in.readBool();
  72012. ascent = in.readFloat();
  72013. defaultCharacter = (juce_wchar) in.readShort();
  72014. int i, numChars = in.readInt();
  72015. for (i = 0; i < numChars; ++i)
  72016. {
  72017. const juce_wchar c = (juce_wchar) in.readShort();
  72018. const float width = in.readFloat();
  72019. Path p;
  72020. p.loadPathFromStream (in);
  72021. addGlyph (c, p, width);
  72022. }
  72023. const int numKerningPairs = in.readInt();
  72024. for (i = 0; i < numKerningPairs; ++i)
  72025. {
  72026. const juce_wchar char1 = (juce_wchar) in.readShort();
  72027. const juce_wchar char2 = (juce_wchar) in.readShort();
  72028. addKerningPair (char1, char2, in.readFloat());
  72029. }
  72030. }
  72031. CustomTypeface::~CustomTypeface()
  72032. {
  72033. }
  72034. void CustomTypeface::clear()
  72035. {
  72036. defaultCharacter = 0;
  72037. ascent = 1.0f;
  72038. isBold = isItalic = false;
  72039. zeromem (lookupTable, sizeof (lookupTable));
  72040. glyphs.clear();
  72041. }
  72042. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  72043. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  72044. {
  72045. name = name_;
  72046. defaultCharacter = defaultCharacter_;
  72047. ascent = ascent_;
  72048. isBold = isBold_;
  72049. isItalic = isItalic_;
  72050. }
  72051. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  72052. {
  72053. // Check that you're not trying to add the same character twice..
  72054. jassert (findGlyph (character, false) == 0);
  72055. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  72056. lookupTable [character] = (short) glyphs.size();
  72057. glyphs.add (new GlyphInfo (character, path, width));
  72058. }
  72059. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  72060. {
  72061. if (extraAmount != 0)
  72062. {
  72063. GlyphInfo* const g = findGlyph (char1, true);
  72064. jassert (g != 0); // can only add kerning pairs for characters that exist!
  72065. if (g != 0)
  72066. g->addKerningPair (char2, extraAmount);
  72067. }
  72068. }
  72069. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  72070. {
  72071. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  72072. return glyphs [(int) lookupTable [(int) character]];
  72073. for (int i = 0; i < glyphs.size(); ++i)
  72074. {
  72075. GlyphInfo* const g = glyphs.getUnchecked(i);
  72076. if (g->character == character)
  72077. return g;
  72078. }
  72079. if (loadIfNeeded && loadGlyphIfPossible (character))
  72080. return findGlyph (character, false);
  72081. return 0;
  72082. }
  72083. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  72084. {
  72085. GlyphInfo* glyph = findGlyph (character, true);
  72086. if (glyph == 0)
  72087. {
  72088. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  72089. glyph = findGlyph (L' ', true);
  72090. if (glyph == 0)
  72091. {
  72092. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  72093. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  72094. if (fallbackTypeface != 0 && fallbackTypeface != this)
  72095. {
  72096. //xxx
  72097. }
  72098. if (glyph == 0)
  72099. glyph = findGlyph (defaultCharacter, true);
  72100. }
  72101. }
  72102. return glyph;
  72103. }
  72104. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  72105. {
  72106. return false;
  72107. }
  72108. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  72109. {
  72110. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  72111. for (int i = 0; i < numCharacters; ++i)
  72112. {
  72113. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  72114. Array <int> glyphIndexes;
  72115. Array <float> offsets;
  72116. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  72117. const int glyphIndex = glyphIndexes.getFirst();
  72118. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  72119. {
  72120. const float glyphWidth = offsets[1];
  72121. Path p;
  72122. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  72123. addGlyph (c, p, glyphWidth);
  72124. for (int j = glyphs.size() - 1; --j >= 0;)
  72125. {
  72126. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  72127. glyphIndexes.clearQuick();
  72128. offsets.clearQuick();
  72129. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  72130. if (offsets.size() > 1)
  72131. addKerningPair (c, char2, offsets[1] - glyphWidth);
  72132. }
  72133. }
  72134. }
  72135. }
  72136. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  72137. {
  72138. GZIPCompressorOutputStream out (&outputStream);
  72139. out.writeString (name);
  72140. out.writeBool (isBold);
  72141. out.writeBool (isItalic);
  72142. out.writeFloat (ascent);
  72143. out.writeShort ((short) (unsigned short) defaultCharacter);
  72144. out.writeInt (glyphs.size());
  72145. int i, numKerningPairs = 0;
  72146. for (i = 0; i < glyphs.size(); ++i)
  72147. {
  72148. const GlyphInfo* const g = glyphs.getUnchecked (i);
  72149. out.writeShort ((short) (unsigned short) g->character);
  72150. out.writeFloat (g->width);
  72151. g->path.writePathToStream (out);
  72152. numKerningPairs += g->kerningPairs.size();
  72153. }
  72154. out.writeInt (numKerningPairs);
  72155. for (i = 0; i < glyphs.size(); ++i)
  72156. {
  72157. const GlyphInfo* const g = glyphs.getUnchecked (i);
  72158. for (int j = 0; j < g->kerningPairs.size(); ++j)
  72159. {
  72160. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  72161. out.writeShort ((short) (unsigned short) g->character);
  72162. out.writeShort ((short) (unsigned short) p.character2);
  72163. out.writeFloat (p.kerningAmount);
  72164. }
  72165. }
  72166. return true;
  72167. }
  72168. float CustomTypeface::getAscent() const
  72169. {
  72170. return ascent;
  72171. }
  72172. float CustomTypeface::getDescent() const
  72173. {
  72174. return 1.0f - ascent;
  72175. }
  72176. float CustomTypeface::getStringWidth (const String& text)
  72177. {
  72178. float x = 0;
  72179. const juce_wchar* t = text;
  72180. while (*t != 0)
  72181. {
  72182. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  72183. if (glyph != 0)
  72184. x += glyph->getHorizontalSpacing (*t);
  72185. }
  72186. return x;
  72187. }
  72188. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  72189. {
  72190. xOffsets.add (0);
  72191. float x = 0;
  72192. const juce_wchar* t = text;
  72193. while (*t != 0)
  72194. {
  72195. const juce_wchar c = *t++;
  72196. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  72197. if (glyph != 0)
  72198. {
  72199. x += glyph->getHorizontalSpacing (*t);
  72200. resultGlyphs.add ((int) glyph->character);
  72201. xOffsets.add (x);
  72202. }
  72203. }
  72204. }
  72205. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  72206. {
  72207. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  72208. if (glyph != 0)
  72209. {
  72210. path = glyph->path;
  72211. return true;
  72212. }
  72213. return false;
  72214. }
  72215. END_JUCE_NAMESPACE
  72216. /*** End of inlined file: juce_Typeface.cpp ***/
  72217. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  72218. BEGIN_JUCE_NAMESPACE
  72219. AffineTransform::AffineTransform() throw()
  72220. : mat00 (1.0f),
  72221. mat01 (0),
  72222. mat02 (0),
  72223. mat10 (0),
  72224. mat11 (1.0f),
  72225. mat12 (0)
  72226. {
  72227. }
  72228. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  72229. : mat00 (other.mat00),
  72230. mat01 (other.mat01),
  72231. mat02 (other.mat02),
  72232. mat10 (other.mat10),
  72233. mat11 (other.mat11),
  72234. mat12 (other.mat12)
  72235. {
  72236. }
  72237. AffineTransform::AffineTransform (const float mat00_,
  72238. const float mat01_,
  72239. const float mat02_,
  72240. const float mat10_,
  72241. const float mat11_,
  72242. const float mat12_) throw()
  72243. : mat00 (mat00_),
  72244. mat01 (mat01_),
  72245. mat02 (mat02_),
  72246. mat10 (mat10_),
  72247. mat11 (mat11_),
  72248. mat12 (mat12_)
  72249. {
  72250. }
  72251. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  72252. {
  72253. mat00 = other.mat00;
  72254. mat01 = other.mat01;
  72255. mat02 = other.mat02;
  72256. mat10 = other.mat10;
  72257. mat11 = other.mat11;
  72258. mat12 = other.mat12;
  72259. return *this;
  72260. }
  72261. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  72262. {
  72263. return mat00 == other.mat00
  72264. && mat01 == other.mat01
  72265. && mat02 == other.mat02
  72266. && mat10 == other.mat10
  72267. && mat11 == other.mat11
  72268. && mat12 == other.mat12;
  72269. }
  72270. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  72271. {
  72272. return ! operator== (other);
  72273. }
  72274. bool AffineTransform::isIdentity() const throw()
  72275. {
  72276. return (mat01 == 0)
  72277. && (mat02 == 0)
  72278. && (mat10 == 0)
  72279. && (mat12 == 0)
  72280. && (mat00 == 1.0f)
  72281. && (mat11 == 1.0f);
  72282. }
  72283. const AffineTransform AffineTransform::identity;
  72284. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  72285. {
  72286. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  72287. other.mat00 * mat01 + other.mat01 * mat11,
  72288. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  72289. other.mat10 * mat00 + other.mat11 * mat10,
  72290. other.mat10 * mat01 + other.mat11 * mat11,
  72291. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  72292. }
  72293. const AffineTransform AffineTransform::followedBy (const float omat00,
  72294. const float omat01,
  72295. const float omat02,
  72296. const float omat10,
  72297. const float omat11,
  72298. const float omat12) const throw()
  72299. {
  72300. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  72301. omat00 * mat01 + omat01 * mat11,
  72302. omat00 * mat02 + omat01 * mat12 + omat02,
  72303. omat10 * mat00 + omat11 * mat10,
  72304. omat10 * mat01 + omat11 * mat11,
  72305. omat10 * mat02 + omat11 * mat12 + omat12);
  72306. }
  72307. const AffineTransform AffineTransform::translated (const float dx,
  72308. const float dy) const throw()
  72309. {
  72310. return AffineTransform (mat00, mat01, mat02 + dx,
  72311. mat10, mat11, mat12 + dy);
  72312. }
  72313. const AffineTransform AffineTransform::translation (const float dx,
  72314. const float dy) throw()
  72315. {
  72316. return AffineTransform (1.0f, 0, dx,
  72317. 0, 1.0f, dy);
  72318. }
  72319. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  72320. {
  72321. const float cosRad = std::cos (rad);
  72322. const float sinRad = std::sin (rad);
  72323. return followedBy (cosRad, -sinRad, 0,
  72324. sinRad, cosRad, 0);
  72325. }
  72326. const AffineTransform AffineTransform::rotation (const float rad) throw()
  72327. {
  72328. const float cosRad = std::cos (rad);
  72329. const float sinRad = std::sin (rad);
  72330. return AffineTransform (cosRad, -sinRad, 0,
  72331. sinRad, cosRad, 0);
  72332. }
  72333. const AffineTransform AffineTransform::rotated (const float angle,
  72334. const float pivotX,
  72335. const float pivotY) const throw()
  72336. {
  72337. return translated (-pivotX, -pivotY)
  72338. .rotated (angle)
  72339. .translated (pivotX, pivotY);
  72340. }
  72341. const AffineTransform AffineTransform::rotation (const float angle,
  72342. const float pivotX,
  72343. const float pivotY) throw()
  72344. {
  72345. return translation (-pivotX, -pivotY)
  72346. .rotated (angle)
  72347. .translated (pivotX, pivotY);
  72348. }
  72349. const AffineTransform AffineTransform::scaled (const float factorX,
  72350. const float factorY) const throw()
  72351. {
  72352. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  72353. factorY * mat10, factorY * mat11, factorY * mat12);
  72354. }
  72355. const AffineTransform AffineTransform::scale (const float factorX,
  72356. const float factorY) throw()
  72357. {
  72358. return AffineTransform (factorX, 0, 0,
  72359. 0, factorY, 0);
  72360. }
  72361. const AffineTransform AffineTransform::sheared (const float shearX,
  72362. const float shearY) const throw()
  72363. {
  72364. return followedBy (1.0f, shearX, 0,
  72365. shearY, 1.0f, 0);
  72366. }
  72367. const AffineTransform AffineTransform::inverted() const throw()
  72368. {
  72369. double determinant = (mat00 * mat11 - mat10 * mat01);
  72370. if (determinant != 0.0)
  72371. {
  72372. determinant = 1.0 / determinant;
  72373. const float dst00 = (float) (mat11 * determinant);
  72374. const float dst10 = (float) (-mat10 * determinant);
  72375. const float dst01 = (float) (-mat01 * determinant);
  72376. const float dst11 = (float) (mat00 * determinant);
  72377. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  72378. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  72379. }
  72380. else
  72381. {
  72382. // singularity..
  72383. return *this;
  72384. }
  72385. }
  72386. bool AffineTransform::isSingularity() const throw()
  72387. {
  72388. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  72389. }
  72390. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  72391. const float x10, const float y10,
  72392. const float x01, const float y01) throw()
  72393. {
  72394. return AffineTransform (x10 - x00, x01 - x00, x00,
  72395. y10 - y00, y01 - y00, y00);
  72396. }
  72397. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  72398. const float sx2, const float sy2, const float tx2, const float ty2,
  72399. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  72400. {
  72401. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  72402. .inverted()
  72403. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  72404. }
  72405. bool AffineTransform::isOnlyTranslation() const throw()
  72406. {
  72407. return (mat01 == 0)
  72408. && (mat10 == 0)
  72409. && (mat00 == 1.0f)
  72410. && (mat11 == 1.0f);
  72411. }
  72412. END_JUCE_NAMESPACE
  72413. /*** End of inlined file: juce_AffineTransform.cpp ***/
  72414. /*** Start of inlined file: juce_BorderSize.cpp ***/
  72415. BEGIN_JUCE_NAMESPACE
  72416. BorderSize::BorderSize() throw()
  72417. : top (0),
  72418. left (0),
  72419. bottom (0),
  72420. right (0)
  72421. {
  72422. }
  72423. BorderSize::BorderSize (const BorderSize& other) throw()
  72424. : top (other.top),
  72425. left (other.left),
  72426. bottom (other.bottom),
  72427. right (other.right)
  72428. {
  72429. }
  72430. BorderSize::BorderSize (const int topGap,
  72431. const int leftGap,
  72432. const int bottomGap,
  72433. const int rightGap) throw()
  72434. : top (topGap),
  72435. left (leftGap),
  72436. bottom (bottomGap),
  72437. right (rightGap)
  72438. {
  72439. }
  72440. BorderSize::BorderSize (const int allGaps) throw()
  72441. : top (allGaps),
  72442. left (allGaps),
  72443. bottom (allGaps),
  72444. right (allGaps)
  72445. {
  72446. }
  72447. BorderSize::~BorderSize() throw()
  72448. {
  72449. }
  72450. void BorderSize::setTop (const int newTopGap) throw()
  72451. {
  72452. top = newTopGap;
  72453. }
  72454. void BorderSize::setLeft (const int newLeftGap) throw()
  72455. {
  72456. left = newLeftGap;
  72457. }
  72458. void BorderSize::setBottom (const int newBottomGap) throw()
  72459. {
  72460. bottom = newBottomGap;
  72461. }
  72462. void BorderSize::setRight (const int newRightGap) throw()
  72463. {
  72464. right = newRightGap;
  72465. }
  72466. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  72467. {
  72468. return Rectangle<int> (r.getX() + left,
  72469. r.getY() + top,
  72470. r.getWidth() - (left + right),
  72471. r.getHeight() - (top + bottom));
  72472. }
  72473. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  72474. {
  72475. r.setBounds (r.getX() + left,
  72476. r.getY() + top,
  72477. r.getWidth() - (left + right),
  72478. r.getHeight() - (top + bottom));
  72479. }
  72480. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  72481. {
  72482. return Rectangle<int> (r.getX() - left,
  72483. r.getY() - top,
  72484. r.getWidth() + (left + right),
  72485. r.getHeight() + (top + bottom));
  72486. }
  72487. void BorderSize::addTo (Rectangle<int>& r) const throw()
  72488. {
  72489. r.setBounds (r.getX() - left,
  72490. r.getY() - top,
  72491. r.getWidth() + (left + right),
  72492. r.getHeight() + (top + bottom));
  72493. }
  72494. bool BorderSize::operator== (const BorderSize& other) const throw()
  72495. {
  72496. return top == other.top
  72497. && left == other.left
  72498. && bottom == other.bottom
  72499. && right == other.right;
  72500. }
  72501. bool BorderSize::operator!= (const BorderSize& other) const throw()
  72502. {
  72503. return ! operator== (other);
  72504. }
  72505. END_JUCE_NAMESPACE
  72506. /*** End of inlined file: juce_BorderSize.cpp ***/
  72507. /*** Start of inlined file: juce_Path.cpp ***/
  72508. BEGIN_JUCE_NAMESPACE
  72509. // tests that some co-ords aren't NaNs
  72510. #define CHECK_COORDS_ARE_VALID(x, y) \
  72511. jassert (x == x && y == y);
  72512. namespace PathHelpers
  72513. {
  72514. static const float ellipseAngularIncrement = 0.05f;
  72515. static const String nextToken (const juce_wchar*& t)
  72516. {
  72517. while (CharacterFunctions::isWhitespace (*t))
  72518. ++t;
  72519. const juce_wchar* const start = t;
  72520. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  72521. ++t;
  72522. return String (start, (int) (t - start));
  72523. }
  72524. }
  72525. const float Path::lineMarker = 100001.0f;
  72526. const float Path::moveMarker = 100002.0f;
  72527. const float Path::quadMarker = 100003.0f;
  72528. const float Path::cubicMarker = 100004.0f;
  72529. const float Path::closeSubPathMarker = 100005.0f;
  72530. Path::Path()
  72531. : numElements (0),
  72532. pathXMin (0),
  72533. pathXMax (0),
  72534. pathYMin (0),
  72535. pathYMax (0),
  72536. useNonZeroWinding (true)
  72537. {
  72538. }
  72539. Path::~Path()
  72540. {
  72541. }
  72542. Path::Path (const Path& other)
  72543. : numElements (other.numElements),
  72544. pathXMin (other.pathXMin),
  72545. pathXMax (other.pathXMax),
  72546. pathYMin (other.pathYMin),
  72547. pathYMax (other.pathYMax),
  72548. useNonZeroWinding (other.useNonZeroWinding)
  72549. {
  72550. if (numElements > 0)
  72551. {
  72552. data.setAllocatedSize ((int) numElements);
  72553. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72554. }
  72555. }
  72556. Path& Path::operator= (const Path& other)
  72557. {
  72558. if (this != &other)
  72559. {
  72560. data.ensureAllocatedSize ((int) other.numElements);
  72561. numElements = other.numElements;
  72562. pathXMin = other.pathXMin;
  72563. pathXMax = other.pathXMax;
  72564. pathYMin = other.pathYMin;
  72565. pathYMax = other.pathYMax;
  72566. useNonZeroWinding = other.useNonZeroWinding;
  72567. if (numElements > 0)
  72568. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72569. }
  72570. return *this;
  72571. }
  72572. bool Path::operator== (const Path& other) const throw()
  72573. {
  72574. return ! operator!= (other);
  72575. }
  72576. bool Path::operator!= (const Path& other) const throw()
  72577. {
  72578. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  72579. return true;
  72580. for (size_t i = 0; i < numElements; ++i)
  72581. if (data.elements[i] != other.data.elements[i])
  72582. return true;
  72583. return false;
  72584. }
  72585. void Path::clear() throw()
  72586. {
  72587. numElements = 0;
  72588. pathXMin = 0;
  72589. pathYMin = 0;
  72590. pathYMax = 0;
  72591. pathXMax = 0;
  72592. }
  72593. void Path::swapWithPath (Path& other) throw()
  72594. {
  72595. data.swapWith (other.data);
  72596. swapVariables <size_t> (numElements, other.numElements);
  72597. swapVariables <float> (pathXMin, other.pathXMin);
  72598. swapVariables <float> (pathXMax, other.pathXMax);
  72599. swapVariables <float> (pathYMin, other.pathYMin);
  72600. swapVariables <float> (pathYMax, other.pathYMax);
  72601. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  72602. }
  72603. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  72604. {
  72605. useNonZeroWinding = isNonZero;
  72606. }
  72607. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  72608. const bool preserveProportions) throw()
  72609. {
  72610. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  72611. }
  72612. bool Path::isEmpty() const throw()
  72613. {
  72614. size_t i = 0;
  72615. while (i < numElements)
  72616. {
  72617. const float type = data.elements [i++];
  72618. if (type == moveMarker)
  72619. {
  72620. i += 2;
  72621. }
  72622. else if (type == lineMarker
  72623. || type == quadMarker
  72624. || type == cubicMarker)
  72625. {
  72626. return false;
  72627. }
  72628. }
  72629. return true;
  72630. }
  72631. const Rectangle<float> Path::getBounds() const throw()
  72632. {
  72633. return Rectangle<float> (pathXMin, pathYMin,
  72634. pathXMax - pathXMin,
  72635. pathYMax - pathYMin);
  72636. }
  72637. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  72638. {
  72639. return getBounds().transformed (transform);
  72640. }
  72641. void Path::startNewSubPath (const float x, const float y)
  72642. {
  72643. CHECK_COORDS_ARE_VALID (x, y);
  72644. if (numElements == 0)
  72645. {
  72646. pathXMin = pathXMax = x;
  72647. pathYMin = pathYMax = y;
  72648. }
  72649. else
  72650. {
  72651. pathXMin = jmin (pathXMin, x);
  72652. pathXMax = jmax (pathXMax, x);
  72653. pathYMin = jmin (pathYMin, y);
  72654. pathYMax = jmax (pathYMax, y);
  72655. }
  72656. data.ensureAllocatedSize ((int) numElements + 3);
  72657. data.elements [numElements++] = moveMarker;
  72658. data.elements [numElements++] = x;
  72659. data.elements [numElements++] = y;
  72660. }
  72661. void Path::startNewSubPath (const Point<float>& start)
  72662. {
  72663. startNewSubPath (start.getX(), start.getY());
  72664. }
  72665. void Path::lineTo (const float x, const float y)
  72666. {
  72667. CHECK_COORDS_ARE_VALID (x, y);
  72668. if (numElements == 0)
  72669. startNewSubPath (0, 0);
  72670. data.ensureAllocatedSize ((int) numElements + 3);
  72671. data.elements [numElements++] = lineMarker;
  72672. data.elements [numElements++] = x;
  72673. data.elements [numElements++] = y;
  72674. pathXMin = jmin (pathXMin, x);
  72675. pathXMax = jmax (pathXMax, x);
  72676. pathYMin = jmin (pathYMin, y);
  72677. pathYMax = jmax (pathYMax, y);
  72678. }
  72679. void Path::lineTo (const Point<float>& end)
  72680. {
  72681. lineTo (end.getX(), end.getY());
  72682. }
  72683. void Path::quadraticTo (const float x1, const float y1,
  72684. const float x2, const float y2)
  72685. {
  72686. CHECK_COORDS_ARE_VALID (x1, y1);
  72687. CHECK_COORDS_ARE_VALID (x2, y2);
  72688. if (numElements == 0)
  72689. startNewSubPath (0, 0);
  72690. data.ensureAllocatedSize ((int) numElements + 5);
  72691. data.elements [numElements++] = quadMarker;
  72692. data.elements [numElements++] = x1;
  72693. data.elements [numElements++] = y1;
  72694. data.elements [numElements++] = x2;
  72695. data.elements [numElements++] = y2;
  72696. pathXMin = jmin (pathXMin, x1, x2);
  72697. pathXMax = jmax (pathXMax, x1, x2);
  72698. pathYMin = jmin (pathYMin, y1, y2);
  72699. pathYMax = jmax (pathYMax, y1, y2);
  72700. }
  72701. void Path::quadraticTo (const Point<float>& controlPoint,
  72702. const Point<float>& endPoint)
  72703. {
  72704. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  72705. endPoint.getX(), endPoint.getY());
  72706. }
  72707. void Path::cubicTo (const float x1, const float y1,
  72708. const float x2, const float y2,
  72709. const float x3, const float y3)
  72710. {
  72711. CHECK_COORDS_ARE_VALID (x1, y1);
  72712. CHECK_COORDS_ARE_VALID (x2, y2);
  72713. CHECK_COORDS_ARE_VALID (x3, y3);
  72714. if (numElements == 0)
  72715. startNewSubPath (0, 0);
  72716. data.ensureAllocatedSize ((int) numElements + 7);
  72717. data.elements [numElements++] = cubicMarker;
  72718. data.elements [numElements++] = x1;
  72719. data.elements [numElements++] = y1;
  72720. data.elements [numElements++] = x2;
  72721. data.elements [numElements++] = y2;
  72722. data.elements [numElements++] = x3;
  72723. data.elements [numElements++] = y3;
  72724. pathXMin = jmin (pathXMin, x1, x2, x3);
  72725. pathXMax = jmax (pathXMax, x1, x2, x3);
  72726. pathYMin = jmin (pathYMin, y1, y2, y3);
  72727. pathYMax = jmax (pathYMax, y1, y2, y3);
  72728. }
  72729. void Path::cubicTo (const Point<float>& controlPoint1,
  72730. const Point<float>& controlPoint2,
  72731. const Point<float>& endPoint)
  72732. {
  72733. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  72734. controlPoint2.getX(), controlPoint2.getY(),
  72735. endPoint.getX(), endPoint.getY());
  72736. }
  72737. void Path::closeSubPath()
  72738. {
  72739. if (numElements > 0
  72740. && data.elements [numElements - 1] != closeSubPathMarker)
  72741. {
  72742. data.ensureAllocatedSize ((int) numElements + 1);
  72743. data.elements [numElements++] = closeSubPathMarker;
  72744. }
  72745. }
  72746. const Point<float> Path::getCurrentPosition() const
  72747. {
  72748. size_t i = numElements - 1;
  72749. if (i > 0 && data.elements[i] == closeSubPathMarker)
  72750. {
  72751. while (i >= 0)
  72752. {
  72753. if (data.elements[i] == moveMarker)
  72754. {
  72755. i += 2;
  72756. break;
  72757. }
  72758. --i;
  72759. }
  72760. }
  72761. if (i > 0)
  72762. return Point<float> (data.elements [i - 1], data.elements [i]);
  72763. return Point<float>();
  72764. }
  72765. void Path::addRectangle (const float x, const float y,
  72766. const float w, const float h)
  72767. {
  72768. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  72769. if (w < 0)
  72770. swapVariables (x1, x2);
  72771. if (h < 0)
  72772. swapVariables (y1, y2);
  72773. data.ensureAllocatedSize ((int) numElements + 13);
  72774. if (numElements == 0)
  72775. {
  72776. pathXMin = x1;
  72777. pathXMax = x2;
  72778. pathYMin = y1;
  72779. pathYMax = y2;
  72780. }
  72781. else
  72782. {
  72783. pathXMin = jmin (pathXMin, x1);
  72784. pathXMax = jmax (pathXMax, x2);
  72785. pathYMin = jmin (pathYMin, y1);
  72786. pathYMax = jmax (pathYMax, y2);
  72787. }
  72788. data.elements [numElements++] = moveMarker;
  72789. data.elements [numElements++] = x1;
  72790. data.elements [numElements++] = y2;
  72791. data.elements [numElements++] = lineMarker;
  72792. data.elements [numElements++] = x1;
  72793. data.elements [numElements++] = y1;
  72794. data.elements [numElements++] = lineMarker;
  72795. data.elements [numElements++] = x2;
  72796. data.elements [numElements++] = y1;
  72797. data.elements [numElements++] = lineMarker;
  72798. data.elements [numElements++] = x2;
  72799. data.elements [numElements++] = y2;
  72800. data.elements [numElements++] = closeSubPathMarker;
  72801. }
  72802. void Path::addRectangle (const Rectangle<int>& rectangle)
  72803. {
  72804. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  72805. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  72806. }
  72807. void Path::addRoundedRectangle (const float x, const float y,
  72808. const float w, const float h,
  72809. float csx,
  72810. float csy)
  72811. {
  72812. csx = jmin (csx, w * 0.5f);
  72813. csy = jmin (csy, h * 0.5f);
  72814. const float cs45x = csx * 0.45f;
  72815. const float cs45y = csy * 0.45f;
  72816. const float x2 = x + w;
  72817. const float y2 = y + h;
  72818. startNewSubPath (x + csx, y);
  72819. lineTo (x2 - csx, y);
  72820. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  72821. lineTo (x2, y2 - csy);
  72822. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  72823. lineTo (x + csx, y2);
  72824. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  72825. lineTo (x, y + csy);
  72826. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  72827. closeSubPath();
  72828. }
  72829. void Path::addRoundedRectangle (const float x, const float y,
  72830. const float w, const float h,
  72831. float cs)
  72832. {
  72833. addRoundedRectangle (x, y, w, h, cs, cs);
  72834. }
  72835. void Path::addTriangle (const float x1, const float y1,
  72836. const float x2, const float y2,
  72837. const float x3, const float y3)
  72838. {
  72839. startNewSubPath (x1, y1);
  72840. lineTo (x2, y2);
  72841. lineTo (x3, y3);
  72842. closeSubPath();
  72843. }
  72844. void Path::addQuadrilateral (const float x1, const float y1,
  72845. const float x2, const float y2,
  72846. const float x3, const float y3,
  72847. const float x4, const float y4)
  72848. {
  72849. startNewSubPath (x1, y1);
  72850. lineTo (x2, y2);
  72851. lineTo (x3, y3);
  72852. lineTo (x4, y4);
  72853. closeSubPath();
  72854. }
  72855. void Path::addEllipse (const float x, const float y,
  72856. const float w, const float h)
  72857. {
  72858. const float hw = w * 0.5f;
  72859. const float hw55 = hw * 0.55f;
  72860. const float hh = h * 0.5f;
  72861. const float hh45 = hh * 0.55f;
  72862. const float cx = x + hw;
  72863. const float cy = y + hh;
  72864. startNewSubPath (cx, cy - hh);
  72865. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  72866. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  72867. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  72868. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  72869. closeSubPath();
  72870. }
  72871. void Path::addArc (const float x, const float y,
  72872. const float w, const float h,
  72873. const float fromRadians,
  72874. const float toRadians,
  72875. const bool startAsNewSubPath)
  72876. {
  72877. const float radiusX = w / 2.0f;
  72878. const float radiusY = h / 2.0f;
  72879. addCentredArc (x + radiusX,
  72880. y + radiusY,
  72881. radiusX, radiusY,
  72882. 0.0f,
  72883. fromRadians, toRadians,
  72884. startAsNewSubPath);
  72885. }
  72886. void Path::addCentredArc (const float centreX, const float centreY,
  72887. const float radiusX, const float radiusY,
  72888. const float rotationOfEllipse,
  72889. const float fromRadians,
  72890. const float toRadians,
  72891. const bool startAsNewSubPath)
  72892. {
  72893. if (radiusX > 0.0f && radiusY > 0.0f)
  72894. {
  72895. const Point<float> centre (centreX, centreY);
  72896. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  72897. float angle = fromRadians;
  72898. if (startAsNewSubPath)
  72899. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72900. if (fromRadians < toRadians)
  72901. {
  72902. if (startAsNewSubPath)
  72903. angle += PathHelpers::ellipseAngularIncrement;
  72904. while (angle < toRadians)
  72905. {
  72906. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72907. angle += PathHelpers::ellipseAngularIncrement;
  72908. }
  72909. }
  72910. else
  72911. {
  72912. if (startAsNewSubPath)
  72913. angle -= PathHelpers::ellipseAngularIncrement;
  72914. while (angle > toRadians)
  72915. {
  72916. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72917. angle -= PathHelpers::ellipseAngularIncrement;
  72918. }
  72919. }
  72920. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  72921. }
  72922. }
  72923. void Path::addPieSegment (const float x, const float y,
  72924. const float width, const float height,
  72925. const float fromRadians,
  72926. const float toRadians,
  72927. const float innerCircleProportionalSize)
  72928. {
  72929. float radiusX = width * 0.5f;
  72930. float radiusY = height * 0.5f;
  72931. const Point<float> centre (x + radiusX, y + radiusY);
  72932. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  72933. addArc (x, y, width, height, fromRadians, toRadians);
  72934. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  72935. {
  72936. closeSubPath();
  72937. if (innerCircleProportionalSize > 0)
  72938. {
  72939. radiusX *= innerCircleProportionalSize;
  72940. radiusY *= innerCircleProportionalSize;
  72941. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  72942. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72943. }
  72944. }
  72945. else
  72946. {
  72947. if (innerCircleProportionalSize > 0)
  72948. {
  72949. radiusX *= innerCircleProportionalSize;
  72950. radiusY *= innerCircleProportionalSize;
  72951. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72952. }
  72953. else
  72954. {
  72955. lineTo (centre);
  72956. }
  72957. }
  72958. closeSubPath();
  72959. }
  72960. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  72961. {
  72962. const Line<float> reversed (line.reversed());
  72963. lineThickness *= 0.5f;
  72964. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72965. lineTo (line.getPointAlongLine (0, -lineThickness));
  72966. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72967. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  72968. closeSubPath();
  72969. }
  72970. void Path::addArrow (const Line<float>& line, float lineThickness,
  72971. float arrowheadWidth, float arrowheadLength)
  72972. {
  72973. const Line<float> reversed (line.reversed());
  72974. lineThickness *= 0.5f;
  72975. arrowheadWidth *= 0.5f;
  72976. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  72977. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72978. lineTo (line.getPointAlongLine (0, -lineThickness));
  72979. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  72980. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  72981. lineTo (line.getEnd());
  72982. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  72983. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  72984. closeSubPath();
  72985. }
  72986. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  72987. const float radius, const float startAngle)
  72988. {
  72989. jassert (numberOfSides > 1); // this would be silly.
  72990. if (numberOfSides > 1)
  72991. {
  72992. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  72993. for (int i = 0; i < numberOfSides; ++i)
  72994. {
  72995. const float angle = startAngle + i * angleBetweenPoints;
  72996. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  72997. if (i == 0)
  72998. startNewSubPath (p);
  72999. else
  73000. lineTo (p);
  73001. }
  73002. closeSubPath();
  73003. }
  73004. }
  73005. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  73006. const float innerRadius, const float outerRadius, const float startAngle)
  73007. {
  73008. jassert (numberOfPoints > 1); // this would be silly.
  73009. if (numberOfPoints > 1)
  73010. {
  73011. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  73012. for (int i = 0; i < numberOfPoints; ++i)
  73013. {
  73014. const float angle = startAngle + i * angleBetweenPoints;
  73015. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  73016. if (i == 0)
  73017. startNewSubPath (p);
  73018. else
  73019. lineTo (p);
  73020. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  73021. }
  73022. closeSubPath();
  73023. }
  73024. }
  73025. void Path::addBubble (float x, float y,
  73026. float w, float h,
  73027. float cs,
  73028. float tipX,
  73029. float tipY,
  73030. int whichSide,
  73031. float arrowPos,
  73032. float arrowWidth)
  73033. {
  73034. if (w > 1.0f && h > 1.0f)
  73035. {
  73036. cs = jmin (cs, w * 0.5f, h * 0.5f);
  73037. const float cs2 = 2.0f * cs;
  73038. startNewSubPath (x + cs, y);
  73039. if (whichSide == 0)
  73040. {
  73041. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73042. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73043. lineTo (arrowX1, y);
  73044. lineTo (tipX, tipY);
  73045. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  73046. }
  73047. lineTo (x + w - cs, y);
  73048. if (cs > 0.0f)
  73049. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  73050. if (whichSide == 3)
  73051. {
  73052. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73053. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73054. lineTo (x + w, arrowY1);
  73055. lineTo (tipX, tipY);
  73056. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  73057. }
  73058. lineTo (x + w, y + h - cs);
  73059. if (cs > 0.0f)
  73060. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  73061. if (whichSide == 2)
  73062. {
  73063. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73064. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73065. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  73066. lineTo (tipX, tipY);
  73067. lineTo (arrowX1, y + h);
  73068. }
  73069. lineTo (x + cs, y + h);
  73070. if (cs > 0.0f)
  73071. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  73072. if (whichSide == 1)
  73073. {
  73074. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73075. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73076. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  73077. lineTo (tipX, tipY);
  73078. lineTo (x, arrowY1);
  73079. }
  73080. lineTo (x, y + cs);
  73081. if (cs > 0.0f)
  73082. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  73083. closeSubPath();
  73084. }
  73085. }
  73086. void Path::addPath (const Path& other)
  73087. {
  73088. size_t i = 0;
  73089. while (i < other.numElements)
  73090. {
  73091. const float type = other.data.elements [i++];
  73092. if (type == moveMarker)
  73093. {
  73094. startNewSubPath (other.data.elements [i],
  73095. other.data.elements [i + 1]);
  73096. i += 2;
  73097. }
  73098. else if (type == lineMarker)
  73099. {
  73100. lineTo (other.data.elements [i],
  73101. other.data.elements [i + 1]);
  73102. i += 2;
  73103. }
  73104. else if (type == quadMarker)
  73105. {
  73106. quadraticTo (other.data.elements [i],
  73107. other.data.elements [i + 1],
  73108. other.data.elements [i + 2],
  73109. other.data.elements [i + 3]);
  73110. i += 4;
  73111. }
  73112. else if (type == cubicMarker)
  73113. {
  73114. cubicTo (other.data.elements [i],
  73115. other.data.elements [i + 1],
  73116. other.data.elements [i + 2],
  73117. other.data.elements [i + 3],
  73118. other.data.elements [i + 4],
  73119. other.data.elements [i + 5]);
  73120. i += 6;
  73121. }
  73122. else if (type == closeSubPathMarker)
  73123. {
  73124. closeSubPath();
  73125. }
  73126. else
  73127. {
  73128. // something's gone wrong with the element list!
  73129. jassertfalse;
  73130. }
  73131. }
  73132. }
  73133. void Path::addPath (const Path& other,
  73134. const AffineTransform& transformToApply)
  73135. {
  73136. size_t i = 0;
  73137. while (i < other.numElements)
  73138. {
  73139. const float type = other.data.elements [i++];
  73140. if (type == closeSubPathMarker)
  73141. {
  73142. closeSubPath();
  73143. }
  73144. else
  73145. {
  73146. float x = other.data.elements [i++];
  73147. float y = other.data.elements [i++];
  73148. transformToApply.transformPoint (x, y);
  73149. if (type == moveMarker)
  73150. {
  73151. startNewSubPath (x, y);
  73152. }
  73153. else if (type == lineMarker)
  73154. {
  73155. lineTo (x, y);
  73156. }
  73157. else if (type == quadMarker)
  73158. {
  73159. float x2 = other.data.elements [i++];
  73160. float y2 = other.data.elements [i++];
  73161. transformToApply.transformPoint (x2, y2);
  73162. quadraticTo (x, y, x2, y2);
  73163. }
  73164. else if (type == cubicMarker)
  73165. {
  73166. float x2 = other.data.elements [i++];
  73167. float y2 = other.data.elements [i++];
  73168. float x3 = other.data.elements [i++];
  73169. float y3 = other.data.elements [i++];
  73170. transformToApply.transformPoints (x2, y2, x3, y3);
  73171. cubicTo (x, y, x2, y2, x3, y3);
  73172. }
  73173. else
  73174. {
  73175. // something's gone wrong with the element list!
  73176. jassertfalse;
  73177. }
  73178. }
  73179. }
  73180. }
  73181. void Path::applyTransform (const AffineTransform& transform) throw()
  73182. {
  73183. size_t i = 0;
  73184. pathYMin = pathXMin = 0;
  73185. pathYMax = pathXMax = 0;
  73186. bool setMaxMin = false;
  73187. while (i < numElements)
  73188. {
  73189. const float type = data.elements [i++];
  73190. if (type == moveMarker)
  73191. {
  73192. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  73193. if (setMaxMin)
  73194. {
  73195. pathXMin = jmin (pathXMin, data.elements [i]);
  73196. pathXMax = jmax (pathXMax, data.elements [i]);
  73197. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  73198. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  73199. }
  73200. else
  73201. {
  73202. pathXMin = pathXMax = data.elements [i];
  73203. pathYMin = pathYMax = data.elements [i + 1];
  73204. setMaxMin = true;
  73205. }
  73206. i += 2;
  73207. }
  73208. else if (type == lineMarker)
  73209. {
  73210. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  73211. pathXMin = jmin (pathXMin, data.elements [i]);
  73212. pathXMax = jmax (pathXMax, data.elements [i]);
  73213. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  73214. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  73215. i += 2;
  73216. }
  73217. else if (type == quadMarker)
  73218. {
  73219. transform.transformPoints (data.elements [i], data.elements [i + 1],
  73220. data.elements [i + 2], data.elements [i + 3]);
  73221. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  73222. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  73223. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  73224. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  73225. i += 4;
  73226. }
  73227. else if (type == cubicMarker)
  73228. {
  73229. transform.transformPoints (data.elements [i], data.elements [i + 1],
  73230. data.elements [i + 2], data.elements [i + 3],
  73231. data.elements [i + 4], data.elements [i + 5]);
  73232. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  73233. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  73234. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  73235. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  73236. i += 6;
  73237. }
  73238. }
  73239. }
  73240. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  73241. const float w, const float h,
  73242. const bool preserveProportions,
  73243. const Justification& justification) const
  73244. {
  73245. Rectangle<float> bounds (getBounds());
  73246. if (preserveProportions)
  73247. {
  73248. if (w <= 0 || h <= 0 || bounds.isEmpty())
  73249. return AffineTransform::identity;
  73250. float newW, newH;
  73251. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  73252. if (srcRatio > h / w)
  73253. {
  73254. newW = h / srcRatio;
  73255. newH = h;
  73256. }
  73257. else
  73258. {
  73259. newW = w;
  73260. newH = w * srcRatio;
  73261. }
  73262. float newXCentre = x;
  73263. float newYCentre = y;
  73264. if (justification.testFlags (Justification::left))
  73265. newXCentre += newW * 0.5f;
  73266. else if (justification.testFlags (Justification::right))
  73267. newXCentre += w - newW * 0.5f;
  73268. else
  73269. newXCentre += w * 0.5f;
  73270. if (justification.testFlags (Justification::top))
  73271. newYCentre += newH * 0.5f;
  73272. else if (justification.testFlags (Justification::bottom))
  73273. newYCentre += h - newH * 0.5f;
  73274. else
  73275. newYCentre += h * 0.5f;
  73276. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  73277. bounds.getHeight() * -0.5f - bounds.getY())
  73278. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  73279. .translated (newXCentre, newYCentre);
  73280. }
  73281. else
  73282. {
  73283. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  73284. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  73285. .translated (x, y);
  73286. }
  73287. }
  73288. bool Path::contains (const float x, const float y, const float tolerence) const
  73289. {
  73290. if (x <= pathXMin || x >= pathXMax
  73291. || y <= pathYMin || y >= pathYMax)
  73292. return false;
  73293. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73294. int positiveCrossings = 0;
  73295. int negativeCrossings = 0;
  73296. while (i.next())
  73297. {
  73298. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  73299. {
  73300. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  73301. if (intersectX <= x)
  73302. {
  73303. if (i.y1 < i.y2)
  73304. ++positiveCrossings;
  73305. else
  73306. ++negativeCrossings;
  73307. }
  73308. }
  73309. }
  73310. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  73311. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  73312. }
  73313. bool Path::contains (const Point<float>& point, const float tolerence) const
  73314. {
  73315. return contains (point.getX(), point.getY(), tolerence);
  73316. }
  73317. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  73318. {
  73319. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73320. Point<float> intersection;
  73321. while (i.next())
  73322. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73323. return true;
  73324. return false;
  73325. }
  73326. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  73327. {
  73328. Line<float> result (line);
  73329. const bool startInside = contains (line.getStart());
  73330. const bool endInside = contains (line.getEnd());
  73331. if (startInside == endInside)
  73332. {
  73333. if (keepSectionOutsidePath == startInside)
  73334. result = Line<float>();
  73335. }
  73336. else
  73337. {
  73338. PathFlatteningIterator i (*this, AffineTransform::identity);
  73339. Point<float> intersection;
  73340. while (i.next())
  73341. {
  73342. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73343. {
  73344. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  73345. result.setStart (intersection);
  73346. else
  73347. result.setEnd (intersection);
  73348. }
  73349. }
  73350. }
  73351. return result;
  73352. }
  73353. float Path::getLength (const AffineTransform& transform) const
  73354. {
  73355. float length = 0;
  73356. PathFlatteningIterator i (*this, transform);
  73357. while (i.next())
  73358. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  73359. return length;
  73360. }
  73361. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  73362. {
  73363. PathFlatteningIterator i (*this, transform);
  73364. while (i.next())
  73365. {
  73366. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  73367. const float lineLength = line.getLength();
  73368. if (distanceFromStart <= lineLength)
  73369. return line.getPointAlongLine (distanceFromStart);
  73370. distanceFromStart -= lineLength;
  73371. }
  73372. return Point<float> (i.x2, i.y2);
  73373. }
  73374. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  73375. const AffineTransform& transform) const
  73376. {
  73377. PathFlatteningIterator i (*this, transform);
  73378. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  73379. float length = 0;
  73380. Point<float> pointOnLine;
  73381. while (i.next())
  73382. {
  73383. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  73384. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  73385. if (distance < bestDistance)
  73386. {
  73387. bestDistance = distance;
  73388. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  73389. pointOnPath = pointOnLine;
  73390. }
  73391. length += line.getLength();
  73392. }
  73393. return bestPosition;
  73394. }
  73395. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  73396. {
  73397. if (cornerRadius <= 0.01f)
  73398. return *this;
  73399. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  73400. size_t n = 0;
  73401. bool lastWasLine = false, firstWasLine = false;
  73402. Path p;
  73403. while (n < numElements)
  73404. {
  73405. const float type = data.elements [n++];
  73406. if (type == moveMarker)
  73407. {
  73408. indexOfPathStart = p.numElements;
  73409. indexOfPathStartThis = n - 1;
  73410. const float x = data.elements [n++];
  73411. const float y = data.elements [n++];
  73412. p.startNewSubPath (x, y);
  73413. lastWasLine = false;
  73414. firstWasLine = (data.elements [n] == lineMarker);
  73415. }
  73416. else if (type == lineMarker || type == closeSubPathMarker)
  73417. {
  73418. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  73419. if (type == lineMarker)
  73420. {
  73421. endX = data.elements [n++];
  73422. endY = data.elements [n++];
  73423. if (n > 8)
  73424. {
  73425. startX = data.elements [n - 8];
  73426. startY = data.elements [n - 7];
  73427. joinX = data.elements [n - 5];
  73428. joinY = data.elements [n - 4];
  73429. }
  73430. }
  73431. else
  73432. {
  73433. endX = data.elements [indexOfPathStartThis + 1];
  73434. endY = data.elements [indexOfPathStartThis + 2];
  73435. if (n > 6)
  73436. {
  73437. startX = data.elements [n - 6];
  73438. startY = data.elements [n - 5];
  73439. joinX = data.elements [n - 3];
  73440. joinY = data.elements [n - 2];
  73441. }
  73442. }
  73443. if (lastWasLine)
  73444. {
  73445. const double len1 = juce_hypot (startX - joinX,
  73446. startY - joinY);
  73447. if (len1 > 0)
  73448. {
  73449. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73450. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73451. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73452. }
  73453. const double len2 = juce_hypot (endX - joinX,
  73454. endY - joinY);
  73455. if (len2 > 0)
  73456. {
  73457. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73458. p.quadraticTo (joinX, joinY,
  73459. (float) (joinX + (endX - joinX) * propNeeded),
  73460. (float) (joinY + (endY - joinY) * propNeeded));
  73461. }
  73462. p.lineTo (endX, endY);
  73463. }
  73464. else if (type == lineMarker)
  73465. {
  73466. p.lineTo (endX, endY);
  73467. lastWasLine = true;
  73468. }
  73469. if (type == closeSubPathMarker)
  73470. {
  73471. if (firstWasLine)
  73472. {
  73473. startX = data.elements [n - 3];
  73474. startY = data.elements [n - 2];
  73475. joinX = endX;
  73476. joinY = endY;
  73477. endX = data.elements [indexOfPathStartThis + 4];
  73478. endY = data.elements [indexOfPathStartThis + 5];
  73479. const double len1 = juce_hypot (startX - joinX,
  73480. startY - joinY);
  73481. if (len1 > 0)
  73482. {
  73483. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73484. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73485. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73486. }
  73487. const double len2 = juce_hypot (endX - joinX,
  73488. endY - joinY);
  73489. if (len2 > 0)
  73490. {
  73491. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73492. endX = (float) (joinX + (endX - joinX) * propNeeded);
  73493. endY = (float) (joinY + (endY - joinY) * propNeeded);
  73494. p.quadraticTo (joinX, joinY, endX, endY);
  73495. p.data.elements [indexOfPathStart + 1] = endX;
  73496. p.data.elements [indexOfPathStart + 2] = endY;
  73497. }
  73498. }
  73499. p.closeSubPath();
  73500. }
  73501. }
  73502. else if (type == quadMarker)
  73503. {
  73504. lastWasLine = false;
  73505. const float x1 = data.elements [n++];
  73506. const float y1 = data.elements [n++];
  73507. const float x2 = data.elements [n++];
  73508. const float y2 = data.elements [n++];
  73509. p.quadraticTo (x1, y1, x2, y2);
  73510. }
  73511. else if (type == cubicMarker)
  73512. {
  73513. lastWasLine = false;
  73514. const float x1 = data.elements [n++];
  73515. const float y1 = data.elements [n++];
  73516. const float x2 = data.elements [n++];
  73517. const float y2 = data.elements [n++];
  73518. const float x3 = data.elements [n++];
  73519. const float y3 = data.elements [n++];
  73520. p.cubicTo (x1, y1, x2, y2, x3, y3);
  73521. }
  73522. }
  73523. return p;
  73524. }
  73525. void Path::loadPathFromStream (InputStream& source)
  73526. {
  73527. while (! source.isExhausted())
  73528. {
  73529. switch (source.readByte())
  73530. {
  73531. case 'm':
  73532. {
  73533. const float x = source.readFloat();
  73534. const float y = source.readFloat();
  73535. startNewSubPath (x, y);
  73536. break;
  73537. }
  73538. case 'l':
  73539. {
  73540. const float x = source.readFloat();
  73541. const float y = source.readFloat();
  73542. lineTo (x, y);
  73543. break;
  73544. }
  73545. case 'q':
  73546. {
  73547. const float x1 = source.readFloat();
  73548. const float y1 = source.readFloat();
  73549. const float x2 = source.readFloat();
  73550. const float y2 = source.readFloat();
  73551. quadraticTo (x1, y1, x2, y2);
  73552. break;
  73553. }
  73554. case 'b':
  73555. {
  73556. const float x1 = source.readFloat();
  73557. const float y1 = source.readFloat();
  73558. const float x2 = source.readFloat();
  73559. const float y2 = source.readFloat();
  73560. const float x3 = source.readFloat();
  73561. const float y3 = source.readFloat();
  73562. cubicTo (x1, y1, x2, y2, x3, y3);
  73563. break;
  73564. }
  73565. case 'c':
  73566. closeSubPath();
  73567. break;
  73568. case 'n':
  73569. useNonZeroWinding = true;
  73570. break;
  73571. case 'z':
  73572. useNonZeroWinding = false;
  73573. break;
  73574. case 'e':
  73575. return; // end of path marker
  73576. default:
  73577. jassertfalse; // illegal char in the stream
  73578. break;
  73579. }
  73580. }
  73581. }
  73582. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  73583. {
  73584. MemoryInputStream in (pathData, numberOfBytes, false);
  73585. loadPathFromStream (in);
  73586. }
  73587. void Path::writePathToStream (OutputStream& dest) const
  73588. {
  73589. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  73590. size_t i = 0;
  73591. while (i < numElements)
  73592. {
  73593. const float type = data.elements [i++];
  73594. if (type == moveMarker)
  73595. {
  73596. dest.writeByte ('m');
  73597. dest.writeFloat (data.elements [i++]);
  73598. dest.writeFloat (data.elements [i++]);
  73599. }
  73600. else if (type == lineMarker)
  73601. {
  73602. dest.writeByte ('l');
  73603. dest.writeFloat (data.elements [i++]);
  73604. dest.writeFloat (data.elements [i++]);
  73605. }
  73606. else if (type == quadMarker)
  73607. {
  73608. dest.writeByte ('q');
  73609. dest.writeFloat (data.elements [i++]);
  73610. dest.writeFloat (data.elements [i++]);
  73611. dest.writeFloat (data.elements [i++]);
  73612. dest.writeFloat (data.elements [i++]);
  73613. }
  73614. else if (type == cubicMarker)
  73615. {
  73616. dest.writeByte ('b');
  73617. dest.writeFloat (data.elements [i++]);
  73618. dest.writeFloat (data.elements [i++]);
  73619. dest.writeFloat (data.elements [i++]);
  73620. dest.writeFloat (data.elements [i++]);
  73621. dest.writeFloat (data.elements [i++]);
  73622. dest.writeFloat (data.elements [i++]);
  73623. }
  73624. else if (type == closeSubPathMarker)
  73625. {
  73626. dest.writeByte ('c');
  73627. }
  73628. }
  73629. dest.writeByte ('e'); // marks the end-of-path
  73630. }
  73631. const String Path::toString() const
  73632. {
  73633. MemoryOutputStream s (2048, 2048);
  73634. if (! useNonZeroWinding)
  73635. s << 'a';
  73636. size_t i = 0;
  73637. float lastMarker = 0.0f;
  73638. while (i < numElements)
  73639. {
  73640. const float marker = data.elements [i++];
  73641. char markerChar = 0;
  73642. int numCoords = 0;
  73643. if (marker == moveMarker)
  73644. {
  73645. markerChar = 'm';
  73646. numCoords = 2;
  73647. }
  73648. else if (marker == lineMarker)
  73649. {
  73650. markerChar = 'l';
  73651. numCoords = 2;
  73652. }
  73653. else if (marker == quadMarker)
  73654. {
  73655. markerChar = 'q';
  73656. numCoords = 4;
  73657. }
  73658. else if (marker == cubicMarker)
  73659. {
  73660. markerChar = 'c';
  73661. numCoords = 6;
  73662. }
  73663. else
  73664. {
  73665. jassert (marker == closeSubPathMarker);
  73666. markerChar = 'z';
  73667. }
  73668. if (marker != lastMarker)
  73669. {
  73670. if (s.getDataSize() != 0)
  73671. s << ' ';
  73672. s << markerChar;
  73673. lastMarker = marker;
  73674. }
  73675. while (--numCoords >= 0 && i < numElements)
  73676. {
  73677. String coord (data.elements [i++], 3);
  73678. while (coord.endsWithChar ('0') && coord != "0")
  73679. coord = coord.dropLastCharacters (1);
  73680. if (coord.endsWithChar ('.'))
  73681. coord = coord.dropLastCharacters (1);
  73682. if (s.getDataSize() != 0)
  73683. s << ' ';
  73684. s << coord;
  73685. }
  73686. }
  73687. return s.toUTF8();
  73688. }
  73689. void Path::restoreFromString (const String& stringVersion)
  73690. {
  73691. clear();
  73692. setUsingNonZeroWinding (true);
  73693. const juce_wchar* t = stringVersion;
  73694. juce_wchar marker = 'm';
  73695. int numValues = 2;
  73696. float values [6];
  73697. for (;;)
  73698. {
  73699. const String token (PathHelpers::nextToken (t));
  73700. const juce_wchar firstChar = token[0];
  73701. int startNum = 0;
  73702. if (firstChar == 0)
  73703. break;
  73704. if (firstChar == 'm' || firstChar == 'l')
  73705. {
  73706. marker = firstChar;
  73707. numValues = 2;
  73708. }
  73709. else if (firstChar == 'q')
  73710. {
  73711. marker = firstChar;
  73712. numValues = 4;
  73713. }
  73714. else if (firstChar == 'c')
  73715. {
  73716. marker = firstChar;
  73717. numValues = 6;
  73718. }
  73719. else if (firstChar == 'z')
  73720. {
  73721. marker = firstChar;
  73722. numValues = 0;
  73723. }
  73724. else if (firstChar == 'a')
  73725. {
  73726. setUsingNonZeroWinding (false);
  73727. continue;
  73728. }
  73729. else
  73730. {
  73731. ++startNum;
  73732. values [0] = token.getFloatValue();
  73733. }
  73734. for (int i = startNum; i < numValues; ++i)
  73735. values [i] = PathHelpers::nextToken (t).getFloatValue();
  73736. switch (marker)
  73737. {
  73738. case 'm':
  73739. startNewSubPath (values[0], values[1]);
  73740. break;
  73741. case 'l':
  73742. lineTo (values[0], values[1]);
  73743. break;
  73744. case 'q':
  73745. quadraticTo (values[0], values[1],
  73746. values[2], values[3]);
  73747. break;
  73748. case 'c':
  73749. cubicTo (values[0], values[1],
  73750. values[2], values[3],
  73751. values[4], values[5]);
  73752. break;
  73753. case 'z':
  73754. closeSubPath();
  73755. break;
  73756. default:
  73757. jassertfalse; // illegal string format?
  73758. break;
  73759. }
  73760. }
  73761. }
  73762. Path::Iterator::Iterator (const Path& path_)
  73763. : path (path_),
  73764. index (0)
  73765. {
  73766. }
  73767. Path::Iterator::~Iterator()
  73768. {
  73769. }
  73770. bool Path::Iterator::next()
  73771. {
  73772. const float* const elements = path.data.elements;
  73773. if (index < path.numElements)
  73774. {
  73775. const float type = elements [index++];
  73776. if (type == moveMarker)
  73777. {
  73778. elementType = startNewSubPath;
  73779. x1 = elements [index++];
  73780. y1 = elements [index++];
  73781. }
  73782. else if (type == lineMarker)
  73783. {
  73784. elementType = lineTo;
  73785. x1 = elements [index++];
  73786. y1 = elements [index++];
  73787. }
  73788. else if (type == quadMarker)
  73789. {
  73790. elementType = quadraticTo;
  73791. x1 = elements [index++];
  73792. y1 = elements [index++];
  73793. x2 = elements [index++];
  73794. y2 = elements [index++];
  73795. }
  73796. else if (type == cubicMarker)
  73797. {
  73798. elementType = cubicTo;
  73799. x1 = elements [index++];
  73800. y1 = elements [index++];
  73801. x2 = elements [index++];
  73802. y2 = elements [index++];
  73803. x3 = elements [index++];
  73804. y3 = elements [index++];
  73805. }
  73806. else if (type == closeSubPathMarker)
  73807. {
  73808. elementType = closePath;
  73809. }
  73810. return true;
  73811. }
  73812. return false;
  73813. }
  73814. END_JUCE_NAMESPACE
  73815. /*** End of inlined file: juce_Path.cpp ***/
  73816. /*** Start of inlined file: juce_PathIterator.cpp ***/
  73817. BEGIN_JUCE_NAMESPACE
  73818. #if JUCE_MSVC && JUCE_DEBUG
  73819. #pragma optimize ("t", on)
  73820. #endif
  73821. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  73822. const AffineTransform& transform_,
  73823. float tolerence_)
  73824. : x2 (0),
  73825. y2 (0),
  73826. closesSubPath (false),
  73827. subPathIndex (-1),
  73828. path (path_),
  73829. transform (transform_),
  73830. points (path_.data.elements),
  73831. tolerence (tolerence_ * tolerence_),
  73832. subPathCloseX (0),
  73833. subPathCloseY (0),
  73834. isIdentityTransform (transform_.isIdentity()),
  73835. stackBase (32),
  73836. index (0),
  73837. stackSize (32)
  73838. {
  73839. stackPos = stackBase;
  73840. }
  73841. PathFlatteningIterator::~PathFlatteningIterator()
  73842. {
  73843. }
  73844. bool PathFlatteningIterator::next()
  73845. {
  73846. x1 = x2;
  73847. y1 = y2;
  73848. float x3 = 0;
  73849. float y3 = 0;
  73850. float x4 = 0;
  73851. float y4 = 0;
  73852. float type;
  73853. for (;;)
  73854. {
  73855. if (stackPos == stackBase)
  73856. {
  73857. if (index >= path.numElements)
  73858. {
  73859. return false;
  73860. }
  73861. else
  73862. {
  73863. type = points [index++];
  73864. if (type != Path::closeSubPathMarker)
  73865. {
  73866. x2 = points [index++];
  73867. y2 = points [index++];
  73868. if (type == Path::quadMarker)
  73869. {
  73870. x3 = points [index++];
  73871. y3 = points [index++];
  73872. if (! isIdentityTransform)
  73873. transform.transformPoints (x2, y2, x3, y3);
  73874. }
  73875. else if (type == Path::cubicMarker)
  73876. {
  73877. x3 = points [index++];
  73878. y3 = points [index++];
  73879. x4 = points [index++];
  73880. y4 = points [index++];
  73881. if (! isIdentityTransform)
  73882. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  73883. }
  73884. else
  73885. {
  73886. if (! isIdentityTransform)
  73887. transform.transformPoint (x2, y2);
  73888. }
  73889. }
  73890. }
  73891. }
  73892. else
  73893. {
  73894. type = *--stackPos;
  73895. if (type != Path::closeSubPathMarker)
  73896. {
  73897. x2 = *--stackPos;
  73898. y2 = *--stackPos;
  73899. if (type == Path::quadMarker)
  73900. {
  73901. x3 = *--stackPos;
  73902. y3 = *--stackPos;
  73903. }
  73904. else if (type == Path::cubicMarker)
  73905. {
  73906. x3 = *--stackPos;
  73907. y3 = *--stackPos;
  73908. x4 = *--stackPos;
  73909. y4 = *--stackPos;
  73910. }
  73911. }
  73912. }
  73913. if (type == Path::lineMarker)
  73914. {
  73915. ++subPathIndex;
  73916. closesSubPath = (stackPos == stackBase)
  73917. && (index < path.numElements)
  73918. && (points [index] == Path::closeSubPathMarker)
  73919. && x2 == subPathCloseX
  73920. && y2 == subPathCloseY;
  73921. return true;
  73922. }
  73923. else if (type == Path::quadMarker)
  73924. {
  73925. const size_t offset = (size_t) (stackPos - stackBase);
  73926. if (offset >= stackSize - 10)
  73927. {
  73928. stackSize <<= 1;
  73929. stackBase.realloc (stackSize);
  73930. stackPos = stackBase + offset;
  73931. }
  73932. const float dx1 = x1 - x2;
  73933. const float dy1 = y1 - y2;
  73934. const float dx2 = x2 - x3;
  73935. const float dy2 = y2 - y3;
  73936. const float m1x = (x1 + x2) * 0.5f;
  73937. const float m1y = (y1 + y2) * 0.5f;
  73938. const float m2x = (x2 + x3) * 0.5f;
  73939. const float m2y = (y2 + y3) * 0.5f;
  73940. const float m3x = (m1x + m2x) * 0.5f;
  73941. const float m3y = (m1y + m2y) * 0.5f;
  73942. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  73943. {
  73944. *stackPos++ = y3;
  73945. *stackPos++ = x3;
  73946. *stackPos++ = m2y;
  73947. *stackPos++ = m2x;
  73948. *stackPos++ = Path::quadMarker;
  73949. *stackPos++ = m3y;
  73950. *stackPos++ = m3x;
  73951. *stackPos++ = m1y;
  73952. *stackPos++ = m1x;
  73953. *stackPos++ = Path::quadMarker;
  73954. }
  73955. else
  73956. {
  73957. *stackPos++ = y3;
  73958. *stackPos++ = x3;
  73959. *stackPos++ = Path::lineMarker;
  73960. *stackPos++ = m3y;
  73961. *stackPos++ = m3x;
  73962. *stackPos++ = Path::lineMarker;
  73963. }
  73964. jassert (stackPos < stackBase + stackSize);
  73965. }
  73966. else if (type == Path::cubicMarker)
  73967. {
  73968. const size_t offset = (size_t) (stackPos - stackBase);
  73969. if (offset >= stackSize - 16)
  73970. {
  73971. stackSize <<= 1;
  73972. stackBase.realloc (stackSize);
  73973. stackPos = stackBase + offset;
  73974. }
  73975. const float dx1 = x1 - x2;
  73976. const float dy1 = y1 - y2;
  73977. const float dx2 = x2 - x3;
  73978. const float dy2 = y2 - y3;
  73979. const float dx3 = x3 - x4;
  73980. const float dy3 = y3 - y4;
  73981. const float m1x = (x1 + x2) * 0.5f;
  73982. const float m1y = (y1 + y2) * 0.5f;
  73983. const float m2x = (x3 + x2) * 0.5f;
  73984. const float m2y = (y3 + y2) * 0.5f;
  73985. const float m3x = (x3 + x4) * 0.5f;
  73986. const float m3y = (y3 + y4) * 0.5f;
  73987. const float m4x = (m1x + m2x) * 0.5f;
  73988. const float m4y = (m1y + m2y) * 0.5f;
  73989. const float m5x = (m3x + m2x) * 0.5f;
  73990. const float m5y = (m3y + m2y) * 0.5f;
  73991. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  73992. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  73993. {
  73994. *stackPos++ = y4;
  73995. *stackPos++ = x4;
  73996. *stackPos++ = m3y;
  73997. *stackPos++ = m3x;
  73998. *stackPos++ = m5y;
  73999. *stackPos++ = m5x;
  74000. *stackPos++ = Path::cubicMarker;
  74001. *stackPos++ = (m4y + m5y) * 0.5f;
  74002. *stackPos++ = (m4x + m5x) * 0.5f;
  74003. *stackPos++ = m4y;
  74004. *stackPos++ = m4x;
  74005. *stackPos++ = m1y;
  74006. *stackPos++ = m1x;
  74007. *stackPos++ = Path::cubicMarker;
  74008. }
  74009. else
  74010. {
  74011. *stackPos++ = y4;
  74012. *stackPos++ = x4;
  74013. *stackPos++ = Path::lineMarker;
  74014. *stackPos++ = m5y;
  74015. *stackPos++ = m5x;
  74016. *stackPos++ = Path::lineMarker;
  74017. *stackPos++ = m4y;
  74018. *stackPos++ = m4x;
  74019. *stackPos++ = Path::lineMarker;
  74020. }
  74021. }
  74022. else if (type == Path::closeSubPathMarker)
  74023. {
  74024. if (x2 != subPathCloseX || y2 != subPathCloseY)
  74025. {
  74026. x1 = x2;
  74027. y1 = y2;
  74028. x2 = subPathCloseX;
  74029. y2 = subPathCloseY;
  74030. closesSubPath = true;
  74031. return true;
  74032. }
  74033. }
  74034. else
  74035. {
  74036. jassert (type == Path::moveMarker);
  74037. subPathIndex = -1;
  74038. subPathCloseX = x1 = x2;
  74039. subPathCloseY = y1 = y2;
  74040. }
  74041. }
  74042. }
  74043. #if JUCE_MSVC && JUCE_DEBUG
  74044. #pragma optimize ("", on) // resets optimisations to the project defaults
  74045. #endif
  74046. END_JUCE_NAMESPACE
  74047. /*** End of inlined file: juce_PathIterator.cpp ***/
  74048. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  74049. BEGIN_JUCE_NAMESPACE
  74050. PathStrokeType::PathStrokeType (const float strokeThickness,
  74051. const JointStyle jointStyle_,
  74052. const EndCapStyle endStyle_) throw()
  74053. : thickness (strokeThickness),
  74054. jointStyle (jointStyle_),
  74055. endStyle (endStyle_)
  74056. {
  74057. }
  74058. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  74059. : thickness (other.thickness),
  74060. jointStyle (other.jointStyle),
  74061. endStyle (other.endStyle)
  74062. {
  74063. }
  74064. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  74065. {
  74066. thickness = other.thickness;
  74067. jointStyle = other.jointStyle;
  74068. endStyle = other.endStyle;
  74069. return *this;
  74070. }
  74071. PathStrokeType::~PathStrokeType() throw()
  74072. {
  74073. }
  74074. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  74075. {
  74076. return thickness == other.thickness
  74077. && jointStyle == other.jointStyle
  74078. && endStyle == other.endStyle;
  74079. }
  74080. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  74081. {
  74082. return ! operator== (other);
  74083. }
  74084. namespace PathStrokeHelpers
  74085. {
  74086. static bool lineIntersection (const float x1, const float y1,
  74087. const float x2, const float y2,
  74088. const float x3, const float y3,
  74089. const float x4, const float y4,
  74090. float& intersectionX,
  74091. float& intersectionY,
  74092. float& distanceBeyondLine1EndSquared) throw()
  74093. {
  74094. if (x2 != x3 || y2 != y3)
  74095. {
  74096. const float dx1 = x2 - x1;
  74097. const float dy1 = y2 - y1;
  74098. const float dx2 = x4 - x3;
  74099. const float dy2 = y4 - y3;
  74100. const float divisor = dx1 * dy2 - dx2 * dy1;
  74101. if (divisor == 0)
  74102. {
  74103. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  74104. {
  74105. if (dy1 == 0 && dy2 != 0)
  74106. {
  74107. const float along = (y1 - y3) / dy2;
  74108. intersectionX = x3 + along * dx2;
  74109. intersectionY = y1;
  74110. distanceBeyondLine1EndSquared = intersectionX - x2;
  74111. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74112. if ((x2 > x1) == (intersectionX < x2))
  74113. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74114. return along >= 0 && along <= 1.0f;
  74115. }
  74116. else if (dy2 == 0 && dy1 != 0)
  74117. {
  74118. const float along = (y3 - y1) / dy1;
  74119. intersectionX = x1 + along * dx1;
  74120. intersectionY = y3;
  74121. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  74122. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74123. if (along < 1.0f)
  74124. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74125. return along >= 0 && along <= 1.0f;
  74126. }
  74127. else if (dx1 == 0 && dx2 != 0)
  74128. {
  74129. const float along = (x1 - x3) / dx2;
  74130. intersectionX = x1;
  74131. intersectionY = y3 + along * dy2;
  74132. distanceBeyondLine1EndSquared = intersectionY - y2;
  74133. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74134. if ((y2 > y1) == (intersectionY < y2))
  74135. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74136. return along >= 0 && along <= 1.0f;
  74137. }
  74138. else if (dx2 == 0 && dx1 != 0)
  74139. {
  74140. const float along = (x3 - x1) / dx1;
  74141. intersectionX = x3;
  74142. intersectionY = y1 + along * dy1;
  74143. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  74144. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74145. if (along < 1.0f)
  74146. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74147. return along >= 0 && along <= 1.0f;
  74148. }
  74149. }
  74150. intersectionX = 0.5f * (x2 + x3);
  74151. intersectionY = 0.5f * (y2 + y3);
  74152. distanceBeyondLine1EndSquared = 0.0f;
  74153. return false;
  74154. }
  74155. else
  74156. {
  74157. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  74158. intersectionX = x1 + along1 * dx1;
  74159. intersectionY = y1 + along1 * dy1;
  74160. if (along1 >= 0 && along1 <= 1.0f)
  74161. {
  74162. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  74163. if (along2 >= 0 && along2 <= divisor)
  74164. {
  74165. distanceBeyondLine1EndSquared = 0.0f;
  74166. return true;
  74167. }
  74168. }
  74169. distanceBeyondLine1EndSquared = along1 - 1.0f;
  74170. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74171. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  74172. if (along1 < 1.0f)
  74173. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74174. return false;
  74175. }
  74176. }
  74177. intersectionX = x2;
  74178. intersectionY = y2;
  74179. distanceBeyondLine1EndSquared = 0.0f;
  74180. return true;
  74181. }
  74182. static void addEdgeAndJoint (Path& destPath,
  74183. const PathStrokeType::JointStyle style,
  74184. const float maxMiterExtensionSquared, const float width,
  74185. const float x1, const float y1,
  74186. const float x2, const float y2,
  74187. const float x3, const float y3,
  74188. const float x4, const float y4,
  74189. const float midX, const float midY)
  74190. {
  74191. if (style == PathStrokeType::beveled
  74192. || (x3 == x4 && y3 == y4)
  74193. || (x1 == x2 && y1 == y2))
  74194. {
  74195. destPath.lineTo (x2, y2);
  74196. destPath.lineTo (x3, y3);
  74197. }
  74198. else
  74199. {
  74200. float jx, jy, distanceBeyondLine1EndSquared;
  74201. // if they intersect, use this point..
  74202. if (lineIntersection (x1, y1, x2, y2,
  74203. x3, y3, x4, y4,
  74204. jx, jy, distanceBeyondLine1EndSquared))
  74205. {
  74206. destPath.lineTo (jx, jy);
  74207. }
  74208. else
  74209. {
  74210. if (style == PathStrokeType::mitered)
  74211. {
  74212. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  74213. && distanceBeyondLine1EndSquared > 0.0f)
  74214. {
  74215. destPath.lineTo (jx, jy);
  74216. }
  74217. else
  74218. {
  74219. // the end sticks out too far, so just use a blunt joint
  74220. destPath.lineTo (x2, y2);
  74221. destPath.lineTo (x3, y3);
  74222. }
  74223. }
  74224. else
  74225. {
  74226. // curved joints
  74227. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  74228. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  74229. const float angleIncrement = 0.1f;
  74230. destPath.lineTo (x2, y2);
  74231. if (std::abs (angle1 - angle2) > angleIncrement)
  74232. {
  74233. if (angle2 > angle1 + float_Pi
  74234. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  74235. {
  74236. if (angle2 > angle1)
  74237. angle2 -= float_Pi * 2.0f;
  74238. jassert (angle1 <= angle2 + float_Pi);
  74239. angle1 -= angleIncrement;
  74240. while (angle1 > angle2)
  74241. {
  74242. destPath.lineTo (midX + width * std::sin (angle1),
  74243. midY + width * std::cos (angle1));
  74244. angle1 -= angleIncrement;
  74245. }
  74246. }
  74247. else
  74248. {
  74249. if (angle1 > angle2)
  74250. angle1 -= float_Pi * 2.0f;
  74251. jassert (angle1 >= angle2 - float_Pi);
  74252. angle1 += angleIncrement;
  74253. while (angle1 < angle2)
  74254. {
  74255. destPath.lineTo (midX + width * std::sin (angle1),
  74256. midY + width * std::cos (angle1));
  74257. angle1 += angleIncrement;
  74258. }
  74259. }
  74260. }
  74261. destPath.lineTo (x3, y3);
  74262. }
  74263. }
  74264. }
  74265. }
  74266. static void addLineEnd (Path& destPath,
  74267. const PathStrokeType::EndCapStyle style,
  74268. const float x1, const float y1,
  74269. const float x2, const float y2,
  74270. const float width)
  74271. {
  74272. if (style == PathStrokeType::butt)
  74273. {
  74274. destPath.lineTo (x2, y2);
  74275. }
  74276. else
  74277. {
  74278. float offx1, offy1, offx2, offy2;
  74279. float dx = x2 - x1;
  74280. float dy = y2 - y1;
  74281. const float len = juce_hypotf (dx, dy);
  74282. if (len == 0)
  74283. {
  74284. offx1 = offx2 = x1;
  74285. offy1 = offy2 = y1;
  74286. }
  74287. else
  74288. {
  74289. const float offset = width / len;
  74290. dx *= offset;
  74291. dy *= offset;
  74292. offx1 = x1 + dy;
  74293. offy1 = y1 - dx;
  74294. offx2 = x2 + dy;
  74295. offy2 = y2 - dx;
  74296. }
  74297. if (style == PathStrokeType::square)
  74298. {
  74299. // sqaure ends
  74300. destPath.lineTo (offx1, offy1);
  74301. destPath.lineTo (offx2, offy2);
  74302. destPath.lineTo (x2, y2);
  74303. }
  74304. else
  74305. {
  74306. // rounded ends
  74307. const float midx = (offx1 + offx2) * 0.5f;
  74308. const float midy = (offy1 + offy2) * 0.5f;
  74309. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  74310. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  74311. midx, midy);
  74312. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  74313. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  74314. x2, y2);
  74315. }
  74316. }
  74317. }
  74318. struct Arrowhead
  74319. {
  74320. float startWidth, startLength;
  74321. float endWidth, endLength;
  74322. };
  74323. static void addArrowhead (Path& destPath,
  74324. const float x1, const float y1,
  74325. const float x2, const float y2,
  74326. const float tipX, const float tipY,
  74327. const float width,
  74328. const float arrowheadWidth)
  74329. {
  74330. Line<float> line (x1, y1, x2, y2);
  74331. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  74332. destPath.lineTo (tipX, tipY);
  74333. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  74334. destPath.lineTo (x2, y2);
  74335. }
  74336. struct LineSection
  74337. {
  74338. float x1, y1, x2, y2; // original line
  74339. float lx1, ly1, lx2, ly2; // the left-hand stroke
  74340. float rx1, ry1, rx2, ry2; // the right-hand stroke
  74341. };
  74342. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  74343. {
  74344. while (amountAtEnd > 0 && subPath.size() > 0)
  74345. {
  74346. LineSection& l = subPath.getReference (subPath.size() - 1);
  74347. float dx = l.rx2 - l.rx1;
  74348. float dy = l.ry2 - l.ry1;
  74349. const float len = juce_hypotf (dx, dy);
  74350. if (len <= amountAtEnd && subPath.size() > 1)
  74351. {
  74352. LineSection& prev = subPath.getReference (subPath.size() - 2);
  74353. prev.x2 = l.x2;
  74354. prev.y2 = l.y2;
  74355. subPath.removeLast();
  74356. amountAtEnd -= len;
  74357. }
  74358. else
  74359. {
  74360. const float prop = jmin (0.9999f, amountAtEnd / len);
  74361. dx *= prop;
  74362. dy *= prop;
  74363. l.rx1 += dx;
  74364. l.ry1 += dy;
  74365. l.lx2 += dx;
  74366. l.ly2 += dy;
  74367. break;
  74368. }
  74369. }
  74370. while (amountAtStart > 0 && subPath.size() > 0)
  74371. {
  74372. LineSection& l = subPath.getReference (0);
  74373. float dx = l.rx2 - l.rx1;
  74374. float dy = l.ry2 - l.ry1;
  74375. const float len = juce_hypotf (dx, dy);
  74376. if (len <= amountAtStart && subPath.size() > 1)
  74377. {
  74378. LineSection& next = subPath.getReference (1);
  74379. next.x1 = l.x1;
  74380. next.y1 = l.y1;
  74381. subPath.remove (0);
  74382. amountAtStart -= len;
  74383. }
  74384. else
  74385. {
  74386. const float prop = jmin (0.9999f, amountAtStart / len);
  74387. dx *= prop;
  74388. dy *= prop;
  74389. l.rx2 -= dx;
  74390. l.ry2 -= dy;
  74391. l.lx1 -= dx;
  74392. l.ly1 -= dy;
  74393. break;
  74394. }
  74395. }
  74396. }
  74397. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  74398. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  74399. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  74400. const Arrowhead* const arrowhead)
  74401. {
  74402. jassert (subPath.size() > 0);
  74403. if (arrowhead != 0)
  74404. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  74405. const LineSection& firstLine = subPath.getReference (0);
  74406. float lastX1 = firstLine.lx1;
  74407. float lastY1 = firstLine.ly1;
  74408. float lastX2 = firstLine.lx2;
  74409. float lastY2 = firstLine.ly2;
  74410. if (isClosed)
  74411. {
  74412. destPath.startNewSubPath (lastX1, lastY1);
  74413. }
  74414. else
  74415. {
  74416. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  74417. if (arrowhead != 0)
  74418. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  74419. width, arrowhead->startWidth);
  74420. else
  74421. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  74422. }
  74423. int i;
  74424. for (i = 1; i < subPath.size(); ++i)
  74425. {
  74426. const LineSection& l = subPath.getReference (i);
  74427. addEdgeAndJoint (destPath, jointStyle,
  74428. maxMiterExtensionSquared, width,
  74429. lastX1, lastY1, lastX2, lastY2,
  74430. l.lx1, l.ly1, l.lx2, l.ly2,
  74431. l.x1, l.y1);
  74432. lastX1 = l.lx1;
  74433. lastY1 = l.ly1;
  74434. lastX2 = l.lx2;
  74435. lastY2 = l.ly2;
  74436. }
  74437. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  74438. if (isClosed)
  74439. {
  74440. const LineSection& l = subPath.getReference (0);
  74441. addEdgeAndJoint (destPath, jointStyle,
  74442. maxMiterExtensionSquared, width,
  74443. lastX1, lastY1, lastX2, lastY2,
  74444. l.lx1, l.ly1, l.lx2, l.ly2,
  74445. l.x1, l.y1);
  74446. destPath.closeSubPath();
  74447. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  74448. }
  74449. else
  74450. {
  74451. destPath.lineTo (lastX2, lastY2);
  74452. if (arrowhead != 0)
  74453. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  74454. width, arrowhead->endWidth);
  74455. else
  74456. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  74457. }
  74458. lastX1 = lastLine.rx1;
  74459. lastY1 = lastLine.ry1;
  74460. lastX2 = lastLine.rx2;
  74461. lastY2 = lastLine.ry2;
  74462. for (i = subPath.size() - 1; --i >= 0;)
  74463. {
  74464. const LineSection& l = subPath.getReference (i);
  74465. addEdgeAndJoint (destPath, jointStyle,
  74466. maxMiterExtensionSquared, width,
  74467. lastX1, lastY1, lastX2, lastY2,
  74468. l.rx1, l.ry1, l.rx2, l.ry2,
  74469. l.x2, l.y2);
  74470. lastX1 = l.rx1;
  74471. lastY1 = l.ry1;
  74472. lastX2 = l.rx2;
  74473. lastY2 = l.ry2;
  74474. }
  74475. if (isClosed)
  74476. {
  74477. addEdgeAndJoint (destPath, jointStyle,
  74478. maxMiterExtensionSquared, width,
  74479. lastX1, lastY1, lastX2, lastY2,
  74480. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  74481. lastLine.x2, lastLine.y2);
  74482. }
  74483. else
  74484. {
  74485. // do the last line
  74486. destPath.lineTo (lastX2, lastY2);
  74487. }
  74488. destPath.closeSubPath();
  74489. }
  74490. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  74491. const PathStrokeType::EndCapStyle endStyle,
  74492. Path& destPath, const Path& source,
  74493. const AffineTransform& transform,
  74494. const float extraAccuracy, const Arrowhead* const arrowhead)
  74495. {
  74496. if (thickness <= 0)
  74497. {
  74498. destPath.clear();
  74499. return;
  74500. }
  74501. const Path* sourcePath = &source;
  74502. Path temp;
  74503. if (sourcePath == &destPath)
  74504. {
  74505. destPath.swapWithPath (temp);
  74506. sourcePath = &temp;
  74507. }
  74508. else
  74509. {
  74510. destPath.clear();
  74511. }
  74512. destPath.setUsingNonZeroWinding (true);
  74513. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  74514. const float width = 0.5f * thickness;
  74515. // Iterate the path, creating a list of the
  74516. // left/right-hand lines along either side of it...
  74517. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  74518. Array <LineSection> subPath;
  74519. subPath.ensureStorageAllocated (512);
  74520. LineSection l;
  74521. l.x1 = 0;
  74522. l.y1 = 0;
  74523. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  74524. while (it.next())
  74525. {
  74526. if (it.subPathIndex == 0)
  74527. {
  74528. if (subPath.size() > 0)
  74529. {
  74530. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74531. subPath.clearQuick();
  74532. }
  74533. l.x1 = it.x1;
  74534. l.y1 = it.y1;
  74535. }
  74536. l.x2 = it.x2;
  74537. l.y2 = it.y2;
  74538. float dx = l.x2 - l.x1;
  74539. float dy = l.y2 - l.y1;
  74540. const float hypotSquared = dx*dx + dy*dy;
  74541. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  74542. {
  74543. const float len = std::sqrt (hypotSquared);
  74544. if (len == 0)
  74545. {
  74546. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  74547. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  74548. }
  74549. else
  74550. {
  74551. const float offset = width / len;
  74552. dx *= offset;
  74553. dy *= offset;
  74554. l.rx2 = l.x1 - dy;
  74555. l.ry2 = l.y1 + dx;
  74556. l.lx1 = l.x1 + dy;
  74557. l.ly1 = l.y1 - dx;
  74558. l.lx2 = l.x2 + dy;
  74559. l.ly2 = l.y2 - dx;
  74560. l.rx1 = l.x2 - dy;
  74561. l.ry1 = l.y2 + dx;
  74562. }
  74563. subPath.add (l);
  74564. if (it.closesSubPath)
  74565. {
  74566. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74567. subPath.clearQuick();
  74568. }
  74569. else
  74570. {
  74571. l.x1 = it.x2;
  74572. l.y1 = it.y2;
  74573. }
  74574. }
  74575. }
  74576. if (subPath.size() > 0)
  74577. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74578. }
  74579. }
  74580. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  74581. const AffineTransform& transform, const float extraAccuracy) const
  74582. {
  74583. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  74584. transform, extraAccuracy, 0);
  74585. }
  74586. void PathStrokeType::createDashedStroke (Path& destPath,
  74587. const Path& sourcePath,
  74588. const float* dashLengths,
  74589. int numDashLengths,
  74590. const AffineTransform& transform,
  74591. const float extraAccuracy) const
  74592. {
  74593. if (thickness <= 0)
  74594. return;
  74595. // this should really be an even number..
  74596. jassert ((numDashLengths & 1) == 0);
  74597. Path newDestPath;
  74598. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  74599. bool first = true;
  74600. int dashNum = 0;
  74601. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  74602. float dx = 0.0f, dy = 0.0f;
  74603. for (;;)
  74604. {
  74605. const bool isSolid = ((dashNum & 1) == 0);
  74606. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  74607. jassert (dashLen > 0); // must be a positive increment!
  74608. if (dashLen <= 0)
  74609. break;
  74610. pos += dashLen;
  74611. while (pos > lineEndPos)
  74612. {
  74613. if (! it.next())
  74614. {
  74615. if (isSolid && ! first)
  74616. newDestPath.lineTo (it.x2, it.y2);
  74617. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  74618. return;
  74619. }
  74620. if (isSolid && ! first)
  74621. newDestPath.lineTo (it.x1, it.y1);
  74622. else
  74623. newDestPath.startNewSubPath (it.x1, it.y1);
  74624. dx = it.x2 - it.x1;
  74625. dy = it.y2 - it.y1;
  74626. lineLen = juce_hypotf (dx, dy);
  74627. lineEndPos += lineLen;
  74628. first = it.closesSubPath;
  74629. }
  74630. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  74631. if (isSolid)
  74632. newDestPath.lineTo (it.x1 + dx * alpha,
  74633. it.y1 + dy * alpha);
  74634. else
  74635. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  74636. it.y1 + dy * alpha);
  74637. }
  74638. }
  74639. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  74640. const Path& sourcePath,
  74641. const float arrowheadStartWidth, const float arrowheadStartLength,
  74642. const float arrowheadEndWidth, const float arrowheadEndLength,
  74643. const AffineTransform& transform,
  74644. const float extraAccuracy) const
  74645. {
  74646. PathStrokeHelpers::Arrowhead head;
  74647. head.startWidth = arrowheadStartWidth;
  74648. head.startLength = arrowheadStartLength;
  74649. head.endWidth = arrowheadEndWidth;
  74650. head.endLength = arrowheadEndLength;
  74651. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  74652. destPath, sourcePath, transform, extraAccuracy, &head);
  74653. }
  74654. END_JUCE_NAMESPACE
  74655. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  74656. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  74657. BEGIN_JUCE_NAMESPACE
  74658. PositionedRectangle::PositionedRectangle() throw()
  74659. : x (0.0),
  74660. y (0.0),
  74661. w (0.0),
  74662. h (0.0),
  74663. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74664. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74665. wMode (absoluteSize),
  74666. hMode (absoluteSize)
  74667. {
  74668. }
  74669. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  74670. : x (other.x),
  74671. y (other.y),
  74672. w (other.w),
  74673. h (other.h),
  74674. xMode (other.xMode),
  74675. yMode (other.yMode),
  74676. wMode (other.wMode),
  74677. hMode (other.hMode)
  74678. {
  74679. }
  74680. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  74681. {
  74682. x = other.x;
  74683. y = other.y;
  74684. w = other.w;
  74685. h = other.h;
  74686. xMode = other.xMode;
  74687. yMode = other.yMode;
  74688. wMode = other.wMode;
  74689. hMode = other.hMode;
  74690. return *this;
  74691. }
  74692. PositionedRectangle::~PositionedRectangle() throw()
  74693. {
  74694. }
  74695. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  74696. {
  74697. return x == other.x
  74698. && y == other.y
  74699. && w == other.w
  74700. && h == other.h
  74701. && xMode == other.xMode
  74702. && yMode == other.yMode
  74703. && wMode == other.wMode
  74704. && hMode == other.hMode;
  74705. }
  74706. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  74707. {
  74708. return ! operator== (other);
  74709. }
  74710. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  74711. {
  74712. StringArray tokens;
  74713. tokens.addTokens (stringVersion, false);
  74714. decodePosString (tokens [0], xMode, x);
  74715. decodePosString (tokens [1], yMode, y);
  74716. decodeSizeString (tokens [2], wMode, w);
  74717. decodeSizeString (tokens [3], hMode, h);
  74718. }
  74719. const String PositionedRectangle::toString() const throw()
  74720. {
  74721. String s;
  74722. s.preallocateStorage (12);
  74723. addPosDescription (s, xMode, x);
  74724. s << ' ';
  74725. addPosDescription (s, yMode, y);
  74726. s << ' ';
  74727. addSizeDescription (s, wMode, w);
  74728. s << ' ';
  74729. addSizeDescription (s, hMode, h);
  74730. return s;
  74731. }
  74732. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  74733. {
  74734. jassert (! target.isEmpty());
  74735. double x_, y_, w_, h_;
  74736. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74737. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74738. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  74739. roundToInt (w_), roundToInt (h_));
  74740. }
  74741. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  74742. double& x_, double& y_,
  74743. double& w_, double& h_) const throw()
  74744. {
  74745. jassert (! target.isEmpty());
  74746. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74747. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74748. }
  74749. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  74750. {
  74751. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  74752. }
  74753. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  74754. const Rectangle<int>& target) throw()
  74755. {
  74756. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  74757. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  74758. }
  74759. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  74760. const double newW, const double newH,
  74761. const Rectangle<int>& target) throw()
  74762. {
  74763. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  74764. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  74765. }
  74766. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  74767. {
  74768. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  74769. updateFrom (comp.getBounds(), Rectangle<int>());
  74770. else
  74771. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  74772. }
  74773. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  74774. {
  74775. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74776. }
  74777. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  74778. {
  74779. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  74780. | absoluteFromParentBottomRight
  74781. | absoluteFromParentCentre
  74782. | proportionOfParentSize));
  74783. }
  74784. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  74785. {
  74786. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74787. }
  74788. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  74789. {
  74790. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  74791. | absoluteFromParentBottomRight
  74792. | absoluteFromParentCentre
  74793. | proportionOfParentSize));
  74794. }
  74795. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  74796. {
  74797. return (SizeMode) wMode;
  74798. }
  74799. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  74800. {
  74801. return (SizeMode) hMode;
  74802. }
  74803. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  74804. const PositionMode xMode_,
  74805. const AnchorPoint yAnchor,
  74806. const PositionMode yMode_,
  74807. const SizeMode widthMode,
  74808. const SizeMode heightMode,
  74809. const Rectangle<int>& target) throw()
  74810. {
  74811. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  74812. {
  74813. double tx, tw;
  74814. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  74815. xMode = (uint8) (xAnchor | xMode_);
  74816. wMode = (uint8) widthMode;
  74817. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  74818. }
  74819. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  74820. {
  74821. double ty, th;
  74822. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  74823. yMode = (uint8) (yAnchor | yMode_);
  74824. hMode = (uint8) heightMode;
  74825. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  74826. }
  74827. }
  74828. bool PositionedRectangle::isPositionAbsolute() const throw()
  74829. {
  74830. return xMode == absoluteFromParentTopLeft
  74831. && yMode == absoluteFromParentTopLeft
  74832. && wMode == absoluteSize
  74833. && hMode == absoluteSize;
  74834. }
  74835. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  74836. {
  74837. if ((mode & proportionOfParentSize) != 0)
  74838. {
  74839. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74840. }
  74841. else
  74842. {
  74843. s << (roundToInt (value * 100.0) / 100.0);
  74844. if ((mode & absoluteFromParentBottomRight) != 0)
  74845. s << 'R';
  74846. else if ((mode & absoluteFromParentCentre) != 0)
  74847. s << 'C';
  74848. }
  74849. if ((mode & anchorAtRightOrBottom) != 0)
  74850. s << 'r';
  74851. else if ((mode & anchorAtCentre) != 0)
  74852. s << 'c';
  74853. }
  74854. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  74855. {
  74856. if (mode == proportionalSize)
  74857. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74858. else if (mode == parentSizeMinusAbsolute)
  74859. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  74860. else
  74861. s << (roundToInt (value * 100.0) / 100.0);
  74862. }
  74863. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  74864. {
  74865. if (s.containsChar ('r'))
  74866. mode = anchorAtRightOrBottom;
  74867. else if (s.containsChar ('c'))
  74868. mode = anchorAtCentre;
  74869. else
  74870. mode = anchorAtLeftOrTop;
  74871. if (s.containsChar ('%'))
  74872. {
  74873. mode |= proportionOfParentSize;
  74874. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  74875. }
  74876. else
  74877. {
  74878. if (s.containsChar ('R'))
  74879. mode |= absoluteFromParentBottomRight;
  74880. else if (s.containsChar ('C'))
  74881. mode |= absoluteFromParentCentre;
  74882. else
  74883. mode |= absoluteFromParentTopLeft;
  74884. value = s.removeCharacters ("rcRC").getDoubleValue();
  74885. }
  74886. }
  74887. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  74888. {
  74889. if (s.containsChar ('%'))
  74890. {
  74891. mode = proportionalSize;
  74892. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  74893. }
  74894. else if (s.containsChar ('M'))
  74895. {
  74896. mode = parentSizeMinusAbsolute;
  74897. value = s.getDoubleValue();
  74898. }
  74899. else
  74900. {
  74901. mode = absoluteSize;
  74902. value = s.getDoubleValue();
  74903. }
  74904. }
  74905. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  74906. const double x_, const double w_,
  74907. const uint8 xMode_, const uint8 wMode_,
  74908. const int parentPos,
  74909. const int parentSize) const throw()
  74910. {
  74911. if (wMode_ == proportionalSize)
  74912. wOut = roundToInt (w_ * parentSize);
  74913. else if (wMode_ == parentSizeMinusAbsolute)
  74914. wOut = jmax (0, parentSize - roundToInt (w_));
  74915. else
  74916. wOut = roundToInt (w_);
  74917. if ((xMode_ & proportionOfParentSize) != 0)
  74918. xOut = parentPos + x_ * parentSize;
  74919. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74920. xOut = (parentPos + parentSize) - x_;
  74921. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74922. xOut = x_ + (parentPos + parentSize / 2);
  74923. else
  74924. xOut = x_ + parentPos;
  74925. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74926. xOut -= wOut;
  74927. else if ((xMode_ & anchorAtCentre) != 0)
  74928. xOut -= wOut / 2;
  74929. }
  74930. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  74931. double x_, const double w_,
  74932. const uint8 xMode_, const uint8 wMode_,
  74933. const int parentPos,
  74934. const int parentSize) const throw()
  74935. {
  74936. if (wMode_ == proportionalSize)
  74937. {
  74938. if (parentSize > 0)
  74939. wOut = w_ / parentSize;
  74940. }
  74941. else if (wMode_ == parentSizeMinusAbsolute)
  74942. wOut = parentSize - w_;
  74943. else
  74944. wOut = w_;
  74945. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74946. x_ += w_;
  74947. else if ((xMode_ & anchorAtCentre) != 0)
  74948. x_ += w_ / 2;
  74949. if ((xMode_ & proportionOfParentSize) != 0)
  74950. {
  74951. if (parentSize > 0)
  74952. xOut = (x_ - parentPos) / parentSize;
  74953. }
  74954. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74955. xOut = (parentPos + parentSize) - x_;
  74956. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74957. xOut = x_ - (parentPos + parentSize / 2);
  74958. else
  74959. xOut = x_ - parentPos;
  74960. }
  74961. END_JUCE_NAMESPACE
  74962. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  74963. /*** Start of inlined file: juce_RectangleList.cpp ***/
  74964. BEGIN_JUCE_NAMESPACE
  74965. RectangleList::RectangleList() throw()
  74966. {
  74967. }
  74968. RectangleList::RectangleList (const Rectangle<int>& rect)
  74969. {
  74970. if (! rect.isEmpty())
  74971. rects.add (rect);
  74972. }
  74973. RectangleList::RectangleList (const RectangleList& other)
  74974. : rects (other.rects)
  74975. {
  74976. }
  74977. RectangleList& RectangleList::operator= (const RectangleList& other)
  74978. {
  74979. rects = other.rects;
  74980. return *this;
  74981. }
  74982. RectangleList::~RectangleList()
  74983. {
  74984. }
  74985. void RectangleList::clear()
  74986. {
  74987. rects.clearQuick();
  74988. }
  74989. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  74990. {
  74991. if (((unsigned int) index) < (unsigned int) rects.size())
  74992. return rects.getReference (index);
  74993. return Rectangle<int>();
  74994. }
  74995. bool RectangleList::isEmpty() const throw()
  74996. {
  74997. return rects.size() == 0;
  74998. }
  74999. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  75000. : current (0),
  75001. owner (list),
  75002. index (list.rects.size())
  75003. {
  75004. }
  75005. RectangleList::Iterator::~Iterator()
  75006. {
  75007. }
  75008. bool RectangleList::Iterator::next() throw()
  75009. {
  75010. if (--index >= 0)
  75011. {
  75012. current = & (owner.rects.getReference (index));
  75013. return true;
  75014. }
  75015. return false;
  75016. }
  75017. void RectangleList::add (const Rectangle<int>& rect)
  75018. {
  75019. if (! rect.isEmpty())
  75020. {
  75021. if (rects.size() == 0)
  75022. {
  75023. rects.add (rect);
  75024. }
  75025. else
  75026. {
  75027. bool anyOverlaps = false;
  75028. int i;
  75029. for (i = rects.size(); --i >= 0;)
  75030. {
  75031. Rectangle<int>& ourRect = rects.getReference (i);
  75032. if (rect.intersects (ourRect))
  75033. {
  75034. if (rect.contains (ourRect))
  75035. rects.remove (i);
  75036. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  75037. anyOverlaps = true;
  75038. }
  75039. }
  75040. if (anyOverlaps && rects.size() > 0)
  75041. {
  75042. RectangleList r (rect);
  75043. for (i = rects.size(); --i >= 0;)
  75044. {
  75045. const Rectangle<int>& ourRect = rects.getReference (i);
  75046. if (rect.intersects (ourRect))
  75047. {
  75048. r.subtract (ourRect);
  75049. if (r.rects.size() == 0)
  75050. return;
  75051. }
  75052. }
  75053. for (i = r.getNumRectangles(); --i >= 0;)
  75054. rects.add (r.rects.getReference (i));
  75055. }
  75056. else
  75057. {
  75058. rects.add (rect);
  75059. }
  75060. }
  75061. }
  75062. }
  75063. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  75064. {
  75065. if (! rect.isEmpty())
  75066. rects.add (rect);
  75067. }
  75068. void RectangleList::add (const int x, const int y, const int w, const int h)
  75069. {
  75070. if (rects.size() == 0)
  75071. {
  75072. if (w > 0 && h > 0)
  75073. rects.add (Rectangle<int> (x, y, w, h));
  75074. }
  75075. else
  75076. {
  75077. add (Rectangle<int> (x, y, w, h));
  75078. }
  75079. }
  75080. void RectangleList::add (const RectangleList& other)
  75081. {
  75082. for (int i = 0; i < other.rects.size(); ++i)
  75083. add (other.rects.getReference (i));
  75084. }
  75085. void RectangleList::subtract (const Rectangle<int>& rect)
  75086. {
  75087. const int originalNumRects = rects.size();
  75088. if (originalNumRects > 0)
  75089. {
  75090. const int x1 = rect.x;
  75091. const int y1 = rect.y;
  75092. const int x2 = x1 + rect.w;
  75093. const int y2 = y1 + rect.h;
  75094. for (int i = getNumRectangles(); --i >= 0;)
  75095. {
  75096. Rectangle<int>& r = rects.getReference (i);
  75097. const int rx1 = r.x;
  75098. const int ry1 = r.y;
  75099. const int rx2 = rx1 + r.w;
  75100. const int ry2 = ry1 + r.h;
  75101. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  75102. {
  75103. if (x1 > rx1 && x1 < rx2)
  75104. {
  75105. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  75106. {
  75107. r.w = x1 - rx1;
  75108. }
  75109. else
  75110. {
  75111. r.x = x1;
  75112. r.w = rx2 - x1;
  75113. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  75114. i += 2;
  75115. }
  75116. }
  75117. else if (x2 > rx1 && x2 < rx2)
  75118. {
  75119. r.x = x2;
  75120. r.w = rx2 - x2;
  75121. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  75122. {
  75123. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  75124. i += 2;
  75125. }
  75126. }
  75127. else if (y1 > ry1 && y1 < ry2)
  75128. {
  75129. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  75130. {
  75131. r.h = y1 - ry1;
  75132. }
  75133. else
  75134. {
  75135. r.y = y1;
  75136. r.h = ry2 - y1;
  75137. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  75138. i += 2;
  75139. }
  75140. }
  75141. else if (y2 > ry1 && y2 < ry2)
  75142. {
  75143. r.y = y2;
  75144. r.h = ry2 - y2;
  75145. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  75146. {
  75147. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  75148. i += 2;
  75149. }
  75150. }
  75151. else
  75152. {
  75153. rects.remove (i);
  75154. }
  75155. }
  75156. }
  75157. }
  75158. }
  75159. bool RectangleList::subtract (const RectangleList& otherList)
  75160. {
  75161. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  75162. subtract (otherList.rects.getReference (i));
  75163. return rects.size() > 0;
  75164. }
  75165. bool RectangleList::clipTo (const Rectangle<int>& rect)
  75166. {
  75167. bool notEmpty = false;
  75168. if (rect.isEmpty())
  75169. {
  75170. clear();
  75171. }
  75172. else
  75173. {
  75174. for (int i = rects.size(); --i >= 0;)
  75175. {
  75176. Rectangle<int>& r = rects.getReference (i);
  75177. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75178. rects.remove (i);
  75179. else
  75180. notEmpty = true;
  75181. }
  75182. }
  75183. return notEmpty;
  75184. }
  75185. bool RectangleList::clipTo (const RectangleList& other)
  75186. {
  75187. if (rects.size() == 0)
  75188. return false;
  75189. RectangleList result;
  75190. for (int j = 0; j < rects.size(); ++j)
  75191. {
  75192. const Rectangle<int>& rect = rects.getReference (j);
  75193. for (int i = other.rects.size(); --i >= 0;)
  75194. {
  75195. Rectangle<int> r (other.rects.getReference (i));
  75196. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75197. result.rects.add (r);
  75198. }
  75199. }
  75200. swapWith (result);
  75201. return ! isEmpty();
  75202. }
  75203. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  75204. {
  75205. destRegion.clear();
  75206. if (! rect.isEmpty())
  75207. {
  75208. for (int i = rects.size(); --i >= 0;)
  75209. {
  75210. Rectangle<int> r (rects.getReference (i));
  75211. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75212. destRegion.rects.add (r);
  75213. }
  75214. }
  75215. return destRegion.rects.size() > 0;
  75216. }
  75217. void RectangleList::swapWith (RectangleList& otherList) throw()
  75218. {
  75219. rects.swapWithArray (otherList.rects);
  75220. }
  75221. void RectangleList::consolidate()
  75222. {
  75223. int i;
  75224. for (i = 0; i < getNumRectangles() - 1; ++i)
  75225. {
  75226. Rectangle<int>& r = rects.getReference (i);
  75227. const int rx1 = r.x;
  75228. const int ry1 = r.y;
  75229. const int rx2 = rx1 + r.w;
  75230. const int ry2 = ry1 + r.h;
  75231. for (int j = rects.size(); --j > i;)
  75232. {
  75233. Rectangle<int>& r2 = rects.getReference (j);
  75234. const int jrx1 = r2.x;
  75235. const int jry1 = r2.y;
  75236. const int jrx2 = jrx1 + r2.w;
  75237. const int jry2 = jry1 + r2.h;
  75238. // if the vertical edges of any blocks are touching and their horizontals don't
  75239. // line up, split them horizontally..
  75240. if (jrx1 == rx2 || jrx2 == rx1)
  75241. {
  75242. if (jry1 > ry1 && jry1 < ry2)
  75243. {
  75244. r.h = jry1 - ry1;
  75245. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  75246. i = -1;
  75247. break;
  75248. }
  75249. if (jry2 > ry1 && jry2 < ry2)
  75250. {
  75251. r.h = jry2 - ry1;
  75252. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  75253. i = -1;
  75254. break;
  75255. }
  75256. else if (ry1 > jry1 && ry1 < jry2)
  75257. {
  75258. r2.h = ry1 - jry1;
  75259. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  75260. i = -1;
  75261. break;
  75262. }
  75263. else if (ry2 > jry1 && ry2 < jry2)
  75264. {
  75265. r2.h = ry2 - jry1;
  75266. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  75267. i = -1;
  75268. break;
  75269. }
  75270. }
  75271. }
  75272. }
  75273. for (i = 0; i < rects.size() - 1; ++i)
  75274. {
  75275. Rectangle<int>& r = rects.getReference (i);
  75276. for (int j = rects.size(); --j > i;)
  75277. {
  75278. if (r.enlargeIfAdjacent (rects.getReference (j)))
  75279. {
  75280. rects.remove (j);
  75281. i = -1;
  75282. break;
  75283. }
  75284. }
  75285. }
  75286. }
  75287. bool RectangleList::containsPoint (const int x, const int y) const throw()
  75288. {
  75289. for (int i = getNumRectangles(); --i >= 0;)
  75290. if (rects.getReference (i).contains (x, y))
  75291. return true;
  75292. return false;
  75293. }
  75294. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  75295. {
  75296. if (rects.size() > 1)
  75297. {
  75298. RectangleList r (rectangleToCheck);
  75299. for (int i = rects.size(); --i >= 0;)
  75300. {
  75301. r.subtract (rects.getReference (i));
  75302. if (r.rects.size() == 0)
  75303. return true;
  75304. }
  75305. }
  75306. else if (rects.size() > 0)
  75307. {
  75308. return rects.getReference (0).contains (rectangleToCheck);
  75309. }
  75310. return false;
  75311. }
  75312. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  75313. {
  75314. for (int i = rects.size(); --i >= 0;)
  75315. if (rects.getReference (i).intersects (rectangleToCheck))
  75316. return true;
  75317. return false;
  75318. }
  75319. bool RectangleList::intersects (const RectangleList& other) const throw()
  75320. {
  75321. for (int i = rects.size(); --i >= 0;)
  75322. if (other.intersectsRectangle (rects.getReference (i)))
  75323. return true;
  75324. return false;
  75325. }
  75326. const Rectangle<int> RectangleList::getBounds() const throw()
  75327. {
  75328. if (rects.size() <= 1)
  75329. {
  75330. if (rects.size() == 0)
  75331. return Rectangle<int>();
  75332. else
  75333. return rects.getReference (0);
  75334. }
  75335. else
  75336. {
  75337. const Rectangle<int>& r = rects.getReference (0);
  75338. int minX = r.x;
  75339. int minY = r.y;
  75340. int maxX = minX + r.w;
  75341. int maxY = minY + r.h;
  75342. for (int i = rects.size(); --i > 0;)
  75343. {
  75344. const Rectangle<int>& r2 = rects.getReference (i);
  75345. minX = jmin (minX, r2.x);
  75346. minY = jmin (minY, r2.y);
  75347. maxX = jmax (maxX, r2.getRight());
  75348. maxY = jmax (maxY, r2.getBottom());
  75349. }
  75350. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  75351. }
  75352. }
  75353. void RectangleList::offsetAll (const int dx, const int dy) throw()
  75354. {
  75355. for (int i = rects.size(); --i >= 0;)
  75356. {
  75357. Rectangle<int>& r = rects.getReference (i);
  75358. r.x += dx;
  75359. r.y += dy;
  75360. }
  75361. }
  75362. const Path RectangleList::toPath() const
  75363. {
  75364. Path p;
  75365. for (int i = rects.size(); --i >= 0;)
  75366. {
  75367. const Rectangle<int>& r = rects.getReference (i);
  75368. p.addRectangle ((float) r.x,
  75369. (float) r.y,
  75370. (float) r.w,
  75371. (float) r.h);
  75372. }
  75373. return p;
  75374. }
  75375. END_JUCE_NAMESPACE
  75376. /*** End of inlined file: juce_RectangleList.cpp ***/
  75377. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  75378. BEGIN_JUCE_NAMESPACE
  75379. namespace RelativeCoordinateHelpers
  75380. {
  75381. static bool isOrigin (const String& name)
  75382. {
  75383. return name.isEmpty()
  75384. || name == RelativeCoordinate::Strings::parentLeft
  75385. || name == RelativeCoordinate::Strings::parentTop;
  75386. }
  75387. static const String getExtentAnchorName (const bool isHorizontal) throw()
  75388. {
  75389. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  75390. : RelativeCoordinate::Strings::parentBottom;
  75391. }
  75392. static const String getObjectName (const String& fullName)
  75393. {
  75394. return fullName.upToFirstOccurrenceOf (".", false, false);
  75395. }
  75396. static const String getEdgeName (const String& fullName)
  75397. {
  75398. return fullName.fromFirstOccurrenceOf (".", false, false);
  75399. }
  75400. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75401. {
  75402. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  75403. : RelativeCoordinate();
  75404. }
  75405. struct RecursionException : public std::runtime_error
  75406. {
  75407. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  75408. {
  75409. }
  75410. };
  75411. static void skipWhitespace (const juce_wchar* const s, int& i)
  75412. {
  75413. while (CharacterFunctions::isWhitespace (s[i]))
  75414. ++i;
  75415. }
  75416. static void skipComma (const juce_wchar* const s, int& i)
  75417. {
  75418. skipWhitespace (s, i);
  75419. if (s[i] == ',')
  75420. ++i;
  75421. }
  75422. static const String readAnchorName (const juce_wchar* const s, int& i)
  75423. {
  75424. skipWhitespace (s, i);
  75425. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  75426. {
  75427. int start = i;
  75428. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  75429. ++i;
  75430. return String (s + start, i - start);
  75431. }
  75432. return String::empty;
  75433. }
  75434. static double readNumber (const juce_wchar* const s, int& i)
  75435. {
  75436. skipWhitespace (s, i);
  75437. int start = i;
  75438. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  75439. ++i;
  75440. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  75441. ++i;
  75442. if ((s[i] == 'e' || s[i] == 'E')
  75443. && (CharacterFunctions::isDigit (s[i + 1])
  75444. || s[i + 1] == '-'
  75445. || s[i + 1] == '+'))
  75446. {
  75447. i += 2;
  75448. while (CharacterFunctions::isDigit (s[i]))
  75449. ++i;
  75450. }
  75451. const double value = String (s + start, i - start).getDoubleValue();
  75452. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  75453. ++i;
  75454. return value;
  75455. }
  75456. static const RelativeCoordinate readNextCoordinate (const juce_wchar* const s, int& i, const bool isHorizontal)
  75457. {
  75458. String anchor1 (readAnchorName (s, i));
  75459. double value = 0;
  75460. if (anchor1.isNotEmpty())
  75461. {
  75462. skipWhitespace (s, i);
  75463. if (s[i] == '+')
  75464. value = readNumber (s, ++i);
  75465. else if (s[i] == '-')
  75466. value = -readNumber (s, ++i);
  75467. return RelativeCoordinate (value, anchor1);
  75468. }
  75469. else
  75470. {
  75471. value = readNumber (s, i);
  75472. skipWhitespace (s, i);
  75473. if (s[i] == '%')
  75474. {
  75475. value /= 100.0;
  75476. skipWhitespace (s, ++i);
  75477. String anchor2;
  75478. if (s[i] == '*')
  75479. {
  75480. anchor1 = readAnchorName (s, ++i);
  75481. skipWhitespace (s, i);
  75482. if (s[i] == '-' && s[i + 1] == '>')
  75483. {
  75484. i += 2;
  75485. anchor2 = readAnchorName (s, i);
  75486. }
  75487. else
  75488. {
  75489. anchor2 = anchor1;
  75490. anchor1 = String::empty;
  75491. }
  75492. }
  75493. else
  75494. {
  75495. anchor1 = String::empty;
  75496. anchor2 = getExtentAnchorName (isHorizontal);
  75497. }
  75498. return RelativeCoordinate (value, anchor1, anchor2);
  75499. }
  75500. return RelativeCoordinate (value);
  75501. }
  75502. }
  75503. static const String limitedAccuracyString (const double n)
  75504. {
  75505. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  75506. return "0";
  75507. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  75508. }
  75509. }
  75510. const String RelativeCoordinate::Strings::parent ("parent");
  75511. const String RelativeCoordinate::Strings::left ("left");
  75512. const String RelativeCoordinate::Strings::right ("right");
  75513. const String RelativeCoordinate::Strings::top ("top");
  75514. const String RelativeCoordinate::Strings::bottom ("bottom");
  75515. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  75516. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  75517. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  75518. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  75519. RelativeCoordinate::RelativeCoordinate()
  75520. : value (0)
  75521. {
  75522. }
  75523. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  75524. : value (absoluteDistanceFromOrigin)
  75525. {
  75526. }
  75527. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  75528. : anchor1 (source.trim()),
  75529. value (absoluteDistance)
  75530. {
  75531. }
  75532. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  75533. : anchor1 (pos1.trim()),
  75534. anchor2 (pos2.trim()),
  75535. value (relativeProportion)
  75536. {
  75537. }
  75538. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  75539. : value (0)
  75540. {
  75541. int i = 0;
  75542. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  75543. }
  75544. RelativeCoordinate::~RelativeCoordinate()
  75545. {
  75546. }
  75547. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  75548. {
  75549. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  75550. }
  75551. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  75552. {
  75553. return ! operator== (other);
  75554. }
  75555. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  75556. {
  75557. return RelativeCoordinate (0.0, anchor1);
  75558. }
  75559. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  75560. {
  75561. return RelativeCoordinate (0.0, anchor2);
  75562. }
  75563. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  75564. {
  75565. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  75566. return 0.0;
  75567. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  75568. }
  75569. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  75570. {
  75571. if (recursionCounter > 150)
  75572. {
  75573. jassertfalse
  75574. throw RelativeCoordinateHelpers::RecursionException();
  75575. }
  75576. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  75577. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  75578. : pos1 + value;
  75579. }
  75580. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  75581. {
  75582. try
  75583. {
  75584. return resolve (nameFinder, 0);
  75585. }
  75586. catch (RelativeCoordinateHelpers::RecursionException&)
  75587. {}
  75588. return 0.0;
  75589. }
  75590. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  75591. {
  75592. try
  75593. {
  75594. (void) resolve (nameFinder, 0);
  75595. }
  75596. catch (RelativeCoordinateHelpers::RecursionException&)
  75597. {
  75598. return true;
  75599. }
  75600. return false;
  75601. }
  75602. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  75603. {
  75604. try
  75605. {
  75606. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  75607. if (isProportional())
  75608. {
  75609. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  75610. if (size != 0)
  75611. value = (newPos - pos1) / size;
  75612. }
  75613. else
  75614. {
  75615. value = newPos - pos1;
  75616. }
  75617. }
  75618. catch (RelativeCoordinateHelpers::RecursionException&)
  75619. {}
  75620. }
  75621. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder,
  75622. const String& proportionalAnchor1, const String& proportionalAnchor2)
  75623. {
  75624. const double oldValue = resolve (nameFinder);
  75625. anchor1 = proportionalAnchor1;
  75626. anchor2 = isProportional() ? String::empty : proportionalAnchor2;
  75627. moveToAbsolute (oldValue, nameFinder);
  75628. }
  75629. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  75630. {
  75631. using namespace RelativeCoordinateHelpers;
  75632. if (isOrigin (anchor1) && ! isProportional())
  75633. return isOrigin (coordName);
  75634. return anchor1 == coordName
  75635. || anchor2 == coordName
  75636. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  75637. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  75638. }
  75639. bool RelativeCoordinate::isDynamic() const
  75640. {
  75641. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  75642. }
  75643. const String RelativeCoordinate::toString() const
  75644. {
  75645. using namespace RelativeCoordinateHelpers;
  75646. if (isProportional())
  75647. {
  75648. const String percent (limitedAccuracyString (value * 100.0));
  75649. if (isOrigin (anchor1))
  75650. {
  75651. if (anchor2 == Strings::parentRight || anchor2 == Strings::parentBottom)
  75652. return percent + "%";
  75653. else
  75654. return percent + "% * " + anchor2;
  75655. }
  75656. else
  75657. return percent + "% * " + anchor1 + " -> " + anchor2;
  75658. }
  75659. else
  75660. {
  75661. if (isOrigin (anchor1))
  75662. return limitedAccuracyString (value);
  75663. else if (value > 0)
  75664. return anchor1 + " + " + limitedAccuracyString (value);
  75665. else if (value < 0)
  75666. return anchor1 + " - " + limitedAccuracyString (-value);
  75667. else
  75668. return anchor1;
  75669. }
  75670. }
  75671. const double RelativeCoordinate::getEditableNumber() const
  75672. {
  75673. return isProportional() ? value * 100.0 : value;
  75674. }
  75675. void RelativeCoordinate::setEditableNumber (const double newValue)
  75676. {
  75677. value = isProportional() ? newValue / 100.0 : newValue;
  75678. }
  75679. const String RelativeCoordinate::getAnchorName1 (const String& returnValueIfOrigin) const
  75680. {
  75681. return RelativeCoordinateHelpers::isOrigin (anchor1) ? returnValueIfOrigin : anchor1;
  75682. }
  75683. const String RelativeCoordinate::getAnchorName2 (const String& returnValueIfOrigin) const
  75684. {
  75685. return RelativeCoordinateHelpers::isOrigin (anchor2) ? returnValueIfOrigin : anchor2;
  75686. }
  75687. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75688. {
  75689. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75690. const double oldValue = resolve (nameFinder);
  75691. anchor1 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  75692. moveToAbsolute (oldValue, nameFinder);
  75693. }
  75694. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75695. {
  75696. jassert (isProportional());
  75697. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75698. const double oldValue = resolve (nameFinder);
  75699. anchor2 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  75700. moveToAbsolute (oldValue, nameFinder);
  75701. }
  75702. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  75703. {
  75704. using namespace RelativeCoordinateHelpers;
  75705. jassert (oldName.isNotEmpty());
  75706. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  75707. if (newName.isEmpty())
  75708. {
  75709. if (getObjectName (anchor1) == oldName
  75710. || getObjectName (anchor2) == oldName)
  75711. {
  75712. value = resolve (nameFinder);
  75713. anchor1 = String::empty;
  75714. anchor2 = String::empty;
  75715. }
  75716. }
  75717. else
  75718. {
  75719. if (getObjectName (anchor1) == oldName)
  75720. anchor1 = newName + "." + getEdgeName (anchor1);
  75721. if (getObjectName (anchor2) == oldName)
  75722. anchor2 = newName + "." + getEdgeName (anchor2);
  75723. }
  75724. }
  75725. RelativePoint::RelativePoint()
  75726. {
  75727. }
  75728. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  75729. : x (absolutePoint.getX()), y (absolutePoint.getY())
  75730. {
  75731. }
  75732. RelativePoint::RelativePoint (const float x_, const float y_)
  75733. : x (x_), y (y_)
  75734. {
  75735. }
  75736. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  75737. : x (x_), y (y_)
  75738. {
  75739. }
  75740. RelativePoint::RelativePoint (const String& s)
  75741. {
  75742. int i = 0;
  75743. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75744. RelativeCoordinateHelpers::skipComma (s, i);
  75745. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75746. }
  75747. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  75748. {
  75749. return x == other.x && y == other.y;
  75750. }
  75751. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  75752. {
  75753. return ! operator== (other);
  75754. }
  75755. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75756. {
  75757. return Point<float> ((float) x.resolve (nameFinder),
  75758. (float) y.resolve (nameFinder));
  75759. }
  75760. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75761. {
  75762. x.moveToAbsolute (newPos.getX(), nameFinder);
  75763. y.moveToAbsolute (newPos.getY(), nameFinder);
  75764. }
  75765. const String RelativePoint::toString() const
  75766. {
  75767. return x.toString() + ", " + y.toString();
  75768. }
  75769. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75770. {
  75771. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  75772. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  75773. }
  75774. bool RelativePoint::isDynamic() const
  75775. {
  75776. return x.isDynamic() || y.isDynamic();
  75777. }
  75778. RelativeRectangle::RelativeRectangle()
  75779. {
  75780. }
  75781. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  75782. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  75783. : left (left_), right (right_), top (top_), bottom (bottom_)
  75784. {
  75785. }
  75786. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  75787. : left (rect.getX()),
  75788. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  75789. top (rect.getY()),
  75790. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  75791. {
  75792. }
  75793. RelativeRectangle::RelativeRectangle (const String& s)
  75794. {
  75795. int i = 0;
  75796. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75797. RelativeCoordinateHelpers::skipComma (s, i);
  75798. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75799. RelativeCoordinateHelpers::skipComma (s, i);
  75800. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75801. RelativeCoordinateHelpers::skipComma (s, i);
  75802. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75803. }
  75804. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  75805. {
  75806. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  75807. }
  75808. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  75809. {
  75810. return ! operator== (other);
  75811. }
  75812. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75813. {
  75814. const double l = left.resolve (nameFinder);
  75815. const double r = right.resolve (nameFinder);
  75816. const double t = top.resolve (nameFinder);
  75817. const double b = bottom.resolve (nameFinder);
  75818. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  75819. }
  75820. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75821. {
  75822. left.moveToAbsolute (newPos.getX(), nameFinder);
  75823. right.moveToAbsolute (newPos.getRight(), nameFinder);
  75824. top.moveToAbsolute (newPos.getY(), nameFinder);
  75825. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  75826. }
  75827. const String RelativeRectangle::toString() const
  75828. {
  75829. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  75830. }
  75831. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  75832. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75833. {
  75834. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  75835. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  75836. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  75837. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  75838. }
  75839. RelativePointPath::RelativePointPath()
  75840. : usesNonZeroWinding (true),
  75841. containsDynamicPoints (false)
  75842. {
  75843. }
  75844. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  75845. : usesNonZeroWinding (true),
  75846. containsDynamicPoints (false)
  75847. {
  75848. ValueTree state (DrawablePath::valueTreeType);
  75849. other.writeTo (state, 0);
  75850. parse (state);
  75851. }
  75852. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  75853. : usesNonZeroWinding (true),
  75854. containsDynamicPoints (false)
  75855. {
  75856. parse (drawable);
  75857. }
  75858. RelativePointPath::RelativePointPath (const Path& path)
  75859. {
  75860. usesNonZeroWinding = path.isUsingNonZeroWinding();
  75861. Path::Iterator i (path);
  75862. while (i.next())
  75863. {
  75864. switch (i.elementType)
  75865. {
  75866. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  75867. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  75868. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  75869. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  75870. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  75871. default: jassertfalse; break;
  75872. }
  75873. }
  75874. }
  75875. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  75876. {
  75877. DrawablePath::ValueTreeWrapper wrapper (state);
  75878. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  75879. ValueTree pathTree (wrapper.getPathState());
  75880. pathTree.removeAllChildren (undoManager);
  75881. for (int i = 0; i < elements.size(); ++i)
  75882. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  75883. }
  75884. void RelativePointPath::parse (const ValueTree& state)
  75885. {
  75886. DrawablePath::ValueTreeWrapper wrapper (state);
  75887. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  75888. RelativePoint points[3];
  75889. const ValueTree pathTree (wrapper.getPathState());
  75890. const int num = pathTree.getNumChildren();
  75891. for (int i = 0; i < num; ++i)
  75892. {
  75893. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  75894. const int numCps = e.getNumControlPoints();
  75895. for (int j = 0; j < numCps; ++j)
  75896. {
  75897. points[j] = e.getControlPoint (j);
  75898. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  75899. }
  75900. const Identifier type (e.getType());
  75901. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  75902. elements.add (new StartSubPath (points[0]));
  75903. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  75904. elements.add (new CloseSubPath());
  75905. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  75906. elements.add (new LineTo (points[0]));
  75907. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  75908. elements.add (new QuadraticTo (points[0], points[1]));
  75909. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  75910. elements.add (new CubicTo (points[0], points[1], points[2]));
  75911. else
  75912. jassertfalse;
  75913. }
  75914. }
  75915. RelativePointPath::~RelativePointPath()
  75916. {
  75917. }
  75918. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  75919. {
  75920. elements.swapWithArray (other.elements);
  75921. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  75922. }
  75923. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  75924. {
  75925. for (int i = 0; i < elements.size(); ++i)
  75926. elements.getUnchecked(i)->addToPath (path, coordFinder);
  75927. }
  75928. bool RelativePointPath::containsAnyDynamicPoints() const
  75929. {
  75930. return containsDynamicPoints;
  75931. }
  75932. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  75933. {
  75934. }
  75935. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  75936. : ElementBase (startSubPathElement), startPos (pos)
  75937. {
  75938. }
  75939. const ValueTree RelativePointPath::StartSubPath::createTree() const
  75940. {
  75941. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  75942. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  75943. return v;
  75944. }
  75945. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75946. {
  75947. path.startNewSubPath (startPos.resolve (coordFinder));
  75948. }
  75949. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  75950. {
  75951. numPoints = 1;
  75952. return &startPos;
  75953. }
  75954. RelativePointPath::CloseSubPath::CloseSubPath()
  75955. : ElementBase (closeSubPathElement)
  75956. {
  75957. }
  75958. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  75959. {
  75960. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  75961. }
  75962. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  75963. {
  75964. path.closeSubPath();
  75965. }
  75966. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  75967. {
  75968. numPoints = 0;
  75969. return 0;
  75970. }
  75971. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  75972. : ElementBase (lineToElement), endPoint (endPoint_)
  75973. {
  75974. }
  75975. const ValueTree RelativePointPath::LineTo::createTree() const
  75976. {
  75977. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  75978. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  75979. return v;
  75980. }
  75981. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75982. {
  75983. path.lineTo (endPoint.resolve (coordFinder));
  75984. }
  75985. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  75986. {
  75987. numPoints = 1;
  75988. return &endPoint;
  75989. }
  75990. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  75991. : ElementBase (quadraticToElement)
  75992. {
  75993. controlPoints[0] = controlPoint;
  75994. controlPoints[1] = endPoint;
  75995. }
  75996. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  75997. {
  75998. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  75999. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  76000. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  76001. return v;
  76002. }
  76003. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  76004. {
  76005. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  76006. controlPoints[1].resolve (coordFinder));
  76007. }
  76008. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  76009. {
  76010. numPoints = 2;
  76011. return controlPoints;
  76012. }
  76013. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  76014. : ElementBase (cubicToElement)
  76015. {
  76016. controlPoints[0] = controlPoint1;
  76017. controlPoints[1] = controlPoint2;
  76018. controlPoints[2] = endPoint;
  76019. }
  76020. const ValueTree RelativePointPath::CubicTo::createTree() const
  76021. {
  76022. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  76023. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  76024. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  76025. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  76026. return v;
  76027. }
  76028. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  76029. {
  76030. path.cubicTo (controlPoints[0].resolve (coordFinder),
  76031. controlPoints[1].resolve (coordFinder),
  76032. controlPoints[2].resolve (coordFinder));
  76033. }
  76034. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  76035. {
  76036. numPoints = 3;
  76037. return controlPoints;
  76038. }
  76039. RelativeParallelogram::RelativeParallelogram()
  76040. {
  76041. }
  76042. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  76043. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  76044. {
  76045. }
  76046. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  76047. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  76048. {
  76049. }
  76050. RelativeParallelogram::~RelativeParallelogram()
  76051. {
  76052. }
  76053. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  76054. {
  76055. points[0] = topLeft.resolve (coordFinder);
  76056. points[1] = topRight.resolve (coordFinder);
  76057. points[2] = bottomLeft.resolve (coordFinder);
  76058. }
  76059. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  76060. {
  76061. resolveThreePoints (points, coordFinder);
  76062. points[3] = points[1] + (points[2] - points[0]);
  76063. }
  76064. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  76065. {
  76066. Point<float> points[4];
  76067. resolveFourCorners (points, coordFinder);
  76068. return Rectangle<float>::findAreaContainingPoints (points, 4);
  76069. }
  76070. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  76071. {
  76072. Point<float> points[4];
  76073. resolveFourCorners (points, coordFinder);
  76074. path.startNewSubPath (points[0]);
  76075. path.lineTo (points[1]);
  76076. path.lineTo (points[3]);
  76077. path.lineTo (points[2]);
  76078. path.closeSubPath();
  76079. }
  76080. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  76081. {
  76082. Point<float> corners[3];
  76083. resolveThreePoints (corners, coordFinder);
  76084. const Line<float> top (corners[0], corners[1]);
  76085. const Line<float> left (corners[0], corners[2]);
  76086. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  76087. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  76088. topRight.moveToAbsolute (newTopRight, coordFinder);
  76089. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  76090. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  76091. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  76092. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  76093. }
  76094. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  76095. {
  76096. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  76097. }
  76098. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  76099. {
  76100. return ! operator== (other);
  76101. }
  76102. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  76103. {
  76104. const Point<float> tr (corners[1] - corners[0]);
  76105. const Point<float> bl (corners[2] - corners[0]);
  76106. target -= corners[0];
  76107. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  76108. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  76109. }
  76110. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  76111. {
  76112. return corners[0]
  76113. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  76114. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  76115. }
  76116. END_JUCE_NAMESPACE
  76117. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  76118. /*** Start of inlined file: juce_Image.cpp ***/
  76119. BEGIN_JUCE_NAMESPACE
  76120. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76121. : format (format_), width (width_), height (height_)
  76122. {
  76123. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76124. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76125. }
  76126. Image::SharedImage::~SharedImage()
  76127. {
  76128. }
  76129. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76130. {
  76131. return imageData + lineStride * y + pixelStride * x;
  76132. }
  76133. class SoftwareSharedImage : public Image::SharedImage
  76134. {
  76135. public:
  76136. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76137. : Image::SharedImage (format_, width_, height_)
  76138. {
  76139. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76140. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76141. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76142. imageData = imageDataAllocated;
  76143. }
  76144. ~SoftwareSharedImage()
  76145. {
  76146. }
  76147. Image::ImageType getType() const
  76148. {
  76149. return Image::SoftwareImage;
  76150. }
  76151. LowLevelGraphicsContext* createLowLevelContext()
  76152. {
  76153. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76154. }
  76155. SharedImage* clone()
  76156. {
  76157. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76158. memcpy (s->imageData, imageData, lineStride * height);
  76159. return s;
  76160. }
  76161. private:
  76162. HeapBlock<uint8> imageDataAllocated;
  76163. };
  76164. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76165. {
  76166. return new SoftwareSharedImage (format, width, height, clearImage);
  76167. }
  76168. Image::Image()
  76169. {
  76170. }
  76171. Image::Image (SharedImage* const instance)
  76172. : image (instance)
  76173. {
  76174. }
  76175. Image::Image (const PixelFormat format,
  76176. const int width, const int height,
  76177. const bool clearImage, const ImageType type)
  76178. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76179. : new SoftwareSharedImage (format, width, height, clearImage))
  76180. {
  76181. }
  76182. Image::Image (const Image& other)
  76183. : image (other.image)
  76184. {
  76185. }
  76186. Image& Image::operator= (const Image& other)
  76187. {
  76188. image = other.image;
  76189. return *this;
  76190. }
  76191. Image::~Image()
  76192. {
  76193. }
  76194. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76195. {
  76196. return image == 0 ? 0 : image->createLowLevelContext();
  76197. }
  76198. void Image::duplicateIfShared()
  76199. {
  76200. if (image != 0 && image->getReferenceCount() > 1)
  76201. image = image->clone();
  76202. }
  76203. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76204. {
  76205. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76206. return *this;
  76207. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76208. Graphics g (newImage);
  76209. g.setImageResamplingQuality (quality);
  76210. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76211. return newImage;
  76212. }
  76213. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76214. {
  76215. if (image == 0 || newFormat == image->format)
  76216. return *this;
  76217. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76218. if (newFormat == SingleChannel)
  76219. {
  76220. if (! hasAlphaChannel())
  76221. {
  76222. newImage.clear (getBounds(), Colours::black);
  76223. }
  76224. else
  76225. {
  76226. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76227. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76228. for (int y = 0; y < image->height; ++y)
  76229. {
  76230. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76231. uint8* dst = destData.getLinePointer (y);
  76232. for (int x = image->width; --x >= 0;)
  76233. {
  76234. *dst++ = src->getAlpha();
  76235. ++src;
  76236. }
  76237. }
  76238. }
  76239. }
  76240. else
  76241. {
  76242. if (hasAlphaChannel())
  76243. newImage.clear (getBounds());
  76244. Graphics g (newImage);
  76245. g.drawImageAt (*this, 0, 0);
  76246. }
  76247. return newImage;
  76248. }
  76249. const var Image::getTag() const
  76250. {
  76251. return image == 0 ? var::null : image->userTag;
  76252. }
  76253. void Image::setTag (const var& newTag)
  76254. {
  76255. if (image != 0)
  76256. image->userTag = newTag;
  76257. }
  76258. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76259. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76260. pixelFormat (image.getFormat()),
  76261. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76262. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76263. width (w),
  76264. height (h)
  76265. {
  76266. jassert (data != 0);
  76267. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76268. }
  76269. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76270. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76271. pixelFormat (image.getFormat()),
  76272. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76273. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76274. width (w),
  76275. height (h)
  76276. {
  76277. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76278. }
  76279. Image::BitmapData::~BitmapData()
  76280. {
  76281. }
  76282. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76283. {
  76284. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76285. const uint8* const pixel = getPixelPointer (x, y);
  76286. switch (pixelFormat)
  76287. {
  76288. case Image::ARGB:
  76289. {
  76290. PixelARGB p (*(const PixelARGB*) pixel);
  76291. p.unpremultiply();
  76292. return Colour (p.getARGB());
  76293. }
  76294. case Image::RGB:
  76295. return Colour (((const PixelRGB*) pixel)->getARGB());
  76296. case Image::SingleChannel:
  76297. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76298. default:
  76299. jassertfalse;
  76300. break;
  76301. }
  76302. return Colour();
  76303. }
  76304. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76305. {
  76306. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76307. uint8* const pixel = getPixelPointer (x, y);
  76308. const PixelARGB col (colour.getPixelARGB());
  76309. switch (pixelFormat)
  76310. {
  76311. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76312. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76313. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76314. default: jassertfalse; break;
  76315. }
  76316. }
  76317. void Image::setPixelData (int x, int y, int w, int h,
  76318. const uint8* const sourcePixelData, const int sourceLineStride)
  76319. {
  76320. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76321. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76322. {
  76323. const BitmapData dest (*this, x, y, w, h, true);
  76324. for (int i = 0; i < h; ++i)
  76325. {
  76326. memcpy (dest.getLinePointer(i),
  76327. sourcePixelData + sourceLineStride * i,
  76328. w * dest.pixelStride);
  76329. }
  76330. }
  76331. }
  76332. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76333. {
  76334. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76335. if (! clipped.isEmpty())
  76336. {
  76337. const PixelARGB col (colourToClearTo.getPixelARGB());
  76338. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76339. uint8* dest = destData.data;
  76340. int dh = clipped.getHeight();
  76341. while (--dh >= 0)
  76342. {
  76343. uint8* line = dest;
  76344. dest += destData.lineStride;
  76345. if (isARGB())
  76346. {
  76347. for (int x = clipped.getWidth(); --x >= 0;)
  76348. {
  76349. ((PixelARGB*) line)->set (col);
  76350. line += destData.pixelStride;
  76351. }
  76352. }
  76353. else if (isRGB())
  76354. {
  76355. for (int x = clipped.getWidth(); --x >= 0;)
  76356. {
  76357. ((PixelRGB*) line)->set (col);
  76358. line += destData.pixelStride;
  76359. }
  76360. }
  76361. else
  76362. {
  76363. for (int x = clipped.getWidth(); --x >= 0;)
  76364. {
  76365. *line = col.getAlpha();
  76366. line += destData.pixelStride;
  76367. }
  76368. }
  76369. }
  76370. }
  76371. }
  76372. const Colour Image::getPixelAt (const int x, const int y) const
  76373. {
  76374. if (((unsigned int) x) < (unsigned int) getWidth()
  76375. && ((unsigned int) y) < (unsigned int) getHeight())
  76376. {
  76377. const BitmapData srcData (*this, x, y, 1, 1);
  76378. return srcData.getPixelColour (0, 0);
  76379. }
  76380. return Colour();
  76381. }
  76382. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76383. {
  76384. if (((unsigned int) x) < (unsigned int) getWidth()
  76385. && ((unsigned int) y) < (unsigned int) getHeight())
  76386. {
  76387. const BitmapData destData (*this, x, y, 1, 1, true);
  76388. destData.setPixelColour (0, 0, colour);
  76389. }
  76390. }
  76391. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76392. {
  76393. if (((unsigned int) x) < (unsigned int) getWidth()
  76394. && ((unsigned int) y) < (unsigned int) getHeight()
  76395. && hasAlphaChannel())
  76396. {
  76397. const BitmapData destData (*this, x, y, 1, 1, true);
  76398. if (isARGB())
  76399. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76400. else
  76401. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76402. }
  76403. }
  76404. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76405. {
  76406. if (hasAlphaChannel())
  76407. {
  76408. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76409. if (isARGB())
  76410. {
  76411. for (int y = 0; y < destData.height; ++y)
  76412. {
  76413. uint8* p = destData.getLinePointer (y);
  76414. for (int x = 0; x < destData.width; ++x)
  76415. {
  76416. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76417. p += destData.pixelStride;
  76418. }
  76419. }
  76420. }
  76421. else
  76422. {
  76423. for (int y = 0; y < destData.height; ++y)
  76424. {
  76425. uint8* p = destData.getLinePointer (y);
  76426. for (int x = 0; x < destData.width; ++x)
  76427. {
  76428. *p = (uint8) (*p * amountToMultiplyBy);
  76429. p += destData.pixelStride;
  76430. }
  76431. }
  76432. }
  76433. }
  76434. else
  76435. {
  76436. jassertfalse; // can't do this without an alpha-channel!
  76437. }
  76438. }
  76439. void Image::desaturate()
  76440. {
  76441. if (isARGB() || isRGB())
  76442. {
  76443. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76444. if (isARGB())
  76445. {
  76446. for (int y = 0; y < destData.height; ++y)
  76447. {
  76448. uint8* p = destData.getLinePointer (y);
  76449. for (int x = 0; x < destData.width; ++x)
  76450. {
  76451. ((PixelARGB*) p)->desaturate();
  76452. p += destData.pixelStride;
  76453. }
  76454. }
  76455. }
  76456. else
  76457. {
  76458. for (int y = 0; y < destData.height; ++y)
  76459. {
  76460. uint8* p = destData.getLinePointer (y);
  76461. for (int x = 0; x < destData.width; ++x)
  76462. {
  76463. ((PixelRGB*) p)->desaturate();
  76464. p += destData.pixelStride;
  76465. }
  76466. }
  76467. }
  76468. }
  76469. }
  76470. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76471. {
  76472. if (hasAlphaChannel())
  76473. {
  76474. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76475. SparseSet<int> pixelsOnRow;
  76476. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76477. for (int y = 0; y < srcData.height; ++y)
  76478. {
  76479. pixelsOnRow.clear();
  76480. const uint8* lineData = srcData.getLinePointer (y);
  76481. if (isARGB())
  76482. {
  76483. for (int x = 0; x < srcData.width; ++x)
  76484. {
  76485. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76486. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76487. lineData += srcData.pixelStride;
  76488. }
  76489. }
  76490. else
  76491. {
  76492. for (int x = 0; x < srcData.width; ++x)
  76493. {
  76494. if (*lineData >= threshold)
  76495. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76496. lineData += srcData.pixelStride;
  76497. }
  76498. }
  76499. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76500. {
  76501. const Range<int> range (pixelsOnRow.getRange (i));
  76502. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76503. }
  76504. result.consolidate();
  76505. }
  76506. }
  76507. else
  76508. {
  76509. result.add (0, 0, getWidth(), getHeight());
  76510. }
  76511. }
  76512. void Image::moveImageSection (int dx, int dy,
  76513. int sx, int sy,
  76514. int w, int h)
  76515. {
  76516. if (dx < 0)
  76517. {
  76518. w += dx;
  76519. sx -= dx;
  76520. dx = 0;
  76521. }
  76522. if (dy < 0)
  76523. {
  76524. h += dy;
  76525. sy -= dy;
  76526. dy = 0;
  76527. }
  76528. if (sx < 0)
  76529. {
  76530. w += sx;
  76531. dx -= sx;
  76532. sx = 0;
  76533. }
  76534. if (sy < 0)
  76535. {
  76536. h += sy;
  76537. dy -= sy;
  76538. sy = 0;
  76539. }
  76540. const int minX = jmin (dx, sx);
  76541. const int minY = jmin (dy, sy);
  76542. w = jmin (w, getWidth() - jmax (sx, dx));
  76543. h = jmin (h, getHeight() - jmax (sy, dy));
  76544. if (w > 0 && h > 0)
  76545. {
  76546. const int maxX = jmax (dx, sx) + w;
  76547. const int maxY = jmax (dy, sy) + h;
  76548. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76549. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76550. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76551. const int lineSize = destData.pixelStride * w;
  76552. if (dy > sy)
  76553. {
  76554. while (--h >= 0)
  76555. {
  76556. const int offset = h * destData.lineStride;
  76557. memmove (dst + offset, src + offset, lineSize);
  76558. }
  76559. }
  76560. else if (dst != src)
  76561. {
  76562. while (--h >= 0)
  76563. {
  76564. memmove (dst, src, lineSize);
  76565. dst += destData.lineStride;
  76566. src += destData.lineStride;
  76567. }
  76568. }
  76569. }
  76570. }
  76571. END_JUCE_NAMESPACE
  76572. /*** End of inlined file: juce_Image.cpp ***/
  76573. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76574. BEGIN_JUCE_NAMESPACE
  76575. class ImageCache::Pimpl : public Timer,
  76576. public DeletedAtShutdown
  76577. {
  76578. public:
  76579. Pimpl()
  76580. : cacheTimeout (5000)
  76581. {
  76582. }
  76583. ~Pimpl()
  76584. {
  76585. clearSingletonInstance();
  76586. }
  76587. const Image getFromHashCode (const int64 hashCode)
  76588. {
  76589. const ScopedLock sl (lock);
  76590. for (int i = images.size(); --i >= 0;)
  76591. {
  76592. Item* const item = images.getUnchecked(i);
  76593. if (item->hashCode == hashCode)
  76594. return item->image;
  76595. }
  76596. return Image();
  76597. }
  76598. void addImageToCache (const Image& image, const int64 hashCode)
  76599. {
  76600. if (image.isValid())
  76601. {
  76602. if (! isTimerRunning())
  76603. startTimer (2000);
  76604. Item* const item = new Item();
  76605. item->hashCode = hashCode;
  76606. item->image = image;
  76607. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76608. const ScopedLock sl (lock);
  76609. images.add (item);
  76610. }
  76611. }
  76612. void timerCallback()
  76613. {
  76614. const uint32 now = Time::getApproximateMillisecondCounter();
  76615. const ScopedLock sl (lock);
  76616. for (int i = images.size(); --i >= 0;)
  76617. {
  76618. Item* const item = images.getUnchecked(i);
  76619. if (item->image.getReferenceCount() <= 1)
  76620. {
  76621. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76622. images.remove (i);
  76623. }
  76624. else
  76625. {
  76626. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76627. }
  76628. }
  76629. if (images.size() == 0)
  76630. stopTimer();
  76631. }
  76632. struct Item
  76633. {
  76634. Image image;
  76635. int64 hashCode;
  76636. uint32 lastUseTime;
  76637. };
  76638. int cacheTimeout;
  76639. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76640. private:
  76641. OwnedArray<Item> images;
  76642. CriticalSection lock;
  76643. Pimpl (const Pimpl&);
  76644. Pimpl& operator= (const Pimpl&);
  76645. };
  76646. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76647. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76648. {
  76649. if (Pimpl::getInstanceWithoutCreating() != 0)
  76650. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76651. return Image();
  76652. }
  76653. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76654. {
  76655. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76656. }
  76657. const Image ImageCache::getFromFile (const File& file)
  76658. {
  76659. const int64 hashCode = file.hashCode64();
  76660. Image image (getFromHashCode (hashCode));
  76661. if (image.isNull())
  76662. {
  76663. image = ImageFileFormat::loadFrom (file);
  76664. addImageToCache (image, hashCode);
  76665. }
  76666. return image;
  76667. }
  76668. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76669. {
  76670. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76671. Image image (getFromHashCode (hashCode));
  76672. if (image.isNull())
  76673. {
  76674. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76675. addImageToCache (image, hashCode);
  76676. }
  76677. return image;
  76678. }
  76679. void ImageCache::setCacheTimeout (const int millisecs)
  76680. {
  76681. Pimpl::getInstance()->cacheTimeout = millisecs;
  76682. }
  76683. END_JUCE_NAMESPACE
  76684. /*** End of inlined file: juce_ImageCache.cpp ***/
  76685. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76686. BEGIN_JUCE_NAMESPACE
  76687. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76688. : values (size_ * size_),
  76689. size (size_)
  76690. {
  76691. clear();
  76692. }
  76693. ImageConvolutionKernel::~ImageConvolutionKernel()
  76694. {
  76695. }
  76696. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76697. {
  76698. if (((unsigned int) x) < (unsigned int) size
  76699. && ((unsigned int) y) < (unsigned int) size)
  76700. {
  76701. return values [x + y * size];
  76702. }
  76703. else
  76704. {
  76705. jassertfalse;
  76706. return 0;
  76707. }
  76708. }
  76709. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76710. {
  76711. if (((unsigned int) x) < (unsigned int) size
  76712. && ((unsigned int) y) < (unsigned int) size)
  76713. {
  76714. values [x + y * size] = value;
  76715. }
  76716. else
  76717. {
  76718. jassertfalse;
  76719. }
  76720. }
  76721. void ImageConvolutionKernel::clear()
  76722. {
  76723. for (int i = size * size; --i >= 0;)
  76724. values[i] = 0;
  76725. }
  76726. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76727. {
  76728. double currentTotal = 0.0;
  76729. for (int i = size * size; --i >= 0;)
  76730. currentTotal += values[i];
  76731. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76732. }
  76733. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76734. {
  76735. for (int i = size * size; --i >= 0;)
  76736. values[i] *= multiplier;
  76737. }
  76738. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76739. {
  76740. const double radiusFactor = -1.0 / (radius * radius * 2);
  76741. const int centre = size >> 1;
  76742. for (int y = size; --y >= 0;)
  76743. {
  76744. for (int x = size; --x >= 0;)
  76745. {
  76746. const int cx = x - centre;
  76747. const int cy = y - centre;
  76748. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76749. }
  76750. }
  76751. setOverallSum (1.0f);
  76752. }
  76753. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76754. const Image& sourceImage,
  76755. const Rectangle<int>& destinationArea) const
  76756. {
  76757. if (sourceImage == destImage)
  76758. {
  76759. destImage.duplicateIfShared();
  76760. }
  76761. else
  76762. {
  76763. if (sourceImage.getWidth() != destImage.getWidth()
  76764. || sourceImage.getHeight() != destImage.getHeight()
  76765. || sourceImage.getFormat() != destImage.getFormat())
  76766. {
  76767. jassertfalse;
  76768. return;
  76769. }
  76770. }
  76771. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76772. if (area.isEmpty())
  76773. return;
  76774. const int right = area.getRight();
  76775. const int bottom = area.getBottom();
  76776. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76777. uint8* line = destData.data;
  76778. const Image::BitmapData srcData (sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  76779. if (destData.pixelStride == 4)
  76780. {
  76781. for (int y = area.getY(); y < bottom; ++y)
  76782. {
  76783. uint8* dest = line;
  76784. line += destData.lineStride;
  76785. for (int x = area.getX(); x < right; ++x)
  76786. {
  76787. float c1 = 0;
  76788. float c2 = 0;
  76789. float c3 = 0;
  76790. float c4 = 0;
  76791. for (int yy = 0; yy < size; ++yy)
  76792. {
  76793. const int sy = y + yy - (size >> 1);
  76794. if (sy >= srcData.height)
  76795. break;
  76796. if (sy >= 0)
  76797. {
  76798. int sx = x - (size >> 1);
  76799. const uint8* src = srcData.getPixelPointer (sx, sy);
  76800. for (int xx = 0; xx < size; ++xx)
  76801. {
  76802. if (sx >= srcData.width)
  76803. break;
  76804. if (sx >= 0)
  76805. {
  76806. const float kernelMult = values [xx + yy * size];
  76807. c1 += kernelMult * *src++;
  76808. c2 += kernelMult * *src++;
  76809. c3 += kernelMult * *src++;
  76810. c4 += kernelMult * *src++;
  76811. }
  76812. else
  76813. {
  76814. src += 4;
  76815. }
  76816. ++sx;
  76817. }
  76818. }
  76819. }
  76820. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  76821. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  76822. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  76823. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  76824. }
  76825. }
  76826. }
  76827. else if (destData.pixelStride == 3)
  76828. {
  76829. for (int y = area.getY(); y < bottom; ++y)
  76830. {
  76831. uint8* dest = line;
  76832. line += destData.lineStride;
  76833. for (int x = area.getX(); x < right; ++x)
  76834. {
  76835. float c1 = 0;
  76836. float c2 = 0;
  76837. float c3 = 0;
  76838. for (int yy = 0; yy < size; ++yy)
  76839. {
  76840. const int sy = y + yy - (size >> 1);
  76841. if (sy >= srcData.height)
  76842. break;
  76843. if (sy >= 0)
  76844. {
  76845. int sx = x - (size >> 1);
  76846. const uint8* src = srcData.getPixelPointer (sx, sy);
  76847. for (int xx = 0; xx < size; ++xx)
  76848. {
  76849. if (sx >= srcData.width)
  76850. break;
  76851. if (sx >= 0)
  76852. {
  76853. const float kernelMult = values [xx + yy * size];
  76854. c1 += kernelMult * *src++;
  76855. c2 += kernelMult * *src++;
  76856. c3 += kernelMult * *src++;
  76857. }
  76858. else
  76859. {
  76860. src += 3;
  76861. }
  76862. ++sx;
  76863. }
  76864. }
  76865. }
  76866. *dest++ = (uint8) roundToInt (c1);
  76867. *dest++ = (uint8) roundToInt (c2);
  76868. *dest++ = (uint8) roundToInt (c3);
  76869. }
  76870. }
  76871. }
  76872. }
  76873. END_JUCE_NAMESPACE
  76874. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76875. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  76876. BEGIN_JUCE_NAMESPACE
  76877. /*** Start of inlined file: juce_GIFLoader.h ***/
  76878. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  76879. #define __JUCE_GIFLOADER_JUCEHEADER__
  76880. #ifndef DOXYGEN
  76881. /**
  76882. Used internally by ImageFileFormat - don't use this class directly in your
  76883. application.
  76884. @see ImageFileFormat
  76885. */
  76886. class GIFLoader
  76887. {
  76888. public:
  76889. GIFLoader (InputStream& in);
  76890. ~GIFLoader();
  76891. const Image& getImage() const { return image; }
  76892. private:
  76893. Image image;
  76894. InputStream& input;
  76895. uint8 buffer [300];
  76896. uint8 palette [256][4];
  76897. bool dataBlockIsZero, fresh, finished;
  76898. int currentBit, lastBit, lastByteIndex;
  76899. int codeSize, setCodeSize;
  76900. int maxCode, maxCodeSize;
  76901. int firstcode, oldcode;
  76902. int clearCode, end_code;
  76903. enum { maxGifCode = 1 << 12 };
  76904. int table [2] [maxGifCode];
  76905. int stack [2 * maxGifCode];
  76906. int *sp;
  76907. bool getSizeFromHeader (int& width, int& height);
  76908. bool readPalette (const int numCols);
  76909. int readDataBlock (unsigned char* dest);
  76910. int processExtension (int type, int& transparent);
  76911. int readLZWByte (bool initialise, int input_code_size);
  76912. int getCode (int code_size, bool initialise);
  76913. bool readImage (int width, int height, int interlace, int transparent);
  76914. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  76915. GIFLoader (const GIFLoader&);
  76916. GIFLoader& operator= (const GIFLoader&);
  76917. };
  76918. #endif // DOXYGEN
  76919. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  76920. /*** End of inlined file: juce_GIFLoader.h ***/
  76921. class GIFImageFormat : public ImageFileFormat
  76922. {
  76923. public:
  76924. GIFImageFormat() {}
  76925. ~GIFImageFormat() {}
  76926. const String getFormatName()
  76927. {
  76928. return "GIF";
  76929. }
  76930. bool canUnderstand (InputStream& in)
  76931. {
  76932. const int bytesNeeded = 4;
  76933. char header [bytesNeeded];
  76934. return (in.read (header, bytesNeeded) == bytesNeeded)
  76935. && header[0] == 'G'
  76936. && header[1] == 'I'
  76937. && header[2] == 'F';
  76938. }
  76939. const Image decodeImage (InputStream& in)
  76940. {
  76941. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  76942. return loader->getImage();
  76943. }
  76944. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  76945. {
  76946. return false;
  76947. }
  76948. };
  76949. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  76950. {
  76951. static PNGImageFormat png;
  76952. static JPEGImageFormat jpg;
  76953. static GIFImageFormat gif;
  76954. ImageFileFormat* formats[4];
  76955. int numFormats = 0;
  76956. formats [numFormats++] = &png;
  76957. formats [numFormats++] = &jpg;
  76958. formats [numFormats++] = &gif;
  76959. const int64 streamPos = input.getPosition();
  76960. for (int i = 0; i < numFormats; ++i)
  76961. {
  76962. const bool found = formats[i]->canUnderstand (input);
  76963. input.setPosition (streamPos);
  76964. if (found)
  76965. return formats[i];
  76966. }
  76967. return 0;
  76968. }
  76969. const Image ImageFileFormat::loadFrom (InputStream& input)
  76970. {
  76971. ImageFileFormat* const format = findImageFormatForStream (input);
  76972. if (format != 0)
  76973. return format->decodeImage (input);
  76974. return Image();
  76975. }
  76976. const Image ImageFileFormat::loadFrom (const File& file)
  76977. {
  76978. InputStream* const in = file.createInputStream();
  76979. if (in != 0)
  76980. {
  76981. BufferedInputStream b (in, 8192, true);
  76982. return loadFrom (b);
  76983. }
  76984. return Image();
  76985. }
  76986. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  76987. {
  76988. if (rawData != 0 && numBytes > 4)
  76989. {
  76990. MemoryInputStream stream (rawData, numBytes, false);
  76991. return loadFrom (stream);
  76992. }
  76993. return Image();
  76994. }
  76995. END_JUCE_NAMESPACE
  76996. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  76997. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  76998. BEGIN_JUCE_NAMESPACE
  76999. GIFLoader::GIFLoader (InputStream& in)
  77000. : image (0),
  77001. input (in),
  77002. dataBlockIsZero (false),
  77003. fresh (false),
  77004. finished (false)
  77005. {
  77006. currentBit = lastBit = lastByteIndex = 0;
  77007. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77008. firstcode = oldcode = 0;
  77009. clearCode = end_code = 0;
  77010. int imageWidth, imageHeight;
  77011. int transparent = -1;
  77012. if (! getSizeFromHeader (imageWidth, imageHeight))
  77013. return;
  77014. if ((imageWidth <= 0) || (imageHeight <= 0))
  77015. return;
  77016. unsigned char buf [16];
  77017. if (in.read (buf, 3) != 3)
  77018. return;
  77019. int numColours = 2 << (buf[0] & 7);
  77020. if ((buf[0] & 0x80) != 0)
  77021. readPalette (numColours);
  77022. for (;;)
  77023. {
  77024. if (input.read (buf, 1) != 1)
  77025. break;
  77026. if (buf[0] == ';')
  77027. break;
  77028. if (buf[0] == '!')
  77029. {
  77030. if (input.read (buf, 1) != 1)
  77031. break;
  77032. if (processExtension (buf[0], transparent) < 0)
  77033. break;
  77034. continue;
  77035. }
  77036. if (buf[0] != ',')
  77037. continue;
  77038. if (input.read (buf, 9) != 9)
  77039. break;
  77040. imageWidth = makeWord (buf[4], buf[5]);
  77041. imageHeight = makeWord (buf[6], buf[7]);
  77042. numColours = 2 << (buf[8] & 7);
  77043. if ((buf[8] & 0x80) != 0)
  77044. if (! readPalette (numColours))
  77045. break;
  77046. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77047. imageWidth, imageHeight, (transparent >= 0));
  77048. readImage (imageWidth, imageHeight,
  77049. (buf[8] & 0x40) != 0,
  77050. transparent);
  77051. break;
  77052. }
  77053. }
  77054. GIFLoader::~GIFLoader()
  77055. {
  77056. }
  77057. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  77058. {
  77059. char b[8];
  77060. if (input.read (b, 6) == 6)
  77061. {
  77062. if ((strncmp ("GIF87a", b, 6) == 0)
  77063. || (strncmp ("GIF89a", b, 6) == 0))
  77064. {
  77065. if (input.read (b, 4) == 4)
  77066. {
  77067. w = makeWord (b[0], b[1]);
  77068. h = makeWord (b[2], b[3]);
  77069. return true;
  77070. }
  77071. }
  77072. }
  77073. return false;
  77074. }
  77075. bool GIFLoader::readPalette (const int numCols)
  77076. {
  77077. unsigned char rgb[4];
  77078. for (int i = 0; i < numCols; ++i)
  77079. {
  77080. input.read (rgb, 3);
  77081. palette [i][0] = rgb[0];
  77082. palette [i][1] = rgb[1];
  77083. palette [i][2] = rgb[2];
  77084. palette [i][3] = 0xff;
  77085. }
  77086. return true;
  77087. }
  77088. int GIFLoader::readDataBlock (unsigned char* const dest)
  77089. {
  77090. unsigned char n;
  77091. if (input.read (&n, 1) == 1)
  77092. {
  77093. dataBlockIsZero = (n == 0);
  77094. if (dataBlockIsZero || (input.read (dest, n) == n))
  77095. return n;
  77096. }
  77097. return -1;
  77098. }
  77099. int GIFLoader::processExtension (const int type, int& transparent)
  77100. {
  77101. unsigned char b [300];
  77102. int n = 0;
  77103. if (type == 0xf9)
  77104. {
  77105. n = readDataBlock (b);
  77106. if (n < 0)
  77107. return 1;
  77108. if ((b[0] & 0x1) != 0)
  77109. transparent = b[3];
  77110. }
  77111. do
  77112. {
  77113. n = readDataBlock (b);
  77114. }
  77115. while (n > 0);
  77116. return n;
  77117. }
  77118. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  77119. {
  77120. if (initialise)
  77121. {
  77122. currentBit = 0;
  77123. lastBit = 0;
  77124. finished = false;
  77125. return 0;
  77126. }
  77127. if ((currentBit + codeSize_) >= lastBit)
  77128. {
  77129. if (finished)
  77130. return -1;
  77131. buffer[0] = buffer [lastByteIndex - 2];
  77132. buffer[1] = buffer [lastByteIndex - 1];
  77133. const int n = readDataBlock (&buffer[2]);
  77134. if (n == 0)
  77135. finished = true;
  77136. lastByteIndex = 2 + n;
  77137. currentBit = (currentBit - lastBit) + 16;
  77138. lastBit = (2 + n) * 8 ;
  77139. }
  77140. int result = 0;
  77141. int i = currentBit;
  77142. for (int j = 0; j < codeSize_; ++j)
  77143. {
  77144. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77145. ++i;
  77146. }
  77147. currentBit += codeSize_;
  77148. return result;
  77149. }
  77150. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77151. {
  77152. int code, incode, i;
  77153. if (initialise)
  77154. {
  77155. setCodeSize = inputCodeSize;
  77156. codeSize = setCodeSize + 1;
  77157. clearCode = 1 << setCodeSize;
  77158. end_code = clearCode + 1;
  77159. maxCodeSize = 2 * clearCode;
  77160. maxCode = clearCode + 2;
  77161. getCode (0, true);
  77162. fresh = true;
  77163. for (i = 0; i < clearCode; ++i)
  77164. {
  77165. table[0][i] = 0;
  77166. table[1][i] = i;
  77167. }
  77168. for (; i < maxGifCode; ++i)
  77169. {
  77170. table[0][i] = 0;
  77171. table[1][i] = 0;
  77172. }
  77173. sp = stack;
  77174. return 0;
  77175. }
  77176. else if (fresh)
  77177. {
  77178. fresh = false;
  77179. do
  77180. {
  77181. firstcode = oldcode
  77182. = getCode (codeSize, false);
  77183. }
  77184. while (firstcode == clearCode);
  77185. return firstcode;
  77186. }
  77187. if (sp > stack)
  77188. return *--sp;
  77189. while ((code = getCode (codeSize, false)) >= 0)
  77190. {
  77191. if (code == clearCode)
  77192. {
  77193. for (i = 0; i < clearCode; ++i)
  77194. {
  77195. table[0][i] = 0;
  77196. table[1][i] = i;
  77197. }
  77198. for (; i < maxGifCode; ++i)
  77199. {
  77200. table[0][i] = 0;
  77201. table[1][i] = 0;
  77202. }
  77203. codeSize = setCodeSize + 1;
  77204. maxCodeSize = 2 * clearCode;
  77205. maxCode = clearCode + 2;
  77206. sp = stack;
  77207. firstcode = oldcode = getCode (codeSize, false);
  77208. return firstcode;
  77209. }
  77210. else if (code == end_code)
  77211. {
  77212. if (dataBlockIsZero)
  77213. return -2;
  77214. unsigned char buf [260];
  77215. int n;
  77216. while ((n = readDataBlock (buf)) > 0)
  77217. {}
  77218. if (n != 0)
  77219. return -2;
  77220. }
  77221. incode = code;
  77222. if (code >= maxCode)
  77223. {
  77224. *sp++ = firstcode;
  77225. code = oldcode;
  77226. }
  77227. while (code >= clearCode)
  77228. {
  77229. *sp++ = table[1][code];
  77230. if (code == table[0][code])
  77231. return -2;
  77232. code = table[0][code];
  77233. }
  77234. *sp++ = firstcode = table[1][code];
  77235. if ((code = maxCode) < maxGifCode)
  77236. {
  77237. table[0][code] = oldcode;
  77238. table[1][code] = firstcode;
  77239. ++maxCode;
  77240. if ((maxCode >= maxCodeSize)
  77241. && (maxCodeSize < maxGifCode))
  77242. {
  77243. maxCodeSize <<= 1;
  77244. ++codeSize;
  77245. }
  77246. }
  77247. oldcode = incode;
  77248. if (sp > stack)
  77249. return *--sp;
  77250. }
  77251. return code;
  77252. }
  77253. bool GIFLoader::readImage (const int width, const int height,
  77254. const int interlace, const int transparent)
  77255. {
  77256. unsigned char c;
  77257. if (input.read (&c, 1) != 1
  77258. || readLZWByte (true, c) < 0)
  77259. return false;
  77260. if (transparent >= 0)
  77261. {
  77262. palette [transparent][0] = 0;
  77263. palette [transparent][1] = 0;
  77264. palette [transparent][2] = 0;
  77265. palette [transparent][3] = 0;
  77266. }
  77267. int index;
  77268. int xpos = 0, ypos = 0, pass = 0;
  77269. const Image::BitmapData destData (image, 0, 0, width, height, true);
  77270. uint8* p = destData.data;
  77271. const bool hasAlpha = image.hasAlphaChannel();
  77272. while ((index = readLZWByte (false, c)) >= 0)
  77273. {
  77274. const uint8* const paletteEntry = palette [index];
  77275. if (hasAlpha)
  77276. {
  77277. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77278. paletteEntry[0],
  77279. paletteEntry[1],
  77280. paletteEntry[2]);
  77281. ((PixelARGB*) p)->premultiply();
  77282. }
  77283. else
  77284. {
  77285. ((PixelRGB*) p)->setARGB (0,
  77286. paletteEntry[0],
  77287. paletteEntry[1],
  77288. paletteEntry[2]);
  77289. }
  77290. p += destData.pixelStride;
  77291. ++xpos;
  77292. if (xpos == width)
  77293. {
  77294. xpos = 0;
  77295. if (interlace)
  77296. {
  77297. switch (pass)
  77298. {
  77299. case 0:
  77300. case 1: ypos += 8; break;
  77301. case 2: ypos += 4; break;
  77302. case 3: ypos += 2; break;
  77303. }
  77304. while (ypos >= height)
  77305. {
  77306. ++pass;
  77307. switch (pass)
  77308. {
  77309. case 1: ypos = 4; break;
  77310. case 2: ypos = 2; break;
  77311. case 3: ypos = 1; break;
  77312. default: return true;
  77313. }
  77314. }
  77315. }
  77316. else
  77317. {
  77318. ++ypos;
  77319. }
  77320. p = destData.getPixelPointer (xpos, ypos);
  77321. }
  77322. if (ypos >= height)
  77323. break;
  77324. }
  77325. return true;
  77326. }
  77327. END_JUCE_NAMESPACE
  77328. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77329. #endif
  77330. //==============================================================================
  77331. // some files include lots of library code, so leave them to the end to avoid cluttering
  77332. // up the build for the clean files.
  77333. #if JUCE_BUILD_CORE
  77334. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77335. namespace zlibNamespace
  77336. {
  77337. #if JUCE_INCLUDE_ZLIB_CODE
  77338. #undef OS_CODE
  77339. #undef fdopen
  77340. /*** Start of inlined file: zlib.h ***/
  77341. #ifndef ZLIB_H
  77342. #define ZLIB_H
  77343. /*** Start of inlined file: zconf.h ***/
  77344. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77345. #ifndef ZCONF_H
  77346. #define ZCONF_H
  77347. // *** Just a few hacks here to make it compile nicely with Juce..
  77348. #define Z_PREFIX 1
  77349. #undef __MACTYPES__
  77350. #ifdef _MSC_VER
  77351. #pragma warning (disable : 4131 4127 4244 4267)
  77352. #endif
  77353. /*
  77354. * If you *really* need a unique prefix for all types and library functions,
  77355. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77356. */
  77357. #ifdef Z_PREFIX
  77358. # define deflateInit_ z_deflateInit_
  77359. # define deflate z_deflate
  77360. # define deflateEnd z_deflateEnd
  77361. # define inflateInit_ z_inflateInit_
  77362. # define inflate z_inflate
  77363. # define inflateEnd z_inflateEnd
  77364. # define inflatePrime z_inflatePrime
  77365. # define inflateGetHeader z_inflateGetHeader
  77366. # define adler32_combine z_adler32_combine
  77367. # define crc32_combine z_crc32_combine
  77368. # define deflateInit2_ z_deflateInit2_
  77369. # define deflateSetDictionary z_deflateSetDictionary
  77370. # define deflateCopy z_deflateCopy
  77371. # define deflateReset z_deflateReset
  77372. # define deflateParams z_deflateParams
  77373. # define deflateBound z_deflateBound
  77374. # define deflatePrime z_deflatePrime
  77375. # define inflateInit2_ z_inflateInit2_
  77376. # define inflateSetDictionary z_inflateSetDictionary
  77377. # define inflateSync z_inflateSync
  77378. # define inflateSyncPoint z_inflateSyncPoint
  77379. # define inflateCopy z_inflateCopy
  77380. # define inflateReset z_inflateReset
  77381. # define inflateBack z_inflateBack
  77382. # define inflateBackEnd z_inflateBackEnd
  77383. # define compress z_compress
  77384. # define compress2 z_compress2
  77385. # define compressBound z_compressBound
  77386. # define uncompress z_uncompress
  77387. # define adler32 z_adler32
  77388. # define crc32 z_crc32
  77389. # define get_crc_table z_get_crc_table
  77390. # define zError z_zError
  77391. # define alloc_func z_alloc_func
  77392. # define free_func z_free_func
  77393. # define in_func z_in_func
  77394. # define out_func z_out_func
  77395. # define Byte z_Byte
  77396. # define uInt z_uInt
  77397. # define uLong z_uLong
  77398. # define Bytef z_Bytef
  77399. # define charf z_charf
  77400. # define intf z_intf
  77401. # define uIntf z_uIntf
  77402. # define uLongf z_uLongf
  77403. # define voidpf z_voidpf
  77404. # define voidp z_voidp
  77405. #endif
  77406. #if defined(__MSDOS__) && !defined(MSDOS)
  77407. # define MSDOS
  77408. #endif
  77409. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77410. # define OS2
  77411. #endif
  77412. #if defined(_WINDOWS) && !defined(WINDOWS)
  77413. # define WINDOWS
  77414. #endif
  77415. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77416. # ifndef WIN32
  77417. # define WIN32
  77418. # endif
  77419. #endif
  77420. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77421. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77422. # ifndef SYS16BIT
  77423. # define SYS16BIT
  77424. # endif
  77425. # endif
  77426. #endif
  77427. /*
  77428. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77429. * than 64k bytes at a time (needed on systems with 16-bit int).
  77430. */
  77431. #ifdef SYS16BIT
  77432. # define MAXSEG_64K
  77433. #endif
  77434. #ifdef MSDOS
  77435. # define UNALIGNED_OK
  77436. #endif
  77437. #ifdef __STDC_VERSION__
  77438. # ifndef STDC
  77439. # define STDC
  77440. # endif
  77441. # if __STDC_VERSION__ >= 199901L
  77442. # ifndef STDC99
  77443. # define STDC99
  77444. # endif
  77445. # endif
  77446. #endif
  77447. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77448. # define STDC
  77449. #endif
  77450. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77451. # define STDC
  77452. #endif
  77453. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77454. # define STDC
  77455. #endif
  77456. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77457. # define STDC
  77458. #endif
  77459. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77460. # define STDC
  77461. #endif
  77462. #ifndef STDC
  77463. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77464. # define const /* note: need a more gentle solution here */
  77465. # endif
  77466. #endif
  77467. /* Some Mac compilers merge all .h files incorrectly: */
  77468. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77469. # define NO_DUMMY_DECL
  77470. #endif
  77471. /* Maximum value for memLevel in deflateInit2 */
  77472. #ifndef MAX_MEM_LEVEL
  77473. # ifdef MAXSEG_64K
  77474. # define MAX_MEM_LEVEL 8
  77475. # else
  77476. # define MAX_MEM_LEVEL 9
  77477. # endif
  77478. #endif
  77479. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77480. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77481. * created by gzip. (Files created by minigzip can still be extracted by
  77482. * gzip.)
  77483. */
  77484. #ifndef MAX_WBITS
  77485. # define MAX_WBITS 15 /* 32K LZ77 window */
  77486. #endif
  77487. /* The memory requirements for deflate are (in bytes):
  77488. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77489. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77490. plus a few kilobytes for small objects. For example, if you want to reduce
  77491. the default memory requirements from 256K to 128K, compile with
  77492. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77493. Of course this will generally degrade compression (there's no free lunch).
  77494. The memory requirements for inflate are (in bytes) 1 << windowBits
  77495. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77496. for small objects.
  77497. */
  77498. /* Type declarations */
  77499. #ifndef OF /* function prototypes */
  77500. # ifdef STDC
  77501. # define OF(args) args
  77502. # else
  77503. # define OF(args) ()
  77504. # endif
  77505. #endif
  77506. /* The following definitions for FAR are needed only for MSDOS mixed
  77507. * model programming (small or medium model with some far allocations).
  77508. * This was tested only with MSC; for other MSDOS compilers you may have
  77509. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77510. * just define FAR to be empty.
  77511. */
  77512. #ifdef SYS16BIT
  77513. # if defined(M_I86SM) || defined(M_I86MM)
  77514. /* MSC small or medium model */
  77515. # define SMALL_MEDIUM
  77516. # ifdef _MSC_VER
  77517. # define FAR _far
  77518. # else
  77519. # define FAR far
  77520. # endif
  77521. # endif
  77522. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77523. /* Turbo C small or medium model */
  77524. # define SMALL_MEDIUM
  77525. # ifdef __BORLANDC__
  77526. # define FAR _far
  77527. # else
  77528. # define FAR far
  77529. # endif
  77530. # endif
  77531. #endif
  77532. #if defined(WINDOWS) || defined(WIN32)
  77533. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77534. * This is not mandatory, but it offers a little performance increase.
  77535. */
  77536. # ifdef ZLIB_DLL
  77537. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77538. # ifdef ZLIB_INTERNAL
  77539. # define ZEXTERN extern __declspec(dllexport)
  77540. # else
  77541. # define ZEXTERN extern __declspec(dllimport)
  77542. # endif
  77543. # endif
  77544. # endif /* ZLIB_DLL */
  77545. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77546. * define ZLIB_WINAPI.
  77547. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77548. */
  77549. # ifdef ZLIB_WINAPI
  77550. # ifdef FAR
  77551. # undef FAR
  77552. # endif
  77553. # include <windows.h>
  77554. /* No need for _export, use ZLIB.DEF instead. */
  77555. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77556. # define ZEXPORT WINAPI
  77557. # ifdef WIN32
  77558. # define ZEXPORTVA WINAPIV
  77559. # else
  77560. # define ZEXPORTVA FAR CDECL
  77561. # endif
  77562. # endif
  77563. #endif
  77564. #if defined (__BEOS__)
  77565. # ifdef ZLIB_DLL
  77566. # ifdef ZLIB_INTERNAL
  77567. # define ZEXPORT __declspec(dllexport)
  77568. # define ZEXPORTVA __declspec(dllexport)
  77569. # else
  77570. # define ZEXPORT __declspec(dllimport)
  77571. # define ZEXPORTVA __declspec(dllimport)
  77572. # endif
  77573. # endif
  77574. #endif
  77575. #ifndef ZEXTERN
  77576. # define ZEXTERN extern
  77577. #endif
  77578. #ifndef ZEXPORT
  77579. # define ZEXPORT
  77580. #endif
  77581. #ifndef ZEXPORTVA
  77582. # define ZEXPORTVA
  77583. #endif
  77584. #ifndef FAR
  77585. # define FAR
  77586. #endif
  77587. #if !defined(__MACTYPES__)
  77588. typedef unsigned char Byte; /* 8 bits */
  77589. #endif
  77590. typedef unsigned int uInt; /* 16 bits or more */
  77591. typedef unsigned long uLong; /* 32 bits or more */
  77592. #ifdef SMALL_MEDIUM
  77593. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77594. # define Bytef Byte FAR
  77595. #else
  77596. typedef Byte FAR Bytef;
  77597. #endif
  77598. typedef char FAR charf;
  77599. typedef int FAR intf;
  77600. typedef uInt FAR uIntf;
  77601. typedef uLong FAR uLongf;
  77602. #ifdef STDC
  77603. typedef void const *voidpc;
  77604. typedef void FAR *voidpf;
  77605. typedef void *voidp;
  77606. #else
  77607. typedef Byte const *voidpc;
  77608. typedef Byte FAR *voidpf;
  77609. typedef Byte *voidp;
  77610. #endif
  77611. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77612. # include <sys/types.h> /* for off_t */
  77613. # include <unistd.h> /* for SEEK_* and off_t */
  77614. # ifdef VMS
  77615. # include <unixio.h> /* for off_t */
  77616. # endif
  77617. # define z_off_t off_t
  77618. #endif
  77619. #ifndef SEEK_SET
  77620. # define SEEK_SET 0 /* Seek from beginning of file. */
  77621. # define SEEK_CUR 1 /* Seek from current position. */
  77622. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77623. #endif
  77624. #ifndef z_off_t
  77625. # define z_off_t long
  77626. #endif
  77627. #if defined(__OS400__)
  77628. # define NO_vsnprintf
  77629. #endif
  77630. #if defined(__MVS__)
  77631. # define NO_vsnprintf
  77632. # ifdef FAR
  77633. # undef FAR
  77634. # endif
  77635. #endif
  77636. /* MVS linker does not support external names larger than 8 bytes */
  77637. #if defined(__MVS__)
  77638. # pragma map(deflateInit_,"DEIN")
  77639. # pragma map(deflateInit2_,"DEIN2")
  77640. # pragma map(deflateEnd,"DEEND")
  77641. # pragma map(deflateBound,"DEBND")
  77642. # pragma map(inflateInit_,"ININ")
  77643. # pragma map(inflateInit2_,"ININ2")
  77644. # pragma map(inflateEnd,"INEND")
  77645. # pragma map(inflateSync,"INSY")
  77646. # pragma map(inflateSetDictionary,"INSEDI")
  77647. # pragma map(compressBound,"CMBND")
  77648. # pragma map(inflate_table,"INTABL")
  77649. # pragma map(inflate_fast,"INFA")
  77650. # pragma map(inflate_copyright,"INCOPY")
  77651. #endif
  77652. #endif /* ZCONF_H */
  77653. /*** End of inlined file: zconf.h ***/
  77654. #ifdef __cplusplus
  77655. extern "C" {
  77656. #endif
  77657. #define ZLIB_VERSION "1.2.3"
  77658. #define ZLIB_VERNUM 0x1230
  77659. /*
  77660. The 'zlib' compression library provides in-memory compression and
  77661. decompression functions, including integrity checks of the uncompressed
  77662. data. This version of the library supports only one compression method
  77663. (deflation) but other algorithms will be added later and will have the same
  77664. stream interface.
  77665. Compression can be done in a single step if the buffers are large
  77666. enough (for example if an input file is mmap'ed), or can be done by
  77667. repeated calls of the compression function. In the latter case, the
  77668. application must provide more input and/or consume the output
  77669. (providing more output space) before each call.
  77670. The compressed data format used by default by the in-memory functions is
  77671. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77672. around a deflate stream, which is itself documented in RFC 1951.
  77673. The library also supports reading and writing files in gzip (.gz) format
  77674. with an interface similar to that of stdio using the functions that start
  77675. with "gz". The gzip format is different from the zlib format. gzip is a
  77676. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77677. This library can optionally read and write gzip streams in memory as well.
  77678. The zlib format was designed to be compact and fast for use in memory
  77679. and on communications channels. The gzip format was designed for single-
  77680. file compression on file systems, has a larger header than zlib to maintain
  77681. directory information, and uses a different, slower check method than zlib.
  77682. The library does not install any signal handler. The decoder checks
  77683. the consistency of the compressed data, so the library should never
  77684. crash even in case of corrupted input.
  77685. */
  77686. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77687. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77688. struct internal_state;
  77689. typedef struct z_stream_s {
  77690. Bytef *next_in; /* next input byte */
  77691. uInt avail_in; /* number of bytes available at next_in */
  77692. uLong total_in; /* total nb of input bytes read so far */
  77693. Bytef *next_out; /* next output byte should be put there */
  77694. uInt avail_out; /* remaining free space at next_out */
  77695. uLong total_out; /* total nb of bytes output so far */
  77696. char *msg; /* last error message, NULL if no error */
  77697. struct internal_state FAR *state; /* not visible by applications */
  77698. alloc_func zalloc; /* used to allocate the internal state */
  77699. free_func zfree; /* used to free the internal state */
  77700. voidpf opaque; /* private data object passed to zalloc and zfree */
  77701. int data_type; /* best guess about the data type: binary or text */
  77702. uLong adler; /* adler32 value of the uncompressed data */
  77703. uLong reserved; /* reserved for future use */
  77704. } z_stream;
  77705. typedef z_stream FAR *z_streamp;
  77706. /*
  77707. gzip header information passed to and from zlib routines. See RFC 1952
  77708. for more details on the meanings of these fields.
  77709. */
  77710. typedef struct gz_header_s {
  77711. int text; /* true if compressed data believed to be text */
  77712. uLong time; /* modification time */
  77713. int xflags; /* extra flags (not used when writing a gzip file) */
  77714. int os; /* operating system */
  77715. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77716. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77717. uInt extra_max; /* space at extra (only when reading header) */
  77718. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77719. uInt name_max; /* space at name (only when reading header) */
  77720. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77721. uInt comm_max; /* space at comment (only when reading header) */
  77722. int hcrc; /* true if there was or will be a header crc */
  77723. int done; /* true when done reading gzip header (not used
  77724. when writing a gzip file) */
  77725. } gz_header;
  77726. typedef gz_header FAR *gz_headerp;
  77727. /*
  77728. The application must update next_in and avail_in when avail_in has
  77729. dropped to zero. It must update next_out and avail_out when avail_out
  77730. has dropped to zero. The application must initialize zalloc, zfree and
  77731. opaque before calling the init function. All other fields are set by the
  77732. compression library and must not be updated by the application.
  77733. The opaque value provided by the application will be passed as the first
  77734. parameter for calls of zalloc and zfree. This can be useful for custom
  77735. memory management. The compression library attaches no meaning to the
  77736. opaque value.
  77737. zalloc must return Z_NULL if there is not enough memory for the object.
  77738. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77739. thread safe.
  77740. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77741. exactly 65536 bytes, but will not be required to allocate more than this
  77742. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77743. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77744. have their offset normalized to zero. The default allocation function
  77745. provided by this library ensures this (see zutil.c). To reduce memory
  77746. requirements and avoid any allocation of 64K objects, at the expense of
  77747. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77748. The fields total_in and total_out can be used for statistics or
  77749. progress reports. After compression, total_in holds the total size of
  77750. the uncompressed data and may be saved for use in the decompressor
  77751. (particularly if the decompressor wants to decompress everything in
  77752. a single step).
  77753. */
  77754. /* constants */
  77755. #define Z_NO_FLUSH 0
  77756. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77757. #define Z_SYNC_FLUSH 2
  77758. #define Z_FULL_FLUSH 3
  77759. #define Z_FINISH 4
  77760. #define Z_BLOCK 5
  77761. /* Allowed flush values; see deflate() and inflate() below for details */
  77762. #define Z_OK 0
  77763. #define Z_STREAM_END 1
  77764. #define Z_NEED_DICT 2
  77765. #define Z_ERRNO (-1)
  77766. #define Z_STREAM_ERROR (-2)
  77767. #define Z_DATA_ERROR (-3)
  77768. #define Z_MEM_ERROR (-4)
  77769. #define Z_BUF_ERROR (-5)
  77770. #define Z_VERSION_ERROR (-6)
  77771. /* Return codes for the compression/decompression functions. Negative
  77772. * values are errors, positive values are used for special but normal events.
  77773. */
  77774. #define Z_NO_COMPRESSION 0
  77775. #define Z_BEST_SPEED 1
  77776. #define Z_BEST_COMPRESSION 9
  77777. #define Z_DEFAULT_COMPRESSION (-1)
  77778. /* compression levels */
  77779. #define Z_FILTERED 1
  77780. #define Z_HUFFMAN_ONLY 2
  77781. #define Z_RLE 3
  77782. #define Z_FIXED 4
  77783. #define Z_DEFAULT_STRATEGY 0
  77784. /* compression strategy; see deflateInit2() below for details */
  77785. #define Z_BINARY 0
  77786. #define Z_TEXT 1
  77787. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77788. #define Z_UNKNOWN 2
  77789. /* Possible values of the data_type field (though see inflate()) */
  77790. #define Z_DEFLATED 8
  77791. /* The deflate compression method (the only one supported in this version) */
  77792. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77793. #define zlib_version zlibVersion()
  77794. /* for compatibility with versions < 1.0.2 */
  77795. /* basic functions */
  77796. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77797. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77798. If the first character differs, the library code actually used is
  77799. not compatible with the zlib.h header file used by the application.
  77800. This check is automatically made by deflateInit and inflateInit.
  77801. */
  77802. /*
  77803. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77804. Initializes the internal stream state for compression. The fields
  77805. zalloc, zfree and opaque must be initialized before by the caller.
  77806. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77807. use default allocation functions.
  77808. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77809. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77810. all (the input data is simply copied a block at a time).
  77811. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77812. compression (currently equivalent to level 6).
  77813. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77814. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77815. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77816. with the version assumed by the caller (ZLIB_VERSION).
  77817. msg is set to null if there is no error message. deflateInit does not
  77818. perform any compression: this will be done by deflate().
  77819. */
  77820. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  77821. /*
  77822. deflate compresses as much data as possible, and stops when the input
  77823. buffer becomes empty or the output buffer becomes full. It may introduce some
  77824. output latency (reading input without producing any output) except when
  77825. forced to flush.
  77826. The detailed semantics are as follows. deflate performs one or both of the
  77827. following actions:
  77828. - Compress more input starting at next_in and update next_in and avail_in
  77829. accordingly. If not all input can be processed (because there is not
  77830. enough room in the output buffer), next_in and avail_in are updated and
  77831. processing will resume at this point for the next call of deflate().
  77832. - Provide more output starting at next_out and update next_out and avail_out
  77833. accordingly. This action is forced if the parameter flush is non zero.
  77834. Forcing flush frequently degrades the compression ratio, so this parameter
  77835. should be set only when necessary (in interactive applications).
  77836. Some output may be provided even if flush is not set.
  77837. Before the call of deflate(), the application should ensure that at least
  77838. one of the actions is possible, by providing more input and/or consuming
  77839. more output, and updating avail_in or avail_out accordingly; avail_out
  77840. should never be zero before the call. The application can consume the
  77841. compressed output when it wants, for example when the output buffer is full
  77842. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  77843. and with zero avail_out, it must be called again after making room in the
  77844. output buffer because there might be more output pending.
  77845. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  77846. decide how much data to accumualte before producing output, in order to
  77847. maximize compression.
  77848. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  77849. flushed to the output buffer and the output is aligned on a byte boundary, so
  77850. that the decompressor can get all input data available so far. (In particular
  77851. avail_in is zero after the call if enough output space has been provided
  77852. before the call.) Flushing may degrade compression for some compression
  77853. algorithms and so it should be used only when necessary.
  77854. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  77855. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  77856. restart from this point if previous compressed data has been damaged or if
  77857. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  77858. compression.
  77859. If deflate returns with avail_out == 0, this function must be called again
  77860. with the same value of the flush parameter and more output space (updated
  77861. avail_out), until the flush is complete (deflate returns with non-zero
  77862. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  77863. avail_out is greater than six to avoid repeated flush markers due to
  77864. avail_out == 0 on return.
  77865. If the parameter flush is set to Z_FINISH, pending input is processed,
  77866. pending output is flushed and deflate returns with Z_STREAM_END if there
  77867. was enough output space; if deflate returns with Z_OK, this function must be
  77868. called again with Z_FINISH and more output space (updated avail_out) but no
  77869. more input data, until it returns with Z_STREAM_END or an error. After
  77870. deflate has returned Z_STREAM_END, the only possible operations on the
  77871. stream are deflateReset or deflateEnd.
  77872. Z_FINISH can be used immediately after deflateInit if all the compression
  77873. is to be done in a single step. In this case, avail_out must be at least
  77874. the value returned by deflateBound (see below). If deflate does not return
  77875. Z_STREAM_END, then it must be called again as described above.
  77876. deflate() sets strm->adler to the adler32 checksum of all input read
  77877. so far (that is, total_in bytes).
  77878. deflate() may update strm->data_type if it can make a good guess about
  77879. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  77880. binary. This field is only for information purposes and does not affect
  77881. the compression algorithm in any manner.
  77882. deflate() returns Z_OK if some progress has been made (more input
  77883. processed or more output produced), Z_STREAM_END if all input has been
  77884. consumed and all output has been produced (only when flush is set to
  77885. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  77886. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  77887. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  77888. fatal, and deflate() can be called again with more input and more output
  77889. space to continue compressing.
  77890. */
  77891. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  77892. /*
  77893. All dynamically allocated data structures for this stream are freed.
  77894. This function discards any unprocessed input and does not flush any
  77895. pending output.
  77896. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  77897. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  77898. prematurely (some input or output was discarded). In the error case,
  77899. msg may be set but then points to a static string (which must not be
  77900. deallocated).
  77901. */
  77902. /*
  77903. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  77904. Initializes the internal stream state for decompression. The fields
  77905. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  77906. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  77907. value depends on the compression method), inflateInit determines the
  77908. compression method from the zlib header and allocates all data structures
  77909. accordingly; otherwise the allocation will be deferred to the first call of
  77910. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  77911. use default allocation functions.
  77912. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77913. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  77914. version assumed by the caller. msg is set to null if there is no error
  77915. message. inflateInit does not perform any decompression apart from reading
  77916. the zlib header if present: this will be done by inflate(). (So next_in and
  77917. avail_in may be modified, but next_out and avail_out are unchanged.)
  77918. */
  77919. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  77920. /*
  77921. inflate decompresses as much data as possible, and stops when the input
  77922. buffer becomes empty or the output buffer becomes full. It may introduce
  77923. some output latency (reading input without producing any output) except when
  77924. forced to flush.
  77925. The detailed semantics are as follows. inflate performs one or both of the
  77926. following actions:
  77927. - Decompress more input starting at next_in and update next_in and avail_in
  77928. accordingly. If not all input can be processed (because there is not
  77929. enough room in the output buffer), next_in is updated and processing
  77930. will resume at this point for the next call of inflate().
  77931. - Provide more output starting at next_out and update next_out and avail_out
  77932. accordingly. inflate() provides as much output as possible, until there
  77933. is no more input data or no more space in the output buffer (see below
  77934. about the flush parameter).
  77935. Before the call of inflate(), the application should ensure that at least
  77936. one of the actions is possible, by providing more input and/or consuming
  77937. more output, and updating the next_* and avail_* values accordingly.
  77938. The application can consume the uncompressed output when it wants, for
  77939. example when the output buffer is full (avail_out == 0), or after each
  77940. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  77941. must be called again after making room in the output buffer because there
  77942. might be more output pending.
  77943. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  77944. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  77945. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  77946. if and when it gets to the next deflate block boundary. When decoding the
  77947. zlib or gzip format, this will cause inflate() to return immediately after
  77948. the header and before the first block. When doing a raw inflate, inflate()
  77949. will go ahead and process the first block, and will return when it gets to
  77950. the end of that block, or when it runs out of data.
  77951. The Z_BLOCK option assists in appending to or combining deflate streams.
  77952. Also to assist in this, on return inflate() will set strm->data_type to the
  77953. number of unused bits in the last byte taken from strm->next_in, plus 64
  77954. if inflate() is currently decoding the last block in the deflate stream,
  77955. plus 128 if inflate() returned immediately after decoding an end-of-block
  77956. code or decoding the complete header up to just before the first byte of the
  77957. deflate stream. The end-of-block will not be indicated until all of the
  77958. uncompressed data from that block has been written to strm->next_out. The
  77959. number of unused bits may in general be greater than seven, except when
  77960. bit 7 of data_type is set, in which case the number of unused bits will be
  77961. less than eight.
  77962. inflate() should normally be called until it returns Z_STREAM_END or an
  77963. error. However if all decompression is to be performed in a single step
  77964. (a single call of inflate), the parameter flush should be set to
  77965. Z_FINISH. In this case all pending input is processed and all pending
  77966. output is flushed; avail_out must be large enough to hold all the
  77967. uncompressed data. (The size of the uncompressed data may have been saved
  77968. by the compressor for this purpose.) The next operation on this stream must
  77969. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  77970. is never required, but can be used to inform inflate that a faster approach
  77971. may be used for the single inflate() call.
  77972. In this implementation, inflate() always flushes as much output as
  77973. possible to the output buffer, and always uses the faster approach on the
  77974. first call. So the only effect of the flush parameter in this implementation
  77975. is on the return value of inflate(), as noted below, or when it returns early
  77976. because Z_BLOCK is used.
  77977. If a preset dictionary is needed after this call (see inflateSetDictionary
  77978. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  77979. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  77980. strm->adler to the adler32 checksum of all output produced so far (that is,
  77981. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  77982. below. At the end of the stream, inflate() checks that its computed adler32
  77983. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  77984. only if the checksum is correct.
  77985. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  77986. deflate data. The header type is detected automatically. Any information
  77987. contained in the gzip header is not retained, so applications that need that
  77988. information should instead use raw inflate, see inflateInit2() below, or
  77989. inflateBack() and perform their own processing of the gzip header and
  77990. trailer.
  77991. inflate() returns Z_OK if some progress has been made (more input processed
  77992. or more output produced), Z_STREAM_END if the end of the compressed data has
  77993. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  77994. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  77995. corrupted (input stream not conforming to the zlib format or incorrect check
  77996. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  77997. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  77998. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  77999. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78000. inflate() can be called again with more input and more output space to
  78001. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78002. call inflateSync() to look for a good compression block if a partial recovery
  78003. of the data is desired.
  78004. */
  78005. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78006. /*
  78007. All dynamically allocated data structures for this stream are freed.
  78008. This function discards any unprocessed input and does not flush any
  78009. pending output.
  78010. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78011. was inconsistent. In the error case, msg may be set but then points to a
  78012. static string (which must not be deallocated).
  78013. */
  78014. /* Advanced functions */
  78015. /*
  78016. The following functions are needed only in some special applications.
  78017. */
  78018. /*
  78019. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78020. int level,
  78021. int method,
  78022. int windowBits,
  78023. int memLevel,
  78024. int strategy));
  78025. This is another version of deflateInit with more compression options. The
  78026. fields next_in, zalloc, zfree and opaque must be initialized before by
  78027. the caller.
  78028. The method parameter is the compression method. It must be Z_DEFLATED in
  78029. this version of the library.
  78030. The windowBits parameter is the base two logarithm of the window size
  78031. (the size of the history buffer). It should be in the range 8..15 for this
  78032. version of the library. Larger values of this parameter result in better
  78033. compression at the expense of memory usage. The default value is 15 if
  78034. deflateInit is used instead.
  78035. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78036. determines the window size. deflate() will then generate raw deflate data
  78037. with no zlib header or trailer, and will not compute an adler32 check value.
  78038. windowBits can also be greater than 15 for optional gzip encoding. Add
  78039. 16 to windowBits to write a simple gzip header and trailer around the
  78040. compressed data instead of a zlib wrapper. The gzip header will have no
  78041. file name, no extra data, no comment, no modification time (set to zero),
  78042. no header crc, and the operating system will be set to 255 (unknown). If a
  78043. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78044. The memLevel parameter specifies how much memory should be allocated
  78045. for the internal compression state. memLevel=1 uses minimum memory but
  78046. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78047. for optimal speed. The default value is 8. See zconf.h for total memory
  78048. usage as a function of windowBits and memLevel.
  78049. The strategy parameter is used to tune the compression algorithm. Use the
  78050. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78051. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78052. string match), or Z_RLE to limit match distances to one (run-length
  78053. encoding). Filtered data consists mostly of small values with a somewhat
  78054. random distribution. In this case, the compression algorithm is tuned to
  78055. compress them better. The effect of Z_FILTERED is to force more Huffman
  78056. coding and less string matching; it is somewhat intermediate between
  78057. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78058. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78059. parameter only affects the compression ratio but not the correctness of the
  78060. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78061. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78062. applications.
  78063. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78064. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78065. method). msg is set to null if there is no error message. deflateInit2 does
  78066. not perform any compression: this will be done by deflate().
  78067. */
  78068. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78069. const Bytef *dictionary,
  78070. uInt dictLength));
  78071. /*
  78072. Initializes the compression dictionary from the given byte sequence
  78073. without producing any compressed output. This function must be called
  78074. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78075. call of deflate. The compressor and decompressor must use exactly the same
  78076. dictionary (see inflateSetDictionary).
  78077. The dictionary should consist of strings (byte sequences) that are likely
  78078. to be encountered later in the data to be compressed, with the most commonly
  78079. used strings preferably put towards the end of the dictionary. Using a
  78080. dictionary is most useful when the data to be compressed is short and can be
  78081. predicted with good accuracy; the data can then be compressed better than
  78082. with the default empty dictionary.
  78083. Depending on the size of the compression data structures selected by
  78084. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78085. discarded, for example if the dictionary is larger than the window size in
  78086. deflate or deflate2. Thus the strings most likely to be useful should be
  78087. put at the end of the dictionary, not at the front. In addition, the
  78088. current implementation of deflate will use at most the window size minus
  78089. 262 bytes of the provided dictionary.
  78090. Upon return of this function, strm->adler is set to the adler32 value
  78091. of the dictionary; the decompressor may later use this value to determine
  78092. which dictionary has been used by the compressor. (The adler32 value
  78093. applies to the whole dictionary even if only a subset of the dictionary is
  78094. actually used by the compressor.) If a raw deflate was requested, then the
  78095. adler32 value is not computed and strm->adler is not set.
  78096. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78097. parameter is invalid (such as NULL dictionary) or the stream state is
  78098. inconsistent (for example if deflate has already been called for this stream
  78099. or if the compression method is bsort). deflateSetDictionary does not
  78100. perform any compression: this will be done by deflate().
  78101. */
  78102. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78103. z_streamp source));
  78104. /*
  78105. Sets the destination stream as a complete copy of the source stream.
  78106. This function can be useful when several compression strategies will be
  78107. tried, for example when there are several ways of pre-processing the input
  78108. data with a filter. The streams that will be discarded should then be freed
  78109. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78110. compression state which can be quite large, so this strategy is slow and
  78111. can consume lots of memory.
  78112. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78113. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78114. (such as zalloc being NULL). msg is left unchanged in both source and
  78115. destination.
  78116. */
  78117. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78118. /*
  78119. This function is equivalent to deflateEnd followed by deflateInit,
  78120. but does not free and reallocate all the internal compression state.
  78121. The stream will keep the same compression level and any other attributes
  78122. that may have been set by deflateInit2.
  78123. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78124. stream state was inconsistent (such as zalloc or state being NULL).
  78125. */
  78126. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78127. int level,
  78128. int strategy));
  78129. /*
  78130. Dynamically update the compression level and compression strategy. The
  78131. interpretation of level and strategy is as in deflateInit2. This can be
  78132. used to switch between compression and straight copy of the input data, or
  78133. to switch to a different kind of input data requiring a different
  78134. strategy. If the compression level is changed, the input available so far
  78135. is compressed with the old level (and may be flushed); the new level will
  78136. take effect only at the next call of deflate().
  78137. Before the call of deflateParams, the stream state must be set as for
  78138. a call of deflate(), since the currently available input may have to
  78139. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78140. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78141. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78142. if strm->avail_out was zero.
  78143. */
  78144. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78145. int good_length,
  78146. int max_lazy,
  78147. int nice_length,
  78148. int max_chain));
  78149. /*
  78150. Fine tune deflate's internal compression parameters. This should only be
  78151. used by someone who understands the algorithm used by zlib's deflate for
  78152. searching for the best matching string, and even then only by the most
  78153. fanatic optimizer trying to squeeze out the last compressed bit for their
  78154. specific input data. Read the deflate.c source code for the meaning of the
  78155. max_lazy, good_length, nice_length, and max_chain parameters.
  78156. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78157. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78158. */
  78159. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78160. uLong sourceLen));
  78161. /*
  78162. deflateBound() returns an upper bound on the compressed size after
  78163. deflation of sourceLen bytes. It must be called after deflateInit()
  78164. or deflateInit2(). This would be used to allocate an output buffer
  78165. for deflation in a single pass, and so would be called before deflate().
  78166. */
  78167. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78168. int bits,
  78169. int value));
  78170. /*
  78171. deflatePrime() inserts bits in the deflate output stream. The intent
  78172. is that this function is used to start off the deflate output with the
  78173. bits leftover from a previous deflate stream when appending to it. As such,
  78174. this function can only be used for raw deflate, and must be used before the
  78175. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78176. less than or equal to 16, and that many of the least significant bits of
  78177. value will be inserted in the output.
  78178. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78179. stream state was inconsistent.
  78180. */
  78181. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78182. gz_headerp head));
  78183. /*
  78184. deflateSetHeader() provides gzip header information for when a gzip
  78185. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78186. after deflateInit2() or deflateReset() and before the first call of
  78187. deflate(). The text, time, os, extra field, name, and comment information
  78188. in the provided gz_header structure are written to the gzip header (xflag is
  78189. ignored -- the extra flags are set according to the compression level). The
  78190. caller must assure that, if not Z_NULL, name and comment are terminated with
  78191. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78192. available there. If hcrc is true, a gzip header crc is included. Note that
  78193. the current versions of the command-line version of gzip (up through version
  78194. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78195. gzip file" and give up.
  78196. If deflateSetHeader is not used, the default gzip header has text false,
  78197. the time set to zero, and os set to 255, with no extra, name, or comment
  78198. fields. The gzip header is returned to the default state by deflateReset().
  78199. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78200. stream state was inconsistent.
  78201. */
  78202. /*
  78203. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78204. int windowBits));
  78205. This is another version of inflateInit with an extra parameter. The
  78206. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78207. before by the caller.
  78208. The windowBits parameter is the base two logarithm of the maximum window
  78209. size (the size of the history buffer). It should be in the range 8..15 for
  78210. this version of the library. The default value is 15 if inflateInit is used
  78211. instead. windowBits must be greater than or equal to the windowBits value
  78212. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78213. deflateInit2() was not used. If a compressed stream with a larger window
  78214. size is given as input, inflate() will return with the error code
  78215. Z_DATA_ERROR instead of trying to allocate a larger window.
  78216. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78217. determines the window size. inflate() will then process raw deflate data,
  78218. not looking for a zlib or gzip header, not generating a check value, and not
  78219. looking for any check values for comparison at the end of the stream. This
  78220. is for use with other formats that use the deflate compressed data format
  78221. such as zip. Those formats provide their own check values. If a custom
  78222. format is developed using the raw deflate format for compressed data, it is
  78223. recommended that a check value such as an adler32 or a crc32 be applied to
  78224. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78225. most applications, the zlib format should be used as is. Note that comments
  78226. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78227. windowBits can also be greater than 15 for optional gzip decoding. Add
  78228. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78229. detection, or add 16 to decode only the gzip format (the zlib format will
  78230. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78231. a crc32 instead of an adler32.
  78232. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78233. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78234. is set to null if there is no error message. inflateInit2 does not perform
  78235. any decompression apart from reading the zlib header if present: this will
  78236. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78237. and avail_out are unchanged.)
  78238. */
  78239. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78240. const Bytef *dictionary,
  78241. uInt dictLength));
  78242. /*
  78243. Initializes the decompression dictionary from the given uncompressed byte
  78244. sequence. This function must be called immediately after a call of inflate,
  78245. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78246. can be determined from the adler32 value returned by that call of inflate.
  78247. The compressor and decompressor must use exactly the same dictionary (see
  78248. deflateSetDictionary). For raw inflate, this function can be called
  78249. immediately after inflateInit2() or inflateReset() and before any call of
  78250. inflate() to set the dictionary. The application must insure that the
  78251. dictionary that was used for compression is provided.
  78252. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78253. parameter is invalid (such as NULL dictionary) or the stream state is
  78254. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78255. expected one (incorrect adler32 value). inflateSetDictionary does not
  78256. perform any decompression: this will be done by subsequent calls of
  78257. inflate().
  78258. */
  78259. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78260. /*
  78261. Skips invalid compressed data until a full flush point (see above the
  78262. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78263. available input is skipped. No output is provided.
  78264. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78265. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78266. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78267. case, the application may save the current current value of total_in which
  78268. indicates where valid compressed data was found. In the error case, the
  78269. application may repeatedly call inflateSync, providing more input each time,
  78270. until success or end of the input data.
  78271. */
  78272. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78273. z_streamp source));
  78274. /*
  78275. Sets the destination stream as a complete copy of the source stream.
  78276. This function can be useful when randomly accessing a large stream. The
  78277. first pass through the stream can periodically record the inflate state,
  78278. allowing restarting inflate at those points when randomly accessing the
  78279. stream.
  78280. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78281. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78282. (such as zalloc being NULL). msg is left unchanged in both source and
  78283. destination.
  78284. */
  78285. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78286. /*
  78287. This function is equivalent to inflateEnd followed by inflateInit,
  78288. but does not free and reallocate all the internal decompression state.
  78289. The stream will keep attributes that may have been set by inflateInit2.
  78290. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78291. stream state was inconsistent (such as zalloc or state being NULL).
  78292. */
  78293. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78294. int bits,
  78295. int value));
  78296. /*
  78297. This function inserts bits in the inflate input stream. The intent is
  78298. that this function is used to start inflating at a bit position in the
  78299. middle of a byte. The provided bits will be used before any bytes are used
  78300. from next_in. This function should only be used with raw inflate, and
  78301. should be used before the first inflate() call after inflateInit2() or
  78302. inflateReset(). bits must be less than or equal to 16, and that many of the
  78303. least significant bits of value will be inserted in the input.
  78304. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78305. stream state was inconsistent.
  78306. */
  78307. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78308. gz_headerp head));
  78309. /*
  78310. inflateGetHeader() requests that gzip header information be stored in the
  78311. provided gz_header structure. inflateGetHeader() may be called after
  78312. inflateInit2() or inflateReset(), and before the first call of inflate().
  78313. As inflate() processes the gzip stream, head->done is zero until the header
  78314. is completed, at which time head->done is set to one. If a zlib stream is
  78315. being decoded, then head->done is set to -1 to indicate that there will be
  78316. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78317. force inflate() to return immediately after header processing is complete
  78318. and before any actual data is decompressed.
  78319. The text, time, xflags, and os fields are filled in with the gzip header
  78320. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78321. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78322. contains the maximum number of bytes to write to extra. Once done is true,
  78323. extra_len contains the actual extra field length, and extra contains the
  78324. extra field, or that field truncated if extra_max is less than extra_len.
  78325. If name is not Z_NULL, then up to name_max characters are written there,
  78326. terminated with a zero unless the length is greater than name_max. If
  78327. comment is not Z_NULL, then up to comm_max characters are written there,
  78328. terminated with a zero unless the length is greater than comm_max. When
  78329. any of extra, name, or comment are not Z_NULL and the respective field is
  78330. not present in the header, then that field is set to Z_NULL to signal its
  78331. absence. This allows the use of deflateSetHeader() with the returned
  78332. structure to duplicate the header. However if those fields are set to
  78333. allocated memory, then the application will need to save those pointers
  78334. elsewhere so that they can be eventually freed.
  78335. If inflateGetHeader is not used, then the header information is simply
  78336. discarded. The header is always checked for validity, including the header
  78337. CRC if present. inflateReset() will reset the process to discard the header
  78338. information. The application would need to call inflateGetHeader() again to
  78339. retrieve the header from the next gzip stream.
  78340. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78341. stream state was inconsistent.
  78342. */
  78343. /*
  78344. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78345. unsigned char FAR *window));
  78346. Initialize the internal stream state for decompression using inflateBack()
  78347. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78348. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78349. derived memory allocation routines are used. windowBits is the base two
  78350. logarithm of the window size, in the range 8..15. window is a caller
  78351. supplied buffer of that size. Except for special applications where it is
  78352. assured that deflate was used with small window sizes, windowBits must be 15
  78353. and a 32K byte window must be supplied to be able to decompress general
  78354. deflate streams.
  78355. See inflateBack() for the usage of these routines.
  78356. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78357. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78358. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78359. match the version of the header file.
  78360. */
  78361. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78362. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78363. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78364. in_func in, void FAR *in_desc,
  78365. out_func out, void FAR *out_desc));
  78366. /*
  78367. inflateBack() does a raw inflate with a single call using a call-back
  78368. interface for input and output. This is more efficient than inflate() for
  78369. file i/o applications in that it avoids copying between the output and the
  78370. sliding window by simply making the window itself the output buffer. This
  78371. function trusts the application to not change the output buffer passed by
  78372. the output function, at least until inflateBack() returns.
  78373. inflateBackInit() must be called first to allocate the internal state
  78374. and to initialize the state with the user-provided window buffer.
  78375. inflateBack() may then be used multiple times to inflate a complete, raw
  78376. deflate stream with each call. inflateBackEnd() is then called to free
  78377. the allocated state.
  78378. A raw deflate stream is one with no zlib or gzip header or trailer.
  78379. This routine would normally be used in a utility that reads zip or gzip
  78380. files and writes out uncompressed files. The utility would decode the
  78381. header and process the trailer on its own, hence this routine expects
  78382. only the raw deflate stream to decompress. This is different from the
  78383. normal behavior of inflate(), which expects either a zlib or gzip header and
  78384. trailer around the deflate stream.
  78385. inflateBack() uses two subroutines supplied by the caller that are then
  78386. called by inflateBack() for input and output. inflateBack() calls those
  78387. routines until it reads a complete deflate stream and writes out all of the
  78388. uncompressed data, or until it encounters an error. The function's
  78389. parameters and return types are defined above in the in_func and out_func
  78390. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78391. number of bytes of provided input, and a pointer to that input in buf. If
  78392. there is no input available, in() must return zero--buf is ignored in that
  78393. case--and inflateBack() will return a buffer error. inflateBack() will call
  78394. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78395. should return zero on success, or non-zero on failure. If out() returns
  78396. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78397. are permitted to change the contents of the window provided to
  78398. inflateBackInit(), which is also the buffer that out() uses to write from.
  78399. The length written by out() will be at most the window size. Any non-zero
  78400. amount of input may be provided by in().
  78401. For convenience, inflateBack() can be provided input on the first call by
  78402. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78403. in() will be called. Therefore strm->next_in must be initialized before
  78404. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78405. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78406. must also be initialized, and then if strm->avail_in is not zero, input will
  78407. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78408. The in_desc and out_desc parameters of inflateBack() is passed as the
  78409. first parameter of in() and out() respectively when they are called. These
  78410. descriptors can be optionally used to pass any information that the caller-
  78411. supplied in() and out() functions need to do their job.
  78412. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78413. pass back any unused input that was provided by the last in() call. The
  78414. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78415. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78416. error in the deflate stream (in which case strm->msg is set to indicate the
  78417. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78418. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78419. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78420. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78421. out() returning non-zero. (in() will always be called before out(), so
  78422. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78423. that inflateBack() cannot return Z_OK.
  78424. */
  78425. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78426. /*
  78427. All memory allocated by inflateBackInit() is freed.
  78428. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78429. state was inconsistent.
  78430. */
  78431. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78432. /* Return flags indicating compile-time options.
  78433. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78434. 1.0: size of uInt
  78435. 3.2: size of uLong
  78436. 5.4: size of voidpf (pointer)
  78437. 7.6: size of z_off_t
  78438. Compiler, assembler, and debug options:
  78439. 8: DEBUG
  78440. 9: ASMV or ASMINF -- use ASM code
  78441. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78442. 11: 0 (reserved)
  78443. One-time table building (smaller code, but not thread-safe if true):
  78444. 12: BUILDFIXED -- build static block decoding tables when needed
  78445. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78446. 14,15: 0 (reserved)
  78447. Library content (indicates missing functionality):
  78448. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78449. deflate code when not needed)
  78450. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78451. and decode gzip streams (to avoid linking crc code)
  78452. 18-19: 0 (reserved)
  78453. Operation variations (changes in library functionality):
  78454. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78455. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78456. 22,23: 0 (reserved)
  78457. The sprintf variant used by gzprintf (zero is best):
  78458. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78459. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78460. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78461. Remainder:
  78462. 27-31: 0 (reserved)
  78463. */
  78464. /* utility functions */
  78465. /*
  78466. The following utility functions are implemented on top of the
  78467. basic stream-oriented functions. To simplify the interface, some
  78468. default options are assumed (compression level and memory usage,
  78469. standard memory allocation functions). The source code of these
  78470. utility functions can easily be modified if you need special options.
  78471. */
  78472. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78473. const Bytef *source, uLong sourceLen));
  78474. /*
  78475. Compresses the source buffer into the destination buffer. sourceLen is
  78476. the byte length of the source buffer. Upon entry, destLen is the total
  78477. size of the destination buffer, which must be at least the value returned
  78478. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78479. compressed buffer.
  78480. This function can be used to compress a whole file at once if the
  78481. input file is mmap'ed.
  78482. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78483. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78484. buffer.
  78485. */
  78486. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78487. const Bytef *source, uLong sourceLen,
  78488. int level));
  78489. /*
  78490. Compresses the source buffer into the destination buffer. The level
  78491. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78492. length of the source buffer. Upon entry, destLen is the total size of the
  78493. destination buffer, which must be at least the value returned by
  78494. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78495. compressed buffer.
  78496. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78497. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78498. Z_STREAM_ERROR if the level parameter is invalid.
  78499. */
  78500. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78501. /*
  78502. compressBound() returns an upper bound on the compressed size after
  78503. compress() or compress2() on sourceLen bytes. It would be used before
  78504. a compress() or compress2() call to allocate the destination buffer.
  78505. */
  78506. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78507. const Bytef *source, uLong sourceLen));
  78508. /*
  78509. Decompresses the source buffer into the destination buffer. sourceLen is
  78510. the byte length of the source buffer. Upon entry, destLen is the total
  78511. size of the destination buffer, which must be large enough to hold the
  78512. entire uncompressed data. (The size of the uncompressed data must have
  78513. been saved previously by the compressor and transmitted to the decompressor
  78514. by some mechanism outside the scope of this compression library.)
  78515. Upon exit, destLen is the actual size of the compressed buffer.
  78516. This function can be used to decompress a whole file at once if the
  78517. input file is mmap'ed.
  78518. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78519. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78520. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78521. */
  78522. typedef voidp gzFile;
  78523. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78524. /*
  78525. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78526. is as in fopen ("rb" or "wb") but can also include a compression level
  78527. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78528. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78529. as in "wb1R". (See the description of deflateInit2 for more information
  78530. about the strategy parameter.)
  78531. gzopen can be used to read a file which is not in gzip format; in this
  78532. case gzread will directly read from the file without decompression.
  78533. gzopen returns NULL if the file could not be opened or if there was
  78534. insufficient memory to allocate the (de)compression state; errno
  78535. can be checked to distinguish the two cases (if errno is zero, the
  78536. zlib error is Z_MEM_ERROR). */
  78537. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78538. /*
  78539. gzdopen() associates a gzFile with the file descriptor fd. File
  78540. descriptors are obtained from calls like open, dup, creat, pipe or
  78541. fileno (in the file has been previously opened with fopen).
  78542. The mode parameter is as in gzopen.
  78543. The next call of gzclose on the returned gzFile will also close the
  78544. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78545. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78546. gzdopen returns NULL if there was insufficient memory to allocate
  78547. the (de)compression state.
  78548. */
  78549. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78550. /*
  78551. Dynamically update the compression level or strategy. See the description
  78552. of deflateInit2 for the meaning of these parameters.
  78553. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78554. opened for writing.
  78555. */
  78556. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78557. /*
  78558. Reads the given number of uncompressed bytes from the compressed file.
  78559. If the input file was not in gzip format, gzread copies the given number
  78560. of bytes into the buffer.
  78561. gzread returns the number of uncompressed bytes actually read (0 for
  78562. end of file, -1 for error). */
  78563. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78564. voidpc buf, unsigned len));
  78565. /*
  78566. Writes the given number of uncompressed bytes into the compressed file.
  78567. gzwrite returns the number of uncompressed bytes actually written
  78568. (0 in case of error).
  78569. */
  78570. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78571. /*
  78572. Converts, formats, and writes the args to the compressed file under
  78573. control of the format string, as in fprintf. gzprintf returns the number of
  78574. uncompressed bytes actually written (0 in case of error). The number of
  78575. uncompressed bytes written is limited to 4095. The caller should assure that
  78576. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78577. return an error (0) with nothing written. In this case, there may also be a
  78578. buffer overflow with unpredictable consequences, which is possible only if
  78579. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78580. because the secure snprintf() or vsnprintf() functions were not available.
  78581. */
  78582. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78583. /*
  78584. Writes the given null-terminated string to the compressed file, excluding
  78585. the terminating null character.
  78586. gzputs returns the number of characters written, or -1 in case of error.
  78587. */
  78588. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78589. /*
  78590. Reads bytes from the compressed file until len-1 characters are read, or
  78591. a newline character is read and transferred to buf, or an end-of-file
  78592. condition is encountered. The string is then terminated with a null
  78593. character.
  78594. gzgets returns buf, or Z_NULL in case of error.
  78595. */
  78596. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78597. /*
  78598. Writes c, converted to an unsigned char, into the compressed file.
  78599. gzputc returns the value that was written, or -1 in case of error.
  78600. */
  78601. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78602. /*
  78603. Reads one byte from the compressed file. gzgetc returns this byte
  78604. or -1 in case of end of file or error.
  78605. */
  78606. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78607. /*
  78608. Push one character back onto the stream to be read again later.
  78609. Only one character of push-back is allowed. gzungetc() returns the
  78610. character pushed, or -1 on failure. gzungetc() will fail if a
  78611. character has been pushed but not read yet, or if c is -1. The pushed
  78612. character will be discarded if the stream is repositioned with gzseek()
  78613. or gzrewind().
  78614. */
  78615. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78616. /*
  78617. Flushes all pending output into the compressed file. The parameter
  78618. flush is as in the deflate() function. The return value is the zlib
  78619. error number (see function gzerror below). gzflush returns Z_OK if
  78620. the flush parameter is Z_FINISH and all output could be flushed.
  78621. gzflush should be called only when strictly necessary because it can
  78622. degrade compression.
  78623. */
  78624. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78625. z_off_t offset, int whence));
  78626. /*
  78627. Sets the starting position for the next gzread or gzwrite on the
  78628. given compressed file. The offset represents a number of bytes in the
  78629. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78630. the value SEEK_END is not supported.
  78631. If the file is opened for reading, this function is emulated but can be
  78632. extremely slow. If the file is opened for writing, only forward seeks are
  78633. supported; gzseek then compresses a sequence of zeroes up to the new
  78634. starting position.
  78635. gzseek returns the resulting offset location as measured in bytes from
  78636. the beginning of the uncompressed stream, or -1 in case of error, in
  78637. particular if the file is opened for writing and the new starting position
  78638. would be before the current position.
  78639. */
  78640. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78641. /*
  78642. Rewinds the given file. This function is supported only for reading.
  78643. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78644. */
  78645. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78646. /*
  78647. Returns the starting position for the next gzread or gzwrite on the
  78648. given compressed file. This position represents a number of bytes in the
  78649. uncompressed data stream.
  78650. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78651. */
  78652. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78653. /*
  78654. Returns 1 when EOF has previously been detected reading the given
  78655. input stream, otherwise zero.
  78656. */
  78657. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78658. /*
  78659. Returns 1 if file is being read directly without decompression, otherwise
  78660. zero.
  78661. */
  78662. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78663. /*
  78664. Flushes all pending output if necessary, closes the compressed file
  78665. and deallocates all the (de)compression state. The return value is the zlib
  78666. error number (see function gzerror below).
  78667. */
  78668. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78669. /*
  78670. Returns the error message for the last error which occurred on the
  78671. given compressed file. errnum is set to zlib error number. If an
  78672. error occurred in the file system and not in the compression library,
  78673. errnum is set to Z_ERRNO and the application may consult errno
  78674. to get the exact error code.
  78675. */
  78676. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78677. /*
  78678. Clears the error and end-of-file flags for file. This is analogous to the
  78679. clearerr() function in stdio. This is useful for continuing to read a gzip
  78680. file that is being written concurrently.
  78681. */
  78682. /* checksum functions */
  78683. /*
  78684. These functions are not related to compression but are exported
  78685. anyway because they might be useful in applications using the
  78686. compression library.
  78687. */
  78688. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78689. /*
  78690. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78691. return the updated checksum. If buf is NULL, this function returns
  78692. the required initial value for the checksum.
  78693. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78694. much faster. Usage example:
  78695. uLong adler = adler32(0L, Z_NULL, 0);
  78696. while (read_buffer(buffer, length) != EOF) {
  78697. adler = adler32(adler, buffer, length);
  78698. }
  78699. if (adler != original_adler) error();
  78700. */
  78701. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78702. z_off_t len2));
  78703. /*
  78704. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78705. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78706. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78707. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78708. */
  78709. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78710. /*
  78711. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78712. updated CRC-32. If buf is NULL, this function returns the required initial
  78713. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78714. performed within this function so it shouldn't be done by the application.
  78715. Usage example:
  78716. uLong crc = crc32(0L, Z_NULL, 0);
  78717. while (read_buffer(buffer, length) != EOF) {
  78718. crc = crc32(crc, buffer, length);
  78719. }
  78720. if (crc != original_crc) error();
  78721. */
  78722. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78723. /*
  78724. Combine two CRC-32 check values into one. For two sequences of bytes,
  78725. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78726. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78727. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78728. len2.
  78729. */
  78730. /* various hacks, don't look :) */
  78731. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78732. * and the compiler's view of z_stream:
  78733. */
  78734. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78735. const char *version, int stream_size));
  78736. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78737. const char *version, int stream_size));
  78738. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78739. int windowBits, int memLevel,
  78740. int strategy, const char *version,
  78741. int stream_size));
  78742. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78743. const char *version, int stream_size));
  78744. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78745. unsigned char FAR *window,
  78746. const char *version,
  78747. int stream_size));
  78748. #define deflateInit(strm, level) \
  78749. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78750. #define inflateInit(strm) \
  78751. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78752. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78753. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78754. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78755. #define inflateInit2(strm, windowBits) \
  78756. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78757. #define inflateBackInit(strm, windowBits, window) \
  78758. inflateBackInit_((strm), (windowBits), (window), \
  78759. ZLIB_VERSION, sizeof(z_stream))
  78760. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78761. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78762. #endif
  78763. ZEXTERN const char * ZEXPORT zError OF((int));
  78764. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78765. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78766. #ifdef __cplusplus
  78767. }
  78768. #endif
  78769. #endif /* ZLIB_H */
  78770. /*** End of inlined file: zlib.h ***/
  78771. #undef OS_CODE
  78772. #else
  78773. #include <zlib.h>
  78774. #endif
  78775. }
  78776. BEGIN_JUCE_NAMESPACE
  78777. // internal helper object that holds the zlib structures so they don't have to be
  78778. // included publicly.
  78779. class GZIPCompressorHelper
  78780. {
  78781. public:
  78782. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78783. : data (0),
  78784. dataSize (0),
  78785. compLevel (compressionLevel),
  78786. strategy (0),
  78787. setParams (true),
  78788. streamIsValid (false),
  78789. finished (false),
  78790. shouldFinish (false)
  78791. {
  78792. using namespace zlibNamespace;
  78793. zerostruct (stream);
  78794. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78795. nowrap ? -MAX_WBITS : MAX_WBITS,
  78796. 8, strategy) == Z_OK);
  78797. }
  78798. ~GZIPCompressorHelper()
  78799. {
  78800. using namespace zlibNamespace;
  78801. if (streamIsValid)
  78802. deflateEnd (&stream);
  78803. }
  78804. bool needsInput() const throw()
  78805. {
  78806. return dataSize <= 0;
  78807. }
  78808. void setInput (const uint8* const newData, const int size) throw()
  78809. {
  78810. data = newData;
  78811. dataSize = size;
  78812. }
  78813. int doNextBlock (uint8* const dest, const int destSize) throw()
  78814. {
  78815. using namespace zlibNamespace;
  78816. if (streamIsValid)
  78817. {
  78818. stream.next_in = const_cast <uint8*> (data);
  78819. stream.next_out = dest;
  78820. stream.avail_in = dataSize;
  78821. stream.avail_out = destSize;
  78822. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  78823. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  78824. setParams = false;
  78825. switch (result)
  78826. {
  78827. case Z_STREAM_END:
  78828. finished = true;
  78829. // Deliberate fall-through..
  78830. case Z_OK:
  78831. data += dataSize - stream.avail_in;
  78832. dataSize = stream.avail_in;
  78833. return destSize - stream.avail_out;
  78834. default:
  78835. break;
  78836. }
  78837. }
  78838. return 0;
  78839. }
  78840. private:
  78841. zlibNamespace::z_stream stream;
  78842. const uint8* data;
  78843. int dataSize, compLevel, strategy;
  78844. bool setParams, streamIsValid;
  78845. public:
  78846. bool finished, shouldFinish;
  78847. };
  78848. const int gzipCompBufferSize = 32768;
  78849. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  78850. int compressionLevel,
  78851. const bool deleteDestStream,
  78852. const bool noWrap)
  78853. : destStream (destStream_),
  78854. streamToDelete (deleteDestStream ? destStream_ : 0),
  78855. buffer (gzipCompBufferSize)
  78856. {
  78857. if (compressionLevel < 1 || compressionLevel > 9)
  78858. compressionLevel = -1;
  78859. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  78860. }
  78861. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  78862. {
  78863. flush();
  78864. }
  78865. void GZIPCompressorOutputStream::flush()
  78866. {
  78867. if (! helper->finished)
  78868. {
  78869. helper->shouldFinish = true;
  78870. while (! helper->finished)
  78871. doNextBlock();
  78872. }
  78873. destStream->flush();
  78874. }
  78875. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  78876. {
  78877. if (! helper->finished)
  78878. {
  78879. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  78880. while (! helper->needsInput())
  78881. {
  78882. if (! doNextBlock())
  78883. return false;
  78884. }
  78885. }
  78886. return true;
  78887. }
  78888. bool GZIPCompressorOutputStream::doNextBlock()
  78889. {
  78890. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  78891. if (len > 0)
  78892. return destStream->write (buffer, len);
  78893. else
  78894. return true;
  78895. }
  78896. int64 GZIPCompressorOutputStream::getPosition()
  78897. {
  78898. return destStream->getPosition();
  78899. }
  78900. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  78901. {
  78902. jassertfalse; // can't do it!
  78903. return false;
  78904. }
  78905. END_JUCE_NAMESPACE
  78906. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78907. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  78908. #if JUCE_MSVC
  78909. #pragma warning (push)
  78910. #pragma warning (disable: 4309 4305)
  78911. #endif
  78912. namespace zlibNamespace
  78913. {
  78914. #if JUCE_INCLUDE_ZLIB_CODE
  78915. extern "C"
  78916. {
  78917. #undef OS_CODE
  78918. #undef fdopen
  78919. #define ZLIB_INTERNAL
  78920. #define NO_DUMMY_DECL
  78921. /*** Start of inlined file: adler32.c ***/
  78922. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78923. #define ZLIB_INTERNAL
  78924. #define BASE 65521UL /* largest prime smaller than 65536 */
  78925. #define NMAX 5552
  78926. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  78927. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  78928. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  78929. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  78930. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  78931. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  78932. /* use NO_DIVIDE if your processor does not do division in hardware */
  78933. #ifdef NO_DIVIDE
  78934. # define MOD(a) \
  78935. do { \
  78936. if (a >= (BASE << 16)) a -= (BASE << 16); \
  78937. if (a >= (BASE << 15)) a -= (BASE << 15); \
  78938. if (a >= (BASE << 14)) a -= (BASE << 14); \
  78939. if (a >= (BASE << 13)) a -= (BASE << 13); \
  78940. if (a >= (BASE << 12)) a -= (BASE << 12); \
  78941. if (a >= (BASE << 11)) a -= (BASE << 11); \
  78942. if (a >= (BASE << 10)) a -= (BASE << 10); \
  78943. if (a >= (BASE << 9)) a -= (BASE << 9); \
  78944. if (a >= (BASE << 8)) a -= (BASE << 8); \
  78945. if (a >= (BASE << 7)) a -= (BASE << 7); \
  78946. if (a >= (BASE << 6)) a -= (BASE << 6); \
  78947. if (a >= (BASE << 5)) a -= (BASE << 5); \
  78948. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78949. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78950. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78951. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78952. if (a >= BASE) a -= BASE; \
  78953. } while (0)
  78954. # define MOD4(a) \
  78955. do { \
  78956. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78957. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78958. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78959. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78960. if (a >= BASE) a -= BASE; \
  78961. } while (0)
  78962. #else
  78963. # define MOD(a) a %= BASE
  78964. # define MOD4(a) a %= BASE
  78965. #endif
  78966. /* ========================================================================= */
  78967. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  78968. {
  78969. unsigned long sum2;
  78970. unsigned n;
  78971. /* split Adler-32 into component sums */
  78972. sum2 = (adler >> 16) & 0xffff;
  78973. adler &= 0xffff;
  78974. /* in case user likes doing a byte at a time, keep it fast */
  78975. if (len == 1) {
  78976. adler += buf[0];
  78977. if (adler >= BASE)
  78978. adler -= BASE;
  78979. sum2 += adler;
  78980. if (sum2 >= BASE)
  78981. sum2 -= BASE;
  78982. return adler | (sum2 << 16);
  78983. }
  78984. /* initial Adler-32 value (deferred check for len == 1 speed) */
  78985. if (buf == Z_NULL)
  78986. return 1L;
  78987. /* in case short lengths are provided, keep it somewhat fast */
  78988. if (len < 16) {
  78989. while (len--) {
  78990. adler += *buf++;
  78991. sum2 += adler;
  78992. }
  78993. if (adler >= BASE)
  78994. adler -= BASE;
  78995. MOD4(sum2); /* only added so many BASE's */
  78996. return adler | (sum2 << 16);
  78997. }
  78998. /* do length NMAX blocks -- requires just one modulo operation */
  78999. while (len >= NMAX) {
  79000. len -= NMAX;
  79001. n = NMAX / 16; /* NMAX is divisible by 16 */
  79002. do {
  79003. DO16(buf); /* 16 sums unrolled */
  79004. buf += 16;
  79005. } while (--n);
  79006. MOD(adler);
  79007. MOD(sum2);
  79008. }
  79009. /* do remaining bytes (less than NMAX, still just one modulo) */
  79010. if (len) { /* avoid modulos if none remaining */
  79011. while (len >= 16) {
  79012. len -= 16;
  79013. DO16(buf);
  79014. buf += 16;
  79015. }
  79016. while (len--) {
  79017. adler += *buf++;
  79018. sum2 += adler;
  79019. }
  79020. MOD(adler);
  79021. MOD(sum2);
  79022. }
  79023. /* return recombined sums */
  79024. return adler | (sum2 << 16);
  79025. }
  79026. /* ========================================================================= */
  79027. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79028. {
  79029. unsigned long sum1;
  79030. unsigned long sum2;
  79031. unsigned rem;
  79032. /* the derivation of this formula is left as an exercise for the reader */
  79033. rem = (unsigned)(len2 % BASE);
  79034. sum1 = adler1 & 0xffff;
  79035. sum2 = rem * sum1;
  79036. MOD(sum2);
  79037. sum1 += (adler2 & 0xffff) + BASE - 1;
  79038. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79039. if (sum1 > BASE) sum1 -= BASE;
  79040. if (sum1 > BASE) sum1 -= BASE;
  79041. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79042. if (sum2 > BASE) sum2 -= BASE;
  79043. return sum1 | (sum2 << 16);
  79044. }
  79045. /*** End of inlined file: adler32.c ***/
  79046. /*** Start of inlined file: compress.c ***/
  79047. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79048. #define ZLIB_INTERNAL
  79049. /* ===========================================================================
  79050. Compresses the source buffer into the destination buffer. The level
  79051. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79052. length of the source buffer. Upon entry, destLen is the total size of the
  79053. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79054. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79055. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79056. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79057. Z_STREAM_ERROR if the level parameter is invalid.
  79058. */
  79059. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79060. uLong sourceLen, int level)
  79061. {
  79062. z_stream stream;
  79063. int err;
  79064. stream.next_in = (Bytef*)source;
  79065. stream.avail_in = (uInt)sourceLen;
  79066. #ifdef MAXSEG_64K
  79067. /* Check for source > 64K on 16-bit machine: */
  79068. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79069. #endif
  79070. stream.next_out = dest;
  79071. stream.avail_out = (uInt)*destLen;
  79072. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79073. stream.zalloc = (alloc_func)0;
  79074. stream.zfree = (free_func)0;
  79075. stream.opaque = (voidpf)0;
  79076. err = deflateInit(&stream, level);
  79077. if (err != Z_OK) return err;
  79078. err = deflate(&stream, Z_FINISH);
  79079. if (err != Z_STREAM_END) {
  79080. deflateEnd(&stream);
  79081. return err == Z_OK ? Z_BUF_ERROR : err;
  79082. }
  79083. *destLen = stream.total_out;
  79084. err = deflateEnd(&stream);
  79085. return err;
  79086. }
  79087. /* ===========================================================================
  79088. */
  79089. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79090. {
  79091. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79092. }
  79093. /* ===========================================================================
  79094. If the default memLevel or windowBits for deflateInit() is changed, then
  79095. this function needs to be updated.
  79096. */
  79097. uLong ZEXPORT compressBound (uLong sourceLen)
  79098. {
  79099. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79100. }
  79101. /*** End of inlined file: compress.c ***/
  79102. #undef DO1
  79103. #undef DO8
  79104. /*** Start of inlined file: crc32.c ***/
  79105. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79106. /*
  79107. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79108. protection on the static variables used to control the first-use generation
  79109. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79110. first call get_crc_table() to initialize the tables before allowing more than
  79111. one thread to use crc32().
  79112. */
  79113. #ifdef MAKECRCH
  79114. # include <stdio.h>
  79115. # ifndef DYNAMIC_CRC_TABLE
  79116. # define DYNAMIC_CRC_TABLE
  79117. # endif /* !DYNAMIC_CRC_TABLE */
  79118. #endif /* MAKECRCH */
  79119. /*** Start of inlined file: zutil.h ***/
  79120. /* WARNING: this file should *not* be used by applications. It is
  79121. part of the implementation of the compression library and is
  79122. subject to change. Applications should only use zlib.h.
  79123. */
  79124. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79125. #ifndef ZUTIL_H
  79126. #define ZUTIL_H
  79127. #define ZLIB_INTERNAL
  79128. #ifdef STDC
  79129. # ifndef _WIN32_WCE
  79130. # include <stddef.h>
  79131. # endif
  79132. # include <string.h>
  79133. # include <stdlib.h>
  79134. #endif
  79135. #ifdef NO_ERRNO_H
  79136. # ifdef _WIN32_WCE
  79137. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79138. * errno. We define it as a global variable to simplify porting.
  79139. * Its value is always 0 and should not be used. We rename it to
  79140. * avoid conflict with other libraries that use the same workaround.
  79141. */
  79142. # define errno z_errno
  79143. # endif
  79144. extern int errno;
  79145. #else
  79146. # ifndef _WIN32_WCE
  79147. # include <errno.h>
  79148. # endif
  79149. #endif
  79150. #ifndef local
  79151. # define local static
  79152. #endif
  79153. /* compile with -Dlocal if your debugger can't find static symbols */
  79154. typedef unsigned char uch;
  79155. typedef uch FAR uchf;
  79156. typedef unsigned short ush;
  79157. typedef ush FAR ushf;
  79158. typedef unsigned long ulg;
  79159. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79160. /* (size given to avoid silly warnings with Visual C++) */
  79161. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79162. #define ERR_RETURN(strm,err) \
  79163. return (strm->msg = (char*)ERR_MSG(err), (err))
  79164. /* To be used only when the state is known to be valid */
  79165. /* common constants */
  79166. #ifndef DEF_WBITS
  79167. # define DEF_WBITS MAX_WBITS
  79168. #endif
  79169. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79170. #if MAX_MEM_LEVEL >= 8
  79171. # define DEF_MEM_LEVEL 8
  79172. #else
  79173. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79174. #endif
  79175. /* default memLevel */
  79176. #define STORED_BLOCK 0
  79177. #define STATIC_TREES 1
  79178. #define DYN_TREES 2
  79179. /* The three kinds of block type */
  79180. #define MIN_MATCH 3
  79181. #define MAX_MATCH 258
  79182. /* The minimum and maximum match lengths */
  79183. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79184. /* target dependencies */
  79185. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79186. # define OS_CODE 0x00
  79187. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79188. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79189. /* Allow compilation with ANSI keywords only enabled */
  79190. void _Cdecl farfree( void *block );
  79191. void *_Cdecl farmalloc( unsigned long nbytes );
  79192. # else
  79193. # include <alloc.h>
  79194. # endif
  79195. # else /* MSC or DJGPP */
  79196. # include <malloc.h>
  79197. # endif
  79198. #endif
  79199. #ifdef AMIGA
  79200. # define OS_CODE 0x01
  79201. #endif
  79202. #if defined(VAXC) || defined(VMS)
  79203. # define OS_CODE 0x02
  79204. # define F_OPEN(name, mode) \
  79205. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79206. #endif
  79207. #if defined(ATARI) || defined(atarist)
  79208. # define OS_CODE 0x05
  79209. #endif
  79210. #ifdef OS2
  79211. # define OS_CODE 0x06
  79212. # ifdef M_I86
  79213. #include <malloc.h>
  79214. # endif
  79215. #endif
  79216. #if defined(MACOS) || TARGET_OS_MAC
  79217. # define OS_CODE 0x07
  79218. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79219. # include <unix.h> /* for fdopen */
  79220. # else
  79221. # ifndef fdopen
  79222. # define fdopen(fd,mode) NULL /* No fdopen() */
  79223. # endif
  79224. # endif
  79225. #endif
  79226. #ifdef TOPS20
  79227. # define OS_CODE 0x0a
  79228. #endif
  79229. #ifdef WIN32
  79230. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79231. # define OS_CODE 0x0b
  79232. # endif
  79233. #endif
  79234. #ifdef __50SERIES /* Prime/PRIMOS */
  79235. # define OS_CODE 0x0f
  79236. #endif
  79237. #if defined(_BEOS_) || defined(RISCOS)
  79238. # define fdopen(fd,mode) NULL /* No fdopen() */
  79239. #endif
  79240. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79241. # if defined(_WIN32_WCE)
  79242. # define fdopen(fd,mode) NULL /* No fdopen() */
  79243. # ifndef _PTRDIFF_T_DEFINED
  79244. typedef int ptrdiff_t;
  79245. # define _PTRDIFF_T_DEFINED
  79246. # endif
  79247. # else
  79248. # define fdopen(fd,type) _fdopen(fd,type)
  79249. # endif
  79250. #endif
  79251. /* common defaults */
  79252. #ifndef OS_CODE
  79253. # define OS_CODE 0x03 /* assume Unix */
  79254. #endif
  79255. #ifndef F_OPEN
  79256. # define F_OPEN(name, mode) fopen((name), (mode))
  79257. #endif
  79258. /* functions */
  79259. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79260. # ifndef HAVE_VSNPRINTF
  79261. # define HAVE_VSNPRINTF
  79262. # endif
  79263. #endif
  79264. #if defined(__CYGWIN__)
  79265. # ifndef HAVE_VSNPRINTF
  79266. # define HAVE_VSNPRINTF
  79267. # endif
  79268. #endif
  79269. #ifndef HAVE_VSNPRINTF
  79270. # ifdef MSDOS
  79271. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79272. but for now we just assume it doesn't. */
  79273. # define NO_vsnprintf
  79274. # endif
  79275. # ifdef __TURBOC__
  79276. # define NO_vsnprintf
  79277. # endif
  79278. # ifdef WIN32
  79279. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79280. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79281. # define vsnprintf _vsnprintf
  79282. # endif
  79283. # endif
  79284. # ifdef __SASC
  79285. # define NO_vsnprintf
  79286. # endif
  79287. #endif
  79288. #ifdef VMS
  79289. # define NO_vsnprintf
  79290. #endif
  79291. #if defined(pyr)
  79292. # define NO_MEMCPY
  79293. #endif
  79294. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79295. /* Use our own functions for small and medium model with MSC <= 5.0.
  79296. * You may have to use the same strategy for Borland C (untested).
  79297. * The __SC__ check is for Symantec.
  79298. */
  79299. # define NO_MEMCPY
  79300. #endif
  79301. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79302. # define HAVE_MEMCPY
  79303. #endif
  79304. #ifdef HAVE_MEMCPY
  79305. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79306. # define zmemcpy _fmemcpy
  79307. # define zmemcmp _fmemcmp
  79308. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79309. # else
  79310. # define zmemcpy memcpy
  79311. # define zmemcmp memcmp
  79312. # define zmemzero(dest, len) memset(dest, 0, len)
  79313. # endif
  79314. #else
  79315. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79316. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79317. extern void zmemzero OF((Bytef* dest, uInt len));
  79318. #endif
  79319. /* Diagnostic functions */
  79320. #ifdef DEBUG
  79321. # include <stdio.h>
  79322. extern int z_verbose;
  79323. extern void z_error OF((const char *m));
  79324. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79325. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79326. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79327. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79328. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79329. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79330. #else
  79331. # define Assert(cond,msg)
  79332. # define Trace(x)
  79333. # define Tracev(x)
  79334. # define Tracevv(x)
  79335. # define Tracec(c,x)
  79336. # define Tracecv(c,x)
  79337. #endif
  79338. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79339. void zcfree OF((voidpf opaque, voidpf ptr));
  79340. #define ZALLOC(strm, items, size) \
  79341. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79342. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79343. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79344. #endif /* ZUTIL_H */
  79345. /*** End of inlined file: zutil.h ***/
  79346. /* for STDC and FAR definitions */
  79347. #define local static
  79348. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79349. #ifndef NOBYFOUR
  79350. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79351. # include <limits.h>
  79352. # define BYFOUR
  79353. # if (UINT_MAX == 0xffffffffUL)
  79354. typedef unsigned int u4;
  79355. # else
  79356. # if (ULONG_MAX == 0xffffffffUL)
  79357. typedef unsigned long u4;
  79358. # else
  79359. # if (USHRT_MAX == 0xffffffffUL)
  79360. typedef unsigned short u4;
  79361. # else
  79362. # undef BYFOUR /* can't find a four-byte integer type! */
  79363. # endif
  79364. # endif
  79365. # endif
  79366. # endif /* STDC */
  79367. #endif /* !NOBYFOUR */
  79368. /* Definitions for doing the crc four data bytes at a time. */
  79369. #ifdef BYFOUR
  79370. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79371. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79372. local unsigned long crc32_little OF((unsigned long,
  79373. const unsigned char FAR *, unsigned));
  79374. local unsigned long crc32_big OF((unsigned long,
  79375. const unsigned char FAR *, unsigned));
  79376. # define TBLS 8
  79377. #else
  79378. # define TBLS 1
  79379. #endif /* BYFOUR */
  79380. /* Local functions for crc concatenation */
  79381. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79382. unsigned long vec));
  79383. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79384. #ifdef DYNAMIC_CRC_TABLE
  79385. local volatile int crc_table_empty = 1;
  79386. local unsigned long FAR crc_table[TBLS][256];
  79387. local void make_crc_table OF((void));
  79388. #ifdef MAKECRCH
  79389. local void write_table OF((FILE *, const unsigned long FAR *));
  79390. #endif /* MAKECRCH */
  79391. /*
  79392. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79393. 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.
  79394. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79395. with the lowest powers in the most significant bit. Then adding polynomials
  79396. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79397. one. If we call the above polynomial p, and represent a byte as the
  79398. polynomial q, also with the lowest power in the most significant bit (so the
  79399. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79400. where a mod b means the remainder after dividing a by b.
  79401. This calculation is done using the shift-register method of multiplying and
  79402. taking the remainder. The register is initialized to zero, and for each
  79403. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79404. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79405. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79406. out is a one). We start with the highest power (least significant bit) of
  79407. q and repeat for all eight bits of q.
  79408. The first table is simply the CRC of all possible eight bit values. This is
  79409. all the information needed to generate CRCs on data a byte at a time for all
  79410. combinations of CRC register values and incoming bytes. The remaining tables
  79411. allow for word-at-a-time CRC calculation for both big-endian and little-
  79412. endian machines, where a word is four bytes.
  79413. */
  79414. local void make_crc_table()
  79415. {
  79416. unsigned long c;
  79417. int n, k;
  79418. unsigned long poly; /* polynomial exclusive-or pattern */
  79419. /* terms of polynomial defining this crc (except x^32): */
  79420. static volatile int first = 1; /* flag to limit concurrent making */
  79421. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79422. /* See if another task is already doing this (not thread-safe, but better
  79423. than nothing -- significantly reduces duration of vulnerability in
  79424. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79425. if (first) {
  79426. first = 0;
  79427. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79428. poly = 0UL;
  79429. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79430. poly |= 1UL << (31 - p[n]);
  79431. /* generate a crc for every 8-bit value */
  79432. for (n = 0; n < 256; n++) {
  79433. c = (unsigned long)n;
  79434. for (k = 0; k < 8; k++)
  79435. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79436. crc_table[0][n] = c;
  79437. }
  79438. #ifdef BYFOUR
  79439. /* generate crc for each value followed by one, two, and three zeros,
  79440. and then the byte reversal of those as well as the first table */
  79441. for (n = 0; n < 256; n++) {
  79442. c = crc_table[0][n];
  79443. crc_table[4][n] = REV(c);
  79444. for (k = 1; k < 4; k++) {
  79445. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79446. crc_table[k][n] = c;
  79447. crc_table[k + 4][n] = REV(c);
  79448. }
  79449. }
  79450. #endif /* BYFOUR */
  79451. crc_table_empty = 0;
  79452. }
  79453. else { /* not first */
  79454. /* wait for the other guy to finish (not efficient, but rare) */
  79455. while (crc_table_empty)
  79456. ;
  79457. }
  79458. #ifdef MAKECRCH
  79459. /* write out CRC tables to crc32.h */
  79460. {
  79461. FILE *out;
  79462. out = fopen("crc32.h", "w");
  79463. if (out == NULL) return;
  79464. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79465. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79466. fprintf(out, "local const unsigned long FAR ");
  79467. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79468. write_table(out, crc_table[0]);
  79469. # ifdef BYFOUR
  79470. fprintf(out, "#ifdef BYFOUR\n");
  79471. for (k = 1; k < 8; k++) {
  79472. fprintf(out, " },\n {\n");
  79473. write_table(out, crc_table[k]);
  79474. }
  79475. fprintf(out, "#endif\n");
  79476. # endif /* BYFOUR */
  79477. fprintf(out, " }\n};\n");
  79478. fclose(out);
  79479. }
  79480. #endif /* MAKECRCH */
  79481. }
  79482. #ifdef MAKECRCH
  79483. local void write_table(out, table)
  79484. FILE *out;
  79485. const unsigned long FAR *table;
  79486. {
  79487. int n;
  79488. for (n = 0; n < 256; n++)
  79489. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79490. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79491. }
  79492. #endif /* MAKECRCH */
  79493. #else /* !DYNAMIC_CRC_TABLE */
  79494. /* ========================================================================
  79495. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79496. */
  79497. /*** Start of inlined file: crc32.h ***/
  79498. local const unsigned long FAR crc_table[TBLS][256] =
  79499. {
  79500. {
  79501. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79502. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79503. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79504. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79505. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79506. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79507. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79508. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79509. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79510. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79511. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79512. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79513. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79514. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79515. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79516. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79517. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79518. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79519. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79520. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79521. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79522. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79523. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79524. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79525. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79526. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79527. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79528. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79529. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79530. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79531. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79532. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79533. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79534. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79535. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79536. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79537. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79538. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79539. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79540. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79541. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79542. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79543. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79544. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79545. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79546. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79547. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79548. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79549. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79550. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79551. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79552. 0x2d02ef8dUL
  79553. #ifdef BYFOUR
  79554. },
  79555. {
  79556. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79557. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79558. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79559. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79560. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79561. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79562. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79563. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79564. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79565. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79566. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79567. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79568. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79569. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79570. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79571. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79572. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79573. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79574. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79575. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79576. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79577. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79578. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79579. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79580. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79581. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79582. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79583. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79584. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79585. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79586. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79587. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79588. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79589. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79590. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79591. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79592. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79593. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79594. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79595. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79596. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79597. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79598. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79599. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79600. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79601. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79602. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79603. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79604. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79605. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79606. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79607. 0x9324fd72UL
  79608. },
  79609. {
  79610. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79611. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79612. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79613. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79614. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79615. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79616. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79617. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79618. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79619. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79620. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79621. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79622. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79623. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79624. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79625. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79626. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79627. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79628. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79629. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79630. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79631. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79632. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79633. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79634. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79635. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79636. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79637. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79638. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79639. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79640. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79641. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79642. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79643. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79644. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79645. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79646. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79647. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79648. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79649. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79650. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79651. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79652. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79653. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79654. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79655. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79656. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79657. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79658. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79659. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79660. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79661. 0xbe9834edUL
  79662. },
  79663. {
  79664. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79665. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79666. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79667. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79668. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79669. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79670. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79671. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79672. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79673. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79674. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79675. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79676. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79677. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79678. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79679. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79680. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79681. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79682. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79683. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79684. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79685. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79686. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79687. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79688. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79689. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79690. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79691. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79692. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79693. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79694. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79695. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79696. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79697. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79698. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79699. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79700. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79701. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79702. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79703. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79704. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79705. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79706. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79707. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79708. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79709. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79710. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79711. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79712. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79713. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79714. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79715. 0xde0506f1UL
  79716. },
  79717. {
  79718. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79719. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79720. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79721. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79722. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79723. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79724. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79725. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79726. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79727. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79728. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79729. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79730. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79731. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79732. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79733. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79734. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79735. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79736. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79737. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79738. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79739. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79740. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79741. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79742. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79743. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79744. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79745. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79746. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79747. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79748. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79749. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79750. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79751. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79752. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79753. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79754. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79755. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79756. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79757. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79758. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79759. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79760. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79761. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79762. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79763. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79764. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79765. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79766. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79767. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79768. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79769. 0x8def022dUL
  79770. },
  79771. {
  79772. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79773. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79774. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79775. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79776. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79777. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79778. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79779. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79780. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79781. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79782. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79783. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79784. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79785. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79786. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79787. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79788. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79789. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79790. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79791. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79792. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79793. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79794. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79795. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79796. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79797. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79798. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79799. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79800. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79801. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79802. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79803. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79804. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79805. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79806. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79807. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79808. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79809. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79810. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79811. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79812. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79813. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79814. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79815. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79816. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79817. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79818. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79819. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  79820. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  79821. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  79822. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  79823. 0x72fd2493UL
  79824. },
  79825. {
  79826. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  79827. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  79828. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  79829. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  79830. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  79831. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  79832. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  79833. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  79834. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  79835. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  79836. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  79837. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  79838. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  79839. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  79840. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  79841. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  79842. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  79843. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  79844. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  79845. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  79846. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  79847. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  79848. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  79849. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  79850. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  79851. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  79852. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  79853. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  79854. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  79855. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  79856. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  79857. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  79858. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  79859. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  79860. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  79861. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  79862. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  79863. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  79864. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  79865. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  79866. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  79867. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  79868. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  79869. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  79870. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  79871. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  79872. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  79873. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  79874. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  79875. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  79876. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  79877. 0xed3498beUL
  79878. },
  79879. {
  79880. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  79881. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  79882. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  79883. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  79884. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  79885. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  79886. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  79887. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  79888. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  79889. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  79890. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  79891. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  79892. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  79893. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  79894. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  79895. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  79896. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  79897. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  79898. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  79899. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  79900. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  79901. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  79902. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  79903. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  79904. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  79905. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  79906. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  79907. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  79908. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  79909. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  79910. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  79911. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  79912. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  79913. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  79914. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  79915. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  79916. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  79917. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  79918. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  79919. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  79920. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  79921. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  79922. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  79923. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  79924. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  79925. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  79926. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  79927. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  79928. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  79929. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  79930. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  79931. 0xf10605deUL
  79932. #endif
  79933. }
  79934. };
  79935. /*** End of inlined file: crc32.h ***/
  79936. #endif /* DYNAMIC_CRC_TABLE */
  79937. /* =========================================================================
  79938. * This function can be used by asm versions of crc32()
  79939. */
  79940. const unsigned long FAR * ZEXPORT get_crc_table()
  79941. {
  79942. #ifdef DYNAMIC_CRC_TABLE
  79943. if (crc_table_empty)
  79944. make_crc_table();
  79945. #endif /* DYNAMIC_CRC_TABLE */
  79946. return (const unsigned long FAR *)crc_table;
  79947. }
  79948. /* ========================================================================= */
  79949. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  79950. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  79951. /* ========================================================================= */
  79952. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79953. {
  79954. if (buf == Z_NULL) return 0UL;
  79955. #ifdef DYNAMIC_CRC_TABLE
  79956. if (crc_table_empty)
  79957. make_crc_table();
  79958. #endif /* DYNAMIC_CRC_TABLE */
  79959. #ifdef BYFOUR
  79960. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  79961. u4 endian;
  79962. endian = 1;
  79963. if (*((unsigned char *)(&endian)))
  79964. return crc32_little(crc, buf, len);
  79965. else
  79966. return crc32_big(crc, buf, len);
  79967. }
  79968. #endif /* BYFOUR */
  79969. crc = crc ^ 0xffffffffUL;
  79970. while (len >= 8) {
  79971. DO8;
  79972. len -= 8;
  79973. }
  79974. if (len) do {
  79975. DO1;
  79976. } while (--len);
  79977. return crc ^ 0xffffffffUL;
  79978. }
  79979. #ifdef BYFOUR
  79980. /* ========================================================================= */
  79981. #define DOLIT4 c ^= *buf4++; \
  79982. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  79983. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  79984. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  79985. /* ========================================================================= */
  79986. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79987. {
  79988. register u4 c;
  79989. register const u4 FAR *buf4;
  79990. c = (u4)crc;
  79991. c = ~c;
  79992. while (len && ((ptrdiff_t)buf & 3)) {
  79993. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79994. len--;
  79995. }
  79996. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79997. while (len >= 32) {
  79998. DOLIT32;
  79999. len -= 32;
  80000. }
  80001. while (len >= 4) {
  80002. DOLIT4;
  80003. len -= 4;
  80004. }
  80005. buf = (const unsigned char FAR *)buf4;
  80006. if (len) do {
  80007. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80008. } while (--len);
  80009. c = ~c;
  80010. return (unsigned long)c;
  80011. }
  80012. /* ========================================================================= */
  80013. #define DOBIG4 c ^= *++buf4; \
  80014. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80015. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80016. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80017. /* ========================================================================= */
  80018. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80019. {
  80020. register u4 c;
  80021. register const u4 FAR *buf4;
  80022. c = REV((u4)crc);
  80023. c = ~c;
  80024. while (len && ((ptrdiff_t)buf & 3)) {
  80025. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80026. len--;
  80027. }
  80028. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80029. buf4--;
  80030. while (len >= 32) {
  80031. DOBIG32;
  80032. len -= 32;
  80033. }
  80034. while (len >= 4) {
  80035. DOBIG4;
  80036. len -= 4;
  80037. }
  80038. buf4++;
  80039. buf = (const unsigned char FAR *)buf4;
  80040. if (len) do {
  80041. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80042. } while (--len);
  80043. c = ~c;
  80044. return (unsigned long)(REV(c));
  80045. }
  80046. #endif /* BYFOUR */
  80047. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80048. /* ========================================================================= */
  80049. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80050. {
  80051. unsigned long sum;
  80052. sum = 0;
  80053. while (vec) {
  80054. if (vec & 1)
  80055. sum ^= *mat;
  80056. vec >>= 1;
  80057. mat++;
  80058. }
  80059. return sum;
  80060. }
  80061. /* ========================================================================= */
  80062. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80063. {
  80064. int n;
  80065. for (n = 0; n < GF2_DIM; n++)
  80066. square[n] = gf2_matrix_times(mat, mat[n]);
  80067. }
  80068. /* ========================================================================= */
  80069. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80070. {
  80071. int n;
  80072. unsigned long row;
  80073. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80074. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80075. /* degenerate case */
  80076. if (len2 == 0)
  80077. return crc1;
  80078. /* put operator for one zero bit in odd */
  80079. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80080. row = 1;
  80081. for (n = 1; n < GF2_DIM; n++) {
  80082. odd[n] = row;
  80083. row <<= 1;
  80084. }
  80085. /* put operator for two zero bits in even */
  80086. gf2_matrix_square(even, odd);
  80087. /* put operator for four zero bits in odd */
  80088. gf2_matrix_square(odd, even);
  80089. /* apply len2 zeros to crc1 (first square will put the operator for one
  80090. zero byte, eight zero bits, in even) */
  80091. do {
  80092. /* apply zeros operator for this bit of len2 */
  80093. gf2_matrix_square(even, odd);
  80094. if (len2 & 1)
  80095. crc1 = gf2_matrix_times(even, crc1);
  80096. len2 >>= 1;
  80097. /* if no more bits set, then done */
  80098. if (len2 == 0)
  80099. break;
  80100. /* another iteration of the loop with odd and even swapped */
  80101. gf2_matrix_square(odd, even);
  80102. if (len2 & 1)
  80103. crc1 = gf2_matrix_times(odd, crc1);
  80104. len2 >>= 1;
  80105. /* if no more bits set, then done */
  80106. } while (len2 != 0);
  80107. /* return combined crc */
  80108. crc1 ^= crc2;
  80109. return crc1;
  80110. }
  80111. /*** End of inlined file: crc32.c ***/
  80112. /*** Start of inlined file: deflate.c ***/
  80113. /*
  80114. * ALGORITHM
  80115. *
  80116. * The "deflation" process depends on being able to identify portions
  80117. * of the input text which are identical to earlier input (within a
  80118. * sliding window trailing behind the input currently being processed).
  80119. *
  80120. * The most straightforward technique turns out to be the fastest for
  80121. * most input files: try all possible matches and select the longest.
  80122. * The key feature of this algorithm is that insertions into the string
  80123. * dictionary are very simple and thus fast, and deletions are avoided
  80124. * completely. Insertions are performed at each input character, whereas
  80125. * string matches are performed only when the previous match ends. So it
  80126. * is preferable to spend more time in matches to allow very fast string
  80127. * insertions and avoid deletions. The matching algorithm for small
  80128. * strings is inspired from that of Rabin & Karp. A brute force approach
  80129. * is used to find longer strings when a small match has been found.
  80130. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80131. * (by Leonid Broukhis).
  80132. * A previous version of this file used a more sophisticated algorithm
  80133. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80134. * time, but has a larger average cost, uses more memory and is patented.
  80135. * However the F&G algorithm may be faster for some highly redundant
  80136. * files if the parameter max_chain_length (described below) is too large.
  80137. *
  80138. * ACKNOWLEDGEMENTS
  80139. *
  80140. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80141. * I found it in 'freeze' written by Leonid Broukhis.
  80142. * Thanks to many people for bug reports and testing.
  80143. *
  80144. * REFERENCES
  80145. *
  80146. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80147. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80148. *
  80149. * A description of the Rabin and Karp algorithm is given in the book
  80150. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80151. *
  80152. * Fiala,E.R., and Greene,D.H.
  80153. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80154. *
  80155. */
  80156. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80157. /*** Start of inlined file: deflate.h ***/
  80158. /* WARNING: this file should *not* be used by applications. It is
  80159. part of the implementation of the compression library and is
  80160. subject to change. Applications should only use zlib.h.
  80161. */
  80162. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80163. #ifndef DEFLATE_H
  80164. #define DEFLATE_H
  80165. /* define NO_GZIP when compiling if you want to disable gzip header and
  80166. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80167. the crc code when it is not needed. For shared libraries, gzip encoding
  80168. should be left enabled. */
  80169. #ifndef NO_GZIP
  80170. # define GZIP
  80171. #endif
  80172. #define NO_DUMMY_DECL
  80173. /* ===========================================================================
  80174. * Internal compression state.
  80175. */
  80176. #define LENGTH_CODES 29
  80177. /* number of length codes, not counting the special END_BLOCK code */
  80178. #define LITERALS 256
  80179. /* number of literal bytes 0..255 */
  80180. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80181. /* number of Literal or Length codes, including the END_BLOCK code */
  80182. #define D_CODES 30
  80183. /* number of distance codes */
  80184. #define BL_CODES 19
  80185. /* number of codes used to transfer the bit lengths */
  80186. #define HEAP_SIZE (2*L_CODES+1)
  80187. /* maximum heap size */
  80188. #define MAX_BITS 15
  80189. /* All codes must not exceed MAX_BITS bits */
  80190. #define INIT_STATE 42
  80191. #define EXTRA_STATE 69
  80192. #define NAME_STATE 73
  80193. #define COMMENT_STATE 91
  80194. #define HCRC_STATE 103
  80195. #define BUSY_STATE 113
  80196. #define FINISH_STATE 666
  80197. /* Stream status */
  80198. /* Data structure describing a single value and its code string. */
  80199. typedef struct ct_data_s {
  80200. union {
  80201. ush freq; /* frequency count */
  80202. ush code; /* bit string */
  80203. } fc;
  80204. union {
  80205. ush dad; /* father node in Huffman tree */
  80206. ush len; /* length of bit string */
  80207. } dl;
  80208. } FAR ct_data;
  80209. #define Freq fc.freq
  80210. #define Code fc.code
  80211. #define Dad dl.dad
  80212. #define Len dl.len
  80213. typedef struct static_tree_desc_s static_tree_desc;
  80214. typedef struct tree_desc_s {
  80215. ct_data *dyn_tree; /* the dynamic tree */
  80216. int max_code; /* largest code with non zero frequency */
  80217. static_tree_desc *stat_desc; /* the corresponding static tree */
  80218. } FAR tree_desc;
  80219. typedef ush Pos;
  80220. typedef Pos FAR Posf;
  80221. typedef unsigned IPos;
  80222. /* A Pos is an index in the character window. We use short instead of int to
  80223. * save space in the various tables. IPos is used only for parameter passing.
  80224. */
  80225. typedef struct internal_state {
  80226. z_streamp strm; /* pointer back to this zlib stream */
  80227. int status; /* as the name implies */
  80228. Bytef *pending_buf; /* output still pending */
  80229. ulg pending_buf_size; /* size of pending_buf */
  80230. Bytef *pending_out; /* next pending byte to output to the stream */
  80231. uInt pending; /* nb of bytes in the pending buffer */
  80232. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80233. gz_headerp gzhead; /* gzip header information to write */
  80234. uInt gzindex; /* where in extra, name, or comment */
  80235. Byte method; /* STORED (for zip only) or DEFLATED */
  80236. int last_flush; /* value of flush param for previous deflate call */
  80237. /* used by deflate.c: */
  80238. uInt w_size; /* LZ77 window size (32K by default) */
  80239. uInt w_bits; /* log2(w_size) (8..16) */
  80240. uInt w_mask; /* w_size - 1 */
  80241. Bytef *window;
  80242. /* Sliding window. Input bytes are read into the second half of the window,
  80243. * and move to the first half later to keep a dictionary of at least wSize
  80244. * bytes. With this organization, matches are limited to a distance of
  80245. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80246. * performed with a length multiple of the block size. Also, it limits
  80247. * the window size to 64K, which is quite useful on MSDOS.
  80248. * To do: use the user input buffer as sliding window.
  80249. */
  80250. ulg window_size;
  80251. /* Actual size of window: 2*wSize, except when the user input buffer
  80252. * is directly used as sliding window.
  80253. */
  80254. Posf *prev;
  80255. /* Link to older string with same hash index. To limit the size of this
  80256. * array to 64K, this link is maintained only for the last 32K strings.
  80257. * An index in this array is thus a window index modulo 32K.
  80258. */
  80259. Posf *head; /* Heads of the hash chains or NIL. */
  80260. uInt ins_h; /* hash index of string to be inserted */
  80261. uInt hash_size; /* number of elements in hash table */
  80262. uInt hash_bits; /* log2(hash_size) */
  80263. uInt hash_mask; /* hash_size-1 */
  80264. uInt hash_shift;
  80265. /* Number of bits by which ins_h must be shifted at each input
  80266. * step. It must be such that after MIN_MATCH steps, the oldest
  80267. * byte no longer takes part in the hash key, that is:
  80268. * hash_shift * MIN_MATCH >= hash_bits
  80269. */
  80270. long block_start;
  80271. /* Window position at the beginning of the current output block. Gets
  80272. * negative when the window is moved backwards.
  80273. */
  80274. uInt match_length; /* length of best match */
  80275. IPos prev_match; /* previous match */
  80276. int match_available; /* set if previous match exists */
  80277. uInt strstart; /* start of string to insert */
  80278. uInt match_start; /* start of matching string */
  80279. uInt lookahead; /* number of valid bytes ahead in window */
  80280. uInt prev_length;
  80281. /* Length of the best match at previous step. Matches not greater than this
  80282. * are discarded. This is used in the lazy match evaluation.
  80283. */
  80284. uInt max_chain_length;
  80285. /* To speed up deflation, hash chains are never searched beyond this
  80286. * length. A higher limit improves compression ratio but degrades the
  80287. * speed.
  80288. */
  80289. uInt max_lazy_match;
  80290. /* Attempt to find a better match only when the current match is strictly
  80291. * smaller than this value. This mechanism is used only for compression
  80292. * levels >= 4.
  80293. */
  80294. # define max_insert_length max_lazy_match
  80295. /* Insert new strings in the hash table only if the match length is not
  80296. * greater than this length. This saves time but degrades compression.
  80297. * max_insert_length is used only for compression levels <= 3.
  80298. */
  80299. int level; /* compression level (1..9) */
  80300. int strategy; /* favor or force Huffman coding*/
  80301. uInt good_match;
  80302. /* Use a faster search when the previous match is longer than this */
  80303. int nice_match; /* Stop searching when current match exceeds this */
  80304. /* used by trees.c: */
  80305. /* Didn't use ct_data typedef below to supress compiler warning */
  80306. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80307. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80308. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80309. struct tree_desc_s l_desc; /* desc. for literal tree */
  80310. struct tree_desc_s d_desc; /* desc. for distance tree */
  80311. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80312. ush bl_count[MAX_BITS+1];
  80313. /* number of codes at each bit length for an optimal tree */
  80314. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80315. int heap_len; /* number of elements in the heap */
  80316. int heap_max; /* element of largest frequency */
  80317. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80318. * The same heap array is used to build all trees.
  80319. */
  80320. uch depth[2*L_CODES+1];
  80321. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80322. */
  80323. uchf *l_buf; /* buffer for literals or lengths */
  80324. uInt lit_bufsize;
  80325. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80326. * limiting lit_bufsize to 64K:
  80327. * - frequencies can be kept in 16 bit counters
  80328. * - if compression is not successful for the first block, all input
  80329. * data is still in the window so we can still emit a stored block even
  80330. * when input comes from standard input. (This can also be done for
  80331. * all blocks if lit_bufsize is not greater than 32K.)
  80332. * - if compression is not successful for a file smaller than 64K, we can
  80333. * even emit a stored file instead of a stored block (saving 5 bytes).
  80334. * This is applicable only for zip (not gzip or zlib).
  80335. * - creating new Huffman trees less frequently may not provide fast
  80336. * adaptation to changes in the input data statistics. (Take for
  80337. * example a binary file with poorly compressible code followed by
  80338. * a highly compressible string table.) Smaller buffer sizes give
  80339. * fast adaptation but have of course the overhead of transmitting
  80340. * trees more frequently.
  80341. * - I can't count above 4
  80342. */
  80343. uInt last_lit; /* running index in l_buf */
  80344. ushf *d_buf;
  80345. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80346. * the same number of elements. To use different lengths, an extra flag
  80347. * array would be necessary.
  80348. */
  80349. ulg opt_len; /* bit length of current block with optimal trees */
  80350. ulg static_len; /* bit length of current block with static trees */
  80351. uInt matches; /* number of string matches in current block */
  80352. int last_eob_len; /* bit length of EOB code for last block */
  80353. #ifdef DEBUG
  80354. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80355. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80356. #endif
  80357. ush bi_buf;
  80358. /* Output buffer. bits are inserted starting at the bottom (least
  80359. * significant bits).
  80360. */
  80361. int bi_valid;
  80362. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80363. * are always zero.
  80364. */
  80365. } FAR deflate_state;
  80366. /* Output a byte on the stream.
  80367. * IN assertion: there is enough room in pending_buf.
  80368. */
  80369. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80370. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80371. /* Minimum amount of lookahead, except at the end of the input file.
  80372. * See deflate.c for comments about the MIN_MATCH+1.
  80373. */
  80374. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80375. /* In order to simplify the code, particularly on 16 bit machines, match
  80376. * distances are limited to MAX_DIST instead of WSIZE.
  80377. */
  80378. /* in trees.c */
  80379. void _tr_init OF((deflate_state *s));
  80380. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80381. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80382. int eof));
  80383. void _tr_align OF((deflate_state *s));
  80384. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80385. int eof));
  80386. #define d_code(dist) \
  80387. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80388. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80389. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80390. * used.
  80391. */
  80392. #ifndef DEBUG
  80393. /* Inline versions of _tr_tally for speed: */
  80394. #if defined(GEN_TREES_H) || !defined(STDC)
  80395. extern uch _length_code[];
  80396. extern uch _dist_code[];
  80397. #else
  80398. extern const uch _length_code[];
  80399. extern const uch _dist_code[];
  80400. #endif
  80401. # define _tr_tally_lit(s, c, flush) \
  80402. { uch cc = (c); \
  80403. s->d_buf[s->last_lit] = 0; \
  80404. s->l_buf[s->last_lit++] = cc; \
  80405. s->dyn_ltree[cc].Freq++; \
  80406. flush = (s->last_lit == s->lit_bufsize-1); \
  80407. }
  80408. # define _tr_tally_dist(s, distance, length, flush) \
  80409. { uch len = (length); \
  80410. ush dist = (distance); \
  80411. s->d_buf[s->last_lit] = dist; \
  80412. s->l_buf[s->last_lit++] = len; \
  80413. dist--; \
  80414. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80415. s->dyn_dtree[d_code(dist)].Freq++; \
  80416. flush = (s->last_lit == s->lit_bufsize-1); \
  80417. }
  80418. #else
  80419. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80420. # define _tr_tally_dist(s, distance, length, flush) \
  80421. flush = _tr_tally(s, distance, length)
  80422. #endif
  80423. #endif /* DEFLATE_H */
  80424. /*** End of inlined file: deflate.h ***/
  80425. const char deflate_copyright[] =
  80426. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80427. /*
  80428. If you use the zlib library in a product, an acknowledgment is welcome
  80429. in the documentation of your product. If for some reason you cannot
  80430. include such an acknowledgment, I would appreciate that you keep this
  80431. copyright string in the executable of your product.
  80432. */
  80433. /* ===========================================================================
  80434. * Function prototypes.
  80435. */
  80436. typedef enum {
  80437. need_more, /* block not completed, need more input or more output */
  80438. block_done, /* block flush performed */
  80439. finish_started, /* finish started, need only more output at next deflate */
  80440. finish_done /* finish done, accept no more input or output */
  80441. } block_state;
  80442. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80443. /* Compression function. Returns the block state after the call. */
  80444. local void fill_window OF((deflate_state *s));
  80445. local block_state deflate_stored OF((deflate_state *s, int flush));
  80446. local block_state deflate_fast OF((deflate_state *s, int flush));
  80447. #ifndef FASTEST
  80448. local block_state deflate_slow OF((deflate_state *s, int flush));
  80449. #endif
  80450. local void lm_init OF((deflate_state *s));
  80451. local void putShortMSB OF((deflate_state *s, uInt b));
  80452. local void flush_pending OF((z_streamp strm));
  80453. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80454. #ifndef FASTEST
  80455. #ifdef ASMV
  80456. void match_init OF((void)); /* asm code initialization */
  80457. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80458. #else
  80459. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80460. #endif
  80461. #endif
  80462. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80463. #ifdef DEBUG
  80464. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80465. int length));
  80466. #endif
  80467. /* ===========================================================================
  80468. * Local data
  80469. */
  80470. #define NIL 0
  80471. /* Tail of hash chains */
  80472. #ifndef TOO_FAR
  80473. # define TOO_FAR 4096
  80474. #endif
  80475. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80476. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80477. /* Minimum amount of lookahead, except at the end of the input file.
  80478. * See deflate.c for comments about the MIN_MATCH+1.
  80479. */
  80480. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80481. * the desired pack level (0..9). The values given below have been tuned to
  80482. * exclude worst case performance for pathological files. Better values may be
  80483. * found for specific files.
  80484. */
  80485. typedef struct config_s {
  80486. ush good_length; /* reduce lazy search above this match length */
  80487. ush max_lazy; /* do not perform lazy search above this match length */
  80488. ush nice_length; /* quit search above this match length */
  80489. ush max_chain;
  80490. compress_func func;
  80491. } config;
  80492. #ifdef FASTEST
  80493. local const config configuration_table[2] = {
  80494. /* good lazy nice chain */
  80495. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80496. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80497. #else
  80498. local const config configuration_table[10] = {
  80499. /* good lazy nice chain */
  80500. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80501. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80502. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80503. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80504. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80505. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80506. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80507. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80508. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80509. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80510. #endif
  80511. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80512. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80513. * meaning.
  80514. */
  80515. #define EQUAL 0
  80516. /* result of memcmp for equal strings */
  80517. #ifndef NO_DUMMY_DECL
  80518. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80519. #endif
  80520. /* ===========================================================================
  80521. * Update a hash value with the given input byte
  80522. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80523. * input characters, so that a running hash key can be computed from the
  80524. * previous key instead of complete recalculation each time.
  80525. */
  80526. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80527. /* ===========================================================================
  80528. * Insert string str in the dictionary and set match_head to the previous head
  80529. * of the hash chain (the most recent string with same hash key). Return
  80530. * the previous length of the hash chain.
  80531. * If this file is compiled with -DFASTEST, the compression level is forced
  80532. * to 1, and no hash chains are maintained.
  80533. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80534. * input characters and the first MIN_MATCH bytes of str are valid
  80535. * (except for the last MIN_MATCH-1 bytes of the input file).
  80536. */
  80537. #ifdef FASTEST
  80538. #define INSERT_STRING(s, str, match_head) \
  80539. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80540. match_head = s->head[s->ins_h], \
  80541. s->head[s->ins_h] = (Pos)(str))
  80542. #else
  80543. #define INSERT_STRING(s, str, match_head) \
  80544. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80545. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80546. s->head[s->ins_h] = (Pos)(str))
  80547. #endif
  80548. /* ===========================================================================
  80549. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80550. * prev[] will be initialized on the fly.
  80551. */
  80552. #define CLEAR_HASH(s) \
  80553. s->head[s->hash_size-1] = NIL; \
  80554. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80555. /* ========================================================================= */
  80556. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80557. {
  80558. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80559. Z_DEFAULT_STRATEGY, version, stream_size);
  80560. /* To do: ignore strm->next_in if we use it as window */
  80561. }
  80562. /* ========================================================================= */
  80563. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80564. {
  80565. deflate_state *s;
  80566. int wrap = 1;
  80567. static const char my_version[] = ZLIB_VERSION;
  80568. ushf *overlay;
  80569. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80570. * output size for (length,distance) codes is <= 24 bits.
  80571. */
  80572. if (version == Z_NULL || version[0] != my_version[0] ||
  80573. stream_size != sizeof(z_stream)) {
  80574. return Z_VERSION_ERROR;
  80575. }
  80576. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80577. strm->msg = Z_NULL;
  80578. if (strm->zalloc == (alloc_func)0) {
  80579. strm->zalloc = zcalloc;
  80580. strm->opaque = (voidpf)0;
  80581. }
  80582. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80583. #ifdef FASTEST
  80584. if (level != 0) level = 1;
  80585. #else
  80586. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80587. #endif
  80588. if (windowBits < 0) { /* suppress zlib wrapper */
  80589. wrap = 0;
  80590. windowBits = -windowBits;
  80591. }
  80592. #ifdef GZIP
  80593. else if (windowBits > 15) {
  80594. wrap = 2; /* write gzip wrapper instead */
  80595. windowBits -= 16;
  80596. }
  80597. #endif
  80598. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80599. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80600. strategy < 0 || strategy > Z_FIXED) {
  80601. return Z_STREAM_ERROR;
  80602. }
  80603. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80604. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80605. if (s == Z_NULL) return Z_MEM_ERROR;
  80606. strm->state = (struct internal_state FAR *)s;
  80607. s->strm = strm;
  80608. s->wrap = wrap;
  80609. s->gzhead = Z_NULL;
  80610. s->w_bits = windowBits;
  80611. s->w_size = 1 << s->w_bits;
  80612. s->w_mask = s->w_size - 1;
  80613. s->hash_bits = memLevel + 7;
  80614. s->hash_size = 1 << s->hash_bits;
  80615. s->hash_mask = s->hash_size - 1;
  80616. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80617. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80618. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80619. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80620. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80621. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80622. s->pending_buf = (uchf *) overlay;
  80623. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80624. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80625. s->pending_buf == Z_NULL) {
  80626. s->status = FINISH_STATE;
  80627. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80628. deflateEnd (strm);
  80629. return Z_MEM_ERROR;
  80630. }
  80631. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80632. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80633. s->level = level;
  80634. s->strategy = strategy;
  80635. s->method = (Byte)method;
  80636. return deflateReset(strm);
  80637. }
  80638. /* ========================================================================= */
  80639. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80640. {
  80641. deflate_state *s;
  80642. uInt length = dictLength;
  80643. uInt n;
  80644. IPos hash_head = 0;
  80645. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80646. strm->state->wrap == 2 ||
  80647. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80648. return Z_STREAM_ERROR;
  80649. s = strm->state;
  80650. if (s->wrap)
  80651. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80652. if (length < MIN_MATCH) return Z_OK;
  80653. if (length > MAX_DIST(s)) {
  80654. length = MAX_DIST(s);
  80655. dictionary += dictLength - length; /* use the tail of the dictionary */
  80656. }
  80657. zmemcpy(s->window, dictionary, length);
  80658. s->strstart = length;
  80659. s->block_start = (long)length;
  80660. /* Insert all strings in the hash table (except for the last two bytes).
  80661. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80662. * call of fill_window.
  80663. */
  80664. s->ins_h = s->window[0];
  80665. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80666. for (n = 0; n <= length - MIN_MATCH; n++) {
  80667. INSERT_STRING(s, n, hash_head);
  80668. }
  80669. if (hash_head) hash_head = 0; /* to make compiler happy */
  80670. return Z_OK;
  80671. }
  80672. /* ========================================================================= */
  80673. int ZEXPORT deflateReset (z_streamp strm)
  80674. {
  80675. deflate_state *s;
  80676. if (strm == Z_NULL || strm->state == Z_NULL ||
  80677. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80678. return Z_STREAM_ERROR;
  80679. }
  80680. strm->total_in = strm->total_out = 0;
  80681. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80682. strm->data_type = Z_UNKNOWN;
  80683. s = (deflate_state *)strm->state;
  80684. s->pending = 0;
  80685. s->pending_out = s->pending_buf;
  80686. if (s->wrap < 0) {
  80687. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80688. }
  80689. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80690. strm->adler =
  80691. #ifdef GZIP
  80692. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80693. #endif
  80694. adler32(0L, Z_NULL, 0);
  80695. s->last_flush = Z_NO_FLUSH;
  80696. _tr_init(s);
  80697. lm_init(s);
  80698. return Z_OK;
  80699. }
  80700. /* ========================================================================= */
  80701. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80702. {
  80703. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80704. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80705. strm->state->gzhead = head;
  80706. return Z_OK;
  80707. }
  80708. /* ========================================================================= */
  80709. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80710. {
  80711. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80712. strm->state->bi_valid = bits;
  80713. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80714. return Z_OK;
  80715. }
  80716. /* ========================================================================= */
  80717. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80718. {
  80719. deflate_state *s;
  80720. compress_func func;
  80721. int err = Z_OK;
  80722. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80723. s = strm->state;
  80724. #ifdef FASTEST
  80725. if (level != 0) level = 1;
  80726. #else
  80727. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80728. #endif
  80729. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80730. return Z_STREAM_ERROR;
  80731. }
  80732. func = configuration_table[s->level].func;
  80733. if (func != configuration_table[level].func && strm->total_in != 0) {
  80734. /* Flush the last buffer: */
  80735. err = deflate(strm, Z_PARTIAL_FLUSH);
  80736. }
  80737. if (s->level != level) {
  80738. s->level = level;
  80739. s->max_lazy_match = configuration_table[level].max_lazy;
  80740. s->good_match = configuration_table[level].good_length;
  80741. s->nice_match = configuration_table[level].nice_length;
  80742. s->max_chain_length = configuration_table[level].max_chain;
  80743. }
  80744. s->strategy = strategy;
  80745. return err;
  80746. }
  80747. /* ========================================================================= */
  80748. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80749. {
  80750. deflate_state *s;
  80751. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80752. s = strm->state;
  80753. s->good_match = good_length;
  80754. s->max_lazy_match = max_lazy;
  80755. s->nice_match = nice_length;
  80756. s->max_chain_length = max_chain;
  80757. return Z_OK;
  80758. }
  80759. /* =========================================================================
  80760. * For the default windowBits of 15 and memLevel of 8, this function returns
  80761. * a close to exact, as well as small, upper bound on the compressed size.
  80762. * They are coded as constants here for a reason--if the #define's are
  80763. * changed, then this function needs to be changed as well. The return
  80764. * value for 15 and 8 only works for those exact settings.
  80765. *
  80766. * For any setting other than those defaults for windowBits and memLevel,
  80767. * the value returned is a conservative worst case for the maximum expansion
  80768. * resulting from using fixed blocks instead of stored blocks, which deflate
  80769. * can emit on compressed data for some combinations of the parameters.
  80770. *
  80771. * This function could be more sophisticated to provide closer upper bounds
  80772. * for every combination of windowBits and memLevel, as well as wrap.
  80773. * But even the conservative upper bound of about 14% expansion does not
  80774. * seem onerous for output buffer allocation.
  80775. */
  80776. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80777. {
  80778. deflate_state *s;
  80779. uLong destLen;
  80780. /* conservative upper bound */
  80781. destLen = sourceLen +
  80782. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80783. /* if can't get parameters, return conservative bound */
  80784. if (strm == Z_NULL || strm->state == Z_NULL)
  80785. return destLen;
  80786. /* if not default parameters, return conservative bound */
  80787. s = strm->state;
  80788. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80789. return destLen;
  80790. /* default settings: return tight bound for that case */
  80791. return compressBound(sourceLen);
  80792. }
  80793. /* =========================================================================
  80794. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80795. * IN assertion: the stream state is correct and there is enough room in
  80796. * pending_buf.
  80797. */
  80798. local void putShortMSB (deflate_state *s, uInt b)
  80799. {
  80800. put_byte(s, (Byte)(b >> 8));
  80801. put_byte(s, (Byte)(b & 0xff));
  80802. }
  80803. /* =========================================================================
  80804. * Flush as much pending output as possible. All deflate() output goes
  80805. * through this function so some applications may wish to modify it
  80806. * to avoid allocating a large strm->next_out buffer and copying into it.
  80807. * (See also read_buf()).
  80808. */
  80809. local void flush_pending (z_streamp strm)
  80810. {
  80811. unsigned len = strm->state->pending;
  80812. if (len > strm->avail_out) len = strm->avail_out;
  80813. if (len == 0) return;
  80814. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80815. strm->next_out += len;
  80816. strm->state->pending_out += len;
  80817. strm->total_out += len;
  80818. strm->avail_out -= len;
  80819. strm->state->pending -= len;
  80820. if (strm->state->pending == 0) {
  80821. strm->state->pending_out = strm->state->pending_buf;
  80822. }
  80823. }
  80824. /* ========================================================================= */
  80825. int ZEXPORT deflate (z_streamp strm, int flush)
  80826. {
  80827. int old_flush; /* value of flush param for previous deflate call */
  80828. deflate_state *s;
  80829. if (strm == Z_NULL || strm->state == Z_NULL ||
  80830. flush > Z_FINISH || flush < 0) {
  80831. return Z_STREAM_ERROR;
  80832. }
  80833. s = strm->state;
  80834. if (strm->next_out == Z_NULL ||
  80835. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  80836. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  80837. ERR_RETURN(strm, Z_STREAM_ERROR);
  80838. }
  80839. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  80840. s->strm = strm; /* just in case */
  80841. old_flush = s->last_flush;
  80842. s->last_flush = flush;
  80843. /* Write the header */
  80844. if (s->status == INIT_STATE) {
  80845. #ifdef GZIP
  80846. if (s->wrap == 2) {
  80847. strm->adler = crc32(0L, Z_NULL, 0);
  80848. put_byte(s, 31);
  80849. put_byte(s, 139);
  80850. put_byte(s, 8);
  80851. if (s->gzhead == NULL) {
  80852. put_byte(s, 0);
  80853. put_byte(s, 0);
  80854. put_byte(s, 0);
  80855. put_byte(s, 0);
  80856. put_byte(s, 0);
  80857. put_byte(s, s->level == 9 ? 2 :
  80858. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80859. 4 : 0));
  80860. put_byte(s, OS_CODE);
  80861. s->status = BUSY_STATE;
  80862. }
  80863. else {
  80864. put_byte(s, (s->gzhead->text ? 1 : 0) +
  80865. (s->gzhead->hcrc ? 2 : 0) +
  80866. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  80867. (s->gzhead->name == Z_NULL ? 0 : 8) +
  80868. (s->gzhead->comment == Z_NULL ? 0 : 16)
  80869. );
  80870. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  80871. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  80872. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  80873. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  80874. put_byte(s, s->level == 9 ? 2 :
  80875. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80876. 4 : 0));
  80877. put_byte(s, s->gzhead->os & 0xff);
  80878. if (s->gzhead->extra != NULL) {
  80879. put_byte(s, s->gzhead->extra_len & 0xff);
  80880. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  80881. }
  80882. if (s->gzhead->hcrc)
  80883. strm->adler = crc32(strm->adler, s->pending_buf,
  80884. s->pending);
  80885. s->gzindex = 0;
  80886. s->status = EXTRA_STATE;
  80887. }
  80888. }
  80889. else
  80890. #endif
  80891. {
  80892. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  80893. uInt level_flags;
  80894. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  80895. level_flags = 0;
  80896. else if (s->level < 6)
  80897. level_flags = 1;
  80898. else if (s->level == 6)
  80899. level_flags = 2;
  80900. else
  80901. level_flags = 3;
  80902. header |= (level_flags << 6);
  80903. if (s->strstart != 0) header |= PRESET_DICT;
  80904. header += 31 - (header % 31);
  80905. s->status = BUSY_STATE;
  80906. putShortMSB(s, header);
  80907. /* Save the adler32 of the preset dictionary: */
  80908. if (s->strstart != 0) {
  80909. putShortMSB(s, (uInt)(strm->adler >> 16));
  80910. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80911. }
  80912. strm->adler = adler32(0L, Z_NULL, 0);
  80913. }
  80914. }
  80915. #ifdef GZIP
  80916. if (s->status == EXTRA_STATE) {
  80917. if (s->gzhead->extra != NULL) {
  80918. uInt beg = s->pending; /* start of bytes to update crc */
  80919. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  80920. if (s->pending == s->pending_buf_size) {
  80921. if (s->gzhead->hcrc && s->pending > beg)
  80922. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80923. s->pending - beg);
  80924. flush_pending(strm);
  80925. beg = s->pending;
  80926. if (s->pending == s->pending_buf_size)
  80927. break;
  80928. }
  80929. put_byte(s, s->gzhead->extra[s->gzindex]);
  80930. s->gzindex++;
  80931. }
  80932. if (s->gzhead->hcrc && s->pending > beg)
  80933. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80934. s->pending - beg);
  80935. if (s->gzindex == s->gzhead->extra_len) {
  80936. s->gzindex = 0;
  80937. s->status = NAME_STATE;
  80938. }
  80939. }
  80940. else
  80941. s->status = NAME_STATE;
  80942. }
  80943. if (s->status == NAME_STATE) {
  80944. if (s->gzhead->name != NULL) {
  80945. uInt beg = s->pending; /* start of bytes to update crc */
  80946. int val;
  80947. do {
  80948. if (s->pending == s->pending_buf_size) {
  80949. if (s->gzhead->hcrc && s->pending > beg)
  80950. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80951. s->pending - beg);
  80952. flush_pending(strm);
  80953. beg = s->pending;
  80954. if (s->pending == s->pending_buf_size) {
  80955. val = 1;
  80956. break;
  80957. }
  80958. }
  80959. val = s->gzhead->name[s->gzindex++];
  80960. put_byte(s, val);
  80961. } while (val != 0);
  80962. if (s->gzhead->hcrc && s->pending > beg)
  80963. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80964. s->pending - beg);
  80965. if (val == 0) {
  80966. s->gzindex = 0;
  80967. s->status = COMMENT_STATE;
  80968. }
  80969. }
  80970. else
  80971. s->status = COMMENT_STATE;
  80972. }
  80973. if (s->status == COMMENT_STATE) {
  80974. if (s->gzhead->comment != NULL) {
  80975. uInt beg = s->pending; /* start of bytes to update crc */
  80976. int val;
  80977. do {
  80978. if (s->pending == s->pending_buf_size) {
  80979. if (s->gzhead->hcrc && s->pending > beg)
  80980. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80981. s->pending - beg);
  80982. flush_pending(strm);
  80983. beg = s->pending;
  80984. if (s->pending == s->pending_buf_size) {
  80985. val = 1;
  80986. break;
  80987. }
  80988. }
  80989. val = s->gzhead->comment[s->gzindex++];
  80990. put_byte(s, val);
  80991. } while (val != 0);
  80992. if (s->gzhead->hcrc && s->pending > beg)
  80993. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80994. s->pending - beg);
  80995. if (val == 0)
  80996. s->status = HCRC_STATE;
  80997. }
  80998. else
  80999. s->status = HCRC_STATE;
  81000. }
  81001. if (s->status == HCRC_STATE) {
  81002. if (s->gzhead->hcrc) {
  81003. if (s->pending + 2 > s->pending_buf_size)
  81004. flush_pending(strm);
  81005. if (s->pending + 2 <= s->pending_buf_size) {
  81006. put_byte(s, (Byte)(strm->adler & 0xff));
  81007. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81008. strm->adler = crc32(0L, Z_NULL, 0);
  81009. s->status = BUSY_STATE;
  81010. }
  81011. }
  81012. else
  81013. s->status = BUSY_STATE;
  81014. }
  81015. #endif
  81016. /* Flush as much pending output as possible */
  81017. if (s->pending != 0) {
  81018. flush_pending(strm);
  81019. if (strm->avail_out == 0) {
  81020. /* Since avail_out is 0, deflate will be called again with
  81021. * more output space, but possibly with both pending and
  81022. * avail_in equal to zero. There won't be anything to do,
  81023. * but this is not an error situation so make sure we
  81024. * return OK instead of BUF_ERROR at next call of deflate:
  81025. */
  81026. s->last_flush = -1;
  81027. return Z_OK;
  81028. }
  81029. /* Make sure there is something to do and avoid duplicate consecutive
  81030. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81031. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81032. */
  81033. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81034. flush != Z_FINISH) {
  81035. ERR_RETURN(strm, Z_BUF_ERROR);
  81036. }
  81037. /* User must not provide more input after the first FINISH: */
  81038. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81039. ERR_RETURN(strm, Z_BUF_ERROR);
  81040. }
  81041. /* Start a new block or continue the current one.
  81042. */
  81043. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81044. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81045. block_state bstate;
  81046. bstate = (*(configuration_table[s->level].func))(s, flush);
  81047. if (bstate == finish_started || bstate == finish_done) {
  81048. s->status = FINISH_STATE;
  81049. }
  81050. if (bstate == need_more || bstate == finish_started) {
  81051. if (strm->avail_out == 0) {
  81052. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81053. }
  81054. return Z_OK;
  81055. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81056. * of deflate should use the same flush parameter to make sure
  81057. * that the flush is complete. So we don't have to output an
  81058. * empty block here, this will be done at next call. This also
  81059. * ensures that for a very small output buffer, we emit at most
  81060. * one empty block.
  81061. */
  81062. }
  81063. if (bstate == block_done) {
  81064. if (flush == Z_PARTIAL_FLUSH) {
  81065. _tr_align(s);
  81066. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81067. _tr_stored_block(s, (char*)0, 0L, 0);
  81068. /* For a full flush, this empty block will be recognized
  81069. * as a special marker by inflate_sync().
  81070. */
  81071. if (flush == Z_FULL_FLUSH) {
  81072. CLEAR_HASH(s); /* forget history */
  81073. }
  81074. }
  81075. flush_pending(strm);
  81076. if (strm->avail_out == 0) {
  81077. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81078. return Z_OK;
  81079. }
  81080. }
  81081. }
  81082. Assert(strm->avail_out > 0, "bug2");
  81083. if (flush != Z_FINISH) return Z_OK;
  81084. if (s->wrap <= 0) return Z_STREAM_END;
  81085. /* Write the trailer */
  81086. #ifdef GZIP
  81087. if (s->wrap == 2) {
  81088. put_byte(s, (Byte)(strm->adler & 0xff));
  81089. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81090. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81091. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81092. put_byte(s, (Byte)(strm->total_in & 0xff));
  81093. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81094. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81095. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81096. }
  81097. else
  81098. #endif
  81099. {
  81100. putShortMSB(s, (uInt)(strm->adler >> 16));
  81101. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81102. }
  81103. flush_pending(strm);
  81104. /* If avail_out is zero, the application will call deflate again
  81105. * to flush the rest.
  81106. */
  81107. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81108. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81109. }
  81110. /* ========================================================================= */
  81111. int ZEXPORT deflateEnd (z_streamp strm)
  81112. {
  81113. int status;
  81114. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81115. status = strm->state->status;
  81116. if (status != INIT_STATE &&
  81117. status != EXTRA_STATE &&
  81118. status != NAME_STATE &&
  81119. status != COMMENT_STATE &&
  81120. status != HCRC_STATE &&
  81121. status != BUSY_STATE &&
  81122. status != FINISH_STATE) {
  81123. return Z_STREAM_ERROR;
  81124. }
  81125. /* Deallocate in reverse order of allocations: */
  81126. TRY_FREE(strm, strm->state->pending_buf);
  81127. TRY_FREE(strm, strm->state->head);
  81128. TRY_FREE(strm, strm->state->prev);
  81129. TRY_FREE(strm, strm->state->window);
  81130. ZFREE(strm, strm->state);
  81131. strm->state = Z_NULL;
  81132. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81133. }
  81134. /* =========================================================================
  81135. * Copy the source state to the destination state.
  81136. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81137. * doesn't have enough memory anyway to duplicate compression states).
  81138. */
  81139. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81140. {
  81141. #ifdef MAXSEG_64K
  81142. return Z_STREAM_ERROR;
  81143. #else
  81144. deflate_state *ds;
  81145. deflate_state *ss;
  81146. ushf *overlay;
  81147. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81148. return Z_STREAM_ERROR;
  81149. }
  81150. ss = source->state;
  81151. zmemcpy(dest, source, sizeof(z_stream));
  81152. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81153. if (ds == Z_NULL) return Z_MEM_ERROR;
  81154. dest->state = (struct internal_state FAR *) ds;
  81155. zmemcpy(ds, ss, sizeof(deflate_state));
  81156. ds->strm = dest;
  81157. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81158. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81159. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81160. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81161. ds->pending_buf = (uchf *) overlay;
  81162. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81163. ds->pending_buf == Z_NULL) {
  81164. deflateEnd (dest);
  81165. return Z_MEM_ERROR;
  81166. }
  81167. /* following zmemcpy do not work for 16-bit MSDOS */
  81168. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81169. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81170. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81171. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81172. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81173. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81174. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81175. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81176. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81177. ds->bl_desc.dyn_tree = ds->bl_tree;
  81178. return Z_OK;
  81179. #endif /* MAXSEG_64K */
  81180. }
  81181. /* ===========================================================================
  81182. * Read a new buffer from the current input stream, update the adler32
  81183. * and total number of bytes read. All deflate() input goes through
  81184. * this function so some applications may wish to modify it to avoid
  81185. * allocating a large strm->next_in buffer and copying from it.
  81186. * (See also flush_pending()).
  81187. */
  81188. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81189. {
  81190. unsigned len = strm->avail_in;
  81191. if (len > size) len = size;
  81192. if (len == 0) return 0;
  81193. strm->avail_in -= len;
  81194. if (strm->state->wrap == 1) {
  81195. strm->adler = adler32(strm->adler, strm->next_in, len);
  81196. }
  81197. #ifdef GZIP
  81198. else if (strm->state->wrap == 2) {
  81199. strm->adler = crc32(strm->adler, strm->next_in, len);
  81200. }
  81201. #endif
  81202. zmemcpy(buf, strm->next_in, len);
  81203. strm->next_in += len;
  81204. strm->total_in += len;
  81205. return (int)len;
  81206. }
  81207. /* ===========================================================================
  81208. * Initialize the "longest match" routines for a new zlib stream
  81209. */
  81210. local void lm_init (deflate_state *s)
  81211. {
  81212. s->window_size = (ulg)2L*s->w_size;
  81213. CLEAR_HASH(s);
  81214. /* Set the default configuration parameters:
  81215. */
  81216. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81217. s->good_match = configuration_table[s->level].good_length;
  81218. s->nice_match = configuration_table[s->level].nice_length;
  81219. s->max_chain_length = configuration_table[s->level].max_chain;
  81220. s->strstart = 0;
  81221. s->block_start = 0L;
  81222. s->lookahead = 0;
  81223. s->match_length = s->prev_length = MIN_MATCH-1;
  81224. s->match_available = 0;
  81225. s->ins_h = 0;
  81226. #ifndef FASTEST
  81227. #ifdef ASMV
  81228. match_init(); /* initialize the asm code */
  81229. #endif
  81230. #endif
  81231. }
  81232. #ifndef FASTEST
  81233. /* ===========================================================================
  81234. * Set match_start to the longest match starting at the given string and
  81235. * return its length. Matches shorter or equal to prev_length are discarded,
  81236. * in which case the result is equal to prev_length and match_start is
  81237. * garbage.
  81238. * IN assertions: cur_match is the head of the hash chain for the current
  81239. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81240. * OUT assertion: the match length is not greater than s->lookahead.
  81241. */
  81242. #ifndef ASMV
  81243. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81244. * match.S. The code will be functionally equivalent.
  81245. */
  81246. local uInt longest_match(deflate_state *s, IPos cur_match)
  81247. {
  81248. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81249. register Bytef *scan = s->window + s->strstart; /* current string */
  81250. register Bytef *match; /* matched string */
  81251. register int len; /* length of current match */
  81252. int best_len = s->prev_length; /* best match length so far */
  81253. int nice_match = s->nice_match; /* stop if match long enough */
  81254. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81255. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81256. /* Stop when cur_match becomes <= limit. To simplify the code,
  81257. * we prevent matches with the string of window index 0.
  81258. */
  81259. Posf *prev = s->prev;
  81260. uInt wmask = s->w_mask;
  81261. #ifdef UNALIGNED_OK
  81262. /* Compare two bytes at a time. Note: this is not always beneficial.
  81263. * Try with and without -DUNALIGNED_OK to check.
  81264. */
  81265. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81266. register ush scan_start = *(ushf*)scan;
  81267. register ush scan_end = *(ushf*)(scan+best_len-1);
  81268. #else
  81269. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81270. register Byte scan_end1 = scan[best_len-1];
  81271. register Byte scan_end = scan[best_len];
  81272. #endif
  81273. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81274. * It is easy to get rid of this optimization if necessary.
  81275. */
  81276. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81277. /* Do not waste too much time if we already have a good match: */
  81278. if (s->prev_length >= s->good_match) {
  81279. chain_length >>= 2;
  81280. }
  81281. /* Do not look for matches beyond the end of the input. This is necessary
  81282. * to make deflate deterministic.
  81283. */
  81284. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81285. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81286. do {
  81287. Assert(cur_match < s->strstart, "no future");
  81288. match = s->window + cur_match;
  81289. /* Skip to next match if the match length cannot increase
  81290. * or if the match length is less than 2. Note that the checks below
  81291. * for insufficient lookahead only occur occasionally for performance
  81292. * reasons. Therefore uninitialized memory will be accessed, and
  81293. * conditional jumps will be made that depend on those values.
  81294. * However the length of the match is limited to the lookahead, so
  81295. * the output of deflate is not affected by the uninitialized values.
  81296. */
  81297. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81298. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81299. * UNALIGNED_OK if your compiler uses a different size.
  81300. */
  81301. if (*(ushf*)(match+best_len-1) != scan_end ||
  81302. *(ushf*)match != scan_start) continue;
  81303. /* It is not necessary to compare scan[2] and match[2] since they are
  81304. * always equal when the other bytes match, given that the hash keys
  81305. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81306. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81307. * lookahead only every 4th comparison; the 128th check will be made
  81308. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81309. * necessary to put more guard bytes at the end of the window, or
  81310. * to check more often for insufficient lookahead.
  81311. */
  81312. Assert(scan[2] == match[2], "scan[2]?");
  81313. scan++, match++;
  81314. do {
  81315. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81316. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81317. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81318. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81319. scan < strend);
  81320. /* The funny "do {}" generates better code on most compilers */
  81321. /* Here, scan <= window+strstart+257 */
  81322. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81323. if (*scan == *match) scan++;
  81324. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81325. scan = strend - (MAX_MATCH-1);
  81326. #else /* UNALIGNED_OK */
  81327. if (match[best_len] != scan_end ||
  81328. match[best_len-1] != scan_end1 ||
  81329. *match != *scan ||
  81330. *++match != scan[1]) continue;
  81331. /* The check at best_len-1 can be removed because it will be made
  81332. * again later. (This heuristic is not always a win.)
  81333. * It is not necessary to compare scan[2] and match[2] since they
  81334. * are always equal when the other bytes match, given that
  81335. * the hash keys are equal and that HASH_BITS >= 8.
  81336. */
  81337. scan += 2, match++;
  81338. Assert(*scan == *match, "match[2]?");
  81339. /* We check for insufficient lookahead only every 8th comparison;
  81340. * the 256th check will be made at strstart+258.
  81341. */
  81342. do {
  81343. } while (*++scan == *++match && *++scan == *++match &&
  81344. *++scan == *++match && *++scan == *++match &&
  81345. *++scan == *++match && *++scan == *++match &&
  81346. *++scan == *++match && *++scan == *++match &&
  81347. scan < strend);
  81348. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81349. len = MAX_MATCH - (int)(strend - scan);
  81350. scan = strend - MAX_MATCH;
  81351. #endif /* UNALIGNED_OK */
  81352. if (len > best_len) {
  81353. s->match_start = cur_match;
  81354. best_len = len;
  81355. if (len >= nice_match) break;
  81356. #ifdef UNALIGNED_OK
  81357. scan_end = *(ushf*)(scan+best_len-1);
  81358. #else
  81359. scan_end1 = scan[best_len-1];
  81360. scan_end = scan[best_len];
  81361. #endif
  81362. }
  81363. } while ((cur_match = prev[cur_match & wmask]) > limit
  81364. && --chain_length != 0);
  81365. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81366. return s->lookahead;
  81367. }
  81368. #endif /* ASMV */
  81369. #endif /* FASTEST */
  81370. /* ---------------------------------------------------------------------------
  81371. * Optimized version for level == 1 or strategy == Z_RLE only
  81372. */
  81373. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81374. {
  81375. register Bytef *scan = s->window + s->strstart; /* current string */
  81376. register Bytef *match; /* matched string */
  81377. register int len; /* length of current match */
  81378. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81379. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81380. * It is easy to get rid of this optimization if necessary.
  81381. */
  81382. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81383. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81384. Assert(cur_match < s->strstart, "no future");
  81385. match = s->window + cur_match;
  81386. /* Return failure if the match length is less than 2:
  81387. */
  81388. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81389. /* The check at best_len-1 can be removed because it will be made
  81390. * again later. (This heuristic is not always a win.)
  81391. * It is not necessary to compare scan[2] and match[2] since they
  81392. * are always equal when the other bytes match, given that
  81393. * the hash keys are equal and that HASH_BITS >= 8.
  81394. */
  81395. scan += 2, match += 2;
  81396. Assert(*scan == *match, "match[2]?");
  81397. /* We check for insufficient lookahead only every 8th comparison;
  81398. * the 256th check will be made at strstart+258.
  81399. */
  81400. do {
  81401. } while (*++scan == *++match && *++scan == *++match &&
  81402. *++scan == *++match && *++scan == *++match &&
  81403. *++scan == *++match && *++scan == *++match &&
  81404. *++scan == *++match && *++scan == *++match &&
  81405. scan < strend);
  81406. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81407. len = MAX_MATCH - (int)(strend - scan);
  81408. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81409. s->match_start = cur_match;
  81410. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81411. }
  81412. #ifdef DEBUG
  81413. /* ===========================================================================
  81414. * Check that the match at match_start is indeed a match.
  81415. */
  81416. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81417. {
  81418. /* check that the match is indeed a match */
  81419. if (zmemcmp(s->window + match,
  81420. s->window + start, length) != EQUAL) {
  81421. fprintf(stderr, " start %u, match %u, length %d\n",
  81422. start, match, length);
  81423. do {
  81424. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81425. } while (--length != 0);
  81426. z_error("invalid match");
  81427. }
  81428. if (z_verbose > 1) {
  81429. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81430. do { putc(s->window[start++], stderr); } while (--length != 0);
  81431. }
  81432. }
  81433. #else
  81434. # define check_match(s, start, match, length)
  81435. #endif /* DEBUG */
  81436. /* ===========================================================================
  81437. * Fill the window when the lookahead becomes insufficient.
  81438. * Updates strstart and lookahead.
  81439. *
  81440. * IN assertion: lookahead < MIN_LOOKAHEAD
  81441. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81442. * At least one byte has been read, or avail_in == 0; reads are
  81443. * performed for at least two bytes (required for the zip translate_eol
  81444. * option -- not supported here).
  81445. */
  81446. local void fill_window (deflate_state *s)
  81447. {
  81448. register unsigned n, m;
  81449. register Posf *p;
  81450. unsigned more; /* Amount of free space at the end of the window. */
  81451. uInt wsize = s->w_size;
  81452. do {
  81453. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81454. /* Deal with !@#$% 64K limit: */
  81455. if (sizeof(int) <= 2) {
  81456. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81457. more = wsize;
  81458. } else if (more == (unsigned)(-1)) {
  81459. /* Very unlikely, but possible on 16 bit machine if
  81460. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81461. */
  81462. more--;
  81463. }
  81464. }
  81465. /* If the window is almost full and there is insufficient lookahead,
  81466. * move the upper half to the lower one to make room in the upper half.
  81467. */
  81468. if (s->strstart >= wsize+MAX_DIST(s)) {
  81469. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81470. s->match_start -= wsize;
  81471. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81472. s->block_start -= (long) wsize;
  81473. /* Slide the hash table (could be avoided with 32 bit values
  81474. at the expense of memory usage). We slide even when level == 0
  81475. to keep the hash table consistent if we switch back to level > 0
  81476. later. (Using level 0 permanently is not an optimal usage of
  81477. zlib, so we don't care about this pathological case.)
  81478. */
  81479. /* %%% avoid this when Z_RLE */
  81480. n = s->hash_size;
  81481. p = &s->head[n];
  81482. do {
  81483. m = *--p;
  81484. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81485. } while (--n);
  81486. n = wsize;
  81487. #ifndef FASTEST
  81488. p = &s->prev[n];
  81489. do {
  81490. m = *--p;
  81491. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81492. /* If n is not on any hash chain, prev[n] is garbage but
  81493. * its value will never be used.
  81494. */
  81495. } while (--n);
  81496. #endif
  81497. more += wsize;
  81498. }
  81499. if (s->strm->avail_in == 0) return;
  81500. /* If there was no sliding:
  81501. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81502. * more == window_size - lookahead - strstart
  81503. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81504. * => more >= window_size - 2*WSIZE + 2
  81505. * In the BIG_MEM or MMAP case (not yet supported),
  81506. * window_size == input_size + MIN_LOOKAHEAD &&
  81507. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81508. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81509. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81510. */
  81511. Assert(more >= 2, "more < 2");
  81512. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81513. s->lookahead += n;
  81514. /* Initialize the hash value now that we have some input: */
  81515. if (s->lookahead >= MIN_MATCH) {
  81516. s->ins_h = s->window[s->strstart];
  81517. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81518. #if MIN_MATCH != 3
  81519. Call UPDATE_HASH() MIN_MATCH-3 more times
  81520. #endif
  81521. }
  81522. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81523. * but this is not important since only literal bytes will be emitted.
  81524. */
  81525. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81526. }
  81527. /* ===========================================================================
  81528. * Flush the current block, with given end-of-file flag.
  81529. * IN assertion: strstart is set to the end of the current match.
  81530. */
  81531. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81532. _tr_flush_block(s, (s->block_start >= 0L ? \
  81533. (charf *)&s->window[(unsigned)s->block_start] : \
  81534. (charf *)Z_NULL), \
  81535. (ulg)((long)s->strstart - s->block_start), \
  81536. (eof)); \
  81537. s->block_start = s->strstart; \
  81538. flush_pending(s->strm); \
  81539. Tracev((stderr,"[FLUSH]")); \
  81540. }
  81541. /* Same but force premature exit if necessary. */
  81542. #define FLUSH_BLOCK(s, eof) { \
  81543. FLUSH_BLOCK_ONLY(s, eof); \
  81544. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81545. }
  81546. /* ===========================================================================
  81547. * Copy without compression as much as possible from the input stream, return
  81548. * the current block state.
  81549. * This function does not insert new strings in the dictionary since
  81550. * uncompressible data is probably not useful. This function is used
  81551. * only for the level=0 compression option.
  81552. * NOTE: this function should be optimized to avoid extra copying from
  81553. * window to pending_buf.
  81554. */
  81555. local block_state deflate_stored(deflate_state *s, int flush)
  81556. {
  81557. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81558. * to pending_buf_size, and each stored block has a 5 byte header:
  81559. */
  81560. ulg max_block_size = 0xffff;
  81561. ulg max_start;
  81562. if (max_block_size > s->pending_buf_size - 5) {
  81563. max_block_size = s->pending_buf_size - 5;
  81564. }
  81565. /* Copy as much as possible from input to output: */
  81566. for (;;) {
  81567. /* Fill the window as much as possible: */
  81568. if (s->lookahead <= 1) {
  81569. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81570. s->block_start >= (long)s->w_size, "slide too late");
  81571. fill_window(s);
  81572. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81573. if (s->lookahead == 0) break; /* flush the current block */
  81574. }
  81575. Assert(s->block_start >= 0L, "block gone");
  81576. s->strstart += s->lookahead;
  81577. s->lookahead = 0;
  81578. /* Emit a stored block if pending_buf will be full: */
  81579. max_start = s->block_start + max_block_size;
  81580. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81581. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81582. s->lookahead = (uInt)(s->strstart - max_start);
  81583. s->strstart = (uInt)max_start;
  81584. FLUSH_BLOCK(s, 0);
  81585. }
  81586. /* Flush if we may have to slide, otherwise block_start may become
  81587. * negative and the data will be gone:
  81588. */
  81589. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81590. FLUSH_BLOCK(s, 0);
  81591. }
  81592. }
  81593. FLUSH_BLOCK(s, flush == Z_FINISH);
  81594. return flush == Z_FINISH ? finish_done : block_done;
  81595. }
  81596. /* ===========================================================================
  81597. * Compress as much as possible from the input stream, return the current
  81598. * block state.
  81599. * This function does not perform lazy evaluation of matches and inserts
  81600. * new strings in the dictionary only for unmatched strings or for short
  81601. * matches. It is used only for the fast compression options.
  81602. */
  81603. local block_state deflate_fast(deflate_state *s, int flush)
  81604. {
  81605. IPos hash_head = NIL; /* head of the hash chain */
  81606. int bflush; /* set if current block must be flushed */
  81607. for (;;) {
  81608. /* Make sure that we always have enough lookahead, except
  81609. * at the end of the input file. We need MAX_MATCH bytes
  81610. * for the next match, plus MIN_MATCH bytes to insert the
  81611. * string following the next match.
  81612. */
  81613. if (s->lookahead < MIN_LOOKAHEAD) {
  81614. fill_window(s);
  81615. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81616. return need_more;
  81617. }
  81618. if (s->lookahead == 0) break; /* flush the current block */
  81619. }
  81620. /* Insert the string window[strstart .. strstart+2] in the
  81621. * dictionary, and set hash_head to the head of the hash chain:
  81622. */
  81623. if (s->lookahead >= MIN_MATCH) {
  81624. INSERT_STRING(s, s->strstart, hash_head);
  81625. }
  81626. /* Find the longest match, discarding those <= prev_length.
  81627. * At this point we have always match_length < MIN_MATCH
  81628. */
  81629. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81630. /* To simplify the code, we prevent matches with the string
  81631. * of window index 0 (in particular we have to avoid a match
  81632. * of the string with itself at the start of the input file).
  81633. */
  81634. #ifdef FASTEST
  81635. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81636. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81637. s->match_length = longest_match_fast (s, hash_head);
  81638. }
  81639. #else
  81640. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81641. s->match_length = longest_match (s, hash_head);
  81642. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81643. s->match_length = longest_match_fast (s, hash_head);
  81644. }
  81645. #endif
  81646. /* longest_match() or longest_match_fast() sets match_start */
  81647. }
  81648. if (s->match_length >= MIN_MATCH) {
  81649. check_match(s, s->strstart, s->match_start, s->match_length);
  81650. _tr_tally_dist(s, s->strstart - s->match_start,
  81651. s->match_length - MIN_MATCH, bflush);
  81652. s->lookahead -= s->match_length;
  81653. /* Insert new strings in the hash table only if the match length
  81654. * is not too large. This saves time but degrades compression.
  81655. */
  81656. #ifndef FASTEST
  81657. if (s->match_length <= s->max_insert_length &&
  81658. s->lookahead >= MIN_MATCH) {
  81659. s->match_length--; /* string at strstart already in table */
  81660. do {
  81661. s->strstart++;
  81662. INSERT_STRING(s, s->strstart, hash_head);
  81663. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81664. * always MIN_MATCH bytes ahead.
  81665. */
  81666. } while (--s->match_length != 0);
  81667. s->strstart++;
  81668. } else
  81669. #endif
  81670. {
  81671. s->strstart += s->match_length;
  81672. s->match_length = 0;
  81673. s->ins_h = s->window[s->strstart];
  81674. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81675. #if MIN_MATCH != 3
  81676. Call UPDATE_HASH() MIN_MATCH-3 more times
  81677. #endif
  81678. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81679. * matter since it will be recomputed at next deflate call.
  81680. */
  81681. }
  81682. } else {
  81683. /* No match, output a literal byte */
  81684. Tracevv((stderr,"%c", s->window[s->strstart]));
  81685. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81686. s->lookahead--;
  81687. s->strstart++;
  81688. }
  81689. if (bflush) FLUSH_BLOCK(s, 0);
  81690. }
  81691. FLUSH_BLOCK(s, flush == Z_FINISH);
  81692. return flush == Z_FINISH ? finish_done : block_done;
  81693. }
  81694. #ifndef FASTEST
  81695. /* ===========================================================================
  81696. * Same as above, but achieves better compression. We use a lazy
  81697. * evaluation for matches: a match is finally adopted only if there is
  81698. * no better match at the next window position.
  81699. */
  81700. local block_state deflate_slow(deflate_state *s, int flush)
  81701. {
  81702. IPos hash_head = NIL; /* head of hash chain */
  81703. int bflush; /* set if current block must be flushed */
  81704. /* Process the input block. */
  81705. for (;;) {
  81706. /* Make sure that we always have enough lookahead, except
  81707. * at the end of the input file. We need MAX_MATCH bytes
  81708. * for the next match, plus MIN_MATCH bytes to insert the
  81709. * string following the next match.
  81710. */
  81711. if (s->lookahead < MIN_LOOKAHEAD) {
  81712. fill_window(s);
  81713. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81714. return need_more;
  81715. }
  81716. if (s->lookahead == 0) break; /* flush the current block */
  81717. }
  81718. /* Insert the string window[strstart .. strstart+2] in the
  81719. * dictionary, and set hash_head to the head of the hash chain:
  81720. */
  81721. if (s->lookahead >= MIN_MATCH) {
  81722. INSERT_STRING(s, s->strstart, hash_head);
  81723. }
  81724. /* Find the longest match, discarding those <= prev_length.
  81725. */
  81726. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81727. s->match_length = MIN_MATCH-1;
  81728. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81729. s->strstart - hash_head <= MAX_DIST(s)) {
  81730. /* To simplify the code, we prevent matches with the string
  81731. * of window index 0 (in particular we have to avoid a match
  81732. * of the string with itself at the start of the input file).
  81733. */
  81734. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81735. s->match_length = longest_match (s, hash_head);
  81736. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81737. s->match_length = longest_match_fast (s, hash_head);
  81738. }
  81739. /* longest_match() or longest_match_fast() sets match_start */
  81740. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81741. #if TOO_FAR <= 32767
  81742. || (s->match_length == MIN_MATCH &&
  81743. s->strstart - s->match_start > TOO_FAR)
  81744. #endif
  81745. )) {
  81746. /* If prev_match is also MIN_MATCH, match_start is garbage
  81747. * but we will ignore the current match anyway.
  81748. */
  81749. s->match_length = MIN_MATCH-1;
  81750. }
  81751. }
  81752. /* If there was a match at the previous step and the current
  81753. * match is not better, output the previous match:
  81754. */
  81755. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81756. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81757. /* Do not insert strings in hash table beyond this. */
  81758. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81759. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81760. s->prev_length - MIN_MATCH, bflush);
  81761. /* Insert in hash table all strings up to the end of the match.
  81762. * strstart-1 and strstart are already inserted. If there is not
  81763. * enough lookahead, the last two strings are not inserted in
  81764. * the hash table.
  81765. */
  81766. s->lookahead -= s->prev_length-1;
  81767. s->prev_length -= 2;
  81768. do {
  81769. if (++s->strstart <= max_insert) {
  81770. INSERT_STRING(s, s->strstart, hash_head);
  81771. }
  81772. } while (--s->prev_length != 0);
  81773. s->match_available = 0;
  81774. s->match_length = MIN_MATCH-1;
  81775. s->strstart++;
  81776. if (bflush) FLUSH_BLOCK(s, 0);
  81777. } else if (s->match_available) {
  81778. /* If there was no match at the previous position, output a
  81779. * single literal. If there was a match but the current match
  81780. * is longer, truncate the previous match to a single literal.
  81781. */
  81782. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81783. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81784. if (bflush) {
  81785. FLUSH_BLOCK_ONLY(s, 0);
  81786. }
  81787. s->strstart++;
  81788. s->lookahead--;
  81789. if (s->strm->avail_out == 0) return need_more;
  81790. } else {
  81791. /* There is no previous match to compare with, wait for
  81792. * the next step to decide.
  81793. */
  81794. s->match_available = 1;
  81795. s->strstart++;
  81796. s->lookahead--;
  81797. }
  81798. }
  81799. Assert (flush != Z_NO_FLUSH, "no flush?");
  81800. if (s->match_available) {
  81801. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81802. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81803. s->match_available = 0;
  81804. }
  81805. FLUSH_BLOCK(s, flush == Z_FINISH);
  81806. return flush == Z_FINISH ? finish_done : block_done;
  81807. }
  81808. #endif /* FASTEST */
  81809. #if 0
  81810. /* ===========================================================================
  81811. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81812. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81813. * deflate switches away from Z_RLE.)
  81814. */
  81815. local block_state deflate_rle(s, flush)
  81816. deflate_state *s;
  81817. int flush;
  81818. {
  81819. int bflush; /* set if current block must be flushed */
  81820. uInt run; /* length of run */
  81821. uInt max; /* maximum length of run */
  81822. uInt prev; /* byte at distance one to match */
  81823. Bytef *scan; /* scan for end of run */
  81824. for (;;) {
  81825. /* Make sure that we always have enough lookahead, except
  81826. * at the end of the input file. We need MAX_MATCH bytes
  81827. * for the longest encodable run.
  81828. */
  81829. if (s->lookahead < MAX_MATCH) {
  81830. fill_window(s);
  81831. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  81832. return need_more;
  81833. }
  81834. if (s->lookahead == 0) break; /* flush the current block */
  81835. }
  81836. /* See how many times the previous byte repeats */
  81837. run = 0;
  81838. if (s->strstart > 0) { /* if there is a previous byte, that is */
  81839. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  81840. scan = s->window + s->strstart - 1;
  81841. prev = *scan++;
  81842. do {
  81843. if (*scan++ != prev)
  81844. break;
  81845. } while (++run < max);
  81846. }
  81847. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  81848. if (run >= MIN_MATCH) {
  81849. check_match(s, s->strstart, s->strstart - 1, run);
  81850. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  81851. s->lookahead -= run;
  81852. s->strstart += run;
  81853. } else {
  81854. /* No match, output a literal byte */
  81855. Tracevv((stderr,"%c", s->window[s->strstart]));
  81856. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81857. s->lookahead--;
  81858. s->strstart++;
  81859. }
  81860. if (bflush) FLUSH_BLOCK(s, 0);
  81861. }
  81862. FLUSH_BLOCK(s, flush == Z_FINISH);
  81863. return flush == Z_FINISH ? finish_done : block_done;
  81864. }
  81865. #endif
  81866. /*** End of inlined file: deflate.c ***/
  81867. /*** Start of inlined file: inffast.c ***/
  81868. /*** Start of inlined file: inftrees.h ***/
  81869. /* WARNING: this file should *not* be used by applications. It is
  81870. part of the implementation of the compression library and is
  81871. subject to change. Applications should only use zlib.h.
  81872. */
  81873. #ifndef _INFTREES_H_
  81874. #define _INFTREES_H_
  81875. /* Structure for decoding tables. Each entry provides either the
  81876. information needed to do the operation requested by the code that
  81877. indexed that table entry, or it provides a pointer to another
  81878. table that indexes more bits of the code. op indicates whether
  81879. the entry is a pointer to another table, a literal, a length or
  81880. distance, an end-of-block, or an invalid code. For a table
  81881. pointer, the low four bits of op is the number of index bits of
  81882. that table. For a length or distance, the low four bits of op
  81883. is the number of extra bits to get after the code. bits is
  81884. the number of bits in this code or part of the code to drop off
  81885. of the bit buffer. val is the actual byte to output in the case
  81886. of a literal, the base length or distance, or the offset from
  81887. the current table to the next table. Each entry is four bytes. */
  81888. typedef struct {
  81889. unsigned char op; /* operation, extra bits, table bits */
  81890. unsigned char bits; /* bits in this part of the code */
  81891. unsigned short val; /* offset in table or code value */
  81892. } code;
  81893. /* op values as set by inflate_table():
  81894. 00000000 - literal
  81895. 0000tttt - table link, tttt != 0 is the number of table index bits
  81896. 0001eeee - length or distance, eeee is the number of extra bits
  81897. 01100000 - end of block
  81898. 01000000 - invalid code
  81899. */
  81900. /* Maximum size of dynamic tree. The maximum found in a long but non-
  81901. exhaustive search was 1444 code structures (852 for length/literals
  81902. and 592 for distances, the latter actually the result of an
  81903. exhaustive search). The true maximum is not known, but the value
  81904. below is more than safe. */
  81905. #define ENOUGH 2048
  81906. #define MAXD 592
  81907. /* Type of code to build for inftable() */
  81908. typedef enum {
  81909. CODES,
  81910. LENS,
  81911. DISTS
  81912. } codetype;
  81913. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  81914. unsigned codes, code FAR * FAR *table,
  81915. unsigned FAR *bits, unsigned short FAR *work));
  81916. #endif
  81917. /*** End of inlined file: inftrees.h ***/
  81918. /*** Start of inlined file: inflate.h ***/
  81919. /* WARNING: this file should *not* be used by applications. It is
  81920. part of the implementation of the compression library and is
  81921. subject to change. Applications should only use zlib.h.
  81922. */
  81923. #ifndef _INFLATE_H_
  81924. #define _INFLATE_H_
  81925. /* define NO_GZIP when compiling if you want to disable gzip header and
  81926. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  81927. the crc code when it is not needed. For shared libraries, gzip decoding
  81928. should be left enabled. */
  81929. #ifndef NO_GZIP
  81930. # define GUNZIP
  81931. #endif
  81932. /* Possible inflate modes between inflate() calls */
  81933. typedef enum {
  81934. HEAD, /* i: waiting for magic header */
  81935. FLAGS, /* i: waiting for method and flags (gzip) */
  81936. TIME, /* i: waiting for modification time (gzip) */
  81937. OS, /* i: waiting for extra flags and operating system (gzip) */
  81938. EXLEN, /* i: waiting for extra length (gzip) */
  81939. EXTRA, /* i: waiting for extra bytes (gzip) */
  81940. NAME, /* i: waiting for end of file name (gzip) */
  81941. COMMENT, /* i: waiting for end of comment (gzip) */
  81942. HCRC, /* i: waiting for header crc (gzip) */
  81943. DICTID, /* i: waiting for dictionary check value */
  81944. DICT, /* waiting for inflateSetDictionary() call */
  81945. TYPE, /* i: waiting for type bits, including last-flag bit */
  81946. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  81947. STORED, /* i: waiting for stored size (length and complement) */
  81948. COPY, /* i/o: waiting for input or output to copy stored block */
  81949. TABLE, /* i: waiting for dynamic block table lengths */
  81950. LENLENS, /* i: waiting for code length code lengths */
  81951. CODELENS, /* i: waiting for length/lit and distance code lengths */
  81952. LEN, /* i: waiting for length/lit code */
  81953. LENEXT, /* i: waiting for length extra bits */
  81954. DIST, /* i: waiting for distance code */
  81955. DISTEXT, /* i: waiting for distance extra bits */
  81956. MATCH, /* o: waiting for output space to copy string */
  81957. LIT, /* o: waiting for output space to write literal */
  81958. CHECK, /* i: waiting for 32-bit check value */
  81959. LENGTH, /* i: waiting for 32-bit length (gzip) */
  81960. DONE, /* finished check, done -- remain here until reset */
  81961. BAD, /* got a data error -- remain here until reset */
  81962. MEM, /* got an inflate() memory error -- remain here until reset */
  81963. SYNC /* looking for synchronization bytes to restart inflate() */
  81964. } inflate_mode;
  81965. /*
  81966. State transitions between above modes -
  81967. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  81968. Process header:
  81969. HEAD -> (gzip) or (zlib)
  81970. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  81971. NAME -> COMMENT -> HCRC -> TYPE
  81972. (zlib) -> DICTID or TYPE
  81973. DICTID -> DICT -> TYPE
  81974. Read deflate blocks:
  81975. TYPE -> STORED or TABLE or LEN or CHECK
  81976. STORED -> COPY -> TYPE
  81977. TABLE -> LENLENS -> CODELENS -> LEN
  81978. Read deflate codes:
  81979. LEN -> LENEXT or LIT or TYPE
  81980. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  81981. LIT -> LEN
  81982. Process trailer:
  81983. CHECK -> LENGTH -> DONE
  81984. */
  81985. /* state maintained between inflate() calls. Approximately 7K bytes. */
  81986. struct inflate_state {
  81987. inflate_mode mode; /* current inflate mode */
  81988. int last; /* true if processing last block */
  81989. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81990. int havedict; /* true if dictionary provided */
  81991. int flags; /* gzip header method and flags (0 if zlib) */
  81992. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  81993. unsigned long check; /* protected copy of check value */
  81994. unsigned long total; /* protected copy of output count */
  81995. gz_headerp head; /* where to save gzip header information */
  81996. /* sliding window */
  81997. unsigned wbits; /* log base 2 of requested window size */
  81998. unsigned wsize; /* window size or zero if not using window */
  81999. unsigned whave; /* valid bytes in the window */
  82000. unsigned write; /* window write index */
  82001. unsigned char FAR *window; /* allocated sliding window, if needed */
  82002. /* bit accumulator */
  82003. unsigned long hold; /* input bit accumulator */
  82004. unsigned bits; /* number of bits in "in" */
  82005. /* for string and stored block copying */
  82006. unsigned length; /* literal or length of data to copy */
  82007. unsigned offset; /* distance back to copy string from */
  82008. /* for table and code decoding */
  82009. unsigned extra; /* extra bits needed */
  82010. /* fixed and dynamic code tables */
  82011. code const FAR *lencode; /* starting table for length/literal codes */
  82012. code const FAR *distcode; /* starting table for distance codes */
  82013. unsigned lenbits; /* index bits for lencode */
  82014. unsigned distbits; /* index bits for distcode */
  82015. /* dynamic table building */
  82016. unsigned ncode; /* number of code length code lengths */
  82017. unsigned nlen; /* number of length code lengths */
  82018. unsigned ndist; /* number of distance code lengths */
  82019. unsigned have; /* number of code lengths in lens[] */
  82020. code FAR *next; /* next available space in codes[] */
  82021. unsigned short lens[320]; /* temporary storage for code lengths */
  82022. unsigned short work[288]; /* work area for code table building */
  82023. code codes[ENOUGH]; /* space for code tables */
  82024. };
  82025. #endif
  82026. /*** End of inlined file: inflate.h ***/
  82027. /*** Start of inlined file: inffast.h ***/
  82028. /* WARNING: this file should *not* be used by applications. It is
  82029. part of the implementation of the compression library and is
  82030. subject to change. Applications should only use zlib.h.
  82031. */
  82032. void inflate_fast OF((z_streamp strm, unsigned start));
  82033. /*** End of inlined file: inffast.h ***/
  82034. #ifndef ASMINF
  82035. /* Allow machine dependent optimization for post-increment or pre-increment.
  82036. Based on testing to date,
  82037. Pre-increment preferred for:
  82038. - PowerPC G3 (Adler)
  82039. - MIPS R5000 (Randers-Pehrson)
  82040. Post-increment preferred for:
  82041. - none
  82042. No measurable difference:
  82043. - Pentium III (Anderson)
  82044. - M68060 (Nikl)
  82045. */
  82046. #ifdef POSTINC
  82047. # define OFF 0
  82048. # define PUP(a) *(a)++
  82049. #else
  82050. # define OFF 1
  82051. # define PUP(a) *++(a)
  82052. #endif
  82053. /*
  82054. Decode literal, length, and distance codes and write out the resulting
  82055. literal and match bytes until either not enough input or output is
  82056. available, an end-of-block is encountered, or a data error is encountered.
  82057. When large enough input and output buffers are supplied to inflate(), for
  82058. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82059. inflate execution time is spent in this routine.
  82060. Entry assumptions:
  82061. state->mode == LEN
  82062. strm->avail_in >= 6
  82063. strm->avail_out >= 258
  82064. start >= strm->avail_out
  82065. state->bits < 8
  82066. On return, state->mode is one of:
  82067. LEN -- ran out of enough output space or enough available input
  82068. TYPE -- reached end of block code, inflate() to interpret next block
  82069. BAD -- error in block data
  82070. Notes:
  82071. - The maximum input bits used by a length/distance pair is 15 bits for the
  82072. length code, 5 bits for the length extra, 15 bits for the distance code,
  82073. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82074. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82075. checking for available input while decoding.
  82076. - The maximum bytes that a single length/distance pair can output is 258
  82077. bytes, which is the maximum length that can be coded. inflate_fast()
  82078. requires strm->avail_out >= 258 for each loop to avoid checking for
  82079. output space.
  82080. */
  82081. void inflate_fast (z_streamp strm, unsigned start)
  82082. {
  82083. struct inflate_state FAR *state;
  82084. unsigned char FAR *in; /* local strm->next_in */
  82085. unsigned char FAR *last; /* while in < last, enough input available */
  82086. unsigned char FAR *out; /* local strm->next_out */
  82087. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82088. unsigned char FAR *end; /* while out < end, enough space available */
  82089. #ifdef INFLATE_STRICT
  82090. unsigned dmax; /* maximum distance from zlib header */
  82091. #endif
  82092. unsigned wsize; /* window size or zero if not using window */
  82093. unsigned whave; /* valid bytes in the window */
  82094. unsigned write; /* window write index */
  82095. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82096. unsigned long hold; /* local strm->hold */
  82097. unsigned bits; /* local strm->bits */
  82098. code const FAR *lcode; /* local strm->lencode */
  82099. code const FAR *dcode; /* local strm->distcode */
  82100. unsigned lmask; /* mask for first level of length codes */
  82101. unsigned dmask; /* mask for first level of distance codes */
  82102. code thisx; /* retrieved table entry */
  82103. unsigned op; /* code bits, operation, extra bits, or */
  82104. /* window position, window bytes to copy */
  82105. unsigned len; /* match length, unused bytes */
  82106. unsigned dist; /* match distance */
  82107. unsigned char FAR *from; /* where to copy match from */
  82108. /* copy state to local variables */
  82109. state = (struct inflate_state FAR *)strm->state;
  82110. in = strm->next_in - OFF;
  82111. last = in + (strm->avail_in - 5);
  82112. out = strm->next_out - OFF;
  82113. beg = out - (start - strm->avail_out);
  82114. end = out + (strm->avail_out - 257);
  82115. #ifdef INFLATE_STRICT
  82116. dmax = state->dmax;
  82117. #endif
  82118. wsize = state->wsize;
  82119. whave = state->whave;
  82120. write = state->write;
  82121. window = state->window;
  82122. hold = state->hold;
  82123. bits = state->bits;
  82124. lcode = state->lencode;
  82125. dcode = state->distcode;
  82126. lmask = (1U << state->lenbits) - 1;
  82127. dmask = (1U << state->distbits) - 1;
  82128. /* decode literals and length/distances until end-of-block or not enough
  82129. input data or output space */
  82130. do {
  82131. if (bits < 15) {
  82132. hold += (unsigned long)(PUP(in)) << bits;
  82133. bits += 8;
  82134. hold += (unsigned long)(PUP(in)) << bits;
  82135. bits += 8;
  82136. }
  82137. thisx = lcode[hold & lmask];
  82138. dolen:
  82139. op = (unsigned)(thisx.bits);
  82140. hold >>= op;
  82141. bits -= op;
  82142. op = (unsigned)(thisx.op);
  82143. if (op == 0) { /* literal */
  82144. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82145. "inflate: literal '%c'\n" :
  82146. "inflate: literal 0x%02x\n", thisx.val));
  82147. PUP(out) = (unsigned char)(thisx.val);
  82148. }
  82149. else if (op & 16) { /* length base */
  82150. len = (unsigned)(thisx.val);
  82151. op &= 15; /* number of extra bits */
  82152. if (op) {
  82153. if (bits < op) {
  82154. hold += (unsigned long)(PUP(in)) << bits;
  82155. bits += 8;
  82156. }
  82157. len += (unsigned)hold & ((1U << op) - 1);
  82158. hold >>= op;
  82159. bits -= op;
  82160. }
  82161. Tracevv((stderr, "inflate: length %u\n", len));
  82162. if (bits < 15) {
  82163. hold += (unsigned long)(PUP(in)) << bits;
  82164. bits += 8;
  82165. hold += (unsigned long)(PUP(in)) << bits;
  82166. bits += 8;
  82167. }
  82168. thisx = dcode[hold & dmask];
  82169. dodist:
  82170. op = (unsigned)(thisx.bits);
  82171. hold >>= op;
  82172. bits -= op;
  82173. op = (unsigned)(thisx.op);
  82174. if (op & 16) { /* distance base */
  82175. dist = (unsigned)(thisx.val);
  82176. op &= 15; /* number of extra bits */
  82177. if (bits < op) {
  82178. hold += (unsigned long)(PUP(in)) << bits;
  82179. bits += 8;
  82180. if (bits < op) {
  82181. hold += (unsigned long)(PUP(in)) << bits;
  82182. bits += 8;
  82183. }
  82184. }
  82185. dist += (unsigned)hold & ((1U << op) - 1);
  82186. #ifdef INFLATE_STRICT
  82187. if (dist > dmax) {
  82188. strm->msg = (char *)"invalid distance too far back";
  82189. state->mode = BAD;
  82190. break;
  82191. }
  82192. #endif
  82193. hold >>= op;
  82194. bits -= op;
  82195. Tracevv((stderr, "inflate: distance %u\n", dist));
  82196. op = (unsigned)(out - beg); /* max distance in output */
  82197. if (dist > op) { /* see if copy from window */
  82198. op = dist - op; /* distance back in window */
  82199. if (op > whave) {
  82200. strm->msg = (char *)"invalid distance too far back";
  82201. state->mode = BAD;
  82202. break;
  82203. }
  82204. from = window - OFF;
  82205. if (write == 0) { /* very common case */
  82206. from += wsize - op;
  82207. if (op < len) { /* some from window */
  82208. len -= op;
  82209. do {
  82210. PUP(out) = PUP(from);
  82211. } while (--op);
  82212. from = out - dist; /* rest from output */
  82213. }
  82214. }
  82215. else if (write < op) { /* wrap around window */
  82216. from += wsize + write - op;
  82217. op -= write;
  82218. if (op < len) { /* some from end of window */
  82219. len -= op;
  82220. do {
  82221. PUP(out) = PUP(from);
  82222. } while (--op);
  82223. from = window - OFF;
  82224. if (write < len) { /* some from start of window */
  82225. op = write;
  82226. len -= op;
  82227. do {
  82228. PUP(out) = PUP(from);
  82229. } while (--op);
  82230. from = out - dist; /* rest from output */
  82231. }
  82232. }
  82233. }
  82234. else { /* contiguous in window */
  82235. from += write - op;
  82236. if (op < len) { /* some from window */
  82237. len -= op;
  82238. do {
  82239. PUP(out) = PUP(from);
  82240. } while (--op);
  82241. from = out - dist; /* rest from output */
  82242. }
  82243. }
  82244. while (len > 2) {
  82245. PUP(out) = PUP(from);
  82246. PUP(out) = PUP(from);
  82247. PUP(out) = PUP(from);
  82248. len -= 3;
  82249. }
  82250. if (len) {
  82251. PUP(out) = PUP(from);
  82252. if (len > 1)
  82253. PUP(out) = PUP(from);
  82254. }
  82255. }
  82256. else {
  82257. from = out - dist; /* copy direct from output */
  82258. do { /* minimum length is three */
  82259. PUP(out) = PUP(from);
  82260. PUP(out) = PUP(from);
  82261. PUP(out) = PUP(from);
  82262. len -= 3;
  82263. } while (len > 2);
  82264. if (len) {
  82265. PUP(out) = PUP(from);
  82266. if (len > 1)
  82267. PUP(out) = PUP(from);
  82268. }
  82269. }
  82270. }
  82271. else if ((op & 64) == 0) { /* 2nd level distance code */
  82272. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82273. goto dodist;
  82274. }
  82275. else {
  82276. strm->msg = (char *)"invalid distance code";
  82277. state->mode = BAD;
  82278. break;
  82279. }
  82280. }
  82281. else if ((op & 64) == 0) { /* 2nd level length code */
  82282. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82283. goto dolen;
  82284. }
  82285. else if (op & 32) { /* end-of-block */
  82286. Tracevv((stderr, "inflate: end of block\n"));
  82287. state->mode = TYPE;
  82288. break;
  82289. }
  82290. else {
  82291. strm->msg = (char *)"invalid literal/length code";
  82292. state->mode = BAD;
  82293. break;
  82294. }
  82295. } while (in < last && out < end);
  82296. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82297. len = bits >> 3;
  82298. in -= len;
  82299. bits -= len << 3;
  82300. hold &= (1U << bits) - 1;
  82301. /* update state and return */
  82302. strm->next_in = in + OFF;
  82303. strm->next_out = out + OFF;
  82304. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82305. strm->avail_out = (unsigned)(out < end ?
  82306. 257 + (end - out) : 257 - (out - end));
  82307. state->hold = hold;
  82308. state->bits = bits;
  82309. return;
  82310. }
  82311. /*
  82312. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82313. - Using bit fields for code structure
  82314. - Different op definition to avoid & for extra bits (do & for table bits)
  82315. - Three separate decoding do-loops for direct, window, and write == 0
  82316. - Special case for distance > 1 copies to do overlapped load and store copy
  82317. - Explicit branch predictions (based on measured branch probabilities)
  82318. - Deferring match copy and interspersed it with decoding subsequent codes
  82319. - Swapping literal/length else
  82320. - Swapping window/direct else
  82321. - Larger unrolled copy loops (three is about right)
  82322. - Moving len -= 3 statement into middle of loop
  82323. */
  82324. #endif /* !ASMINF */
  82325. /*** End of inlined file: inffast.c ***/
  82326. #undef PULLBYTE
  82327. #undef LOAD
  82328. #undef RESTORE
  82329. #undef INITBITS
  82330. #undef NEEDBITS
  82331. #undef DROPBITS
  82332. #undef BYTEBITS
  82333. /*** Start of inlined file: inflate.c ***/
  82334. /*
  82335. * Change history:
  82336. *
  82337. * 1.2.beta0 24 Nov 2002
  82338. * - First version -- complete rewrite of inflate to simplify code, avoid
  82339. * creation of window when not needed, minimize use of window when it is
  82340. * needed, make inffast.c even faster, implement gzip decoding, and to
  82341. * improve code readability and style over the previous zlib inflate code
  82342. *
  82343. * 1.2.beta1 25 Nov 2002
  82344. * - Use pointers for available input and output checking in inffast.c
  82345. * - Remove input and output counters in inffast.c
  82346. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82347. * - Remove unnecessary second byte pull from length extra in inffast.c
  82348. * - Unroll direct copy to three copies per loop in inffast.c
  82349. *
  82350. * 1.2.beta2 4 Dec 2002
  82351. * - Change external routine names to reduce potential conflicts
  82352. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82353. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82354. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82355. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82356. *
  82357. * 1.2.beta3 22 Dec 2002
  82358. * - Add comments on state->bits assertion in inffast.c
  82359. * - Add comments on op field in inftrees.h
  82360. * - Fix bug in reuse of allocated window after inflateReset()
  82361. * - Remove bit fields--back to byte structure for speed
  82362. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82363. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82364. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82365. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82366. * - Use local copies of stream next and avail values, as well as local bit
  82367. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82368. *
  82369. * 1.2.beta4 1 Jan 2003
  82370. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82371. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82372. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82373. * - Rearrange window copies in inflate_fast() for speed and simplification
  82374. * - Unroll last copy for window match in inflate_fast()
  82375. * - Use local copies of window variables in inflate_fast() for speed
  82376. * - Pull out common write == 0 case for speed in inflate_fast()
  82377. * - Make op and len in inflate_fast() unsigned for consistency
  82378. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82379. * - Simplified bad distance check in inflate_fast()
  82380. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82381. * source file infback.c to provide a call-back interface to inflate for
  82382. * programs like gzip and unzip -- uses window as output buffer to avoid
  82383. * window copying
  82384. *
  82385. * 1.2.beta5 1 Jan 2003
  82386. * - Improved inflateBack() interface to allow the caller to provide initial
  82387. * input in strm.
  82388. * - Fixed stored blocks bug in inflateBack()
  82389. *
  82390. * 1.2.beta6 4 Jan 2003
  82391. * - Added comments in inffast.c on effectiveness of POSTINC
  82392. * - Typecasting all around to reduce compiler warnings
  82393. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82394. * make compilers happy
  82395. * - Changed type of window in inflateBackInit() to unsigned char *
  82396. *
  82397. * 1.2.beta7 27 Jan 2003
  82398. * - Changed many types to unsigned or unsigned short to avoid warnings
  82399. * - Added inflateCopy() function
  82400. *
  82401. * 1.2.0 9 Mar 2003
  82402. * - Changed inflateBack() interface to provide separate opaque descriptors
  82403. * for the in() and out() functions
  82404. * - Changed inflateBack() argument and in_func typedef to swap the length
  82405. * and buffer address return values for the input function
  82406. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82407. *
  82408. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82409. */
  82410. /*** Start of inlined file: inffast.h ***/
  82411. /* WARNING: this file should *not* be used by applications. It is
  82412. part of the implementation of the compression library and is
  82413. subject to change. Applications should only use zlib.h.
  82414. */
  82415. void inflate_fast OF((z_streamp strm, unsigned start));
  82416. /*** End of inlined file: inffast.h ***/
  82417. #ifdef MAKEFIXED
  82418. # ifndef BUILDFIXED
  82419. # define BUILDFIXED
  82420. # endif
  82421. #endif
  82422. /* function prototypes */
  82423. local void fixedtables OF((struct inflate_state FAR *state));
  82424. local int updatewindow OF((z_streamp strm, unsigned out));
  82425. #ifdef BUILDFIXED
  82426. void makefixed OF((void));
  82427. #endif
  82428. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82429. unsigned len));
  82430. int ZEXPORT inflateReset (z_streamp strm)
  82431. {
  82432. struct inflate_state FAR *state;
  82433. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82434. state = (struct inflate_state FAR *)strm->state;
  82435. strm->total_in = strm->total_out = state->total = 0;
  82436. strm->msg = Z_NULL;
  82437. strm->adler = 1; /* to support ill-conceived Java test suite */
  82438. state->mode = HEAD;
  82439. state->last = 0;
  82440. state->havedict = 0;
  82441. state->dmax = 32768U;
  82442. state->head = Z_NULL;
  82443. state->wsize = 0;
  82444. state->whave = 0;
  82445. state->write = 0;
  82446. state->hold = 0;
  82447. state->bits = 0;
  82448. state->lencode = state->distcode = state->next = state->codes;
  82449. Tracev((stderr, "inflate: reset\n"));
  82450. return Z_OK;
  82451. }
  82452. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82453. {
  82454. struct inflate_state FAR *state;
  82455. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82456. state = (struct inflate_state FAR *)strm->state;
  82457. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82458. value &= (1L << bits) - 1;
  82459. state->hold += value << state->bits;
  82460. state->bits += bits;
  82461. return Z_OK;
  82462. }
  82463. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82464. {
  82465. struct inflate_state FAR *state;
  82466. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82467. stream_size != (int)(sizeof(z_stream)))
  82468. return Z_VERSION_ERROR;
  82469. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82470. strm->msg = Z_NULL; /* in case we return an error */
  82471. if (strm->zalloc == (alloc_func)0) {
  82472. strm->zalloc = zcalloc;
  82473. strm->opaque = (voidpf)0;
  82474. }
  82475. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82476. state = (struct inflate_state FAR *)
  82477. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82478. if (state == Z_NULL) return Z_MEM_ERROR;
  82479. Tracev((stderr, "inflate: allocated\n"));
  82480. strm->state = (struct internal_state FAR *)state;
  82481. if (windowBits < 0) {
  82482. state->wrap = 0;
  82483. windowBits = -windowBits;
  82484. }
  82485. else {
  82486. state->wrap = (windowBits >> 4) + 1;
  82487. #ifdef GUNZIP
  82488. if (windowBits < 48) windowBits &= 15;
  82489. #endif
  82490. }
  82491. if (windowBits < 8 || windowBits > 15) {
  82492. ZFREE(strm, state);
  82493. strm->state = Z_NULL;
  82494. return Z_STREAM_ERROR;
  82495. }
  82496. state->wbits = (unsigned)windowBits;
  82497. state->window = Z_NULL;
  82498. return inflateReset(strm);
  82499. }
  82500. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82501. {
  82502. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82503. }
  82504. /*
  82505. Return state with length and distance decoding tables and index sizes set to
  82506. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82507. If BUILDFIXED is defined, then instead this routine builds the tables the
  82508. first time it's called, and returns those tables the first time and
  82509. thereafter. This reduces the size of the code by about 2K bytes, in
  82510. exchange for a little execution time. However, BUILDFIXED should not be
  82511. used for threaded applications, since the rewriting of the tables and virgin
  82512. may not be thread-safe.
  82513. */
  82514. local void fixedtables (struct inflate_state FAR *state)
  82515. {
  82516. #ifdef BUILDFIXED
  82517. static int virgin = 1;
  82518. static code *lenfix, *distfix;
  82519. static code fixed[544];
  82520. /* build fixed huffman tables if first call (may not be thread safe) */
  82521. if (virgin) {
  82522. unsigned sym, bits;
  82523. static code *next;
  82524. /* literal/length table */
  82525. sym = 0;
  82526. while (sym < 144) state->lens[sym++] = 8;
  82527. while (sym < 256) state->lens[sym++] = 9;
  82528. while (sym < 280) state->lens[sym++] = 7;
  82529. while (sym < 288) state->lens[sym++] = 8;
  82530. next = fixed;
  82531. lenfix = next;
  82532. bits = 9;
  82533. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82534. /* distance table */
  82535. sym = 0;
  82536. while (sym < 32) state->lens[sym++] = 5;
  82537. distfix = next;
  82538. bits = 5;
  82539. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82540. /* do this just once */
  82541. virgin = 0;
  82542. }
  82543. #else /* !BUILDFIXED */
  82544. /*** Start of inlined file: inffixed.h ***/
  82545. /* WARNING: this file should *not* be used by applications. It
  82546. is part of the implementation of the compression library and
  82547. is subject to change. Applications should only use zlib.h.
  82548. */
  82549. static const code lenfix[512] = {
  82550. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82551. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82552. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82553. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82554. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82555. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82556. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82557. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82558. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82559. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82560. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82561. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82562. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82563. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82564. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82565. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82566. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82567. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82568. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82569. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82570. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82571. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82572. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82573. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82574. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82575. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82576. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82577. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82578. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82579. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82580. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82581. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82582. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82583. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82584. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82585. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82586. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82587. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82588. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82589. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82590. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82591. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82592. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82593. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82594. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82595. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82596. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82597. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82598. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82599. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82600. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82601. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82602. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82603. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82604. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82605. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82606. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82607. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82608. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82609. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82610. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82611. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82612. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82613. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82614. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82615. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82616. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82617. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82618. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82619. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82620. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82621. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82622. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82623. {0,9,255}
  82624. };
  82625. static const code distfix[32] = {
  82626. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82627. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82628. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82629. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82630. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82631. {22,5,193},{64,5,0}
  82632. };
  82633. /*** End of inlined file: inffixed.h ***/
  82634. #endif /* BUILDFIXED */
  82635. state->lencode = lenfix;
  82636. state->lenbits = 9;
  82637. state->distcode = distfix;
  82638. state->distbits = 5;
  82639. }
  82640. #ifdef MAKEFIXED
  82641. #include <stdio.h>
  82642. /*
  82643. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82644. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82645. those tables to stdout, which would be piped to inffixed.h. A small program
  82646. can simply call makefixed to do this:
  82647. void makefixed(void);
  82648. int main(void)
  82649. {
  82650. makefixed();
  82651. return 0;
  82652. }
  82653. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82654. a.out > inffixed.h
  82655. */
  82656. void makefixed()
  82657. {
  82658. unsigned low, size;
  82659. struct inflate_state state;
  82660. fixedtables(&state);
  82661. puts(" /* inffixed.h -- table for decoding fixed codes");
  82662. puts(" * Generated automatically by makefixed().");
  82663. puts(" */");
  82664. puts("");
  82665. puts(" /* WARNING: this file should *not* be used by applications.");
  82666. puts(" It is part of the implementation of this library and is");
  82667. puts(" subject to change. Applications should only use zlib.h.");
  82668. puts(" */");
  82669. puts("");
  82670. size = 1U << 9;
  82671. printf(" static const code lenfix[%u] = {", size);
  82672. low = 0;
  82673. for (;;) {
  82674. if ((low % 7) == 0) printf("\n ");
  82675. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82676. state.lencode[low].val);
  82677. if (++low == size) break;
  82678. putchar(',');
  82679. }
  82680. puts("\n };");
  82681. size = 1U << 5;
  82682. printf("\n static const code distfix[%u] = {", size);
  82683. low = 0;
  82684. for (;;) {
  82685. if ((low % 6) == 0) printf("\n ");
  82686. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82687. state.distcode[low].val);
  82688. if (++low == size) break;
  82689. putchar(',');
  82690. }
  82691. puts("\n };");
  82692. }
  82693. #endif /* MAKEFIXED */
  82694. /*
  82695. Update the window with the last wsize (normally 32K) bytes written before
  82696. returning. If window does not exist yet, create it. This is only called
  82697. when a window is already in use, or when output has been written during this
  82698. inflate call, but the end of the deflate stream has not been reached yet.
  82699. It is also called to create a window for dictionary data when a dictionary
  82700. is loaded.
  82701. Providing output buffers larger than 32K to inflate() should provide a speed
  82702. advantage, since only the last 32K of output is copied to the sliding window
  82703. upon return from inflate(), and since all distances after the first 32K of
  82704. output will fall in the output data, making match copies simpler and faster.
  82705. The advantage may be dependent on the size of the processor's data caches.
  82706. */
  82707. local int updatewindow (z_streamp strm, unsigned out)
  82708. {
  82709. struct inflate_state FAR *state;
  82710. unsigned copy, dist;
  82711. state = (struct inflate_state FAR *)strm->state;
  82712. /* if it hasn't been done already, allocate space for the window */
  82713. if (state->window == Z_NULL) {
  82714. state->window = (unsigned char FAR *)
  82715. ZALLOC(strm, 1U << state->wbits,
  82716. sizeof(unsigned char));
  82717. if (state->window == Z_NULL) return 1;
  82718. }
  82719. /* if window not in use yet, initialize */
  82720. if (state->wsize == 0) {
  82721. state->wsize = 1U << state->wbits;
  82722. state->write = 0;
  82723. state->whave = 0;
  82724. }
  82725. /* copy state->wsize or less output bytes into the circular window */
  82726. copy = out - strm->avail_out;
  82727. if (copy >= state->wsize) {
  82728. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82729. state->write = 0;
  82730. state->whave = state->wsize;
  82731. }
  82732. else {
  82733. dist = state->wsize - state->write;
  82734. if (dist > copy) dist = copy;
  82735. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82736. copy -= dist;
  82737. if (copy) {
  82738. zmemcpy(state->window, strm->next_out - copy, copy);
  82739. state->write = copy;
  82740. state->whave = state->wsize;
  82741. }
  82742. else {
  82743. state->write += dist;
  82744. if (state->write == state->wsize) state->write = 0;
  82745. if (state->whave < state->wsize) state->whave += dist;
  82746. }
  82747. }
  82748. return 0;
  82749. }
  82750. /* Macros for inflate(): */
  82751. /* check function to use adler32() for zlib or crc32() for gzip */
  82752. #ifdef GUNZIP
  82753. # define UPDATE(check, buf, len) \
  82754. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82755. #else
  82756. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82757. #endif
  82758. /* check macros for header crc */
  82759. #ifdef GUNZIP
  82760. # define CRC2(check, word) \
  82761. do { \
  82762. hbuf[0] = (unsigned char)(word); \
  82763. hbuf[1] = (unsigned char)((word) >> 8); \
  82764. check = crc32(check, hbuf, 2); \
  82765. } while (0)
  82766. # define CRC4(check, word) \
  82767. do { \
  82768. hbuf[0] = (unsigned char)(word); \
  82769. hbuf[1] = (unsigned char)((word) >> 8); \
  82770. hbuf[2] = (unsigned char)((word) >> 16); \
  82771. hbuf[3] = (unsigned char)((word) >> 24); \
  82772. check = crc32(check, hbuf, 4); \
  82773. } while (0)
  82774. #endif
  82775. /* Load registers with state in inflate() for speed */
  82776. #define LOAD() \
  82777. do { \
  82778. put = strm->next_out; \
  82779. left = strm->avail_out; \
  82780. next = strm->next_in; \
  82781. have = strm->avail_in; \
  82782. hold = state->hold; \
  82783. bits = state->bits; \
  82784. } while (0)
  82785. /* Restore state from registers in inflate() */
  82786. #define RESTORE() \
  82787. do { \
  82788. strm->next_out = put; \
  82789. strm->avail_out = left; \
  82790. strm->next_in = next; \
  82791. strm->avail_in = have; \
  82792. state->hold = hold; \
  82793. state->bits = bits; \
  82794. } while (0)
  82795. /* Clear the input bit accumulator */
  82796. #define INITBITS() \
  82797. do { \
  82798. hold = 0; \
  82799. bits = 0; \
  82800. } while (0)
  82801. /* Get a byte of input into the bit accumulator, or return from inflate()
  82802. if there is no input available. */
  82803. #define PULLBYTE() \
  82804. do { \
  82805. if (have == 0) goto inf_leave; \
  82806. have--; \
  82807. hold += (unsigned long)(*next++) << bits; \
  82808. bits += 8; \
  82809. } while (0)
  82810. /* Assure that there are at least n bits in the bit accumulator. If there is
  82811. not enough available input to do that, then return from inflate(). */
  82812. #define NEEDBITS(n) \
  82813. do { \
  82814. while (bits < (unsigned)(n)) \
  82815. PULLBYTE(); \
  82816. } while (0)
  82817. /* Return the low n bits of the bit accumulator (n < 16) */
  82818. #define BITS(n) \
  82819. ((unsigned)hold & ((1U << (n)) - 1))
  82820. /* Remove n bits from the bit accumulator */
  82821. #define DROPBITS(n) \
  82822. do { \
  82823. hold >>= (n); \
  82824. bits -= (unsigned)(n); \
  82825. } while (0)
  82826. /* Remove zero to seven bits as needed to go to a byte boundary */
  82827. #define BYTEBITS() \
  82828. do { \
  82829. hold >>= bits & 7; \
  82830. bits -= bits & 7; \
  82831. } while (0)
  82832. /* Reverse the bytes in a 32-bit value */
  82833. #define REVERSE(q) \
  82834. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  82835. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  82836. /*
  82837. inflate() uses a state machine to process as much input data and generate as
  82838. much output data as possible before returning. The state machine is
  82839. structured roughly as follows:
  82840. for (;;) switch (state) {
  82841. ...
  82842. case STATEn:
  82843. if (not enough input data or output space to make progress)
  82844. return;
  82845. ... make progress ...
  82846. state = STATEm;
  82847. break;
  82848. ...
  82849. }
  82850. so when inflate() is called again, the same case is attempted again, and
  82851. if the appropriate resources are provided, the machine proceeds to the
  82852. next state. The NEEDBITS() macro is usually the way the state evaluates
  82853. whether it can proceed or should return. NEEDBITS() does the return if
  82854. the requested bits are not available. The typical use of the BITS macros
  82855. is:
  82856. NEEDBITS(n);
  82857. ... do something with BITS(n) ...
  82858. DROPBITS(n);
  82859. where NEEDBITS(n) either returns from inflate() if there isn't enough
  82860. input left to load n bits into the accumulator, or it continues. BITS(n)
  82861. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  82862. the low n bits off the accumulator. INITBITS() clears the accumulator
  82863. and sets the number of available bits to zero. BYTEBITS() discards just
  82864. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  82865. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  82866. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  82867. if there is no input available. The decoding of variable length codes uses
  82868. PULLBYTE() directly in order to pull just enough bytes to decode the next
  82869. code, and no more.
  82870. Some states loop until they get enough input, making sure that enough
  82871. state information is maintained to continue the loop where it left off
  82872. if NEEDBITS() returns in the loop. For example, want, need, and keep
  82873. would all have to actually be part of the saved state in case NEEDBITS()
  82874. returns:
  82875. case STATEw:
  82876. while (want < need) {
  82877. NEEDBITS(n);
  82878. keep[want++] = BITS(n);
  82879. DROPBITS(n);
  82880. }
  82881. state = STATEx;
  82882. case STATEx:
  82883. As shown above, if the next state is also the next case, then the break
  82884. is omitted.
  82885. A state may also return if there is not enough output space available to
  82886. complete that state. Those states are copying stored data, writing a
  82887. literal byte, and copying a matching string.
  82888. When returning, a "goto inf_leave" is used to update the total counters,
  82889. update the check value, and determine whether any progress has been made
  82890. during that inflate() call in order to return the proper return code.
  82891. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  82892. When there is a window, goto inf_leave will update the window with the last
  82893. output written. If a goto inf_leave occurs in the middle of decompression
  82894. and there is no window currently, goto inf_leave will create one and copy
  82895. output to the window for the next call of inflate().
  82896. In this implementation, the flush parameter of inflate() only affects the
  82897. return code (per zlib.h). inflate() always writes as much as possible to
  82898. strm->next_out, given the space available and the provided input--the effect
  82899. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  82900. the allocation of and copying into a sliding window until necessary, which
  82901. provides the effect documented in zlib.h for Z_FINISH when the entire input
  82902. stream available. So the only thing the flush parameter actually does is:
  82903. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  82904. will return Z_BUF_ERROR if it has not reached the end of the stream.
  82905. */
  82906. int ZEXPORT inflate (z_streamp strm, int flush)
  82907. {
  82908. struct inflate_state FAR *state;
  82909. unsigned char FAR *next; /* next input */
  82910. unsigned char FAR *put; /* next output */
  82911. unsigned have, left; /* available input and output */
  82912. unsigned long hold; /* bit buffer */
  82913. unsigned bits; /* bits in bit buffer */
  82914. unsigned in, out; /* save starting available input and output */
  82915. unsigned copy; /* number of stored or match bytes to copy */
  82916. unsigned char FAR *from; /* where to copy match bytes from */
  82917. code thisx; /* current decoding table entry */
  82918. code last; /* parent table entry */
  82919. unsigned len; /* length to copy for repeats, bits to drop */
  82920. int ret; /* return code */
  82921. #ifdef GUNZIP
  82922. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  82923. #endif
  82924. static const unsigned short order[19] = /* permutation of code lengths */
  82925. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  82926. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  82927. (strm->next_in == Z_NULL && strm->avail_in != 0))
  82928. return Z_STREAM_ERROR;
  82929. state = (struct inflate_state FAR *)strm->state;
  82930. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  82931. LOAD();
  82932. in = have;
  82933. out = left;
  82934. ret = Z_OK;
  82935. for (;;)
  82936. switch (state->mode) {
  82937. case HEAD:
  82938. if (state->wrap == 0) {
  82939. state->mode = TYPEDO;
  82940. break;
  82941. }
  82942. NEEDBITS(16);
  82943. #ifdef GUNZIP
  82944. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  82945. state->check = crc32(0L, Z_NULL, 0);
  82946. CRC2(state->check, hold);
  82947. INITBITS();
  82948. state->mode = FLAGS;
  82949. break;
  82950. }
  82951. state->flags = 0; /* expect zlib header */
  82952. if (state->head != Z_NULL)
  82953. state->head->done = -1;
  82954. if (!(state->wrap & 1) || /* check if zlib header allowed */
  82955. #else
  82956. if (
  82957. #endif
  82958. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  82959. strm->msg = (char *)"incorrect header check";
  82960. state->mode = BAD;
  82961. break;
  82962. }
  82963. if (BITS(4) != Z_DEFLATED) {
  82964. strm->msg = (char *)"unknown compression method";
  82965. state->mode = BAD;
  82966. break;
  82967. }
  82968. DROPBITS(4);
  82969. len = BITS(4) + 8;
  82970. if (len > state->wbits) {
  82971. strm->msg = (char *)"invalid window size";
  82972. state->mode = BAD;
  82973. break;
  82974. }
  82975. state->dmax = 1U << len;
  82976. Tracev((stderr, "inflate: zlib header ok\n"));
  82977. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82978. state->mode = hold & 0x200 ? DICTID : TYPE;
  82979. INITBITS();
  82980. break;
  82981. #ifdef GUNZIP
  82982. case FLAGS:
  82983. NEEDBITS(16);
  82984. state->flags = (int)(hold);
  82985. if ((state->flags & 0xff) != Z_DEFLATED) {
  82986. strm->msg = (char *)"unknown compression method";
  82987. state->mode = BAD;
  82988. break;
  82989. }
  82990. if (state->flags & 0xe000) {
  82991. strm->msg = (char *)"unknown header flags set";
  82992. state->mode = BAD;
  82993. break;
  82994. }
  82995. if (state->head != Z_NULL)
  82996. state->head->text = (int)((hold >> 8) & 1);
  82997. if (state->flags & 0x0200) CRC2(state->check, hold);
  82998. INITBITS();
  82999. state->mode = TIME;
  83000. case TIME:
  83001. NEEDBITS(32);
  83002. if (state->head != Z_NULL)
  83003. state->head->time = hold;
  83004. if (state->flags & 0x0200) CRC4(state->check, hold);
  83005. INITBITS();
  83006. state->mode = OS;
  83007. case OS:
  83008. NEEDBITS(16);
  83009. if (state->head != Z_NULL) {
  83010. state->head->xflags = (int)(hold & 0xff);
  83011. state->head->os = (int)(hold >> 8);
  83012. }
  83013. if (state->flags & 0x0200) CRC2(state->check, hold);
  83014. INITBITS();
  83015. state->mode = EXLEN;
  83016. case EXLEN:
  83017. if (state->flags & 0x0400) {
  83018. NEEDBITS(16);
  83019. state->length = (unsigned)(hold);
  83020. if (state->head != Z_NULL)
  83021. state->head->extra_len = (unsigned)hold;
  83022. if (state->flags & 0x0200) CRC2(state->check, hold);
  83023. INITBITS();
  83024. }
  83025. else if (state->head != Z_NULL)
  83026. state->head->extra = Z_NULL;
  83027. state->mode = EXTRA;
  83028. case EXTRA:
  83029. if (state->flags & 0x0400) {
  83030. copy = state->length;
  83031. if (copy > have) copy = have;
  83032. if (copy) {
  83033. if (state->head != Z_NULL &&
  83034. state->head->extra != Z_NULL) {
  83035. len = state->head->extra_len - state->length;
  83036. zmemcpy(state->head->extra + len, next,
  83037. len + copy > state->head->extra_max ?
  83038. state->head->extra_max - len : copy);
  83039. }
  83040. if (state->flags & 0x0200)
  83041. state->check = crc32(state->check, next, copy);
  83042. have -= copy;
  83043. next += copy;
  83044. state->length -= copy;
  83045. }
  83046. if (state->length) goto inf_leave;
  83047. }
  83048. state->length = 0;
  83049. state->mode = NAME;
  83050. case NAME:
  83051. if (state->flags & 0x0800) {
  83052. if (have == 0) goto inf_leave;
  83053. copy = 0;
  83054. do {
  83055. len = (unsigned)(next[copy++]);
  83056. if (state->head != Z_NULL &&
  83057. state->head->name != Z_NULL &&
  83058. state->length < state->head->name_max)
  83059. state->head->name[state->length++] = len;
  83060. } while (len && copy < have);
  83061. if (state->flags & 0x0200)
  83062. state->check = crc32(state->check, next, copy);
  83063. have -= copy;
  83064. next += copy;
  83065. if (len) goto inf_leave;
  83066. }
  83067. else if (state->head != Z_NULL)
  83068. state->head->name = Z_NULL;
  83069. state->length = 0;
  83070. state->mode = COMMENT;
  83071. case COMMENT:
  83072. if (state->flags & 0x1000) {
  83073. if (have == 0) goto inf_leave;
  83074. copy = 0;
  83075. do {
  83076. len = (unsigned)(next[copy++]);
  83077. if (state->head != Z_NULL &&
  83078. state->head->comment != Z_NULL &&
  83079. state->length < state->head->comm_max)
  83080. state->head->comment[state->length++] = len;
  83081. } while (len && copy < have);
  83082. if (state->flags & 0x0200)
  83083. state->check = crc32(state->check, next, copy);
  83084. have -= copy;
  83085. next += copy;
  83086. if (len) goto inf_leave;
  83087. }
  83088. else if (state->head != Z_NULL)
  83089. state->head->comment = Z_NULL;
  83090. state->mode = HCRC;
  83091. case HCRC:
  83092. if (state->flags & 0x0200) {
  83093. NEEDBITS(16);
  83094. if (hold != (state->check & 0xffff)) {
  83095. strm->msg = (char *)"header crc mismatch";
  83096. state->mode = BAD;
  83097. break;
  83098. }
  83099. INITBITS();
  83100. }
  83101. if (state->head != Z_NULL) {
  83102. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83103. state->head->done = 1;
  83104. }
  83105. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83106. state->mode = TYPE;
  83107. break;
  83108. #endif
  83109. case DICTID:
  83110. NEEDBITS(32);
  83111. strm->adler = state->check = REVERSE(hold);
  83112. INITBITS();
  83113. state->mode = DICT;
  83114. case DICT:
  83115. if (state->havedict == 0) {
  83116. RESTORE();
  83117. return Z_NEED_DICT;
  83118. }
  83119. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83120. state->mode = TYPE;
  83121. case TYPE:
  83122. if (flush == Z_BLOCK) goto inf_leave;
  83123. case TYPEDO:
  83124. if (state->last) {
  83125. BYTEBITS();
  83126. state->mode = CHECK;
  83127. break;
  83128. }
  83129. NEEDBITS(3);
  83130. state->last = BITS(1);
  83131. DROPBITS(1);
  83132. switch (BITS(2)) {
  83133. case 0: /* stored block */
  83134. Tracev((stderr, "inflate: stored block%s\n",
  83135. state->last ? " (last)" : ""));
  83136. state->mode = STORED;
  83137. break;
  83138. case 1: /* fixed block */
  83139. fixedtables(state);
  83140. Tracev((stderr, "inflate: fixed codes block%s\n",
  83141. state->last ? " (last)" : ""));
  83142. state->mode = LEN; /* decode codes */
  83143. break;
  83144. case 2: /* dynamic block */
  83145. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83146. state->last ? " (last)" : ""));
  83147. state->mode = TABLE;
  83148. break;
  83149. case 3:
  83150. strm->msg = (char *)"invalid block type";
  83151. state->mode = BAD;
  83152. }
  83153. DROPBITS(2);
  83154. break;
  83155. case STORED:
  83156. BYTEBITS(); /* go to byte boundary */
  83157. NEEDBITS(32);
  83158. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83159. strm->msg = (char *)"invalid stored block lengths";
  83160. state->mode = BAD;
  83161. break;
  83162. }
  83163. state->length = (unsigned)hold & 0xffff;
  83164. Tracev((stderr, "inflate: stored length %u\n",
  83165. state->length));
  83166. INITBITS();
  83167. state->mode = COPY;
  83168. case COPY:
  83169. copy = state->length;
  83170. if (copy) {
  83171. if (copy > have) copy = have;
  83172. if (copy > left) copy = left;
  83173. if (copy == 0) goto inf_leave;
  83174. zmemcpy(put, next, copy);
  83175. have -= copy;
  83176. next += copy;
  83177. left -= copy;
  83178. put += copy;
  83179. state->length -= copy;
  83180. break;
  83181. }
  83182. Tracev((stderr, "inflate: stored end\n"));
  83183. state->mode = TYPE;
  83184. break;
  83185. case TABLE:
  83186. NEEDBITS(14);
  83187. state->nlen = BITS(5) + 257;
  83188. DROPBITS(5);
  83189. state->ndist = BITS(5) + 1;
  83190. DROPBITS(5);
  83191. state->ncode = BITS(4) + 4;
  83192. DROPBITS(4);
  83193. #ifndef PKZIP_BUG_WORKAROUND
  83194. if (state->nlen > 286 || state->ndist > 30) {
  83195. strm->msg = (char *)"too many length or distance symbols";
  83196. state->mode = BAD;
  83197. break;
  83198. }
  83199. #endif
  83200. Tracev((stderr, "inflate: table sizes ok\n"));
  83201. state->have = 0;
  83202. state->mode = LENLENS;
  83203. case LENLENS:
  83204. while (state->have < state->ncode) {
  83205. NEEDBITS(3);
  83206. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83207. DROPBITS(3);
  83208. }
  83209. while (state->have < 19)
  83210. state->lens[order[state->have++]] = 0;
  83211. state->next = state->codes;
  83212. state->lencode = (code const FAR *)(state->next);
  83213. state->lenbits = 7;
  83214. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83215. &(state->lenbits), state->work);
  83216. if (ret) {
  83217. strm->msg = (char *)"invalid code lengths set";
  83218. state->mode = BAD;
  83219. break;
  83220. }
  83221. Tracev((stderr, "inflate: code lengths ok\n"));
  83222. state->have = 0;
  83223. state->mode = CODELENS;
  83224. case CODELENS:
  83225. while (state->have < state->nlen + state->ndist) {
  83226. for (;;) {
  83227. thisx = state->lencode[BITS(state->lenbits)];
  83228. if ((unsigned)(thisx.bits) <= bits) break;
  83229. PULLBYTE();
  83230. }
  83231. if (thisx.val < 16) {
  83232. NEEDBITS(thisx.bits);
  83233. DROPBITS(thisx.bits);
  83234. state->lens[state->have++] = thisx.val;
  83235. }
  83236. else {
  83237. if (thisx.val == 16) {
  83238. NEEDBITS(thisx.bits + 2);
  83239. DROPBITS(thisx.bits);
  83240. if (state->have == 0) {
  83241. strm->msg = (char *)"invalid bit length repeat";
  83242. state->mode = BAD;
  83243. break;
  83244. }
  83245. len = state->lens[state->have - 1];
  83246. copy = 3 + BITS(2);
  83247. DROPBITS(2);
  83248. }
  83249. else if (thisx.val == 17) {
  83250. NEEDBITS(thisx.bits + 3);
  83251. DROPBITS(thisx.bits);
  83252. len = 0;
  83253. copy = 3 + BITS(3);
  83254. DROPBITS(3);
  83255. }
  83256. else {
  83257. NEEDBITS(thisx.bits + 7);
  83258. DROPBITS(thisx.bits);
  83259. len = 0;
  83260. copy = 11 + BITS(7);
  83261. DROPBITS(7);
  83262. }
  83263. if (state->have + copy > state->nlen + state->ndist) {
  83264. strm->msg = (char *)"invalid bit length repeat";
  83265. state->mode = BAD;
  83266. break;
  83267. }
  83268. while (copy--)
  83269. state->lens[state->have++] = (unsigned short)len;
  83270. }
  83271. }
  83272. /* handle error breaks in while */
  83273. if (state->mode == BAD) break;
  83274. /* build code tables */
  83275. state->next = state->codes;
  83276. state->lencode = (code const FAR *)(state->next);
  83277. state->lenbits = 9;
  83278. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83279. &(state->lenbits), state->work);
  83280. if (ret) {
  83281. strm->msg = (char *)"invalid literal/lengths set";
  83282. state->mode = BAD;
  83283. break;
  83284. }
  83285. state->distcode = (code const FAR *)(state->next);
  83286. state->distbits = 6;
  83287. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83288. &(state->next), &(state->distbits), state->work);
  83289. if (ret) {
  83290. strm->msg = (char *)"invalid distances set";
  83291. state->mode = BAD;
  83292. break;
  83293. }
  83294. Tracev((stderr, "inflate: codes ok\n"));
  83295. state->mode = LEN;
  83296. case LEN:
  83297. if (have >= 6 && left >= 258) {
  83298. RESTORE();
  83299. inflate_fast(strm, out);
  83300. LOAD();
  83301. break;
  83302. }
  83303. for (;;) {
  83304. thisx = state->lencode[BITS(state->lenbits)];
  83305. if ((unsigned)(thisx.bits) <= bits) break;
  83306. PULLBYTE();
  83307. }
  83308. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83309. last = thisx;
  83310. for (;;) {
  83311. thisx = state->lencode[last.val +
  83312. (BITS(last.bits + last.op) >> last.bits)];
  83313. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83314. PULLBYTE();
  83315. }
  83316. DROPBITS(last.bits);
  83317. }
  83318. DROPBITS(thisx.bits);
  83319. state->length = (unsigned)thisx.val;
  83320. if ((int)(thisx.op) == 0) {
  83321. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83322. "inflate: literal '%c'\n" :
  83323. "inflate: literal 0x%02x\n", thisx.val));
  83324. state->mode = LIT;
  83325. break;
  83326. }
  83327. if (thisx.op & 32) {
  83328. Tracevv((stderr, "inflate: end of block\n"));
  83329. state->mode = TYPE;
  83330. break;
  83331. }
  83332. if (thisx.op & 64) {
  83333. strm->msg = (char *)"invalid literal/length code";
  83334. state->mode = BAD;
  83335. break;
  83336. }
  83337. state->extra = (unsigned)(thisx.op) & 15;
  83338. state->mode = LENEXT;
  83339. case LENEXT:
  83340. if (state->extra) {
  83341. NEEDBITS(state->extra);
  83342. state->length += BITS(state->extra);
  83343. DROPBITS(state->extra);
  83344. }
  83345. Tracevv((stderr, "inflate: length %u\n", state->length));
  83346. state->mode = DIST;
  83347. case DIST:
  83348. for (;;) {
  83349. thisx = state->distcode[BITS(state->distbits)];
  83350. if ((unsigned)(thisx.bits) <= bits) break;
  83351. PULLBYTE();
  83352. }
  83353. if ((thisx.op & 0xf0) == 0) {
  83354. last = thisx;
  83355. for (;;) {
  83356. thisx = state->distcode[last.val +
  83357. (BITS(last.bits + last.op) >> last.bits)];
  83358. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83359. PULLBYTE();
  83360. }
  83361. DROPBITS(last.bits);
  83362. }
  83363. DROPBITS(thisx.bits);
  83364. if (thisx.op & 64) {
  83365. strm->msg = (char *)"invalid distance code";
  83366. state->mode = BAD;
  83367. break;
  83368. }
  83369. state->offset = (unsigned)thisx.val;
  83370. state->extra = (unsigned)(thisx.op) & 15;
  83371. state->mode = DISTEXT;
  83372. case DISTEXT:
  83373. if (state->extra) {
  83374. NEEDBITS(state->extra);
  83375. state->offset += BITS(state->extra);
  83376. DROPBITS(state->extra);
  83377. }
  83378. #ifdef INFLATE_STRICT
  83379. if (state->offset > state->dmax) {
  83380. strm->msg = (char *)"invalid distance too far back";
  83381. state->mode = BAD;
  83382. break;
  83383. }
  83384. #endif
  83385. if (state->offset > state->whave + out - left) {
  83386. strm->msg = (char *)"invalid distance too far back";
  83387. state->mode = BAD;
  83388. break;
  83389. }
  83390. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83391. state->mode = MATCH;
  83392. case MATCH:
  83393. if (left == 0) goto inf_leave;
  83394. copy = out - left;
  83395. if (state->offset > copy) { /* copy from window */
  83396. copy = state->offset - copy;
  83397. if (copy > state->write) {
  83398. copy -= state->write;
  83399. from = state->window + (state->wsize - copy);
  83400. }
  83401. else
  83402. from = state->window + (state->write - copy);
  83403. if (copy > state->length) copy = state->length;
  83404. }
  83405. else { /* copy from output */
  83406. from = put - state->offset;
  83407. copy = state->length;
  83408. }
  83409. if (copy > left) copy = left;
  83410. left -= copy;
  83411. state->length -= copy;
  83412. do {
  83413. *put++ = *from++;
  83414. } while (--copy);
  83415. if (state->length == 0) state->mode = LEN;
  83416. break;
  83417. case LIT:
  83418. if (left == 0) goto inf_leave;
  83419. *put++ = (unsigned char)(state->length);
  83420. left--;
  83421. state->mode = LEN;
  83422. break;
  83423. case CHECK:
  83424. if (state->wrap) {
  83425. NEEDBITS(32);
  83426. out -= left;
  83427. strm->total_out += out;
  83428. state->total += out;
  83429. if (out)
  83430. strm->adler = state->check =
  83431. UPDATE(state->check, put - out, out);
  83432. out = left;
  83433. if ((
  83434. #ifdef GUNZIP
  83435. state->flags ? hold :
  83436. #endif
  83437. REVERSE(hold)) != state->check) {
  83438. strm->msg = (char *)"incorrect data check";
  83439. state->mode = BAD;
  83440. break;
  83441. }
  83442. INITBITS();
  83443. Tracev((stderr, "inflate: check matches trailer\n"));
  83444. }
  83445. #ifdef GUNZIP
  83446. state->mode = LENGTH;
  83447. case LENGTH:
  83448. if (state->wrap && state->flags) {
  83449. NEEDBITS(32);
  83450. if (hold != (state->total & 0xffffffffUL)) {
  83451. strm->msg = (char *)"incorrect length check";
  83452. state->mode = BAD;
  83453. break;
  83454. }
  83455. INITBITS();
  83456. Tracev((stderr, "inflate: length matches trailer\n"));
  83457. }
  83458. #endif
  83459. state->mode = DONE;
  83460. case DONE:
  83461. ret = Z_STREAM_END;
  83462. goto inf_leave;
  83463. case BAD:
  83464. ret = Z_DATA_ERROR;
  83465. goto inf_leave;
  83466. case MEM:
  83467. return Z_MEM_ERROR;
  83468. case SYNC:
  83469. default:
  83470. return Z_STREAM_ERROR;
  83471. }
  83472. /*
  83473. Return from inflate(), updating the total counts and the check value.
  83474. If there was no progress during the inflate() call, return a buffer
  83475. error. Call updatewindow() to create and/or update the window state.
  83476. Note: a memory error from inflate() is non-recoverable.
  83477. */
  83478. inf_leave:
  83479. RESTORE();
  83480. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83481. if (updatewindow(strm, out)) {
  83482. state->mode = MEM;
  83483. return Z_MEM_ERROR;
  83484. }
  83485. in -= strm->avail_in;
  83486. out -= strm->avail_out;
  83487. strm->total_in += in;
  83488. strm->total_out += out;
  83489. state->total += out;
  83490. if (state->wrap && out)
  83491. strm->adler = state->check =
  83492. UPDATE(state->check, strm->next_out - out, out);
  83493. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83494. (state->mode == TYPE ? 128 : 0);
  83495. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83496. ret = Z_BUF_ERROR;
  83497. return ret;
  83498. }
  83499. int ZEXPORT inflateEnd (z_streamp strm)
  83500. {
  83501. struct inflate_state FAR *state;
  83502. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83503. return Z_STREAM_ERROR;
  83504. state = (struct inflate_state FAR *)strm->state;
  83505. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83506. ZFREE(strm, strm->state);
  83507. strm->state = Z_NULL;
  83508. Tracev((stderr, "inflate: end\n"));
  83509. return Z_OK;
  83510. }
  83511. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83512. {
  83513. struct inflate_state FAR *state;
  83514. unsigned long id_;
  83515. /* check state */
  83516. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83517. state = (struct inflate_state FAR *)strm->state;
  83518. if (state->wrap != 0 && state->mode != DICT)
  83519. return Z_STREAM_ERROR;
  83520. /* check for correct dictionary id */
  83521. if (state->mode == DICT) {
  83522. id_ = adler32(0L, Z_NULL, 0);
  83523. id_ = adler32(id_, dictionary, dictLength);
  83524. if (id_ != state->check)
  83525. return Z_DATA_ERROR;
  83526. }
  83527. /* copy dictionary to window */
  83528. if (updatewindow(strm, strm->avail_out)) {
  83529. state->mode = MEM;
  83530. return Z_MEM_ERROR;
  83531. }
  83532. if (dictLength > state->wsize) {
  83533. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83534. state->wsize);
  83535. state->whave = state->wsize;
  83536. }
  83537. else {
  83538. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83539. dictLength);
  83540. state->whave = dictLength;
  83541. }
  83542. state->havedict = 1;
  83543. Tracev((stderr, "inflate: dictionary set\n"));
  83544. return Z_OK;
  83545. }
  83546. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83547. {
  83548. struct inflate_state FAR *state;
  83549. /* check state */
  83550. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83551. state = (struct inflate_state FAR *)strm->state;
  83552. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83553. /* save header structure */
  83554. state->head = head;
  83555. head->done = 0;
  83556. return Z_OK;
  83557. }
  83558. /*
  83559. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83560. or when out of input. When called, *have is the number of pattern bytes
  83561. found in order so far, in 0..3. On return *have is updated to the new
  83562. state. If on return *have equals four, then the pattern was found and the
  83563. return value is how many bytes were read including the last byte of the
  83564. pattern. If *have is less than four, then the pattern has not been found
  83565. yet and the return value is len. In the latter case, syncsearch() can be
  83566. called again with more data and the *have state. *have is initialized to
  83567. zero for the first call.
  83568. */
  83569. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83570. {
  83571. unsigned got;
  83572. unsigned next;
  83573. got = *have;
  83574. next = 0;
  83575. while (next < len && got < 4) {
  83576. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83577. got++;
  83578. else if (buf[next])
  83579. got = 0;
  83580. else
  83581. got = 4 - got;
  83582. next++;
  83583. }
  83584. *have = got;
  83585. return next;
  83586. }
  83587. int ZEXPORT inflateSync (z_streamp strm)
  83588. {
  83589. unsigned len; /* number of bytes to look at or looked at */
  83590. unsigned long in, out; /* temporary to save total_in and total_out */
  83591. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83592. struct inflate_state FAR *state;
  83593. /* check parameters */
  83594. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83595. state = (struct inflate_state FAR *)strm->state;
  83596. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83597. /* if first time, start search in bit buffer */
  83598. if (state->mode != SYNC) {
  83599. state->mode = SYNC;
  83600. state->hold <<= state->bits & 7;
  83601. state->bits -= state->bits & 7;
  83602. len = 0;
  83603. while (state->bits >= 8) {
  83604. buf[len++] = (unsigned char)(state->hold);
  83605. state->hold >>= 8;
  83606. state->bits -= 8;
  83607. }
  83608. state->have = 0;
  83609. syncsearch(&(state->have), buf, len);
  83610. }
  83611. /* search available input */
  83612. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83613. strm->avail_in -= len;
  83614. strm->next_in += len;
  83615. strm->total_in += len;
  83616. /* return no joy or set up to restart inflate() on a new block */
  83617. if (state->have != 4) return Z_DATA_ERROR;
  83618. in = strm->total_in; out = strm->total_out;
  83619. inflateReset(strm);
  83620. strm->total_in = in; strm->total_out = out;
  83621. state->mode = TYPE;
  83622. return Z_OK;
  83623. }
  83624. /*
  83625. Returns true if inflate is currently at the end of a block generated by
  83626. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83627. implementation to provide an additional safety check. PPP uses
  83628. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83629. block. When decompressing, PPP checks that at the end of input packet,
  83630. inflate is waiting for these length bytes.
  83631. */
  83632. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83633. {
  83634. struct inflate_state FAR *state;
  83635. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83636. state = (struct inflate_state FAR *)strm->state;
  83637. return state->mode == STORED && state->bits == 0;
  83638. }
  83639. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83640. {
  83641. struct inflate_state FAR *state;
  83642. struct inflate_state FAR *copy;
  83643. unsigned char FAR *window;
  83644. unsigned wsize;
  83645. /* check input */
  83646. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83647. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83648. return Z_STREAM_ERROR;
  83649. state = (struct inflate_state FAR *)source->state;
  83650. /* allocate space */
  83651. copy = (struct inflate_state FAR *)
  83652. ZALLOC(source, 1, sizeof(struct inflate_state));
  83653. if (copy == Z_NULL) return Z_MEM_ERROR;
  83654. window = Z_NULL;
  83655. if (state->window != Z_NULL) {
  83656. window = (unsigned char FAR *)
  83657. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83658. if (window == Z_NULL) {
  83659. ZFREE(source, copy);
  83660. return Z_MEM_ERROR;
  83661. }
  83662. }
  83663. /* copy state */
  83664. zmemcpy(dest, source, sizeof(z_stream));
  83665. zmemcpy(copy, state, sizeof(struct inflate_state));
  83666. if (state->lencode >= state->codes &&
  83667. state->lencode <= state->codes + ENOUGH - 1) {
  83668. copy->lencode = copy->codes + (state->lencode - state->codes);
  83669. copy->distcode = copy->codes + (state->distcode - state->codes);
  83670. }
  83671. copy->next = copy->codes + (state->next - state->codes);
  83672. if (window != Z_NULL) {
  83673. wsize = 1U << state->wbits;
  83674. zmemcpy(window, state->window, wsize);
  83675. }
  83676. copy->window = window;
  83677. dest->state = (struct internal_state FAR *)copy;
  83678. return Z_OK;
  83679. }
  83680. /*** End of inlined file: inflate.c ***/
  83681. /*** Start of inlined file: inftrees.c ***/
  83682. #define MAXBITS 15
  83683. const char inflate_copyright[] =
  83684. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83685. /*
  83686. If you use the zlib library in a product, an acknowledgment is welcome
  83687. in the documentation of your product. If for some reason you cannot
  83688. include such an acknowledgment, I would appreciate that you keep this
  83689. copyright string in the executable of your product.
  83690. */
  83691. /*
  83692. Build a set of tables to decode the provided canonical Huffman code.
  83693. The code lengths are lens[0..codes-1]. The result starts at *table,
  83694. whose indices are 0..2^bits-1. work is a writable array of at least
  83695. lens shorts, which is used as a work area. type is the type of code
  83696. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83697. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83698. on return points to the next available entry's address. bits is the
  83699. requested root table index bits, and on return it is the actual root
  83700. table index bits. It will differ if the request is greater than the
  83701. longest code or if it is less than the shortest code.
  83702. */
  83703. int inflate_table (codetype type,
  83704. unsigned short FAR *lens,
  83705. unsigned codes,
  83706. code FAR * FAR *table,
  83707. unsigned FAR *bits,
  83708. unsigned short FAR *work)
  83709. {
  83710. unsigned len; /* a code's length in bits */
  83711. unsigned sym; /* index of code symbols */
  83712. unsigned min, max; /* minimum and maximum code lengths */
  83713. unsigned root; /* number of index bits for root table */
  83714. unsigned curr; /* number of index bits for current table */
  83715. unsigned drop; /* code bits to drop for sub-table */
  83716. int left; /* number of prefix codes available */
  83717. unsigned used; /* code entries in table used */
  83718. unsigned huff; /* Huffman code */
  83719. unsigned incr; /* for incrementing code, index */
  83720. unsigned fill; /* index for replicating entries */
  83721. unsigned low; /* low bits for current root entry */
  83722. unsigned mask; /* mask for low root bits */
  83723. code thisx; /* table entry for duplication */
  83724. code FAR *next; /* next available space in table */
  83725. const unsigned short FAR *base; /* base value table to use */
  83726. const unsigned short FAR *extra; /* extra bits table to use */
  83727. int end; /* use base and extra for symbol > end */
  83728. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83729. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83730. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83731. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83732. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83733. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83734. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83735. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83736. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83737. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83738. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83739. 8193, 12289, 16385, 24577, 0, 0};
  83740. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83741. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83742. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83743. 28, 28, 29, 29, 64, 64};
  83744. /*
  83745. Process a set of code lengths to create a canonical Huffman code. The
  83746. code lengths are lens[0..codes-1]. Each length corresponds to the
  83747. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83748. symbols by length from short to long, and retaining the symbol order
  83749. for codes with equal lengths. Then the code starts with all zero bits
  83750. for the first code of the shortest length, and the codes are integer
  83751. increments for the same length, and zeros are appended as the length
  83752. increases. For the deflate format, these bits are stored backwards
  83753. from their more natural integer increment ordering, and so when the
  83754. decoding tables are built in the large loop below, the integer codes
  83755. are incremented backwards.
  83756. This routine assumes, but does not check, that all of the entries in
  83757. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83758. 1..MAXBITS is interpreted as that code length. zero means that that
  83759. symbol does not occur in this code.
  83760. The codes are sorted by computing a count of codes for each length,
  83761. creating from that a table of starting indices for each length in the
  83762. sorted table, and then entering the symbols in order in the sorted
  83763. table. The sorted table is work[], with that space being provided by
  83764. the caller.
  83765. The length counts are used for other purposes as well, i.e. finding
  83766. the minimum and maximum length codes, determining if there are any
  83767. codes at all, checking for a valid set of lengths, and looking ahead
  83768. at length counts to determine sub-table sizes when building the
  83769. decoding tables.
  83770. */
  83771. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83772. for (len = 0; len <= MAXBITS; len++)
  83773. count[len] = 0;
  83774. for (sym = 0; sym < codes; sym++)
  83775. count[lens[sym]]++;
  83776. /* bound code lengths, force root to be within code lengths */
  83777. root = *bits;
  83778. for (max = MAXBITS; max >= 1; max--)
  83779. if (count[max] != 0) break;
  83780. if (root > max) root = max;
  83781. if (max == 0) { /* no symbols to code at all */
  83782. thisx.op = (unsigned char)64; /* invalid code marker */
  83783. thisx.bits = (unsigned char)1;
  83784. thisx.val = (unsigned short)0;
  83785. *(*table)++ = thisx; /* make a table to force an error */
  83786. *(*table)++ = thisx;
  83787. *bits = 1;
  83788. return 0; /* no symbols, but wait for decoding to report error */
  83789. }
  83790. for (min = 1; min <= MAXBITS; min++)
  83791. if (count[min] != 0) break;
  83792. if (root < min) root = min;
  83793. /* check for an over-subscribed or incomplete set of lengths */
  83794. left = 1;
  83795. for (len = 1; len <= MAXBITS; len++) {
  83796. left <<= 1;
  83797. left -= count[len];
  83798. if (left < 0) return -1; /* over-subscribed */
  83799. }
  83800. if (left > 0 && (type == CODES || max != 1))
  83801. return -1; /* incomplete set */
  83802. /* generate offsets into symbol table for each length for sorting */
  83803. offs[1] = 0;
  83804. for (len = 1; len < MAXBITS; len++)
  83805. offs[len + 1] = offs[len] + count[len];
  83806. /* sort symbols by length, by symbol order within each length */
  83807. for (sym = 0; sym < codes; sym++)
  83808. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83809. /*
  83810. Create and fill in decoding tables. In this loop, the table being
  83811. filled is at next and has curr index bits. The code being used is huff
  83812. with length len. That code is converted to an index by dropping drop
  83813. bits off of the bottom. For codes where len is less than drop + curr,
  83814. those top drop + curr - len bits are incremented through all values to
  83815. fill the table with replicated entries.
  83816. root is the number of index bits for the root table. When len exceeds
  83817. root, sub-tables are created pointed to by the root entry with an index
  83818. of the low root bits of huff. This is saved in low to check for when a
  83819. new sub-table should be started. drop is zero when the root table is
  83820. being filled, and drop is root when sub-tables are being filled.
  83821. When a new sub-table is needed, it is necessary to look ahead in the
  83822. code lengths to determine what size sub-table is needed. The length
  83823. counts are used for this, and so count[] is decremented as codes are
  83824. entered in the tables.
  83825. used keeps track of how many table entries have been allocated from the
  83826. provided *table space. It is checked when a LENS table is being made
  83827. against the space in *table, ENOUGH, minus the maximum space needed by
  83828. the worst case distance code, MAXD. This should never happen, but the
  83829. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  83830. This assumes that when type == LENS, bits == 9.
  83831. sym increments through all symbols, and the loop terminates when
  83832. all codes of length max, i.e. all codes, have been processed. This
  83833. routine permits incomplete codes, so another loop after this one fills
  83834. in the rest of the decoding tables with invalid code markers.
  83835. */
  83836. /* set up for code type */
  83837. switch (type) {
  83838. case CODES:
  83839. base = extra = work; /* dummy value--not used */
  83840. end = 19;
  83841. break;
  83842. case LENS:
  83843. base = lbase;
  83844. base -= 257;
  83845. extra = lext;
  83846. extra -= 257;
  83847. end = 256;
  83848. break;
  83849. default: /* DISTS */
  83850. base = dbase;
  83851. extra = dext;
  83852. end = -1;
  83853. }
  83854. /* initialize state for loop */
  83855. huff = 0; /* starting code */
  83856. sym = 0; /* starting code symbol */
  83857. len = min; /* starting code length */
  83858. next = *table; /* current table to fill in */
  83859. curr = root; /* current table index bits */
  83860. drop = 0; /* current bits to drop from code for index */
  83861. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  83862. used = 1U << root; /* use root table entries */
  83863. mask = used - 1; /* mask for comparing low */
  83864. /* check available table space */
  83865. if (type == LENS && used >= ENOUGH - MAXD)
  83866. return 1;
  83867. /* process all codes and make table entries */
  83868. for (;;) {
  83869. /* create table entry */
  83870. thisx.bits = (unsigned char)(len - drop);
  83871. if ((int)(work[sym]) < end) {
  83872. thisx.op = (unsigned char)0;
  83873. thisx.val = work[sym];
  83874. }
  83875. else if ((int)(work[sym]) > end) {
  83876. thisx.op = (unsigned char)(extra[work[sym]]);
  83877. thisx.val = base[work[sym]];
  83878. }
  83879. else {
  83880. thisx.op = (unsigned char)(32 + 64); /* end of block */
  83881. thisx.val = 0;
  83882. }
  83883. /* replicate for those indices with low len bits equal to huff */
  83884. incr = 1U << (len - drop);
  83885. fill = 1U << curr;
  83886. min = fill; /* save offset to next table */
  83887. do {
  83888. fill -= incr;
  83889. next[(huff >> drop) + fill] = thisx;
  83890. } while (fill != 0);
  83891. /* backwards increment the len-bit code huff */
  83892. incr = 1U << (len - 1);
  83893. while (huff & incr)
  83894. incr >>= 1;
  83895. if (incr != 0) {
  83896. huff &= incr - 1;
  83897. huff += incr;
  83898. }
  83899. else
  83900. huff = 0;
  83901. /* go to next symbol, update count, len */
  83902. sym++;
  83903. if (--(count[len]) == 0) {
  83904. if (len == max) break;
  83905. len = lens[work[sym]];
  83906. }
  83907. /* create new sub-table if needed */
  83908. if (len > root && (huff & mask) != low) {
  83909. /* if first time, transition to sub-tables */
  83910. if (drop == 0)
  83911. drop = root;
  83912. /* increment past last table */
  83913. next += min; /* here min is 1 << curr */
  83914. /* determine length of next table */
  83915. curr = len - drop;
  83916. left = (int)(1 << curr);
  83917. while (curr + drop < max) {
  83918. left -= count[curr + drop];
  83919. if (left <= 0) break;
  83920. curr++;
  83921. left <<= 1;
  83922. }
  83923. /* check for enough space */
  83924. used += 1U << curr;
  83925. if (type == LENS && used >= ENOUGH - MAXD)
  83926. return 1;
  83927. /* point entry in root table to sub-table */
  83928. low = huff & mask;
  83929. (*table)[low].op = (unsigned char)curr;
  83930. (*table)[low].bits = (unsigned char)root;
  83931. (*table)[low].val = (unsigned short)(next - *table);
  83932. }
  83933. }
  83934. /*
  83935. Fill in rest of table for incomplete codes. This loop is similar to the
  83936. loop above in incrementing huff for table indices. It is assumed that
  83937. len is equal to curr + drop, so there is no loop needed to increment
  83938. through high index bits. When the current sub-table is filled, the loop
  83939. drops back to the root table to fill in any remaining entries there.
  83940. */
  83941. thisx.op = (unsigned char)64; /* invalid code marker */
  83942. thisx.bits = (unsigned char)(len - drop);
  83943. thisx.val = (unsigned short)0;
  83944. while (huff != 0) {
  83945. /* when done with sub-table, drop back to root table */
  83946. if (drop != 0 && (huff & mask) != low) {
  83947. drop = 0;
  83948. len = root;
  83949. next = *table;
  83950. thisx.bits = (unsigned char)len;
  83951. }
  83952. /* put invalid code marker in table */
  83953. next[huff >> drop] = thisx;
  83954. /* backwards increment the len-bit code huff */
  83955. incr = 1U << (len - 1);
  83956. while (huff & incr)
  83957. incr >>= 1;
  83958. if (incr != 0) {
  83959. huff &= incr - 1;
  83960. huff += incr;
  83961. }
  83962. else
  83963. huff = 0;
  83964. }
  83965. /* set return parameters */
  83966. *table += used;
  83967. *bits = root;
  83968. return 0;
  83969. }
  83970. /*** End of inlined file: inftrees.c ***/
  83971. /*** Start of inlined file: trees.c ***/
  83972. /*
  83973. * ALGORITHM
  83974. *
  83975. * The "deflation" process uses several Huffman trees. The more
  83976. * common source values are represented by shorter bit sequences.
  83977. *
  83978. * Each code tree is stored in a compressed form which is itself
  83979. * a Huffman encoding of the lengths of all the code strings (in
  83980. * ascending order by source values). The actual code strings are
  83981. * reconstructed from the lengths in the inflate process, as described
  83982. * in the deflate specification.
  83983. *
  83984. * REFERENCES
  83985. *
  83986. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  83987. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  83988. *
  83989. * Storer, James A.
  83990. * Data Compression: Methods and Theory, pp. 49-50.
  83991. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  83992. *
  83993. * Sedgewick, R.
  83994. * Algorithms, p290.
  83995. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  83996. */
  83997. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  83998. /* #define GEN_TREES_H */
  83999. #ifdef DEBUG
  84000. # include <ctype.h>
  84001. #endif
  84002. /* ===========================================================================
  84003. * Constants
  84004. */
  84005. #define MAX_BL_BITS 7
  84006. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84007. #define END_BLOCK 256
  84008. /* end of block literal code */
  84009. #define REP_3_6 16
  84010. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84011. #define REPZ_3_10 17
  84012. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84013. #define REPZ_11_138 18
  84014. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84015. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84016. = {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};
  84017. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84018. = {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};
  84019. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84020. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84021. local const uch bl_order[BL_CODES]
  84022. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84023. /* The lengths of the bit length codes are sent in order of decreasing
  84024. * probability, to avoid transmitting the lengths for unused bit length codes.
  84025. */
  84026. #define Buf_size (8 * 2*sizeof(char))
  84027. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84028. * more than 16 bits on some systems.)
  84029. */
  84030. /* ===========================================================================
  84031. * Local data. These are initialized only once.
  84032. */
  84033. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84034. #if defined(GEN_TREES_H) || !defined(STDC)
  84035. /* non ANSI compilers may not accept trees.h */
  84036. local ct_data static_ltree[L_CODES+2];
  84037. /* The static literal tree. Since the bit lengths are imposed, there is no
  84038. * need for the L_CODES extra codes used during heap construction. However
  84039. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84040. * below).
  84041. */
  84042. local ct_data static_dtree[D_CODES];
  84043. /* The static distance tree. (Actually a trivial tree since all codes use
  84044. * 5 bits.)
  84045. */
  84046. uch _dist_code[DIST_CODE_LEN];
  84047. /* Distance codes. The first 256 values correspond to the distances
  84048. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84049. * the 15 bit distances.
  84050. */
  84051. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84052. /* length code for each normalized match length (0 == MIN_MATCH) */
  84053. local int base_length[LENGTH_CODES];
  84054. /* First normalized length for each code (0 = MIN_MATCH) */
  84055. local int base_dist[D_CODES];
  84056. /* First normalized distance for each code (0 = distance of 1) */
  84057. #else
  84058. /*** Start of inlined file: trees.h ***/
  84059. local const ct_data static_ltree[L_CODES+2] = {
  84060. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84061. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84062. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84063. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84064. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84065. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84066. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84067. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84068. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84069. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84070. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84071. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84072. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84073. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84074. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84075. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84076. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84077. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84078. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84079. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84080. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84081. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84082. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84083. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84084. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84085. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84086. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84087. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84088. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84089. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84090. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84091. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84092. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84093. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84094. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84095. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84096. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84097. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84098. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84099. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84100. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84101. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84102. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84103. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84104. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84105. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84106. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84107. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84108. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84109. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84110. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84111. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84112. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84113. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84114. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84115. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84116. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84117. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84118. };
  84119. local const ct_data static_dtree[D_CODES] = {
  84120. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84121. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84122. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84123. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84124. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84125. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84126. };
  84127. const uch _dist_code[DIST_CODE_LEN] = {
  84128. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84129. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84130. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84131. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84132. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84133. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84134. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84135. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84136. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84137. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84138. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84139. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84140. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84141. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84142. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84143. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84144. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84145. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84146. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84147. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84148. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84149. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84150. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84151. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84152. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84153. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84154. };
  84155. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84156. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84157. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84158. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84159. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84160. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84161. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84162. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84163. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84164. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84165. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84166. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84167. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84168. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84169. };
  84170. local const int base_length[LENGTH_CODES] = {
  84171. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84172. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84173. };
  84174. local const int base_dist[D_CODES] = {
  84175. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84176. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84177. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84178. };
  84179. /*** End of inlined file: trees.h ***/
  84180. #endif /* GEN_TREES_H */
  84181. struct static_tree_desc_s {
  84182. const ct_data *static_tree; /* static tree or NULL */
  84183. const intf *extra_bits; /* extra bits for each code or NULL */
  84184. int extra_base; /* base index for extra_bits */
  84185. int elems; /* max number of elements in the tree */
  84186. int max_length; /* max bit length for the codes */
  84187. };
  84188. local static_tree_desc static_l_desc =
  84189. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84190. local static_tree_desc static_d_desc =
  84191. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84192. local static_tree_desc static_bl_desc =
  84193. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84194. /* ===========================================================================
  84195. * Local (static) routines in this file.
  84196. */
  84197. local void tr_static_init OF((void));
  84198. local void init_block OF((deflate_state *s));
  84199. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84200. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84201. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84202. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84203. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84204. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84205. local int build_bl_tree OF((deflate_state *s));
  84206. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84207. int blcodes));
  84208. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84209. ct_data *dtree));
  84210. local void set_data_type OF((deflate_state *s));
  84211. local unsigned bi_reverse OF((unsigned value, int length));
  84212. local void bi_windup OF((deflate_state *s));
  84213. local void bi_flush OF((deflate_state *s));
  84214. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84215. int header));
  84216. #ifdef GEN_TREES_H
  84217. local void gen_trees_header OF((void));
  84218. #endif
  84219. #ifndef DEBUG
  84220. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84221. /* Send a code of the given tree. c and tree must not have side effects */
  84222. #else /* DEBUG */
  84223. # define send_code(s, c, tree) \
  84224. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84225. send_bits(s, tree[c].Code, tree[c].Len); }
  84226. #endif
  84227. /* ===========================================================================
  84228. * Output a short LSB first on the stream.
  84229. * IN assertion: there is enough room in pendingBuf.
  84230. */
  84231. #define put_short(s, w) { \
  84232. put_byte(s, (uch)((w) & 0xff)); \
  84233. put_byte(s, (uch)((ush)(w) >> 8)); \
  84234. }
  84235. /* ===========================================================================
  84236. * Send a value on a given number of bits.
  84237. * IN assertion: length <= 16 and value fits in length bits.
  84238. */
  84239. #ifdef DEBUG
  84240. local void send_bits OF((deflate_state *s, int value, int length));
  84241. local void send_bits (deflate_state *s, int value, int length)
  84242. {
  84243. Tracevv((stderr," l %2d v %4x ", length, value));
  84244. Assert(length > 0 && length <= 15, "invalid length");
  84245. s->bits_sent += (ulg)length;
  84246. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84247. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84248. * unused bits in value.
  84249. */
  84250. if (s->bi_valid > (int)Buf_size - length) {
  84251. s->bi_buf |= (value << s->bi_valid);
  84252. put_short(s, s->bi_buf);
  84253. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84254. s->bi_valid += length - Buf_size;
  84255. } else {
  84256. s->bi_buf |= value << s->bi_valid;
  84257. s->bi_valid += length;
  84258. }
  84259. }
  84260. #else /* !DEBUG */
  84261. #define send_bits(s, value, length) \
  84262. { int len = length;\
  84263. if (s->bi_valid > (int)Buf_size - len) {\
  84264. int val = value;\
  84265. s->bi_buf |= (val << s->bi_valid);\
  84266. put_short(s, s->bi_buf);\
  84267. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84268. s->bi_valid += len - Buf_size;\
  84269. } else {\
  84270. s->bi_buf |= (value) << s->bi_valid;\
  84271. s->bi_valid += len;\
  84272. }\
  84273. }
  84274. #endif /* DEBUG */
  84275. /* the arguments must not have side effects */
  84276. /* ===========================================================================
  84277. * Initialize the various 'constant' tables.
  84278. */
  84279. local void tr_static_init()
  84280. {
  84281. #if defined(GEN_TREES_H) || !defined(STDC)
  84282. static int static_init_done = 0;
  84283. int n; /* iterates over tree elements */
  84284. int bits; /* bit counter */
  84285. int length; /* length value */
  84286. int code; /* code value */
  84287. int dist; /* distance index */
  84288. ush bl_count[MAX_BITS+1];
  84289. /* number of codes at each bit length for an optimal tree */
  84290. if (static_init_done) return;
  84291. /* For some embedded targets, global variables are not initialized: */
  84292. static_l_desc.static_tree = static_ltree;
  84293. static_l_desc.extra_bits = extra_lbits;
  84294. static_d_desc.static_tree = static_dtree;
  84295. static_d_desc.extra_bits = extra_dbits;
  84296. static_bl_desc.extra_bits = extra_blbits;
  84297. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84298. length = 0;
  84299. for (code = 0; code < LENGTH_CODES-1; code++) {
  84300. base_length[code] = length;
  84301. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84302. _length_code[length++] = (uch)code;
  84303. }
  84304. }
  84305. Assert (length == 256, "tr_static_init: length != 256");
  84306. /* Note that the length 255 (match length 258) can be represented
  84307. * in two different ways: code 284 + 5 bits or code 285, so we
  84308. * overwrite length_code[255] to use the best encoding:
  84309. */
  84310. _length_code[length-1] = (uch)code;
  84311. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84312. dist = 0;
  84313. for (code = 0 ; code < 16; code++) {
  84314. base_dist[code] = dist;
  84315. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84316. _dist_code[dist++] = (uch)code;
  84317. }
  84318. }
  84319. Assert (dist == 256, "tr_static_init: dist != 256");
  84320. dist >>= 7; /* from now on, all distances are divided by 128 */
  84321. for ( ; code < D_CODES; code++) {
  84322. base_dist[code] = dist << 7;
  84323. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84324. _dist_code[256 + dist++] = (uch)code;
  84325. }
  84326. }
  84327. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84328. /* Construct the codes of the static literal tree */
  84329. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84330. n = 0;
  84331. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84332. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84333. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84334. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84335. /* Codes 286 and 287 do not exist, but we must include them in the
  84336. * tree construction to get a canonical Huffman tree (longest code
  84337. * all ones)
  84338. */
  84339. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84340. /* The static distance tree is trivial: */
  84341. for (n = 0; n < D_CODES; n++) {
  84342. static_dtree[n].Len = 5;
  84343. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84344. }
  84345. static_init_done = 1;
  84346. # ifdef GEN_TREES_H
  84347. gen_trees_header();
  84348. # endif
  84349. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84350. }
  84351. /* ===========================================================================
  84352. * Genererate the file trees.h describing the static trees.
  84353. */
  84354. #ifdef GEN_TREES_H
  84355. # ifndef DEBUG
  84356. # include <stdio.h>
  84357. # endif
  84358. # define SEPARATOR(i, last, width) \
  84359. ((i) == (last)? "\n};\n\n" : \
  84360. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84361. void gen_trees_header()
  84362. {
  84363. FILE *header = fopen("trees.h", "w");
  84364. int i;
  84365. Assert (header != NULL, "Can't open trees.h");
  84366. fprintf(header,
  84367. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84368. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84369. for (i = 0; i < L_CODES+2; i++) {
  84370. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84371. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84372. }
  84373. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84374. for (i = 0; i < D_CODES; i++) {
  84375. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84376. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84377. }
  84378. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84379. for (i = 0; i < DIST_CODE_LEN; i++) {
  84380. fprintf(header, "%2u%s", _dist_code[i],
  84381. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84382. }
  84383. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84384. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84385. fprintf(header, "%2u%s", _length_code[i],
  84386. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84387. }
  84388. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84389. for (i = 0; i < LENGTH_CODES; i++) {
  84390. fprintf(header, "%1u%s", base_length[i],
  84391. SEPARATOR(i, LENGTH_CODES-1, 20));
  84392. }
  84393. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84394. for (i = 0; i < D_CODES; i++) {
  84395. fprintf(header, "%5u%s", base_dist[i],
  84396. SEPARATOR(i, D_CODES-1, 10));
  84397. }
  84398. fclose(header);
  84399. }
  84400. #endif /* GEN_TREES_H */
  84401. /* ===========================================================================
  84402. * Initialize the tree data structures for a new zlib stream.
  84403. */
  84404. void _tr_init(deflate_state *s)
  84405. {
  84406. tr_static_init();
  84407. s->l_desc.dyn_tree = s->dyn_ltree;
  84408. s->l_desc.stat_desc = &static_l_desc;
  84409. s->d_desc.dyn_tree = s->dyn_dtree;
  84410. s->d_desc.stat_desc = &static_d_desc;
  84411. s->bl_desc.dyn_tree = s->bl_tree;
  84412. s->bl_desc.stat_desc = &static_bl_desc;
  84413. s->bi_buf = 0;
  84414. s->bi_valid = 0;
  84415. s->last_eob_len = 8; /* enough lookahead for inflate */
  84416. #ifdef DEBUG
  84417. s->compressed_len = 0L;
  84418. s->bits_sent = 0L;
  84419. #endif
  84420. /* Initialize the first block of the first file: */
  84421. init_block(s);
  84422. }
  84423. /* ===========================================================================
  84424. * Initialize a new block.
  84425. */
  84426. local void init_block (deflate_state *s)
  84427. {
  84428. int n; /* iterates over tree elements */
  84429. /* Initialize the trees. */
  84430. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84431. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84432. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84433. s->dyn_ltree[END_BLOCK].Freq = 1;
  84434. s->opt_len = s->static_len = 0L;
  84435. s->last_lit = s->matches = 0;
  84436. }
  84437. #define SMALLEST 1
  84438. /* Index within the heap array of least frequent node in the Huffman tree */
  84439. /* ===========================================================================
  84440. * Remove the smallest element from the heap and recreate the heap with
  84441. * one less element. Updates heap and heap_len.
  84442. */
  84443. #define pqremove(s, tree, top) \
  84444. {\
  84445. top = s->heap[SMALLEST]; \
  84446. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84447. pqdownheap(s, tree, SMALLEST); \
  84448. }
  84449. /* ===========================================================================
  84450. * Compares to subtrees, using the tree depth as tie breaker when
  84451. * the subtrees have equal frequency. This minimizes the worst case length.
  84452. */
  84453. #define smaller(tree, n, m, depth) \
  84454. (tree[n].Freq < tree[m].Freq || \
  84455. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84456. /* ===========================================================================
  84457. * Restore the heap property by moving down the tree starting at node k,
  84458. * exchanging a node with the smallest of its two sons if necessary, stopping
  84459. * when the heap property is re-established (each father smaller than its
  84460. * two sons).
  84461. */
  84462. local void pqdownheap (deflate_state *s,
  84463. ct_data *tree, /* the tree to restore */
  84464. int k) /* node to move down */
  84465. {
  84466. int v = s->heap[k];
  84467. int j = k << 1; /* left son of k */
  84468. while (j <= s->heap_len) {
  84469. /* Set j to the smallest of the two sons: */
  84470. if (j < s->heap_len &&
  84471. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84472. j++;
  84473. }
  84474. /* Exit if v is smaller than both sons */
  84475. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84476. /* Exchange v with the smallest son */
  84477. s->heap[k] = s->heap[j]; k = j;
  84478. /* And continue down the tree, setting j to the left son of k */
  84479. j <<= 1;
  84480. }
  84481. s->heap[k] = v;
  84482. }
  84483. /* ===========================================================================
  84484. * Compute the optimal bit lengths for a tree and update the total bit length
  84485. * for the current block.
  84486. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84487. * above are the tree nodes sorted by increasing frequency.
  84488. * OUT assertions: the field len is set to the optimal bit length, the
  84489. * array bl_count contains the frequencies for each bit length.
  84490. * The length opt_len is updated; static_len is also updated if stree is
  84491. * not null.
  84492. */
  84493. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84494. {
  84495. ct_data *tree = desc->dyn_tree;
  84496. int max_code = desc->max_code;
  84497. const ct_data *stree = desc->stat_desc->static_tree;
  84498. const intf *extra = desc->stat_desc->extra_bits;
  84499. int base = desc->stat_desc->extra_base;
  84500. int max_length = desc->stat_desc->max_length;
  84501. int h; /* heap index */
  84502. int n, m; /* iterate over the tree elements */
  84503. int bits; /* bit length */
  84504. int xbits; /* extra bits */
  84505. ush f; /* frequency */
  84506. int overflow = 0; /* number of elements with bit length too large */
  84507. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84508. /* In a first pass, compute the optimal bit lengths (which may
  84509. * overflow in the case of the bit length tree).
  84510. */
  84511. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84512. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84513. n = s->heap[h];
  84514. bits = tree[tree[n].Dad].Len + 1;
  84515. if (bits > max_length) bits = max_length, overflow++;
  84516. tree[n].Len = (ush)bits;
  84517. /* We overwrite tree[n].Dad which is no longer needed */
  84518. if (n > max_code) continue; /* not a leaf node */
  84519. s->bl_count[bits]++;
  84520. xbits = 0;
  84521. if (n >= base) xbits = extra[n-base];
  84522. f = tree[n].Freq;
  84523. s->opt_len += (ulg)f * (bits + xbits);
  84524. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84525. }
  84526. if (overflow == 0) return;
  84527. Trace((stderr,"\nbit length overflow\n"));
  84528. /* This happens for example on obj2 and pic of the Calgary corpus */
  84529. /* Find the first bit length which could increase: */
  84530. do {
  84531. bits = max_length-1;
  84532. while (s->bl_count[bits] == 0) bits--;
  84533. s->bl_count[bits]--; /* move one leaf down the tree */
  84534. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84535. s->bl_count[max_length]--;
  84536. /* The brother of the overflow item also moves one step up,
  84537. * but this does not affect bl_count[max_length]
  84538. */
  84539. overflow -= 2;
  84540. } while (overflow > 0);
  84541. /* Now recompute all bit lengths, scanning in increasing frequency.
  84542. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84543. * lengths instead of fixing only the wrong ones. This idea is taken
  84544. * from 'ar' written by Haruhiko Okumura.)
  84545. */
  84546. for (bits = max_length; bits != 0; bits--) {
  84547. n = s->bl_count[bits];
  84548. while (n != 0) {
  84549. m = s->heap[--h];
  84550. if (m > max_code) continue;
  84551. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84552. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84553. s->opt_len += ((long)bits - (long)tree[m].Len)
  84554. *(long)tree[m].Freq;
  84555. tree[m].Len = (ush)bits;
  84556. }
  84557. n--;
  84558. }
  84559. }
  84560. }
  84561. /* ===========================================================================
  84562. * Generate the codes for a given tree and bit counts (which need not be
  84563. * optimal).
  84564. * IN assertion: the array bl_count contains the bit length statistics for
  84565. * the given tree and the field len is set for all tree elements.
  84566. * OUT assertion: the field code is set for all tree elements of non
  84567. * zero code length.
  84568. */
  84569. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84570. int max_code, /* largest code with non zero frequency */
  84571. ushf *bl_count) /* number of codes at each bit length */
  84572. {
  84573. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84574. ush code = 0; /* running code value */
  84575. int bits; /* bit index */
  84576. int n; /* code index */
  84577. /* The distribution counts are first used to generate the code values
  84578. * without bit reversal.
  84579. */
  84580. for (bits = 1; bits <= MAX_BITS; bits++) {
  84581. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84582. }
  84583. /* Check that the bit counts in bl_count are consistent. The last code
  84584. * must be all ones.
  84585. */
  84586. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84587. "inconsistent bit counts");
  84588. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84589. for (n = 0; n <= max_code; n++) {
  84590. int len = tree[n].Len;
  84591. if (len == 0) continue;
  84592. /* Now reverse the bits */
  84593. tree[n].Code = bi_reverse(next_code[len]++, len);
  84594. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84595. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84596. }
  84597. }
  84598. /* ===========================================================================
  84599. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84600. * Update the total bit length for the current block.
  84601. * IN assertion: the field freq is set for all tree elements.
  84602. * OUT assertions: the fields len and code are set to the optimal bit length
  84603. * and corresponding code. The length opt_len is updated; static_len is
  84604. * also updated if stree is not null. The field max_code is set.
  84605. */
  84606. local void build_tree (deflate_state *s,
  84607. tree_desc *desc) /* the tree descriptor */
  84608. {
  84609. ct_data *tree = desc->dyn_tree;
  84610. const ct_data *stree = desc->stat_desc->static_tree;
  84611. int elems = desc->stat_desc->elems;
  84612. int n, m; /* iterate over heap elements */
  84613. int max_code = -1; /* largest code with non zero frequency */
  84614. int node; /* new node being created */
  84615. /* Construct the initial heap, with least frequent element in
  84616. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84617. * heap[0] is not used.
  84618. */
  84619. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84620. for (n = 0; n < elems; n++) {
  84621. if (tree[n].Freq != 0) {
  84622. s->heap[++(s->heap_len)] = max_code = n;
  84623. s->depth[n] = 0;
  84624. } else {
  84625. tree[n].Len = 0;
  84626. }
  84627. }
  84628. /* The pkzip format requires that at least one distance code exists,
  84629. * and that at least one bit should be sent even if there is only one
  84630. * possible code. So to avoid special checks later on we force at least
  84631. * two codes of non zero frequency.
  84632. */
  84633. while (s->heap_len < 2) {
  84634. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84635. tree[node].Freq = 1;
  84636. s->depth[node] = 0;
  84637. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84638. /* node is 0 or 1 so it does not have extra bits */
  84639. }
  84640. desc->max_code = max_code;
  84641. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84642. * establish sub-heaps of increasing lengths:
  84643. */
  84644. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84645. /* Construct the Huffman tree by repeatedly combining the least two
  84646. * frequent nodes.
  84647. */
  84648. node = elems; /* next internal node of the tree */
  84649. do {
  84650. pqremove(s, tree, n); /* n = node of least frequency */
  84651. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84652. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84653. s->heap[--(s->heap_max)] = m;
  84654. /* Create a new node father of n and m */
  84655. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84656. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84657. s->depth[n] : s->depth[m]) + 1);
  84658. tree[n].Dad = tree[m].Dad = (ush)node;
  84659. #ifdef DUMP_BL_TREE
  84660. if (tree == s->bl_tree) {
  84661. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84662. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84663. }
  84664. #endif
  84665. /* and insert the new node in the heap */
  84666. s->heap[SMALLEST] = node++;
  84667. pqdownheap(s, tree, SMALLEST);
  84668. } while (s->heap_len >= 2);
  84669. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84670. /* At this point, the fields freq and dad are set. We can now
  84671. * generate the bit lengths.
  84672. */
  84673. gen_bitlen(s, (tree_desc *)desc);
  84674. /* The field len is now set, we can generate the bit codes */
  84675. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84676. }
  84677. /* ===========================================================================
  84678. * Scan a literal or distance tree to determine the frequencies of the codes
  84679. * in the bit length tree.
  84680. */
  84681. local void scan_tree (deflate_state *s,
  84682. ct_data *tree, /* the tree to be scanned */
  84683. int max_code) /* and its largest code of non zero frequency */
  84684. {
  84685. int n; /* iterates over all tree elements */
  84686. int prevlen = -1; /* last emitted length */
  84687. int curlen; /* length of current code */
  84688. int nextlen = tree[0].Len; /* length of next code */
  84689. int count = 0; /* repeat count of the current code */
  84690. int max_count = 7; /* max repeat count */
  84691. int min_count = 4; /* min repeat count */
  84692. if (nextlen == 0) max_count = 138, min_count = 3;
  84693. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84694. for (n = 0; n <= max_code; n++) {
  84695. curlen = nextlen; nextlen = tree[n+1].Len;
  84696. if (++count < max_count && curlen == nextlen) {
  84697. continue;
  84698. } else if (count < min_count) {
  84699. s->bl_tree[curlen].Freq += count;
  84700. } else if (curlen != 0) {
  84701. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84702. s->bl_tree[REP_3_6].Freq++;
  84703. } else if (count <= 10) {
  84704. s->bl_tree[REPZ_3_10].Freq++;
  84705. } else {
  84706. s->bl_tree[REPZ_11_138].Freq++;
  84707. }
  84708. count = 0; prevlen = curlen;
  84709. if (nextlen == 0) {
  84710. max_count = 138, min_count = 3;
  84711. } else if (curlen == nextlen) {
  84712. max_count = 6, min_count = 3;
  84713. } else {
  84714. max_count = 7, min_count = 4;
  84715. }
  84716. }
  84717. }
  84718. /* ===========================================================================
  84719. * Send a literal or distance tree in compressed form, using the codes in
  84720. * bl_tree.
  84721. */
  84722. local void send_tree (deflate_state *s,
  84723. ct_data *tree, /* the tree to be scanned */
  84724. int max_code) /* and its largest code of non zero frequency */
  84725. {
  84726. int n; /* iterates over all tree elements */
  84727. int prevlen = -1; /* last emitted length */
  84728. int curlen; /* length of current code */
  84729. int nextlen = tree[0].Len; /* length of next code */
  84730. int count = 0; /* repeat count of the current code */
  84731. int max_count = 7; /* max repeat count */
  84732. int min_count = 4; /* min repeat count */
  84733. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84734. if (nextlen == 0) max_count = 138, min_count = 3;
  84735. for (n = 0; n <= max_code; n++) {
  84736. curlen = nextlen; nextlen = tree[n+1].Len;
  84737. if (++count < max_count && curlen == nextlen) {
  84738. continue;
  84739. } else if (count < min_count) {
  84740. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84741. } else if (curlen != 0) {
  84742. if (curlen != prevlen) {
  84743. send_code(s, curlen, s->bl_tree); count--;
  84744. }
  84745. Assert(count >= 3 && count <= 6, " 3_6?");
  84746. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84747. } else if (count <= 10) {
  84748. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84749. } else {
  84750. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84751. }
  84752. count = 0; prevlen = curlen;
  84753. if (nextlen == 0) {
  84754. max_count = 138, min_count = 3;
  84755. } else if (curlen == nextlen) {
  84756. max_count = 6, min_count = 3;
  84757. } else {
  84758. max_count = 7, min_count = 4;
  84759. }
  84760. }
  84761. }
  84762. /* ===========================================================================
  84763. * Construct the Huffman tree for the bit lengths and return the index in
  84764. * bl_order of the last bit length code to send.
  84765. */
  84766. local int build_bl_tree (deflate_state *s)
  84767. {
  84768. int max_blindex; /* index of last bit length code of non zero freq */
  84769. /* Determine the bit length frequencies for literal and distance trees */
  84770. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84771. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84772. /* Build the bit length tree: */
  84773. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84774. /* opt_len now includes the length of the tree representations, except
  84775. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84776. */
  84777. /* Determine the number of bit length codes to send. The pkzip format
  84778. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84779. * 3 but the actual value used is 4.)
  84780. */
  84781. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84782. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84783. }
  84784. /* Update opt_len to include the bit length tree and counts */
  84785. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84786. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84787. s->opt_len, s->static_len));
  84788. return max_blindex;
  84789. }
  84790. /* ===========================================================================
  84791. * Send the header for a block using dynamic Huffman trees: the counts, the
  84792. * lengths of the bit length codes, the literal tree and the distance tree.
  84793. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84794. */
  84795. local void send_all_trees (deflate_state *s,
  84796. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84797. {
  84798. int rank; /* index in bl_order */
  84799. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84800. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84801. "too many codes");
  84802. Tracev((stderr, "\nbl counts: "));
  84803. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84804. send_bits(s, dcodes-1, 5);
  84805. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84806. for (rank = 0; rank < blcodes; rank++) {
  84807. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84808. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84809. }
  84810. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84811. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84812. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84813. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84814. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84815. }
  84816. /* ===========================================================================
  84817. * Send a stored block
  84818. */
  84819. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  84820. {
  84821. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  84822. #ifdef DEBUG
  84823. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  84824. s->compressed_len += (stored_len + 4) << 3;
  84825. #endif
  84826. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  84827. }
  84828. /* ===========================================================================
  84829. * Send one empty static block to give enough lookahead for inflate.
  84830. * This takes 10 bits, of which 7 may remain in the bit buffer.
  84831. * The current inflate code requires 9 bits of lookahead. If the
  84832. * last two codes for the previous block (real code plus EOB) were coded
  84833. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  84834. * the last real code. In this case we send two empty static blocks instead
  84835. * of one. (There are no problems if the previous block is stored or fixed.)
  84836. * To simplify the code, we assume the worst case of last real code encoded
  84837. * on one bit only.
  84838. */
  84839. void _tr_align (deflate_state *s)
  84840. {
  84841. send_bits(s, STATIC_TREES<<1, 3);
  84842. send_code(s, END_BLOCK, static_ltree);
  84843. #ifdef DEBUG
  84844. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  84845. #endif
  84846. bi_flush(s);
  84847. /* Of the 10 bits for the empty block, we have already sent
  84848. * (10 - bi_valid) bits. The lookahead for the last real code (before
  84849. * the EOB of the previous block) was thus at least one plus the length
  84850. * of the EOB plus what we have just sent of the empty static block.
  84851. */
  84852. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  84853. send_bits(s, STATIC_TREES<<1, 3);
  84854. send_code(s, END_BLOCK, static_ltree);
  84855. #ifdef DEBUG
  84856. s->compressed_len += 10L;
  84857. #endif
  84858. bi_flush(s);
  84859. }
  84860. s->last_eob_len = 7;
  84861. }
  84862. /* ===========================================================================
  84863. * Determine the best encoding for the current block: dynamic trees, static
  84864. * trees or store, and output the encoded block to the zip file.
  84865. */
  84866. void _tr_flush_block (deflate_state *s,
  84867. charf *buf, /* input block, or NULL if too old */
  84868. ulg stored_len, /* length of input block */
  84869. int eof) /* true if this is the last block for a file */
  84870. {
  84871. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  84872. int max_blindex = 0; /* index of last bit length code of non zero freq */
  84873. /* Build the Huffman trees unless a stored block is forced */
  84874. if (s->level > 0) {
  84875. /* Check if the file is binary or text */
  84876. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  84877. set_data_type(s);
  84878. /* Construct the literal and distance trees */
  84879. build_tree(s, (tree_desc *)(&(s->l_desc)));
  84880. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  84881. s->static_len));
  84882. build_tree(s, (tree_desc *)(&(s->d_desc)));
  84883. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  84884. s->static_len));
  84885. /* At this point, opt_len and static_len are the total bit lengths of
  84886. * the compressed block data, excluding the tree representations.
  84887. */
  84888. /* Build the bit length tree for the above two trees, and get the index
  84889. * in bl_order of the last bit length code to send.
  84890. */
  84891. max_blindex = build_bl_tree(s);
  84892. /* Determine the best encoding. Compute the block lengths in bytes. */
  84893. opt_lenb = (s->opt_len+3+7)>>3;
  84894. static_lenb = (s->static_len+3+7)>>3;
  84895. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  84896. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  84897. s->last_lit));
  84898. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  84899. } else {
  84900. Assert(buf != (char*)0, "lost buf");
  84901. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  84902. }
  84903. #ifdef FORCE_STORED
  84904. if (buf != (char*)0) { /* force stored block */
  84905. #else
  84906. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  84907. /* 4: two words for the lengths */
  84908. #endif
  84909. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  84910. * Otherwise we can't have processed more than WSIZE input bytes since
  84911. * the last block flush, because compression would have been
  84912. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  84913. * transform a block into a stored block.
  84914. */
  84915. _tr_stored_block(s, buf, stored_len, eof);
  84916. #ifdef FORCE_STATIC
  84917. } else if (static_lenb >= 0) { /* force static trees */
  84918. #else
  84919. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  84920. #endif
  84921. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  84922. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  84923. #ifdef DEBUG
  84924. s->compressed_len += 3 + s->static_len;
  84925. #endif
  84926. } else {
  84927. send_bits(s, (DYN_TREES<<1)+eof, 3);
  84928. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  84929. max_blindex+1);
  84930. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  84931. #ifdef DEBUG
  84932. s->compressed_len += 3 + s->opt_len;
  84933. #endif
  84934. }
  84935. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  84936. /* The above check is made mod 2^32, for files larger than 512 MB
  84937. * and uLong implemented on 32 bits.
  84938. */
  84939. init_block(s);
  84940. if (eof) {
  84941. bi_windup(s);
  84942. #ifdef DEBUG
  84943. s->compressed_len += 7; /* align on byte boundary */
  84944. #endif
  84945. }
  84946. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  84947. s->compressed_len-7*eof));
  84948. }
  84949. /* ===========================================================================
  84950. * Save the match info and tally the frequency counts. Return true if
  84951. * the current block must be flushed.
  84952. */
  84953. int _tr_tally (deflate_state *s,
  84954. unsigned dist, /* distance of matched string */
  84955. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  84956. {
  84957. s->d_buf[s->last_lit] = (ush)dist;
  84958. s->l_buf[s->last_lit++] = (uch)lc;
  84959. if (dist == 0) {
  84960. /* lc is the unmatched char */
  84961. s->dyn_ltree[lc].Freq++;
  84962. } else {
  84963. s->matches++;
  84964. /* Here, lc is the match length - MIN_MATCH */
  84965. dist--; /* dist = match distance - 1 */
  84966. Assert((ush)dist < (ush)MAX_DIST(s) &&
  84967. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  84968. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  84969. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  84970. s->dyn_dtree[d_code(dist)].Freq++;
  84971. }
  84972. #ifdef TRUNCATE_BLOCK
  84973. /* Try to guess if it is profitable to stop the current block here */
  84974. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  84975. /* Compute an upper bound for the compressed length */
  84976. ulg out_length = (ulg)s->last_lit*8L;
  84977. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  84978. int dcode;
  84979. for (dcode = 0; dcode < D_CODES; dcode++) {
  84980. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  84981. (5L+extra_dbits[dcode]);
  84982. }
  84983. out_length >>= 3;
  84984. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  84985. s->last_lit, in_length, out_length,
  84986. 100L - out_length*100L/in_length));
  84987. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  84988. }
  84989. #endif
  84990. return (s->last_lit == s->lit_bufsize-1);
  84991. /* We avoid equality with lit_bufsize because of wraparound at 64K
  84992. * on 16 bit machines and because stored blocks are restricted to
  84993. * 64K-1 bytes.
  84994. */
  84995. }
  84996. /* ===========================================================================
  84997. * Send the block data compressed using the given Huffman trees
  84998. */
  84999. local void compress_block (deflate_state *s,
  85000. ct_data *ltree, /* literal tree */
  85001. ct_data *dtree) /* distance tree */
  85002. {
  85003. unsigned dist; /* distance of matched string */
  85004. int lc; /* match length or unmatched char (if dist == 0) */
  85005. unsigned lx = 0; /* running index in l_buf */
  85006. unsigned code; /* the code to send */
  85007. int extra; /* number of extra bits to send */
  85008. if (s->last_lit != 0) do {
  85009. dist = s->d_buf[lx];
  85010. lc = s->l_buf[lx++];
  85011. if (dist == 0) {
  85012. send_code(s, lc, ltree); /* send a literal byte */
  85013. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85014. } else {
  85015. /* Here, lc is the match length - MIN_MATCH */
  85016. code = _length_code[lc];
  85017. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85018. extra = extra_lbits[code];
  85019. if (extra != 0) {
  85020. lc -= base_length[code];
  85021. send_bits(s, lc, extra); /* send the extra length bits */
  85022. }
  85023. dist--; /* dist is now the match distance - 1 */
  85024. code = d_code(dist);
  85025. Assert (code < D_CODES, "bad d_code");
  85026. send_code(s, code, dtree); /* send the distance code */
  85027. extra = extra_dbits[code];
  85028. if (extra != 0) {
  85029. dist -= base_dist[code];
  85030. send_bits(s, dist, extra); /* send the extra distance bits */
  85031. }
  85032. } /* literal or match pair ? */
  85033. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85034. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85035. "pendingBuf overflow");
  85036. } while (lx < s->last_lit);
  85037. send_code(s, END_BLOCK, ltree);
  85038. s->last_eob_len = ltree[END_BLOCK].Len;
  85039. }
  85040. /* ===========================================================================
  85041. * Set the data type to BINARY or TEXT, using a crude approximation:
  85042. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85043. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85044. * IN assertion: the fields Freq of dyn_ltree are set.
  85045. */
  85046. local void set_data_type (deflate_state *s)
  85047. {
  85048. int n;
  85049. for (n = 0; n < 9; n++)
  85050. if (s->dyn_ltree[n].Freq != 0)
  85051. break;
  85052. if (n == 9)
  85053. for (n = 14; n < 32; n++)
  85054. if (s->dyn_ltree[n].Freq != 0)
  85055. break;
  85056. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85057. }
  85058. /* ===========================================================================
  85059. * Reverse the first len bits of a code, using straightforward code (a faster
  85060. * method would use a table)
  85061. * IN assertion: 1 <= len <= 15
  85062. */
  85063. local unsigned bi_reverse (unsigned code, int len)
  85064. {
  85065. register unsigned res = 0;
  85066. do {
  85067. res |= code & 1;
  85068. code >>= 1, res <<= 1;
  85069. } while (--len > 0);
  85070. return res >> 1;
  85071. }
  85072. /* ===========================================================================
  85073. * Flush the bit buffer, keeping at most 7 bits in it.
  85074. */
  85075. local void bi_flush (deflate_state *s)
  85076. {
  85077. if (s->bi_valid == 16) {
  85078. put_short(s, s->bi_buf);
  85079. s->bi_buf = 0;
  85080. s->bi_valid = 0;
  85081. } else if (s->bi_valid >= 8) {
  85082. put_byte(s, (Byte)s->bi_buf);
  85083. s->bi_buf >>= 8;
  85084. s->bi_valid -= 8;
  85085. }
  85086. }
  85087. /* ===========================================================================
  85088. * Flush the bit buffer and align the output on a byte boundary
  85089. */
  85090. local void bi_windup (deflate_state *s)
  85091. {
  85092. if (s->bi_valid > 8) {
  85093. put_short(s, s->bi_buf);
  85094. } else if (s->bi_valid > 0) {
  85095. put_byte(s, (Byte)s->bi_buf);
  85096. }
  85097. s->bi_buf = 0;
  85098. s->bi_valid = 0;
  85099. #ifdef DEBUG
  85100. s->bits_sent = (s->bits_sent+7) & ~7;
  85101. #endif
  85102. }
  85103. /* ===========================================================================
  85104. * Copy a stored block, storing first the length and its
  85105. * one's complement if requested.
  85106. */
  85107. local void copy_block(deflate_state *s,
  85108. charf *buf, /* the input data */
  85109. unsigned len, /* its length */
  85110. int header) /* true if block header must be written */
  85111. {
  85112. bi_windup(s); /* align on byte boundary */
  85113. s->last_eob_len = 8; /* enough lookahead for inflate */
  85114. if (header) {
  85115. put_short(s, (ush)len);
  85116. put_short(s, (ush)~len);
  85117. #ifdef DEBUG
  85118. s->bits_sent += 2*16;
  85119. #endif
  85120. }
  85121. #ifdef DEBUG
  85122. s->bits_sent += (ulg)len<<3;
  85123. #endif
  85124. while (len--) {
  85125. put_byte(s, *buf++);
  85126. }
  85127. }
  85128. /*** End of inlined file: trees.c ***/
  85129. /*** Start of inlined file: zutil.c ***/
  85130. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85131. #ifndef NO_DUMMY_DECL
  85132. struct internal_state {int dummy;}; /* for buggy compilers */
  85133. #endif
  85134. const char * const z_errmsg[10] = {
  85135. "need dictionary", /* Z_NEED_DICT 2 */
  85136. "stream end", /* Z_STREAM_END 1 */
  85137. "", /* Z_OK 0 */
  85138. "file error", /* Z_ERRNO (-1) */
  85139. "stream error", /* Z_STREAM_ERROR (-2) */
  85140. "data error", /* Z_DATA_ERROR (-3) */
  85141. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85142. "buffer error", /* Z_BUF_ERROR (-5) */
  85143. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85144. ""};
  85145. /*const char * ZEXPORT zlibVersion()
  85146. {
  85147. return ZLIB_VERSION;
  85148. }
  85149. uLong ZEXPORT zlibCompileFlags()
  85150. {
  85151. uLong flags;
  85152. flags = 0;
  85153. switch (sizeof(uInt)) {
  85154. case 2: break;
  85155. case 4: flags += 1; break;
  85156. case 8: flags += 2; break;
  85157. default: flags += 3;
  85158. }
  85159. switch (sizeof(uLong)) {
  85160. case 2: break;
  85161. case 4: flags += 1 << 2; break;
  85162. case 8: flags += 2 << 2; break;
  85163. default: flags += 3 << 2;
  85164. }
  85165. switch (sizeof(voidpf)) {
  85166. case 2: break;
  85167. case 4: flags += 1 << 4; break;
  85168. case 8: flags += 2 << 4; break;
  85169. default: flags += 3 << 4;
  85170. }
  85171. switch (sizeof(z_off_t)) {
  85172. case 2: break;
  85173. case 4: flags += 1 << 6; break;
  85174. case 8: flags += 2 << 6; break;
  85175. default: flags += 3 << 6;
  85176. }
  85177. #ifdef DEBUG
  85178. flags += 1 << 8;
  85179. #endif
  85180. #if defined(ASMV) || defined(ASMINF)
  85181. flags += 1 << 9;
  85182. #endif
  85183. #ifdef ZLIB_WINAPI
  85184. flags += 1 << 10;
  85185. #endif
  85186. #ifdef BUILDFIXED
  85187. flags += 1 << 12;
  85188. #endif
  85189. #ifdef DYNAMIC_CRC_TABLE
  85190. flags += 1 << 13;
  85191. #endif
  85192. #ifdef NO_GZCOMPRESS
  85193. flags += 1L << 16;
  85194. #endif
  85195. #ifdef NO_GZIP
  85196. flags += 1L << 17;
  85197. #endif
  85198. #ifdef PKZIP_BUG_WORKAROUND
  85199. flags += 1L << 20;
  85200. #endif
  85201. #ifdef FASTEST
  85202. flags += 1L << 21;
  85203. #endif
  85204. #ifdef STDC
  85205. # ifdef NO_vsnprintf
  85206. flags += 1L << 25;
  85207. # ifdef HAS_vsprintf_void
  85208. flags += 1L << 26;
  85209. # endif
  85210. # else
  85211. # ifdef HAS_vsnprintf_void
  85212. flags += 1L << 26;
  85213. # endif
  85214. # endif
  85215. #else
  85216. flags += 1L << 24;
  85217. # ifdef NO_snprintf
  85218. flags += 1L << 25;
  85219. # ifdef HAS_sprintf_void
  85220. flags += 1L << 26;
  85221. # endif
  85222. # else
  85223. # ifdef HAS_snprintf_void
  85224. flags += 1L << 26;
  85225. # endif
  85226. # endif
  85227. #endif
  85228. return flags;
  85229. }*/
  85230. #ifdef DEBUG
  85231. # ifndef verbose
  85232. # define verbose 0
  85233. # endif
  85234. int z_verbose = verbose;
  85235. void z_error (const char *m)
  85236. {
  85237. fprintf(stderr, "%s\n", m);
  85238. exit(1);
  85239. }
  85240. #endif
  85241. /* exported to allow conversion of error code to string for compress() and
  85242. * uncompress()
  85243. */
  85244. const char * ZEXPORT zError(int err)
  85245. {
  85246. return ERR_MSG(err);
  85247. }
  85248. #if defined(_WIN32_WCE)
  85249. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85250. * errno. We define it as a global variable to simplify porting.
  85251. * Its value is always 0 and should not be used.
  85252. */
  85253. int errno = 0;
  85254. #endif
  85255. #ifndef HAVE_MEMCPY
  85256. void zmemcpy(dest, source, len)
  85257. Bytef* dest;
  85258. const Bytef* source;
  85259. uInt len;
  85260. {
  85261. if (len == 0) return;
  85262. do {
  85263. *dest++ = *source++; /* ??? to be unrolled */
  85264. } while (--len != 0);
  85265. }
  85266. int zmemcmp(s1, s2, len)
  85267. const Bytef* s1;
  85268. const Bytef* s2;
  85269. uInt len;
  85270. {
  85271. uInt j;
  85272. for (j = 0; j < len; j++) {
  85273. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85274. }
  85275. return 0;
  85276. }
  85277. void zmemzero(dest, len)
  85278. Bytef* dest;
  85279. uInt len;
  85280. {
  85281. if (len == 0) return;
  85282. do {
  85283. *dest++ = 0; /* ??? to be unrolled */
  85284. } while (--len != 0);
  85285. }
  85286. #endif
  85287. #ifdef SYS16BIT
  85288. #ifdef __TURBOC__
  85289. /* Turbo C in 16-bit mode */
  85290. # define MY_ZCALLOC
  85291. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85292. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85293. * must fix the pointer. Warning: the pointer must be put back to its
  85294. * original form in order to free it, use zcfree().
  85295. */
  85296. #define MAX_PTR 10
  85297. /* 10*64K = 640K */
  85298. local int next_ptr = 0;
  85299. typedef struct ptr_table_s {
  85300. voidpf org_ptr;
  85301. voidpf new_ptr;
  85302. } ptr_table;
  85303. local ptr_table table[MAX_PTR];
  85304. /* This table is used to remember the original form of pointers
  85305. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85306. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85307. * protected from concurrent access. This hack doesn't work anyway on
  85308. * a protected system like OS/2. Use Microsoft C instead.
  85309. */
  85310. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85311. {
  85312. voidpf buf = opaque; /* just to make some compilers happy */
  85313. ulg bsize = (ulg)items*size;
  85314. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85315. * will return a usable pointer which doesn't have to be normalized.
  85316. */
  85317. if (bsize < 65520L) {
  85318. buf = farmalloc(bsize);
  85319. if (*(ush*)&buf != 0) return buf;
  85320. } else {
  85321. buf = farmalloc(bsize + 16L);
  85322. }
  85323. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85324. table[next_ptr].org_ptr = buf;
  85325. /* Normalize the pointer to seg:0 */
  85326. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85327. *(ush*)&buf = 0;
  85328. table[next_ptr++].new_ptr = buf;
  85329. return buf;
  85330. }
  85331. void zcfree (voidpf opaque, voidpf ptr)
  85332. {
  85333. int n;
  85334. if (*(ush*)&ptr != 0) { /* object < 64K */
  85335. farfree(ptr);
  85336. return;
  85337. }
  85338. /* Find the original pointer */
  85339. for (n = 0; n < next_ptr; n++) {
  85340. if (ptr != table[n].new_ptr) continue;
  85341. farfree(table[n].org_ptr);
  85342. while (++n < next_ptr) {
  85343. table[n-1] = table[n];
  85344. }
  85345. next_ptr--;
  85346. return;
  85347. }
  85348. ptr = opaque; /* just to make some compilers happy */
  85349. Assert(0, "zcfree: ptr not found");
  85350. }
  85351. #endif /* __TURBOC__ */
  85352. #ifdef M_I86
  85353. /* Microsoft C in 16-bit mode */
  85354. # define MY_ZCALLOC
  85355. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85356. # define _halloc halloc
  85357. # define _hfree hfree
  85358. #endif
  85359. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85360. {
  85361. if (opaque) opaque = 0; /* to make compiler happy */
  85362. return _halloc((long)items, size);
  85363. }
  85364. void zcfree (voidpf opaque, voidpf ptr)
  85365. {
  85366. if (opaque) opaque = 0; /* to make compiler happy */
  85367. _hfree(ptr);
  85368. }
  85369. #endif /* M_I86 */
  85370. #endif /* SYS16BIT */
  85371. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85372. #ifndef STDC
  85373. extern voidp malloc OF((uInt size));
  85374. extern voidp calloc OF((uInt items, uInt size));
  85375. extern void free OF((voidpf ptr));
  85376. #endif
  85377. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85378. {
  85379. if (opaque) items += size - size; /* make compiler happy */
  85380. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85381. (voidpf)calloc(items, size);
  85382. }
  85383. void zcfree (voidpf opaque, voidpf ptr)
  85384. {
  85385. free(ptr);
  85386. if (opaque) return; /* make compiler happy */
  85387. }
  85388. #endif /* MY_ZCALLOC */
  85389. /*** End of inlined file: zutil.c ***/
  85390. #undef Byte
  85391. }
  85392. #else
  85393. #include <zlib.h>
  85394. #endif
  85395. }
  85396. #if JUCE_MSVC
  85397. #pragma warning (pop)
  85398. #endif
  85399. BEGIN_JUCE_NAMESPACE
  85400. // internal helper object that holds the zlib structures so they don't have to be
  85401. // included publicly.
  85402. class GZIPDecompressHelper
  85403. {
  85404. public:
  85405. GZIPDecompressHelper (const bool noWrap)
  85406. : finished (true),
  85407. needsDictionary (false),
  85408. error (true),
  85409. streamIsValid (false),
  85410. data (0),
  85411. dataSize (0)
  85412. {
  85413. using namespace zlibNamespace;
  85414. zerostruct (stream);
  85415. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85416. finished = error = ! streamIsValid;
  85417. }
  85418. ~GZIPDecompressHelper()
  85419. {
  85420. using namespace zlibNamespace;
  85421. if (streamIsValid)
  85422. inflateEnd (&stream);
  85423. }
  85424. bool needsInput() const throw() { return dataSize <= 0; }
  85425. void setInput (uint8* const data_, const int size) throw()
  85426. {
  85427. data = data_;
  85428. dataSize = size;
  85429. }
  85430. int doNextBlock (uint8* const dest, const int destSize)
  85431. {
  85432. using namespace zlibNamespace;
  85433. if (streamIsValid && data != 0 && ! finished)
  85434. {
  85435. stream.next_in = data;
  85436. stream.next_out = dest;
  85437. stream.avail_in = dataSize;
  85438. stream.avail_out = destSize;
  85439. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85440. {
  85441. case Z_STREAM_END:
  85442. finished = true;
  85443. // deliberate fall-through
  85444. case Z_OK:
  85445. data += dataSize - stream.avail_in;
  85446. dataSize = stream.avail_in;
  85447. return destSize - stream.avail_out;
  85448. case Z_NEED_DICT:
  85449. needsDictionary = true;
  85450. data += dataSize - stream.avail_in;
  85451. dataSize = stream.avail_in;
  85452. break;
  85453. case Z_DATA_ERROR:
  85454. case Z_MEM_ERROR:
  85455. error = true;
  85456. default:
  85457. break;
  85458. }
  85459. }
  85460. return 0;
  85461. }
  85462. bool finished, needsDictionary, error, streamIsValid;
  85463. private:
  85464. zlibNamespace::z_stream stream;
  85465. uint8* data;
  85466. int dataSize;
  85467. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85468. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85469. };
  85470. const int gzipDecompBufferSize = 32768;
  85471. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85472. const bool deleteSourceWhenDestroyed,
  85473. const bool noWrap_,
  85474. const int64 uncompressedStreamLength_)
  85475. : sourceStream (sourceStream_),
  85476. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85477. uncompressedStreamLength (uncompressedStreamLength_),
  85478. noWrap (noWrap_),
  85479. isEof (false),
  85480. activeBufferSize (0),
  85481. originalSourcePos (sourceStream_->getPosition()),
  85482. currentPos (0),
  85483. buffer (gzipDecompBufferSize),
  85484. helper (new GZIPDecompressHelper (noWrap_))
  85485. {
  85486. }
  85487. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85488. {
  85489. }
  85490. int64 GZIPDecompressorInputStream::getTotalLength()
  85491. {
  85492. return uncompressedStreamLength;
  85493. }
  85494. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85495. {
  85496. if ((howMany > 0) && ! isEof)
  85497. {
  85498. jassert (destBuffer != 0);
  85499. if (destBuffer != 0)
  85500. {
  85501. int numRead = 0;
  85502. uint8* d = static_cast <uint8*> (destBuffer);
  85503. while (! helper->error)
  85504. {
  85505. const int n = helper->doNextBlock (d, howMany);
  85506. currentPos += n;
  85507. if (n == 0)
  85508. {
  85509. if (helper->finished || helper->needsDictionary)
  85510. {
  85511. isEof = true;
  85512. return numRead;
  85513. }
  85514. if (helper->needsInput())
  85515. {
  85516. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85517. if (activeBufferSize > 0)
  85518. {
  85519. helper->setInput (buffer, activeBufferSize);
  85520. }
  85521. else
  85522. {
  85523. isEof = true;
  85524. return numRead;
  85525. }
  85526. }
  85527. }
  85528. else
  85529. {
  85530. numRead += n;
  85531. howMany -= n;
  85532. d += n;
  85533. if (howMany <= 0)
  85534. return numRead;
  85535. }
  85536. }
  85537. }
  85538. }
  85539. return 0;
  85540. }
  85541. bool GZIPDecompressorInputStream::isExhausted()
  85542. {
  85543. return helper->error || isEof;
  85544. }
  85545. int64 GZIPDecompressorInputStream::getPosition()
  85546. {
  85547. return currentPos;
  85548. }
  85549. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85550. {
  85551. if (newPos < currentPos)
  85552. {
  85553. // to go backwards, reset the stream and start again..
  85554. isEof = false;
  85555. activeBufferSize = 0;
  85556. currentPos = 0;
  85557. helper = new GZIPDecompressHelper (noWrap);
  85558. sourceStream->setPosition (originalSourcePos);
  85559. }
  85560. skipNextBytes (newPos - currentPos);
  85561. return true;
  85562. }
  85563. END_JUCE_NAMESPACE
  85564. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85565. #endif
  85566. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85567. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85568. #if JUCE_USE_FLAC
  85569. #if JUCE_WINDOWS
  85570. #include <windows.h>
  85571. #endif
  85572. namespace FlacNamespace
  85573. {
  85574. #if JUCE_INCLUDE_FLAC_CODE
  85575. #if JUCE_MSVC
  85576. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85577. #endif
  85578. #define FLAC__NO_DLL 1
  85579. #if ! defined (SIZE_MAX)
  85580. #define SIZE_MAX 0xffffffff
  85581. #endif
  85582. #define __STDC_LIMIT_MACROS 1
  85583. /*** Start of inlined file: all.h ***/
  85584. #ifndef FLAC__ALL_H
  85585. #define FLAC__ALL_H
  85586. /*** Start of inlined file: export.h ***/
  85587. #ifndef FLAC__EXPORT_H
  85588. #define FLAC__EXPORT_H
  85589. /** \file include/FLAC/export.h
  85590. *
  85591. * \brief
  85592. * This module contains #defines and symbols for exporting function
  85593. * calls, and providing version information and compiled-in features.
  85594. *
  85595. * See the \link flac_export export \endlink module.
  85596. */
  85597. /** \defgroup flac_export FLAC/export.h: export symbols
  85598. * \ingroup flac
  85599. *
  85600. * \brief
  85601. * This module contains #defines and symbols for exporting function
  85602. * calls, and providing version information and compiled-in features.
  85603. *
  85604. * If you are compiling with MSVC and will link to the static library
  85605. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85606. * make sure the symbols are exported properly.
  85607. *
  85608. * \{
  85609. */
  85610. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85611. #define FLAC_API
  85612. #else
  85613. #ifdef FLAC_API_EXPORTS
  85614. #define FLAC_API _declspec(dllexport)
  85615. #else
  85616. #define FLAC_API _declspec(dllimport)
  85617. #endif
  85618. #endif
  85619. /** These #defines will mirror the libtool-based library version number, see
  85620. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85621. */
  85622. #define FLAC_API_VERSION_CURRENT 10
  85623. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85624. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85625. #ifdef __cplusplus
  85626. extern "C" {
  85627. #endif
  85628. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85629. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85630. #ifdef __cplusplus
  85631. }
  85632. #endif
  85633. /* \} */
  85634. #endif
  85635. /*** End of inlined file: export.h ***/
  85636. /*** Start of inlined file: assert.h ***/
  85637. #ifndef FLAC__ASSERT_H
  85638. #define FLAC__ASSERT_H
  85639. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85640. #ifdef DEBUG
  85641. #include <assert.h>
  85642. #define FLAC__ASSERT(x) assert(x)
  85643. #define FLAC__ASSERT_DECLARATION(x) x
  85644. #else
  85645. #define FLAC__ASSERT(x)
  85646. #define FLAC__ASSERT_DECLARATION(x)
  85647. #endif
  85648. #endif
  85649. /*** End of inlined file: assert.h ***/
  85650. /*** Start of inlined file: callback.h ***/
  85651. #ifndef FLAC__CALLBACK_H
  85652. #define FLAC__CALLBACK_H
  85653. /*** Start of inlined file: ordinals.h ***/
  85654. #ifndef FLAC__ORDINALS_H
  85655. #define FLAC__ORDINALS_H
  85656. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85657. #include <inttypes.h>
  85658. #endif
  85659. typedef signed char FLAC__int8;
  85660. typedef unsigned char FLAC__uint8;
  85661. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85662. typedef __int16 FLAC__int16;
  85663. typedef __int32 FLAC__int32;
  85664. typedef __int64 FLAC__int64;
  85665. typedef unsigned __int16 FLAC__uint16;
  85666. typedef unsigned __int32 FLAC__uint32;
  85667. typedef unsigned __int64 FLAC__uint64;
  85668. #elif defined(__EMX__)
  85669. typedef short FLAC__int16;
  85670. typedef long FLAC__int32;
  85671. typedef long long FLAC__int64;
  85672. typedef unsigned short FLAC__uint16;
  85673. typedef unsigned long FLAC__uint32;
  85674. typedef unsigned long long FLAC__uint64;
  85675. #else
  85676. typedef int16_t FLAC__int16;
  85677. typedef int32_t FLAC__int32;
  85678. typedef int64_t FLAC__int64;
  85679. typedef uint16_t FLAC__uint16;
  85680. typedef uint32_t FLAC__uint32;
  85681. typedef uint64_t FLAC__uint64;
  85682. #endif
  85683. typedef int FLAC__bool;
  85684. typedef FLAC__uint8 FLAC__byte;
  85685. #ifdef true
  85686. #undef true
  85687. #endif
  85688. #ifdef false
  85689. #undef false
  85690. #endif
  85691. #ifndef __cplusplus
  85692. #define true 1
  85693. #define false 0
  85694. #endif
  85695. #endif
  85696. /*** End of inlined file: ordinals.h ***/
  85697. #include <stdlib.h> /* for size_t */
  85698. /** \file include/FLAC/callback.h
  85699. *
  85700. * \brief
  85701. * This module defines the structures for describing I/O callbacks
  85702. * to the other FLAC interfaces.
  85703. *
  85704. * See the detailed documentation for callbacks in the
  85705. * \link flac_callbacks callbacks \endlink module.
  85706. */
  85707. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85708. * \ingroup flac
  85709. *
  85710. * \brief
  85711. * This module defines the structures for describing I/O callbacks
  85712. * to the other FLAC interfaces.
  85713. *
  85714. * The purpose of the I/O callback functions is to create a common way
  85715. * for the metadata interfaces to handle I/O.
  85716. *
  85717. * Originally the metadata interfaces required filenames as the way of
  85718. * specifying FLAC files to operate on. This is problematic in some
  85719. * environments so there is an additional option to specify a set of
  85720. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85721. *
  85722. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85723. * opaque structure for a data source.
  85724. *
  85725. * The callback function prototypes are similar (but not identical) to the
  85726. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85727. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85728. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85729. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85730. * is required. \warning You generally CANNOT directly use fseek or ftell
  85731. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85732. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85733. * large files. You will have to find an equivalent function (e.g. ftello),
  85734. * or write a wrapper. The same is true for feof() since this is usually
  85735. * implemented as a macro, not as a function whose address can be taken.
  85736. *
  85737. * \{
  85738. */
  85739. #ifdef __cplusplus
  85740. extern "C" {
  85741. #endif
  85742. /** This is the opaque handle type used by the callbacks. Typically
  85743. * this is a \c FILE* or address of a file descriptor.
  85744. */
  85745. typedef void* FLAC__IOHandle;
  85746. /** Signature for the read callback.
  85747. * The signature and semantics match POSIX fread() implementations
  85748. * and can generally be used interchangeably.
  85749. *
  85750. * \param ptr The address of the read buffer.
  85751. * \param size The size of the records to be read.
  85752. * \param nmemb The number of records to be read.
  85753. * \param handle The handle to the data source.
  85754. * \retval size_t
  85755. * The number of records read.
  85756. */
  85757. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85758. /** Signature for the write callback.
  85759. * The signature and semantics match POSIX fwrite() implementations
  85760. * and can generally be used interchangeably.
  85761. *
  85762. * \param ptr The address of the write buffer.
  85763. * \param size The size of the records to be written.
  85764. * \param nmemb The number of records to be written.
  85765. * \param handle The handle to the data source.
  85766. * \retval size_t
  85767. * The number of records written.
  85768. */
  85769. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85770. /** Signature for the seek callback.
  85771. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85772. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85773. * and 32-bits wide.
  85774. *
  85775. * \param handle The handle to the data source.
  85776. * \param offset The new position, relative to \a whence
  85777. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85778. * \retval int
  85779. * \c 0 on success, \c -1 on error.
  85780. */
  85781. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85782. /** Signature for the tell callback.
  85783. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85784. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85785. * and 32-bits wide.
  85786. *
  85787. * \param handle The handle to the data source.
  85788. * \retval FLAC__int64
  85789. * The current position on success, \c -1 on error.
  85790. */
  85791. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85792. /** Signature for the EOF callback.
  85793. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85794. * on many systems, feof() is a macro, so in this case a wrapper function
  85795. * must be provided instead.
  85796. *
  85797. * \param handle The handle to the data source.
  85798. * \retval int
  85799. * \c 0 if not at end of file, nonzero if at end of file.
  85800. */
  85801. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85802. /** Signature for the close callback.
  85803. * The signature and semantics match POSIX fclose() implementations
  85804. * and can generally be used interchangeably.
  85805. *
  85806. * \param handle The handle to the data source.
  85807. * \retval int
  85808. * \c 0 on success, \c EOF on error.
  85809. */
  85810. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85811. /** A structure for holding a set of callbacks.
  85812. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85813. * describe which of the callbacks are required. The ones that are not
  85814. * required may be set to NULL.
  85815. *
  85816. * If the seek requirement for an interface is optional, you can signify that
  85817. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85818. */
  85819. typedef struct {
  85820. FLAC__IOCallback_Read read;
  85821. FLAC__IOCallback_Write write;
  85822. FLAC__IOCallback_Seek seek;
  85823. FLAC__IOCallback_Tell tell;
  85824. FLAC__IOCallback_Eof eof;
  85825. FLAC__IOCallback_Close close;
  85826. } FLAC__IOCallbacks;
  85827. /* \} */
  85828. #ifdef __cplusplus
  85829. }
  85830. #endif
  85831. #endif
  85832. /*** End of inlined file: callback.h ***/
  85833. /*** Start of inlined file: format.h ***/
  85834. #ifndef FLAC__FORMAT_H
  85835. #define FLAC__FORMAT_H
  85836. #ifdef __cplusplus
  85837. extern "C" {
  85838. #endif
  85839. /** \file include/FLAC/format.h
  85840. *
  85841. * \brief
  85842. * This module contains structure definitions for the representation
  85843. * of FLAC format components in memory. These are the basic
  85844. * structures used by the rest of the interfaces.
  85845. *
  85846. * See the detailed documentation in the
  85847. * \link flac_format format \endlink module.
  85848. */
  85849. /** \defgroup flac_format FLAC/format.h: format components
  85850. * \ingroup flac
  85851. *
  85852. * \brief
  85853. * This module contains structure definitions for the representation
  85854. * of FLAC format components in memory. These are the basic
  85855. * structures used by the rest of the interfaces.
  85856. *
  85857. * First, you should be familiar with the
  85858. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  85859. * follow directly from the specification. As a user of libFLAC, the
  85860. * interesting parts really are the structures that describe the frame
  85861. * header and metadata blocks.
  85862. *
  85863. * The format structures here are very primitive, designed to store
  85864. * information in an efficient way. Reading information from the
  85865. * structures is easy but creating or modifying them directly is
  85866. * more complex. For the most part, as a user of a library, editing
  85867. * is not necessary; however, for metadata blocks it is, so there are
  85868. * convenience functions provided in the \link flac_metadata metadata
  85869. * module \endlink to simplify the manipulation of metadata blocks.
  85870. *
  85871. * \note
  85872. * It's not the best convention, but symbols ending in _LEN are in bits
  85873. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  85874. * global variables because they are usually used when declaring byte
  85875. * arrays and some compilers require compile-time knowledge of array
  85876. * sizes when declared on the stack.
  85877. *
  85878. * \{
  85879. */
  85880. /*
  85881. Most of the values described in this file are defined by the FLAC
  85882. format specification. There is nothing to tune here.
  85883. */
  85884. /** The largest legal metadata type code. */
  85885. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  85886. /** The minimum block size, in samples, permitted by the format. */
  85887. #define FLAC__MIN_BLOCK_SIZE (16u)
  85888. /** The maximum block size, in samples, permitted by the format. */
  85889. #define FLAC__MAX_BLOCK_SIZE (65535u)
  85890. /** The maximum block size, in samples, permitted by the FLAC subset for
  85891. * sample rates up to 48kHz. */
  85892. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  85893. /** The maximum number of channels permitted by the format. */
  85894. #define FLAC__MAX_CHANNELS (8u)
  85895. /** The minimum sample resolution permitted by the format. */
  85896. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  85897. /** The maximum sample resolution permitted by the format. */
  85898. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  85899. /** The maximum sample resolution permitted by libFLAC.
  85900. *
  85901. * \warning
  85902. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  85903. * the reference encoder/decoder is currently limited to 24 bits because
  85904. * of prevalent 32-bit math, so make sure and use this value when
  85905. * appropriate.
  85906. */
  85907. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  85908. /** The maximum sample rate permitted by the format. The value is
  85909. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  85910. * as to why.
  85911. */
  85912. #define FLAC__MAX_SAMPLE_RATE (655350u)
  85913. /** The maximum LPC order permitted by the format. */
  85914. #define FLAC__MAX_LPC_ORDER (32u)
  85915. /** The maximum LPC order permitted by the FLAC subset for sample rates
  85916. * up to 48kHz. */
  85917. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  85918. /** The minimum quantized linear predictor coefficient precision
  85919. * permitted by the format.
  85920. */
  85921. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  85922. /** The maximum quantized linear predictor coefficient precision
  85923. * permitted by the format.
  85924. */
  85925. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  85926. /** The maximum order of the fixed predictors permitted by the format. */
  85927. #define FLAC__MAX_FIXED_ORDER (4u)
  85928. /** The maximum Rice partition order permitted by the format. */
  85929. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  85930. /** The maximum Rice partition order permitted by the FLAC Subset. */
  85931. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  85932. /** The version string of the release, stamped onto the libraries and binaries.
  85933. *
  85934. * \note
  85935. * This does not correspond to the shared library version number, which
  85936. * is used to determine binary compatibility.
  85937. */
  85938. extern FLAC_API const char *FLAC__VERSION_STRING;
  85939. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  85940. * This is a NUL-terminated ASCII string; when inserted into the
  85941. * VORBIS_COMMENT the trailing null is stripped.
  85942. */
  85943. extern FLAC_API const char *FLAC__VENDOR_STRING;
  85944. /** The byte string representation of the beginning of a FLAC stream. */
  85945. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  85946. /** The 32-bit integer big-endian representation of the beginning of
  85947. * a FLAC stream.
  85948. */
  85949. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  85950. /** The length of the FLAC signature in bits. */
  85951. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  85952. /** The length of the FLAC signature in bytes. */
  85953. #define FLAC__STREAM_SYNC_LENGTH (4u)
  85954. /*****************************************************************************
  85955. *
  85956. * Subframe structures
  85957. *
  85958. *****************************************************************************/
  85959. /*****************************************************************************/
  85960. /** An enumeration of the available entropy coding methods. */
  85961. typedef enum {
  85962. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  85963. /**< Residual is coded by partitioning into contexts, each with it's own
  85964. * 4-bit Rice parameter. */
  85965. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  85966. /**< Residual is coded by partitioning into contexts, each with it's own
  85967. * 5-bit Rice parameter. */
  85968. } FLAC__EntropyCodingMethodType;
  85969. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  85970. *
  85971. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  85972. * give the string equivalent. The contents should not be modified.
  85973. */
  85974. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  85975. /** Contents of a Rice partitioned residual
  85976. */
  85977. typedef struct {
  85978. unsigned *parameters;
  85979. /**< The Rice parameters for each context. */
  85980. unsigned *raw_bits;
  85981. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  85982. * partitions and zero for unescaped partitions.
  85983. */
  85984. unsigned capacity_by_order;
  85985. /**< The capacity of the \a parameters and \a raw_bits arrays
  85986. * specified as an order, i.e. the number of array elements
  85987. * allocated is 2 ^ \a capacity_by_order.
  85988. */
  85989. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  85990. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  85991. */
  85992. typedef struct {
  85993. unsigned order;
  85994. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  85995. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  85996. /**< The context's Rice parameters and/or raw bits. */
  85997. } FLAC__EntropyCodingMethod_PartitionedRice;
  85998. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  85999. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86000. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86001. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86002. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86003. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86004. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86005. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86006. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86007. */
  86008. typedef struct {
  86009. FLAC__EntropyCodingMethodType type;
  86010. union {
  86011. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86012. } data;
  86013. } FLAC__EntropyCodingMethod;
  86014. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86015. /*****************************************************************************/
  86016. /** An enumeration of the available subframe types. */
  86017. typedef enum {
  86018. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86019. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86020. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86021. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86022. } FLAC__SubframeType;
  86023. /** Maps a FLAC__SubframeType to a C string.
  86024. *
  86025. * Using a FLAC__SubframeType as the index to this array will
  86026. * give the string equivalent. The contents should not be modified.
  86027. */
  86028. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86029. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86030. */
  86031. typedef struct {
  86032. FLAC__int32 value; /**< The constant signal value. */
  86033. } FLAC__Subframe_Constant;
  86034. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86035. */
  86036. typedef struct {
  86037. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86038. } FLAC__Subframe_Verbatim;
  86039. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86040. */
  86041. typedef struct {
  86042. FLAC__EntropyCodingMethod entropy_coding_method;
  86043. /**< The residual coding method. */
  86044. unsigned order;
  86045. /**< The polynomial order. */
  86046. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86047. /**< Warmup samples to prime the predictor, length == order. */
  86048. const FLAC__int32 *residual;
  86049. /**< The residual signal, length == (blocksize minus order) samples. */
  86050. } FLAC__Subframe_Fixed;
  86051. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86052. */
  86053. typedef struct {
  86054. FLAC__EntropyCodingMethod entropy_coding_method;
  86055. /**< The residual coding method. */
  86056. unsigned order;
  86057. /**< The FIR order. */
  86058. unsigned qlp_coeff_precision;
  86059. /**< Quantized FIR filter coefficient precision in bits. */
  86060. int quantization_level;
  86061. /**< The qlp coeff shift needed. */
  86062. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86063. /**< FIR filter coefficients. */
  86064. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86065. /**< Warmup samples to prime the predictor, length == order. */
  86066. const FLAC__int32 *residual;
  86067. /**< The residual signal, length == (blocksize minus order) samples. */
  86068. } FLAC__Subframe_LPC;
  86069. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86070. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86071. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86072. */
  86073. typedef struct {
  86074. FLAC__SubframeType type;
  86075. union {
  86076. FLAC__Subframe_Constant constant;
  86077. FLAC__Subframe_Fixed fixed;
  86078. FLAC__Subframe_LPC lpc;
  86079. FLAC__Subframe_Verbatim verbatim;
  86080. } data;
  86081. unsigned wasted_bits;
  86082. } FLAC__Subframe;
  86083. /** == 1 (bit)
  86084. *
  86085. * This used to be a zero-padding bit (hence the name
  86086. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86087. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86088. * to mean something else.
  86089. */
  86090. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86091. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86092. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86093. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86094. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86095. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86096. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86097. /*****************************************************************************/
  86098. /*****************************************************************************
  86099. *
  86100. * Frame structures
  86101. *
  86102. *****************************************************************************/
  86103. /** An enumeration of the available channel assignments. */
  86104. typedef enum {
  86105. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86106. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86107. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86108. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86109. } FLAC__ChannelAssignment;
  86110. /** Maps a FLAC__ChannelAssignment to a C string.
  86111. *
  86112. * Using a FLAC__ChannelAssignment as the index to this array will
  86113. * give the string equivalent. The contents should not be modified.
  86114. */
  86115. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86116. /** An enumeration of the possible frame numbering methods. */
  86117. typedef enum {
  86118. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86119. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86120. } FLAC__FrameNumberType;
  86121. /** Maps a FLAC__FrameNumberType to a C string.
  86122. *
  86123. * Using a FLAC__FrameNumberType as the index to this array will
  86124. * give the string equivalent. The contents should not be modified.
  86125. */
  86126. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86127. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86128. */
  86129. typedef struct {
  86130. unsigned blocksize;
  86131. /**< The number of samples per subframe. */
  86132. unsigned sample_rate;
  86133. /**< The sample rate in Hz. */
  86134. unsigned channels;
  86135. /**< The number of channels (== number of subframes). */
  86136. FLAC__ChannelAssignment channel_assignment;
  86137. /**< The channel assignment for the frame. */
  86138. unsigned bits_per_sample;
  86139. /**< The sample resolution. */
  86140. FLAC__FrameNumberType number_type;
  86141. /**< The numbering scheme used for the frame. As a convenience, the
  86142. * decoder will always convert a frame number to a sample number because
  86143. * the rules are complex. */
  86144. union {
  86145. FLAC__uint32 frame_number;
  86146. FLAC__uint64 sample_number;
  86147. } number;
  86148. /**< The frame number or sample number of first sample in frame;
  86149. * use the \a number_type value to determine which to use. */
  86150. FLAC__uint8 crc;
  86151. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86152. * of the raw frame header bytes, meaning everything before the CRC byte
  86153. * including the sync code.
  86154. */
  86155. } FLAC__FrameHeader;
  86156. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86157. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86158. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86159. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86160. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86161. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86162. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86163. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86164. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86165. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86166. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86167. */
  86168. typedef struct {
  86169. FLAC__uint16 crc;
  86170. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86171. * 0) of the bytes before the crc, back to and including the frame header
  86172. * sync code.
  86173. */
  86174. } FLAC__FrameFooter;
  86175. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86176. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86177. */
  86178. typedef struct {
  86179. FLAC__FrameHeader header;
  86180. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86181. FLAC__FrameFooter footer;
  86182. } FLAC__Frame;
  86183. /*****************************************************************************/
  86184. /*****************************************************************************
  86185. *
  86186. * Meta-data structures
  86187. *
  86188. *****************************************************************************/
  86189. /** An enumeration of the available metadata block types. */
  86190. typedef enum {
  86191. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86192. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86193. FLAC__METADATA_TYPE_PADDING = 1,
  86194. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86195. FLAC__METADATA_TYPE_APPLICATION = 2,
  86196. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86197. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86198. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86199. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86200. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86201. FLAC__METADATA_TYPE_CUESHEET = 5,
  86202. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86203. FLAC__METADATA_TYPE_PICTURE = 6,
  86204. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86205. FLAC__METADATA_TYPE_UNDEFINED = 7
  86206. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86207. } FLAC__MetadataType;
  86208. /** Maps a FLAC__MetadataType to a C string.
  86209. *
  86210. * Using a FLAC__MetadataType as the index to this array will
  86211. * give the string equivalent. The contents should not be modified.
  86212. */
  86213. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86214. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86215. */
  86216. typedef struct {
  86217. unsigned min_blocksize, max_blocksize;
  86218. unsigned min_framesize, max_framesize;
  86219. unsigned sample_rate;
  86220. unsigned channels;
  86221. unsigned bits_per_sample;
  86222. FLAC__uint64 total_samples;
  86223. FLAC__byte md5sum[16];
  86224. } FLAC__StreamMetadata_StreamInfo;
  86225. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86226. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86227. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86228. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86229. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86230. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86231. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86232. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86233. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86234. /** The total stream length of the STREAMINFO block in bytes. */
  86235. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86236. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86237. */
  86238. typedef struct {
  86239. int dummy;
  86240. /**< Conceptually this is an empty struct since we don't store the
  86241. * padding bytes. Empty structs are not allowed by some C compilers,
  86242. * hence the dummy.
  86243. */
  86244. } FLAC__StreamMetadata_Padding;
  86245. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86246. */
  86247. typedef struct {
  86248. FLAC__byte id[4];
  86249. FLAC__byte *data;
  86250. } FLAC__StreamMetadata_Application;
  86251. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86252. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86253. */
  86254. typedef struct {
  86255. FLAC__uint64 sample_number;
  86256. /**< The sample number of the target frame. */
  86257. FLAC__uint64 stream_offset;
  86258. /**< The offset, in bytes, of the target frame with respect to
  86259. * beginning of the first frame. */
  86260. unsigned frame_samples;
  86261. /**< The number of samples in the target frame. */
  86262. } FLAC__StreamMetadata_SeekPoint;
  86263. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86264. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86265. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86266. /** The total stream length of a seek point in bytes. */
  86267. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86268. /** The value used in the \a sample_number field of
  86269. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86270. * point (== 0xffffffffffffffff).
  86271. */
  86272. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86273. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86274. *
  86275. * \note From the format specification:
  86276. * - The seek points must be sorted by ascending sample number.
  86277. * - Each seek point's sample number must be the first sample of the
  86278. * target frame.
  86279. * - Each seek point's sample number must be unique within the table.
  86280. * - Existence of a SEEKTABLE block implies a correct setting of
  86281. * total_samples in the stream_info block.
  86282. * - Behavior is undefined when more than one SEEKTABLE block is
  86283. * present in a stream.
  86284. */
  86285. typedef struct {
  86286. unsigned num_points;
  86287. FLAC__StreamMetadata_SeekPoint *points;
  86288. } FLAC__StreamMetadata_SeekTable;
  86289. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86290. *
  86291. * For convenience, the APIs maintain a trailing NUL character at the end of
  86292. * \a entry which is not counted toward \a length, i.e.
  86293. * \code strlen(entry) == length \endcode
  86294. */
  86295. typedef struct {
  86296. FLAC__uint32 length;
  86297. FLAC__byte *entry;
  86298. } FLAC__StreamMetadata_VorbisComment_Entry;
  86299. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86300. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86301. */
  86302. typedef struct {
  86303. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86304. FLAC__uint32 num_comments;
  86305. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86306. } FLAC__StreamMetadata_VorbisComment;
  86307. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86308. /** FLAC CUESHEET track index structure. (See the
  86309. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86310. * the full description of each field.)
  86311. */
  86312. typedef struct {
  86313. FLAC__uint64 offset;
  86314. /**< Offset in samples, relative to the track offset, of the index
  86315. * point.
  86316. */
  86317. FLAC__byte number;
  86318. /**< The index point number. */
  86319. } FLAC__StreamMetadata_CueSheet_Index;
  86320. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86322. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86323. /** FLAC CUESHEET track structure. (See the
  86324. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86325. * the full description of each field.)
  86326. */
  86327. typedef struct {
  86328. FLAC__uint64 offset;
  86329. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86330. FLAC__byte number;
  86331. /**< The track number. */
  86332. char isrc[13];
  86333. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86334. unsigned type:1;
  86335. /**< The track type: 0 for audio, 1 for non-audio. */
  86336. unsigned pre_emphasis:1;
  86337. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86338. FLAC__byte num_indices;
  86339. /**< The number of track index points. */
  86340. FLAC__StreamMetadata_CueSheet_Index *indices;
  86341. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86342. } FLAC__StreamMetadata_CueSheet_Track;
  86343. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86344. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86345. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86346. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86347. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86348. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86349. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86350. /** FLAC CUESHEET structure. (See the
  86351. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86352. * for the full description of each field.)
  86353. */
  86354. typedef struct {
  86355. char media_catalog_number[129];
  86356. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86357. * general, the media catalog number may be 0 to 128 bytes long; any
  86358. * unused characters should be right-padded with NUL characters.
  86359. */
  86360. FLAC__uint64 lead_in;
  86361. /**< The number of lead-in samples. */
  86362. FLAC__bool is_cd;
  86363. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86364. unsigned num_tracks;
  86365. /**< The number of tracks. */
  86366. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86367. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86368. } FLAC__StreamMetadata_CueSheet;
  86369. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86370. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86371. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86372. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86373. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86374. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86375. typedef enum {
  86376. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86377. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86378. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86379. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86380. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86381. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86382. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86383. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86384. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86385. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86386. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86387. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86388. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86389. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86390. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86391. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86392. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86393. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86394. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86395. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86396. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86397. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86398. } FLAC__StreamMetadata_Picture_Type;
  86399. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86400. *
  86401. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86402. * will give the string equivalent. The contents should not be
  86403. * modified.
  86404. */
  86405. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86406. /** FLAC PICTURE structure. (See the
  86407. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86408. * for the full description of each field.)
  86409. */
  86410. typedef struct {
  86411. FLAC__StreamMetadata_Picture_Type type;
  86412. /**< The kind of picture stored. */
  86413. char *mime_type;
  86414. /**< Picture data's MIME type, in ASCII printable characters
  86415. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86416. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86417. * MIME type of '-->' is also allowed, in which case the picture
  86418. * data should be a complete URL. In file storage, the MIME type is
  86419. * stored as a 32-bit length followed by the ASCII string with no NUL
  86420. * terminator, but is converted to a plain C string in this structure
  86421. * for convenience.
  86422. */
  86423. FLAC__byte *description;
  86424. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86425. * the description is stored as a 32-bit length followed by the UTF-8
  86426. * string with no NUL terminator, but is converted to a plain C string
  86427. * in this structure for convenience.
  86428. */
  86429. FLAC__uint32 width;
  86430. /**< Picture's width in pixels. */
  86431. FLAC__uint32 height;
  86432. /**< Picture's height in pixels. */
  86433. FLAC__uint32 depth;
  86434. /**< Picture's color depth in bits-per-pixel. */
  86435. FLAC__uint32 colors;
  86436. /**< For indexed palettes (like GIF), picture's number of colors (the
  86437. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86438. */
  86439. FLAC__uint32 data_length;
  86440. /**< Length of binary picture data in bytes. */
  86441. FLAC__byte *data;
  86442. /**< Binary picture data. */
  86443. } FLAC__StreamMetadata_Picture;
  86444. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86445. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86446. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86447. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86448. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86449. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86450. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86451. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86452. /** Structure that is used when a metadata block of unknown type is loaded.
  86453. * The contents are opaque. The structure is used only internally to
  86454. * correctly handle unknown metadata.
  86455. */
  86456. typedef struct {
  86457. FLAC__byte *data;
  86458. } FLAC__StreamMetadata_Unknown;
  86459. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86460. */
  86461. typedef struct {
  86462. FLAC__MetadataType type;
  86463. /**< The type of the metadata block; used determine which member of the
  86464. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86465. * then \a data.unknown must be used. */
  86466. FLAC__bool is_last;
  86467. /**< \c true if this metadata block is the last, else \a false */
  86468. unsigned length;
  86469. /**< Length, in bytes, of the block data as it appears in the stream. */
  86470. union {
  86471. FLAC__StreamMetadata_StreamInfo stream_info;
  86472. FLAC__StreamMetadata_Padding padding;
  86473. FLAC__StreamMetadata_Application application;
  86474. FLAC__StreamMetadata_SeekTable seek_table;
  86475. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86476. FLAC__StreamMetadata_CueSheet cue_sheet;
  86477. FLAC__StreamMetadata_Picture picture;
  86478. FLAC__StreamMetadata_Unknown unknown;
  86479. } data;
  86480. /**< Polymorphic block data; use the \a type value to determine which
  86481. * to use. */
  86482. } FLAC__StreamMetadata;
  86483. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86484. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86485. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86486. /** The total stream length of a metadata block header in bytes. */
  86487. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86488. /*****************************************************************************/
  86489. /*****************************************************************************
  86490. *
  86491. * Utility functions
  86492. *
  86493. *****************************************************************************/
  86494. /** Tests that a sample rate is valid for FLAC.
  86495. *
  86496. * \param sample_rate The sample rate to test for compliance.
  86497. * \retval FLAC__bool
  86498. * \c true if the given sample rate conforms to the specification, else
  86499. * \c false.
  86500. */
  86501. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86502. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86503. * for valid sample rates are slightly more complex since the rate has to
  86504. * be expressible completely in the frame header.
  86505. *
  86506. * \param sample_rate The sample rate to test for compliance.
  86507. * \retval FLAC__bool
  86508. * \c true if the given sample rate conforms to the specification for the
  86509. * subset, else \c false.
  86510. */
  86511. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86512. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86513. * comment specification.
  86514. *
  86515. * Vorbis comment names must be composed only of characters from
  86516. * [0x20-0x3C,0x3E-0x7D].
  86517. *
  86518. * \param name A NUL-terminated string to be checked.
  86519. * \assert
  86520. * \code name != NULL \endcode
  86521. * \retval FLAC__bool
  86522. * \c false if entry name is illegal, else \c true.
  86523. */
  86524. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86525. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86526. * comment specification.
  86527. *
  86528. * Vorbis comment values must be valid UTF-8 sequences.
  86529. *
  86530. * \param value A string to be checked.
  86531. * \param length A the length of \a value in bytes. May be
  86532. * \c (unsigned)(-1) to indicate that \a value is a plain
  86533. * UTF-8 NUL-terminated string.
  86534. * \assert
  86535. * \code value != NULL \endcode
  86536. * \retval FLAC__bool
  86537. * \c false if entry name is illegal, else \c true.
  86538. */
  86539. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86540. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86541. * comment specification.
  86542. *
  86543. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86544. * 'value' must be legal according to
  86545. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86546. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86547. *
  86548. * \param entry An entry to be checked.
  86549. * \param length The length of \a entry in bytes.
  86550. * \assert
  86551. * \code value != NULL \endcode
  86552. * \retval FLAC__bool
  86553. * \c false if entry name is illegal, else \c true.
  86554. */
  86555. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86556. /** Check a seek table to see if it conforms to the FLAC specification.
  86557. * See the format specification for limits on the contents of the
  86558. * seek table.
  86559. *
  86560. * \param seek_table A pointer to a seek table to be checked.
  86561. * \assert
  86562. * \code seek_table != NULL \endcode
  86563. * \retval FLAC__bool
  86564. * \c false if seek table is illegal, else \c true.
  86565. */
  86566. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86567. /** Sort a seek table's seek points according to the format specification.
  86568. * This includes a "unique-ification" step to remove duplicates, i.e.
  86569. * seek points with identical \a sample_number values. Duplicate seek
  86570. * points are converted into placeholder points and sorted to the end of
  86571. * the table.
  86572. *
  86573. * \param seek_table A pointer to a seek table to be sorted.
  86574. * \assert
  86575. * \code seek_table != NULL \endcode
  86576. * \retval unsigned
  86577. * The number of duplicate seek points converted into placeholders.
  86578. */
  86579. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86580. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86581. * See the format specification for limits on the contents of the
  86582. * cue sheet.
  86583. *
  86584. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86585. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86586. * stringent requirements for a CD-DA (audio) disc.
  86587. * \param violation Address of a pointer to a string. If there is a
  86588. * violation, a pointer to a string explanation of the
  86589. * violation will be returned here. \a violation may be
  86590. * \c NULL if you don't need the returned string. Do not
  86591. * free the returned string; it will always point to static
  86592. * data.
  86593. * \assert
  86594. * \code cue_sheet != NULL \endcode
  86595. * \retval FLAC__bool
  86596. * \c false if cue sheet is illegal, else \c true.
  86597. */
  86598. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86599. /** Check picture data to see if it conforms to the FLAC specification.
  86600. * See the format specification for limits on the contents of the
  86601. * PICTURE block.
  86602. *
  86603. * \param picture A pointer to existing picture data to be checked.
  86604. * \param violation Address of a pointer to a string. If there is a
  86605. * violation, a pointer to a string explanation of the
  86606. * violation will be returned here. \a violation may be
  86607. * \c NULL if you don't need the returned string. Do not
  86608. * free the returned string; it will always point to static
  86609. * data.
  86610. * \assert
  86611. * \code picture != NULL \endcode
  86612. * \retval FLAC__bool
  86613. * \c false if picture data is illegal, else \c true.
  86614. */
  86615. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86616. /* \} */
  86617. #ifdef __cplusplus
  86618. }
  86619. #endif
  86620. #endif
  86621. /*** End of inlined file: format.h ***/
  86622. /*** Start of inlined file: metadata.h ***/
  86623. #ifndef FLAC__METADATA_H
  86624. #define FLAC__METADATA_H
  86625. #include <sys/types.h> /* for off_t */
  86626. /* --------------------------------------------------------------------
  86627. (For an example of how all these routines are used, see the source
  86628. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86629. metaflac in src/metaflac/)
  86630. ------------------------------------------------------------------*/
  86631. /** \file include/FLAC/metadata.h
  86632. *
  86633. * \brief
  86634. * This module provides functions for creating and manipulating FLAC
  86635. * metadata blocks in memory, and three progressively more powerful
  86636. * interfaces for traversing and editing metadata in FLAC files.
  86637. *
  86638. * See the detailed documentation for each interface in the
  86639. * \link flac_metadata metadata \endlink module.
  86640. */
  86641. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86642. * \ingroup flac
  86643. *
  86644. * \brief
  86645. * This module provides functions for creating and manipulating FLAC
  86646. * metadata blocks in memory, and three progressively more powerful
  86647. * interfaces for traversing and editing metadata in native FLAC files.
  86648. * Note that currently only the Chain interface (level 2) supports Ogg
  86649. * FLAC files, and it is read-only i.e. no writing back changed
  86650. * metadata to file.
  86651. *
  86652. * There are three metadata interfaces of increasing complexity:
  86653. *
  86654. * Level 0:
  86655. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86656. * PICTURE blocks.
  86657. *
  86658. * Level 1:
  86659. * Read-write access to all metadata blocks. This level is write-
  86660. * efficient in most cases (more on this below), and uses less memory
  86661. * than level 2.
  86662. *
  86663. * Level 2:
  86664. * Read-write access to all metadata blocks. This level is write-
  86665. * efficient in all cases, but uses more memory since all metadata for
  86666. * the whole file is read into memory and manipulated before writing
  86667. * out again.
  86668. *
  86669. * What do we mean by efficient? Since FLAC metadata appears at the
  86670. * beginning of the file, when writing metadata back to a FLAC file
  86671. * it is possible to grow or shrink the metadata such that the entire
  86672. * file must be rewritten. However, if the size remains the same during
  86673. * changes or PADDING blocks are utilized, only the metadata needs to be
  86674. * overwritten, which is much faster.
  86675. *
  86676. * Efficient means the whole file is rewritten at most one time, and only
  86677. * when necessary. Level 1 is not efficient only in the case that you
  86678. * cause more than one metadata block to grow or shrink beyond what can
  86679. * be accomodated by padding. In this case you should probably use level
  86680. * 2, which allows you to edit all the metadata for a file in memory and
  86681. * write it out all at once.
  86682. *
  86683. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86684. * front of the file.
  86685. *
  86686. * All levels access files via their filenames. In addition, level 2
  86687. * has additional alternative read and write functions that take an I/O
  86688. * handle and callbacks, for situations where access by filename is not
  86689. * possible.
  86690. *
  86691. * In addition to the three interfaces, this module defines functions for
  86692. * creating and manipulating various metadata objects in memory. As we see
  86693. * from the Format module, FLAC metadata blocks in memory are very primitive
  86694. * structures for storing information in an efficient way. Reading
  86695. * information from the structures is easy but creating or modifying them
  86696. * directly is more complex. The metadata object routines here facilitate
  86697. * this by taking care of the consistency and memory management drudgery.
  86698. *
  86699. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86700. * metadata however, you will not probably not need these.
  86701. *
  86702. * From a dependency standpoint, none of the encoders or decoders require
  86703. * the metadata module. This is so that embedded users can strip out the
  86704. * metadata module from libFLAC to reduce the size and complexity.
  86705. */
  86706. #ifdef __cplusplus
  86707. extern "C" {
  86708. #endif
  86709. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86710. * \ingroup flac_metadata
  86711. *
  86712. * \brief
  86713. * The level 0 interface consists of individual routines to read the
  86714. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86715. * only a filename.
  86716. *
  86717. * They try to skip any ID3v2 tag at the head of the file.
  86718. *
  86719. * \{
  86720. */
  86721. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86722. * will try to skip any ID3v2 tag at the head of the file.
  86723. *
  86724. * \param filename The path to the FLAC file to read.
  86725. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86726. * FLAC__StreamMetadata is a simple structure with no
  86727. * memory allocation involved, you pass the address of
  86728. * an existing structure. It need not be initialized.
  86729. * \assert
  86730. * \code filename != NULL \endcode
  86731. * \code streaminfo != NULL \endcode
  86732. * \retval FLAC__bool
  86733. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86734. * \c false if there was a memory allocation error, a file decoder error,
  86735. * or the file contained no STREAMINFO block. (A memory allocation error
  86736. * is possible because this function must set up a file decoder.)
  86737. */
  86738. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86739. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86740. * function will try to skip any ID3v2 tag at the head of the file.
  86741. *
  86742. * \param filename The path to the FLAC file to read.
  86743. * \param tags The address where the returned pointer will be
  86744. * stored. The \a tags object must be deleted by
  86745. * the caller using FLAC__metadata_object_delete().
  86746. * \assert
  86747. * \code filename != NULL \endcode
  86748. * \code tags != NULL \endcode
  86749. * \retval FLAC__bool
  86750. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86751. * and \a *tags will be set to the address of the metadata structure.
  86752. * Returns \c false if there was a memory allocation error, a file
  86753. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86754. * \a *tags will be set to \c NULL.
  86755. */
  86756. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86757. /** Read the CUESHEET metadata block of the given FLAC file. This
  86758. * function will try to skip any ID3v2 tag at the head of the file.
  86759. *
  86760. * \param filename The path to the FLAC file to read.
  86761. * \param cuesheet The address where the returned pointer will be
  86762. * stored. The \a cuesheet object must be deleted by
  86763. * the caller using FLAC__metadata_object_delete().
  86764. * \assert
  86765. * \code filename != NULL \endcode
  86766. * \code cuesheet != NULL \endcode
  86767. * \retval FLAC__bool
  86768. * \c true if a valid CUESHEET block was read from \a filename,
  86769. * and \a *cuesheet will be set to the address of the metadata
  86770. * structure. Returns \c false if there was a memory allocation
  86771. * error, a file decoder error, or the file contained no CUESHEET
  86772. * block, and \a *cuesheet will be set to \c NULL.
  86773. */
  86774. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86775. /** Read a PICTURE metadata block of the given FLAC file. This
  86776. * function will try to skip any ID3v2 tag at the head of the file.
  86777. * Since there can be more than one PICTURE block in a file, this
  86778. * function takes a number of parameters that act as constraints to
  86779. * the search. The PICTURE block with the largest area matching all
  86780. * the constraints will be returned, or \a *picture will be set to
  86781. * \c NULL if there was no such block.
  86782. *
  86783. * \param filename The path to the FLAC file to read.
  86784. * \param picture The address where the returned pointer will be
  86785. * stored. The \a picture object must be deleted by
  86786. * the caller using FLAC__metadata_object_delete().
  86787. * \param type The desired picture type. Use \c -1 to mean
  86788. * "any type".
  86789. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86790. * string will be matched exactly. Use \c NULL to
  86791. * mean "any MIME type".
  86792. * \param description The desired description. The string will be
  86793. * matched exactly. Use \c NULL to mean "any
  86794. * description".
  86795. * \param max_width The maximum width in pixels desired. Use
  86796. * \c (unsigned)(-1) to mean "any width".
  86797. * \param max_height The maximum height in pixels desired. Use
  86798. * \c (unsigned)(-1) to mean "any height".
  86799. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86800. * Use \c (unsigned)(-1) to mean "any depth".
  86801. * \param max_colors The maximum number of colors desired. Use
  86802. * \c (unsigned)(-1) to mean "any number of colors".
  86803. * \assert
  86804. * \code filename != NULL \endcode
  86805. * \code picture != NULL \endcode
  86806. * \retval FLAC__bool
  86807. * \c true if a valid PICTURE block was read from \a filename,
  86808. * and \a *picture will be set to the address of the metadata
  86809. * structure. Returns \c false if there was a memory allocation
  86810. * error, a file decoder error, or the file contained no PICTURE
  86811. * block, and \a *picture will be set to \c NULL.
  86812. */
  86813. 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);
  86814. /* \} */
  86815. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86816. * \ingroup flac_metadata
  86817. *
  86818. * \brief
  86819. * The level 1 interface provides read-write access to FLAC file metadata and
  86820. * operates directly on the FLAC file.
  86821. *
  86822. * The general usage of this interface is:
  86823. *
  86824. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  86825. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  86826. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  86827. * see if the file is writable, or only read access is allowed.
  86828. * - Use FLAC__metadata_simple_iterator_next() and
  86829. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  86830. * This is does not read the actual blocks themselves.
  86831. * FLAC__metadata_simple_iterator_next() is relatively fast.
  86832. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  86833. * forward from the front of the file.
  86834. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  86835. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  86836. * the current iterator position. The returned object is yours to modify
  86837. * and free.
  86838. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  86839. * back. You must have write permission to the original file. Make sure to
  86840. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  86841. * below.
  86842. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  86843. * Use the object creation functions from
  86844. * \link flac_metadata_object here \endlink to generate new objects.
  86845. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  86846. * currently referred to by the iterator, or replace it with padding.
  86847. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  86848. * finished.
  86849. *
  86850. * \note
  86851. * The FLAC file remains open the whole time between
  86852. * FLAC__metadata_simple_iterator_init() and
  86853. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  86854. * the file during this time.
  86855. *
  86856. * \note
  86857. * Do not modify the \a is_last, \a length, or \a type fields of returned
  86858. * FLAC__StreamMetadata objects. These are managed automatically.
  86859. *
  86860. * \note
  86861. * If any of the modification functions
  86862. * (FLAC__metadata_simple_iterator_set_block(),
  86863. * FLAC__metadata_simple_iterator_delete_block(),
  86864. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  86865. * you should delete the iterator as it may no longer be valid.
  86866. *
  86867. * \{
  86868. */
  86869. struct FLAC__Metadata_SimpleIterator;
  86870. /** The opaque structure definition for the level 1 iterator type.
  86871. * See the
  86872. * \link flac_metadata_level1 metadata level 1 module \endlink
  86873. * for a detailed description.
  86874. */
  86875. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  86876. /** Status type for FLAC__Metadata_SimpleIterator.
  86877. *
  86878. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  86879. */
  86880. typedef enum {
  86881. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  86882. /**< The iterator is in the normal OK state */
  86883. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  86884. /**< The data passed into a function violated the function's usage criteria */
  86885. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  86886. /**< The iterator could not open the target file */
  86887. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  86888. /**< The iterator could not find the FLAC signature at the start of the file */
  86889. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  86890. /**< The iterator tried to write to a file that was not writable */
  86891. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  86892. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  86893. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  86894. /**< The iterator encountered an error while reading the FLAC file */
  86895. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  86896. /**< The iterator encountered an error while seeking in the FLAC file */
  86897. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  86898. /**< The iterator encountered an error while writing the FLAC file */
  86899. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  86900. /**< The iterator encountered an error renaming the FLAC file */
  86901. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  86902. /**< The iterator encountered an error removing the temporary file */
  86903. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  86904. /**< Memory allocation failed */
  86905. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  86906. /**< The caller violated an assertion or an unexpected error occurred */
  86907. } FLAC__Metadata_SimpleIteratorStatus;
  86908. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  86909. *
  86910. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  86911. * will give the string equivalent. The contents should not be modified.
  86912. */
  86913. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  86914. /** Create a new iterator instance.
  86915. *
  86916. * \retval FLAC__Metadata_SimpleIterator*
  86917. * \c NULL if there was an error allocating memory, else the new instance.
  86918. */
  86919. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  86920. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  86921. *
  86922. * \param iterator A pointer to an existing iterator.
  86923. * \assert
  86924. * \code iterator != NULL \endcode
  86925. */
  86926. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  86927. /** Get the current status of the iterator. Call this after a function
  86928. * returns \c false to get the reason for the error. Also resets the status
  86929. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  86930. *
  86931. * \param iterator A pointer to an existing iterator.
  86932. * \assert
  86933. * \code iterator != NULL \endcode
  86934. * \retval FLAC__Metadata_SimpleIteratorStatus
  86935. * The current status of the iterator.
  86936. */
  86937. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  86938. /** Initialize the iterator to point to the first metadata block in the
  86939. * given FLAC file.
  86940. *
  86941. * \param iterator A pointer to an existing iterator.
  86942. * \param filename The path to the FLAC file.
  86943. * \param read_only If \c true, the FLAC file will be opened
  86944. * in read-only mode; if \c false, the FLAC
  86945. * file will be opened for edit even if no
  86946. * edits are performed.
  86947. * \param preserve_file_stats If \c true, the owner and modification
  86948. * time will be preserved even if the FLAC
  86949. * file is written to.
  86950. * \assert
  86951. * \code iterator != NULL \endcode
  86952. * \code filename != NULL \endcode
  86953. * \retval FLAC__bool
  86954. * \c false if a memory allocation error occurs, the file can't be
  86955. * opened, or another error occurs, else \c true.
  86956. */
  86957. 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);
  86958. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  86959. * FLAC__metadata_simple_iterator_set_block() and
  86960. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  86961. *
  86962. * \param iterator A pointer to an existing iterator.
  86963. * \assert
  86964. * \code iterator != NULL \endcode
  86965. * \retval FLAC__bool
  86966. * See above.
  86967. */
  86968. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  86969. /** Moves the iterator forward one metadata block, returning \c false if
  86970. * already at the end.
  86971. *
  86972. * \param iterator A pointer to an existing initialized iterator.
  86973. * \assert
  86974. * \code iterator != NULL \endcode
  86975. * \a iterator has been successfully initialized with
  86976. * FLAC__metadata_simple_iterator_init()
  86977. * \retval FLAC__bool
  86978. * \c false if already at the last metadata block of the chain, else
  86979. * \c true.
  86980. */
  86981. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  86982. /** Moves the iterator backward one metadata block, returning \c false if
  86983. * already at the beginning.
  86984. *
  86985. * \param iterator A pointer to an existing initialized iterator.
  86986. * \assert
  86987. * \code iterator != NULL \endcode
  86988. * \a iterator has been successfully initialized with
  86989. * FLAC__metadata_simple_iterator_init()
  86990. * \retval FLAC__bool
  86991. * \c false if already at the first metadata block of the chain, else
  86992. * \c true.
  86993. */
  86994. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  86995. /** Returns a flag telling if the current metadata block is the last.
  86996. *
  86997. * \param iterator A pointer to an existing initialized iterator.
  86998. * \assert
  86999. * \code iterator != NULL \endcode
  87000. * \a iterator has been successfully initialized with
  87001. * FLAC__metadata_simple_iterator_init()
  87002. * \retval FLAC__bool
  87003. * \c true if the current metadata block is the last in the file,
  87004. * else \c false.
  87005. */
  87006. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87007. /** Get the offset of the metadata block at the current position. This
  87008. * avoids reading the actual block data which can save time for large
  87009. * blocks.
  87010. *
  87011. * \param iterator A pointer to an existing initialized iterator.
  87012. * \assert
  87013. * \code iterator != NULL \endcode
  87014. * \a iterator has been successfully initialized with
  87015. * FLAC__metadata_simple_iterator_init()
  87016. * \retval off_t
  87017. * The offset of the metadata block at the current iterator position.
  87018. * This is the byte offset relative to the beginning of the file of
  87019. * the current metadata block's header.
  87020. */
  87021. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87022. /** Get the type of the metadata block at the current position. This
  87023. * avoids reading the actual block data which can save time for large
  87024. * blocks.
  87025. *
  87026. * \param iterator A pointer to an existing initialized iterator.
  87027. * \assert
  87028. * \code iterator != NULL \endcode
  87029. * \a iterator has been successfully initialized with
  87030. * FLAC__metadata_simple_iterator_init()
  87031. * \retval FLAC__MetadataType
  87032. * The type of the metadata block at the current iterator position.
  87033. */
  87034. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87035. /** Get the length of the metadata block at the current position. This
  87036. * avoids reading the actual block data which can save time for large
  87037. * blocks.
  87038. *
  87039. * \param iterator A pointer to an existing initialized iterator.
  87040. * \assert
  87041. * \code iterator != NULL \endcode
  87042. * \a iterator has been successfully initialized with
  87043. * FLAC__metadata_simple_iterator_init()
  87044. * \retval unsigned
  87045. * The length of the metadata block at the current iterator position.
  87046. * The is same length as that in the
  87047. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87048. * i.e. the length of the metadata body that follows the header.
  87049. */
  87050. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87051. /** Get the application ID of the \c APPLICATION block at the current
  87052. * position. This avoids reading the actual block data which can save
  87053. * time for large blocks.
  87054. *
  87055. * \param iterator A pointer to an existing initialized iterator.
  87056. * \param id A pointer to a buffer of at least \c 4 bytes where
  87057. * the ID will be stored.
  87058. * \assert
  87059. * \code iterator != NULL \endcode
  87060. * \code id != NULL \endcode
  87061. * \a iterator has been successfully initialized with
  87062. * FLAC__metadata_simple_iterator_init()
  87063. * \retval FLAC__bool
  87064. * \c true if the ID was successfully read, else \c false, in which
  87065. * case you should check FLAC__metadata_simple_iterator_status() to
  87066. * find out why. If the status is
  87067. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87068. * current metadata block is not an \c APPLICATION block. Otherwise
  87069. * if the status is
  87070. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87071. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87072. * occurred and the iterator can no longer be used.
  87073. */
  87074. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87075. /** Get the metadata block at the current position. You can modify the
  87076. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87077. * write it back to the FLAC file.
  87078. *
  87079. * You must call FLAC__metadata_object_delete() on the returned object
  87080. * when you are finished with it.
  87081. *
  87082. * \param iterator A pointer to an existing initialized iterator.
  87083. * \assert
  87084. * \code iterator != NULL \endcode
  87085. * \a iterator has been successfully initialized with
  87086. * FLAC__metadata_simple_iterator_init()
  87087. * \retval FLAC__StreamMetadata*
  87088. * The current metadata block, or \c NULL if there was a memory
  87089. * allocation error.
  87090. */
  87091. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87092. /** Write a block back to the FLAC file. This function tries to be
  87093. * as efficient as possible; how the block is actually written is
  87094. * shown by the following:
  87095. *
  87096. * Existing block is a STREAMINFO block and the new block is a
  87097. * STREAMINFO block: the new block is written in place. Make sure
  87098. * you know what you're doing when changing the values of a
  87099. * STREAMINFO block.
  87100. *
  87101. * Existing block is a STREAMINFO block and the new block is a
  87102. * not a STREAMINFO block: this is an error since the first block
  87103. * must be a STREAMINFO block. Returns \c false without altering the
  87104. * file.
  87105. *
  87106. * Existing block is not a STREAMINFO block and the new block is a
  87107. * STREAMINFO block: this is an error since there may be only one
  87108. * STREAMINFO block. Returns \c false without altering the file.
  87109. *
  87110. * Existing block and new block are the same length: the existing
  87111. * block will be replaced by the new block, written in place.
  87112. *
  87113. * Existing block is longer than new block: if use_padding is \c true,
  87114. * the existing block will be overwritten in place with the new
  87115. * block followed by a PADDING block, if possible, to make the total
  87116. * size the same as the existing block. Remember that a padding
  87117. * block requires at least four bytes so if the difference in size
  87118. * between the new block and existing block is less than that, the
  87119. * entire file will have to be rewritten, using the new block's
  87120. * exact size. If use_padding is \c false, the entire file will be
  87121. * rewritten, replacing the existing block by the new block.
  87122. *
  87123. * Existing block is shorter than new block: if use_padding is \c true,
  87124. * the function will try and expand the new block into the following
  87125. * PADDING block, if it exists and doing so won't shrink the PADDING
  87126. * block to less than 4 bytes. If there is no following PADDING
  87127. * block, or it will shrink to less than 4 bytes, or use_padding is
  87128. * \c false, the entire file is rewritten, replacing the existing block
  87129. * with the new block. Note that in this case any following PADDING
  87130. * block is preserved as is.
  87131. *
  87132. * After writing the block, the iterator will remain in the same
  87133. * place, i.e. pointing to the new block.
  87134. *
  87135. * \param iterator A pointer to an existing initialized iterator.
  87136. * \param block The block to set.
  87137. * \param use_padding See above.
  87138. * \assert
  87139. * \code iterator != NULL \endcode
  87140. * \a iterator has been successfully initialized with
  87141. * FLAC__metadata_simple_iterator_init()
  87142. * \code block != NULL \endcode
  87143. * \retval FLAC__bool
  87144. * \c true if successful, else \c false.
  87145. */
  87146. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87147. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87148. * except that instead of writing over an existing block, it appends
  87149. * a block after the existing block. \a use_padding is again used to
  87150. * tell the function to try an expand into following padding in an
  87151. * attempt to avoid rewriting the entire file.
  87152. *
  87153. * This function will fail and return \c false if given a STREAMINFO
  87154. * block.
  87155. *
  87156. * After writing the block, the iterator will be pointing to the
  87157. * new block.
  87158. *
  87159. * \param iterator A pointer to an existing initialized iterator.
  87160. * \param block The block to set.
  87161. * \param use_padding See above.
  87162. * \assert
  87163. * \code iterator != NULL \endcode
  87164. * \a iterator has been successfully initialized with
  87165. * FLAC__metadata_simple_iterator_init()
  87166. * \code block != NULL \endcode
  87167. * \retval FLAC__bool
  87168. * \c true if successful, else \c false.
  87169. */
  87170. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87171. /** Deletes the block at the current position. This will cause the
  87172. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87173. * in which case the block will be replaced by an equal-sized PADDING
  87174. * block. The iterator will be left pointing to the block before the
  87175. * one just deleted.
  87176. *
  87177. * You may not delete the STREAMINFO block.
  87178. *
  87179. * \param iterator A pointer to an existing initialized iterator.
  87180. * \param use_padding See above.
  87181. * \assert
  87182. * \code iterator != NULL \endcode
  87183. * \a iterator has been successfully initialized with
  87184. * FLAC__metadata_simple_iterator_init()
  87185. * \retval FLAC__bool
  87186. * \c true if successful, else \c false.
  87187. */
  87188. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87189. /* \} */
  87190. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87191. * \ingroup flac_metadata
  87192. *
  87193. * \brief
  87194. * The level 2 interface provides read-write access to FLAC file metadata;
  87195. * all metadata is read into memory, operated on in memory, and then written
  87196. * to file, which is more efficient than level 1 when editing multiple blocks.
  87197. *
  87198. * Currently Ogg FLAC is supported for read only, via
  87199. * FLAC__metadata_chain_read_ogg() but a subsequent
  87200. * FLAC__metadata_chain_write() will fail.
  87201. *
  87202. * The general usage of this interface is:
  87203. *
  87204. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87205. * linked list of FLAC metadata blocks.
  87206. * - Read all metadata into the the chain from a FLAC file using
  87207. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87208. * check the status.
  87209. * - Optionally, consolidate the padding using
  87210. * FLAC__metadata_chain_merge_padding() or
  87211. * FLAC__metadata_chain_sort_padding().
  87212. * - Create a new iterator using FLAC__metadata_iterator_new()
  87213. * - Initialize the iterator to point to the first element in the chain
  87214. * using FLAC__metadata_iterator_init()
  87215. * - Traverse the chain using FLAC__metadata_iterator_next and
  87216. * FLAC__metadata_iterator_prev().
  87217. * - Get a block for reading or modification using
  87218. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87219. * inside the chain is returned, so the block is yours to modify.
  87220. * Changes will be reflected in the FLAC file when you write the
  87221. * chain. You can also add and delete blocks (see functions below).
  87222. * - When done, write out the chain using FLAC__metadata_chain_write().
  87223. * Make sure to read the whole comment to the function below.
  87224. * - Delete the chain using FLAC__metadata_chain_delete().
  87225. *
  87226. * \note
  87227. * Even though the FLAC file is not open while the chain is being
  87228. * manipulated, you must not alter the file externally during
  87229. * this time. The chain assumes the FLAC file will not change
  87230. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87231. * and FLAC__metadata_chain_write().
  87232. *
  87233. * \note
  87234. * Do not modify the is_last, length, or type fields of returned
  87235. * FLAC__StreamMetadata objects. These are managed automatically.
  87236. *
  87237. * \note
  87238. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87239. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87240. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87241. * become owned by the chain and they will be deleted when the chain is
  87242. * deleted.
  87243. *
  87244. * \{
  87245. */
  87246. struct FLAC__Metadata_Chain;
  87247. /** The opaque structure definition for the level 2 chain type.
  87248. */
  87249. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87250. struct FLAC__Metadata_Iterator;
  87251. /** The opaque structure definition for the level 2 iterator type.
  87252. */
  87253. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87254. typedef enum {
  87255. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87256. /**< The chain is in the normal OK state */
  87257. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87258. /**< The data passed into a function violated the function's usage criteria */
  87259. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87260. /**< The chain could not open the target file */
  87261. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87262. /**< The chain could not find the FLAC signature at the start of the file */
  87263. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87264. /**< The chain tried to write to a file that was not writable */
  87265. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87266. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87267. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87268. /**< The chain encountered an error while reading the FLAC file */
  87269. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87270. /**< The chain encountered an error while seeking in the FLAC file */
  87271. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87272. /**< The chain encountered an error while writing the FLAC file */
  87273. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87274. /**< The chain encountered an error renaming the FLAC file */
  87275. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87276. /**< The chain encountered an error removing the temporary file */
  87277. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87278. /**< Memory allocation failed */
  87279. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87280. /**< The caller violated an assertion or an unexpected error occurred */
  87281. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87282. /**< One or more of the required callbacks was NULL */
  87283. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87284. /**< FLAC__metadata_chain_write() was called on a chain read by
  87285. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87286. * or
  87287. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87288. * was called on a chain read by
  87289. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87290. * Matching read/write methods must always be used. */
  87291. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87292. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87293. * chain write requires a tempfile; use
  87294. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87295. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87296. * called when the chain write does not require a tempfile; use
  87297. * FLAC__metadata_chain_write_with_callbacks() instead.
  87298. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87299. * before writing via callbacks. */
  87300. } FLAC__Metadata_ChainStatus;
  87301. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87302. *
  87303. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87304. * will give the string equivalent. The contents should not be modified.
  87305. */
  87306. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87307. /*********** FLAC__Metadata_Chain ***********/
  87308. /** Create a new chain instance.
  87309. *
  87310. * \retval FLAC__Metadata_Chain*
  87311. * \c NULL if there was an error allocating memory, else the new instance.
  87312. */
  87313. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87314. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87315. *
  87316. * \param chain A pointer to an existing chain.
  87317. * \assert
  87318. * \code chain != NULL \endcode
  87319. */
  87320. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87321. /** Get the current status of the chain. Call this after a function
  87322. * returns \c false to get the reason for the error. Also resets the
  87323. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87324. *
  87325. * \param chain A pointer to an existing chain.
  87326. * \assert
  87327. * \code chain != NULL \endcode
  87328. * \retval FLAC__Metadata_ChainStatus
  87329. * The current status of the chain.
  87330. */
  87331. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87332. /** Read all metadata from a FLAC file into the chain.
  87333. *
  87334. * \param chain A pointer to an existing chain.
  87335. * \param filename The path to the FLAC file to read.
  87336. * \assert
  87337. * \code chain != NULL \endcode
  87338. * \code filename != NULL \endcode
  87339. * \retval FLAC__bool
  87340. * \c true if a valid list of metadata blocks was read from
  87341. * \a filename, else \c false. On failure, check the status with
  87342. * FLAC__metadata_chain_status().
  87343. */
  87344. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87345. /** Read all metadata from an Ogg FLAC file into the chain.
  87346. *
  87347. * \note Ogg FLAC metadata data writing is not supported yet and
  87348. * FLAC__metadata_chain_write() will fail.
  87349. *
  87350. * \param chain A pointer to an existing chain.
  87351. * \param filename The path to the Ogg FLAC file to read.
  87352. * \assert
  87353. * \code chain != NULL \endcode
  87354. * \code filename != NULL \endcode
  87355. * \retval FLAC__bool
  87356. * \c true if a valid list of metadata blocks was read from
  87357. * \a filename, else \c false. On failure, check the status with
  87358. * FLAC__metadata_chain_status().
  87359. */
  87360. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87361. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87362. *
  87363. * The \a handle need only be open for reading, but must be seekable.
  87364. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87365. * for Windows).
  87366. *
  87367. * \param chain A pointer to an existing chain.
  87368. * \param handle The I/O handle of the FLAC stream to read. The
  87369. * handle will NOT be closed after the metadata is read;
  87370. * that is the duty of the caller.
  87371. * \param callbacks
  87372. * A set of callbacks to use for I/O. The mandatory
  87373. * callbacks are \a read, \a seek, and \a tell.
  87374. * \assert
  87375. * \code chain != NULL \endcode
  87376. * \retval FLAC__bool
  87377. * \c true if a valid list of metadata blocks was read from
  87378. * \a handle, else \c false. On failure, check the status with
  87379. * FLAC__metadata_chain_status().
  87380. */
  87381. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87382. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87383. *
  87384. * The \a handle need only be open for reading, but must be seekable.
  87385. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87386. * for Windows).
  87387. *
  87388. * \note Ogg FLAC metadata data writing is not supported yet and
  87389. * FLAC__metadata_chain_write() will fail.
  87390. *
  87391. * \param chain A pointer to an existing chain.
  87392. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87393. * handle will NOT be closed after the metadata is read;
  87394. * that is the duty of the caller.
  87395. * \param callbacks
  87396. * A set of callbacks to use for I/O. The mandatory
  87397. * callbacks are \a read, \a seek, and \a tell.
  87398. * \assert
  87399. * \code chain != NULL \endcode
  87400. * \retval FLAC__bool
  87401. * \c true if a valid list of metadata blocks was read from
  87402. * \a handle, else \c false. On failure, check the status with
  87403. * FLAC__metadata_chain_status().
  87404. */
  87405. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87406. /** Checks if writing the given chain would require the use of a
  87407. * temporary file, or if it could be written in place.
  87408. *
  87409. * Under certain conditions, padding can be utilized so that writing
  87410. * edited metadata back to the FLAC file does not require rewriting the
  87411. * entire file. If rewriting is required, then a temporary workfile is
  87412. * required. When writing metadata using callbacks, you must check
  87413. * this function to know whether to call
  87414. * FLAC__metadata_chain_write_with_callbacks() or
  87415. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87416. * writing with FLAC__metadata_chain_write(), the temporary file is
  87417. * handled internally.
  87418. *
  87419. * \param chain A pointer to an existing chain.
  87420. * \param use_padding
  87421. * Whether or not padding will be allowed to be used
  87422. * during the write. The value of \a use_padding given
  87423. * here must match the value later passed to
  87424. * FLAC__metadata_chain_write_with_callbacks() or
  87425. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87426. * \assert
  87427. * \code chain != NULL \endcode
  87428. * \retval FLAC__bool
  87429. * \c true if writing the current chain would require a tempfile, or
  87430. * \c false if metadata can be written in place.
  87431. */
  87432. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87433. /** Write all metadata out to the FLAC file. This function tries to be as
  87434. * efficient as possible; how the metadata is actually written is shown by
  87435. * the following:
  87436. *
  87437. * If the current chain is the same size as the existing metadata, the new
  87438. * data is written in place.
  87439. *
  87440. * If the current chain is longer than the existing metadata, and
  87441. * \a use_padding is \c true, and the last block is a PADDING block of
  87442. * sufficient length, the function will truncate the final padding block
  87443. * so that the overall size of the metadata is the same as the existing
  87444. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87445. * the above conditions are met, the entire FLAC file must be rewritten.
  87446. * If you want to use padding this way it is a good idea to call
  87447. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87448. * amount of padding to work with, unless you need to preserve ordering
  87449. * of the PADDING blocks for some reason.
  87450. *
  87451. * If the current chain is shorter than the existing metadata, and
  87452. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87453. * is extended to make the overall size the same as the existing data. If
  87454. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87455. * PADDING block is added to the end of the new data to make it the same
  87456. * size as the existing data (if possible, see the note to
  87457. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87458. * and the new data is written in place. If none of the above apply or
  87459. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87460. *
  87461. * If \a preserve_file_stats is \c true, the owner and modification time will
  87462. * be preserved even if the FLAC file is written.
  87463. *
  87464. * For this write function to be used, the chain must have been read with
  87465. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87466. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87467. *
  87468. * \param chain A pointer to an existing chain.
  87469. * \param use_padding See above.
  87470. * \param preserve_file_stats See above.
  87471. * \assert
  87472. * \code chain != NULL \endcode
  87473. * \retval FLAC__bool
  87474. * \c true if the write succeeded, else \c false. On failure,
  87475. * check the status with FLAC__metadata_chain_status().
  87476. */
  87477. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87478. /** Write all metadata out to a FLAC stream via callbacks.
  87479. *
  87480. * (See FLAC__metadata_chain_write() for the details on how padding is
  87481. * used to write metadata in place if possible.)
  87482. *
  87483. * The \a handle must be open for updating and be seekable. The
  87484. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87485. * for Windows).
  87486. *
  87487. * For this write function to be used, the chain must have been read with
  87488. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87489. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87490. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87491. * \c false.
  87492. *
  87493. * \param chain A pointer to an existing chain.
  87494. * \param use_padding See FLAC__metadata_chain_write()
  87495. * \param handle The I/O handle of the FLAC stream to write. The
  87496. * handle will NOT be closed after the metadata is
  87497. * written; that is the duty of the caller.
  87498. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87499. * callbacks are \a write and \a seek.
  87500. * \assert
  87501. * \code chain != NULL \endcode
  87502. * \retval FLAC__bool
  87503. * \c true if the write succeeded, else \c false. On failure,
  87504. * check the status with FLAC__metadata_chain_status().
  87505. */
  87506. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87507. /** Write all metadata out to a FLAC stream via callbacks.
  87508. *
  87509. * (See FLAC__metadata_chain_write() for the details on how padding is
  87510. * used to write metadata in place if possible.)
  87511. *
  87512. * This version of the write-with-callbacks function must be used when
  87513. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87514. * this function, you must supply an I/O handle corresponding to the
  87515. * FLAC file to edit, and a temporary handle to which the new FLAC
  87516. * file will be written. It is the caller's job to move this temporary
  87517. * FLAC file on top of the original FLAC file to complete the metadata
  87518. * edit.
  87519. *
  87520. * The \a handle must be open for reading and be seekable. The
  87521. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87522. * for Windows).
  87523. *
  87524. * The \a temp_handle must be open for writing. The
  87525. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87526. * for Windows). It should be an empty stream, or at least positioned
  87527. * at the start-of-file (in which case it is the caller's duty to
  87528. * truncate it on return).
  87529. *
  87530. * For this write function to be used, the chain must have been read with
  87531. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87532. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87533. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87534. * \c true.
  87535. *
  87536. * \param chain A pointer to an existing chain.
  87537. * \param use_padding See FLAC__metadata_chain_write()
  87538. * \param handle The I/O handle of the original FLAC stream to read.
  87539. * The handle will NOT be closed after the metadata is
  87540. * written; that is the duty of the caller.
  87541. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87542. * The mandatory callbacks are \a read, \a seek, and
  87543. * \a eof.
  87544. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87545. * handle will NOT be closed after the metadata is
  87546. * written; that is the duty of the caller.
  87547. * \param temp_callbacks
  87548. * A set of callbacks to use for I/O on temp_handle.
  87549. * The only mandatory callback is \a write.
  87550. * \assert
  87551. * \code chain != NULL \endcode
  87552. * \retval FLAC__bool
  87553. * \c true if the write succeeded, else \c false. On failure,
  87554. * check the status with FLAC__metadata_chain_status().
  87555. */
  87556. 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);
  87557. /** Merge adjacent PADDING blocks into a single block.
  87558. *
  87559. * \note This function does not write to the FLAC file, it only
  87560. * modifies the chain.
  87561. *
  87562. * \warning Any iterator on the current chain will become invalid after this
  87563. * call. You should delete the iterator and get a new one.
  87564. *
  87565. * \param chain A pointer to an existing chain.
  87566. * \assert
  87567. * \code chain != NULL \endcode
  87568. */
  87569. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87570. /** This function will move all PADDING blocks to the end on the metadata,
  87571. * then merge them into a single block.
  87572. *
  87573. * \note This function does not write to the FLAC file, it only
  87574. * modifies the chain.
  87575. *
  87576. * \warning Any iterator on the current chain will become invalid after this
  87577. * call. You should delete the iterator and get a new one.
  87578. *
  87579. * \param chain A pointer to an existing chain.
  87580. * \assert
  87581. * \code chain != NULL \endcode
  87582. */
  87583. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87584. /*********** FLAC__Metadata_Iterator ***********/
  87585. /** Create a new iterator instance.
  87586. *
  87587. * \retval FLAC__Metadata_Iterator*
  87588. * \c NULL if there was an error allocating memory, else the new instance.
  87589. */
  87590. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87591. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87592. *
  87593. * \param iterator A pointer to an existing iterator.
  87594. * \assert
  87595. * \code iterator != NULL \endcode
  87596. */
  87597. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87598. /** Initialize the iterator to point to the first metadata block in the
  87599. * given chain.
  87600. *
  87601. * \param iterator A pointer to an existing iterator.
  87602. * \param chain A pointer to an existing and initialized (read) chain.
  87603. * \assert
  87604. * \code iterator != NULL \endcode
  87605. * \code chain != NULL \endcode
  87606. */
  87607. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87608. /** Moves the iterator forward one metadata block, returning \c false if
  87609. * already at the end.
  87610. *
  87611. * \param iterator A pointer to an existing initialized iterator.
  87612. * \assert
  87613. * \code iterator != NULL \endcode
  87614. * \a iterator has been successfully initialized with
  87615. * FLAC__metadata_iterator_init()
  87616. * \retval FLAC__bool
  87617. * \c false if already at the last metadata block of the chain, else
  87618. * \c true.
  87619. */
  87620. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87621. /** Moves the iterator backward one metadata block, returning \c false if
  87622. * already at the beginning.
  87623. *
  87624. * \param iterator A pointer to an existing initialized iterator.
  87625. * \assert
  87626. * \code iterator != NULL \endcode
  87627. * \a iterator has been successfully initialized with
  87628. * FLAC__metadata_iterator_init()
  87629. * \retval FLAC__bool
  87630. * \c false if already at the first metadata block of the chain, else
  87631. * \c true.
  87632. */
  87633. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87634. /** Get the type of the metadata block at the current position.
  87635. *
  87636. * \param iterator A pointer to an existing initialized iterator.
  87637. * \assert
  87638. * \code iterator != NULL \endcode
  87639. * \a iterator has been successfully initialized with
  87640. * FLAC__metadata_iterator_init()
  87641. * \retval FLAC__MetadataType
  87642. * The type of the metadata block at the current iterator position.
  87643. */
  87644. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87645. /** Get the metadata block at the current position. You can modify
  87646. * the block in place but must write the chain before the changes
  87647. * are reflected to the FLAC file. You do not need to call
  87648. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87649. * the pointer returned by FLAC__metadata_iterator_get_block()
  87650. * points directly into the chain.
  87651. *
  87652. * \warning
  87653. * Do not call FLAC__metadata_object_delete() on the returned object;
  87654. * to delete a block use FLAC__metadata_iterator_delete_block().
  87655. *
  87656. * \param iterator A pointer to an existing initialized iterator.
  87657. * \assert
  87658. * \code iterator != NULL \endcode
  87659. * \a iterator has been successfully initialized with
  87660. * FLAC__metadata_iterator_init()
  87661. * \retval FLAC__StreamMetadata*
  87662. * The current metadata block.
  87663. */
  87664. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87665. /** Set the metadata block at the current position, replacing the existing
  87666. * block. The new block passed in becomes owned by the chain and it will be
  87667. * deleted when the chain is deleted.
  87668. *
  87669. * \param iterator A pointer to an existing initialized iterator.
  87670. * \param block A pointer to a metadata block.
  87671. * \assert
  87672. * \code iterator != NULL \endcode
  87673. * \a iterator has been successfully initialized with
  87674. * FLAC__metadata_iterator_init()
  87675. * \code block != NULL \endcode
  87676. * \retval FLAC__bool
  87677. * \c false if the conditions in the above description are not met, or
  87678. * a memory allocation error occurs, otherwise \c true.
  87679. */
  87680. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87681. /** Removes the current block from the chain. If \a replace_with_padding is
  87682. * \c true, the block will instead be replaced with a padding block of equal
  87683. * size. You can not delete the STREAMINFO block. The iterator will be
  87684. * left pointing to the block before the one just "deleted", even if
  87685. * \a replace_with_padding is \c true.
  87686. *
  87687. * \param iterator A pointer to an existing initialized iterator.
  87688. * \param replace_with_padding See above.
  87689. * \assert
  87690. * \code iterator != NULL \endcode
  87691. * \a iterator has been successfully initialized with
  87692. * FLAC__metadata_iterator_init()
  87693. * \retval FLAC__bool
  87694. * \c false if the conditions in the above description are not met,
  87695. * otherwise \c true.
  87696. */
  87697. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87698. /** Insert a new block before the current block. You cannot insert a block
  87699. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87700. * as there can be only one, the one that already exists at the head when you
  87701. * read in a chain. The chain takes ownership of the new block and it will be
  87702. * deleted when the chain is deleted. The iterator will be left pointing to
  87703. * the new block.
  87704. *
  87705. * \param iterator A pointer to an existing initialized iterator.
  87706. * \param block A pointer to a metadata block to insert.
  87707. * \assert
  87708. * \code iterator != NULL \endcode
  87709. * \a iterator has been successfully initialized with
  87710. * FLAC__metadata_iterator_init()
  87711. * \retval FLAC__bool
  87712. * \c false if the conditions in the above description are not met, or
  87713. * a memory allocation error occurs, otherwise \c true.
  87714. */
  87715. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87716. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87717. * block as there can be only one, the one that already exists at the head when
  87718. * you read in a chain. The chain takes ownership of the new block and it will
  87719. * be deleted when the chain is deleted. The iterator will be left pointing to
  87720. * the new block.
  87721. *
  87722. * \param iterator A pointer to an existing initialized iterator.
  87723. * \param block A pointer to a metadata block to insert.
  87724. * \assert
  87725. * \code iterator != NULL \endcode
  87726. * \a iterator has been successfully initialized with
  87727. * FLAC__metadata_iterator_init()
  87728. * \retval FLAC__bool
  87729. * \c false if the conditions in the above description are not met, or
  87730. * a memory allocation error occurs, otherwise \c true.
  87731. */
  87732. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87733. /* \} */
  87734. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87735. * \ingroup flac_metadata
  87736. *
  87737. * \brief
  87738. * This module contains methods for manipulating FLAC metadata objects.
  87739. *
  87740. * Since many are variable length we have to be careful about the memory
  87741. * management. We decree that all pointers to data in the object are
  87742. * owned by the object and memory-managed by the object.
  87743. *
  87744. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87745. * functions to create all instances. When using the
  87746. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87747. * \a copy to \c true to have the function make it's own copy of the data, or
  87748. * to \c false to give the object ownership of your data. In the latter case
  87749. * your pointer must be freeable by free() and will be free()d when the object
  87750. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87751. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87752. * the length argument is 0 and the \a copy argument is \c false.
  87753. *
  87754. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87755. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87756. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87757. * case of a memory allocation error.
  87758. *
  87759. * We don't have the convenience of C++ here, so note that the library relies
  87760. * on you to keep the types straight. In other words, if you pass, for
  87761. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87762. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87763. * failure.
  87764. *
  87765. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87766. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87767. * toward the length or stored in the stream, but it can make working with plain
  87768. * comments (those that don't contain embedded-NULs in the value) easier.
  87769. * Entries passed into these functions have trailing NULs added if missing, and
  87770. * returned entries are guaranteed to have a trailing NUL.
  87771. *
  87772. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87773. * comment entry/name/value will first validate that it complies with the Vorbis
  87774. * comment specification and return false if it does not.
  87775. *
  87776. * There is no need to recalculate the length field on metadata blocks you
  87777. * have modified. They will be calculated automatically before they are
  87778. * written back to a file.
  87779. *
  87780. * \{
  87781. */
  87782. /** Create a new metadata object instance of the given type.
  87783. *
  87784. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87785. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87786. * the vendor string set (but zero comments).
  87787. *
  87788. * Do not pass in a value greater than or equal to
  87789. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87790. * doing.
  87791. *
  87792. * \param type Type of object to create
  87793. * \retval FLAC__StreamMetadata*
  87794. * \c NULL if there was an error allocating memory or the type code is
  87795. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87796. */
  87797. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87798. /** Create a copy of an existing metadata object.
  87799. *
  87800. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87801. * object is also copied. The caller takes ownership of the new block and
  87802. * is responsible for freeing it with FLAC__metadata_object_delete().
  87803. *
  87804. * \param object Pointer to object to copy.
  87805. * \assert
  87806. * \code object != NULL \endcode
  87807. * \retval FLAC__StreamMetadata*
  87808. * \c NULL if there was an error allocating memory, else the new instance.
  87809. */
  87810. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87811. /** Free a metadata object. Deletes the object pointed to by \a object.
  87812. *
  87813. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87814. * object is also deleted.
  87815. *
  87816. * \param object A pointer to an existing object.
  87817. * \assert
  87818. * \code object != NULL \endcode
  87819. */
  87820. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  87821. /** Compares two metadata objects.
  87822. *
  87823. * The compare is "deep", i.e. dynamically allocated data within the
  87824. * object is also compared.
  87825. *
  87826. * \param block1 A pointer to an existing object.
  87827. * \param block2 A pointer to an existing object.
  87828. * \assert
  87829. * \code block1 != NULL \endcode
  87830. * \code block2 != NULL \endcode
  87831. * \retval FLAC__bool
  87832. * \c true if objects are identical, else \c false.
  87833. */
  87834. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  87835. /** Sets the application data of an APPLICATION block.
  87836. *
  87837. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  87838. * takes ownership of the pointer. The existing data will be freed if this
  87839. * function is successful, otherwise the original data will remain if \a copy
  87840. * is \c true and malloc() fails.
  87841. *
  87842. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  87843. *
  87844. * \param object A pointer to an existing APPLICATION object.
  87845. * \param data A pointer to the data to set.
  87846. * \param length The length of \a data in bytes.
  87847. * \param copy See above.
  87848. * \assert
  87849. * \code object != NULL \endcode
  87850. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  87851. * \code (data != NULL && length > 0) ||
  87852. * (data == NULL && length == 0 && copy == false) \endcode
  87853. * \retval FLAC__bool
  87854. * \c false if \a copy is \c true and malloc() fails, else \c true.
  87855. */
  87856. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  87857. /** Resize the seekpoint array.
  87858. *
  87859. * If the size shrinks, elements will truncated; if it grows, new placeholder
  87860. * points will be added to the end.
  87861. *
  87862. * \param object A pointer to an existing SEEKTABLE object.
  87863. * \param new_num_points The desired length of the array; may be \c 0.
  87864. * \assert
  87865. * \code object != NULL \endcode
  87866. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87867. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  87868. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  87869. * \retval FLAC__bool
  87870. * \c false if memory allocation error, else \c true.
  87871. */
  87872. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  87873. /** Set a seekpoint in a seektable.
  87874. *
  87875. * \param object A pointer to an existing SEEKTABLE object.
  87876. * \param point_num Index into seekpoint array to set.
  87877. * \param point The point to set.
  87878. * \assert
  87879. * \code object != NULL \endcode
  87880. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87881. * \code object->data.seek_table.num_points > point_num \endcode
  87882. */
  87883. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87884. /** Insert a seekpoint into a seektable.
  87885. *
  87886. * \param object A pointer to an existing SEEKTABLE object.
  87887. * \param point_num Index into seekpoint array to set.
  87888. * \param point The point to set.
  87889. * \assert
  87890. * \code object != NULL \endcode
  87891. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87892. * \code object->data.seek_table.num_points >= point_num \endcode
  87893. * \retval FLAC__bool
  87894. * \c false if memory allocation error, else \c true.
  87895. */
  87896. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87897. /** Delete a seekpoint from a seektable.
  87898. *
  87899. * \param object A pointer to an existing SEEKTABLE object.
  87900. * \param point_num Index into seekpoint array to set.
  87901. * \assert
  87902. * \code object != NULL \endcode
  87903. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87904. * \code object->data.seek_table.num_points > point_num \endcode
  87905. * \retval FLAC__bool
  87906. * \c false if memory allocation error, else \c true.
  87907. */
  87908. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  87909. /** Check a seektable to see if it conforms to the FLAC specification.
  87910. * See the format specification for limits on the contents of the
  87911. * seektable.
  87912. *
  87913. * \param object A pointer to an existing SEEKTABLE object.
  87914. * \assert
  87915. * \code object != NULL \endcode
  87916. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87917. * \retval FLAC__bool
  87918. * \c false if seek table is illegal, else \c true.
  87919. */
  87920. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  87921. /** Append a number of placeholder points to the end of a seek table.
  87922. *
  87923. * \note
  87924. * As with the other ..._seektable_template_... functions, you should
  87925. * call FLAC__metadata_object_seektable_template_sort() when finished
  87926. * to make the seek table legal.
  87927. *
  87928. * \param object A pointer to an existing SEEKTABLE object.
  87929. * \param num The number of placeholder points to append.
  87930. * \assert
  87931. * \code object != NULL \endcode
  87932. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87933. * \retval FLAC__bool
  87934. * \c false if memory allocation fails, else \c true.
  87935. */
  87936. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  87937. /** Append a specific seek point template to the end of a seek table.
  87938. *
  87939. * \note
  87940. * As with the other ..._seektable_template_... functions, you should
  87941. * call FLAC__metadata_object_seektable_template_sort() when finished
  87942. * to make the seek table legal.
  87943. *
  87944. * \param object A pointer to an existing SEEKTABLE object.
  87945. * \param sample_number The sample number of the seek point template.
  87946. * \assert
  87947. * \code object != NULL \endcode
  87948. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87949. * \retval FLAC__bool
  87950. * \c false if memory allocation fails, else \c true.
  87951. */
  87952. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  87953. /** Append specific seek point templates to the end of a seek table.
  87954. *
  87955. * \note
  87956. * As with the other ..._seektable_template_... functions, you should
  87957. * call FLAC__metadata_object_seektable_template_sort() when finished
  87958. * to make the seek table legal.
  87959. *
  87960. * \param object A pointer to an existing SEEKTABLE object.
  87961. * \param sample_numbers An array of sample numbers for the seek points.
  87962. * \param num The number of seek point templates to append.
  87963. * \assert
  87964. * \code object != NULL \endcode
  87965. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87966. * \retval FLAC__bool
  87967. * \c false if memory allocation fails, else \c true.
  87968. */
  87969. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  87970. /** Append a set of evenly-spaced seek point templates to the end of a
  87971. * seek table.
  87972. *
  87973. * \note
  87974. * As with the other ..._seektable_template_... functions, you should
  87975. * call FLAC__metadata_object_seektable_template_sort() when finished
  87976. * to make the seek table legal.
  87977. *
  87978. * \param object A pointer to an existing SEEKTABLE object.
  87979. * \param num The number of placeholder points to append.
  87980. * \param total_samples The total number of samples to be encoded;
  87981. * the seekpoints will be spaced approximately
  87982. * \a total_samples / \a num samples apart.
  87983. * \assert
  87984. * \code object != NULL \endcode
  87985. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87986. * \code total_samples > 0 \endcode
  87987. * \retval FLAC__bool
  87988. * \c false if memory allocation fails, else \c true.
  87989. */
  87990. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  87991. /** Append a set of evenly-spaced seek point templates to the end of a
  87992. * seek table.
  87993. *
  87994. * \note
  87995. * As with the other ..._seektable_template_... functions, you should
  87996. * call FLAC__metadata_object_seektable_template_sort() when finished
  87997. * to make the seek table legal.
  87998. *
  87999. * \param object A pointer to an existing SEEKTABLE object.
  88000. * \param samples The number of samples apart to space the placeholder
  88001. * points. The first point will be at sample \c 0, the
  88002. * second at sample \a samples, then 2*\a samples, and
  88003. * so on. As long as \a samples and \a total_samples
  88004. * are greater than \c 0, there will always be at least
  88005. * one seekpoint at sample \c 0.
  88006. * \param total_samples The total number of samples to be encoded;
  88007. * the seekpoints will be spaced
  88008. * \a samples samples apart.
  88009. * \assert
  88010. * \code object != NULL \endcode
  88011. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88012. * \code samples > 0 \endcode
  88013. * \code total_samples > 0 \endcode
  88014. * \retval FLAC__bool
  88015. * \c false if memory allocation fails, else \c true.
  88016. */
  88017. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88018. /** Sort a seek table's seek points according to the format specification,
  88019. * removing duplicates.
  88020. *
  88021. * \param object A pointer to a seek table to be sorted.
  88022. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88023. * If \c true, duplicates are deleted and the seek table is
  88024. * shrunk appropriately; the number of placeholder points
  88025. * present in the seek table will be the same after the call
  88026. * as before.
  88027. * \assert
  88028. * \code object != NULL \endcode
  88029. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88030. * \retval FLAC__bool
  88031. * \c false if realloc() fails, else \c true.
  88032. */
  88033. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88034. /** Sets the vendor string in a VORBIS_COMMENT block.
  88035. *
  88036. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88037. * one already.
  88038. *
  88039. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88040. * takes ownership of the \c entry.entry pointer.
  88041. *
  88042. * \note If this function returns \c false, the caller still owns the
  88043. * pointer.
  88044. *
  88045. * \param object A pointer to an existing VORBIS_COMMENT object.
  88046. * \param entry The entry to set the vendor string to.
  88047. * \param copy See above.
  88048. * \assert
  88049. * \code object != NULL \endcode
  88050. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88051. * \code (entry.entry != NULL && entry.length > 0) ||
  88052. * (entry.entry == NULL && entry.length == 0) \endcode
  88053. * \retval FLAC__bool
  88054. * \c false if memory allocation fails or \a entry does not comply with the
  88055. * Vorbis comment specification, else \c true.
  88056. */
  88057. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88058. /** Resize the comment array.
  88059. *
  88060. * If the size shrinks, elements will truncated; if it grows, new empty
  88061. * fields will be added to the end.
  88062. *
  88063. * \param object A pointer to an existing VORBIS_COMMENT object.
  88064. * \param new_num_comments The desired length of the array; may be \c 0.
  88065. * \assert
  88066. * \code object != NULL \endcode
  88067. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88068. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88069. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88070. * \retval FLAC__bool
  88071. * \c false if memory allocation fails, else \c true.
  88072. */
  88073. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88074. /** Sets a comment in a VORBIS_COMMENT block.
  88075. *
  88076. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88077. * one already.
  88078. *
  88079. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88080. * takes ownership of the \c entry.entry pointer.
  88081. *
  88082. * \note If this function returns \c false, the caller still owns the
  88083. * pointer.
  88084. *
  88085. * \param object A pointer to an existing VORBIS_COMMENT object.
  88086. * \param comment_num Index into comment array to set.
  88087. * \param entry The entry to set the comment to.
  88088. * \param copy See above.
  88089. * \assert
  88090. * \code object != NULL \endcode
  88091. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88092. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88093. * \code (entry.entry != NULL && entry.length > 0) ||
  88094. * (entry.entry == NULL && entry.length == 0) \endcode
  88095. * \retval FLAC__bool
  88096. * \c false if memory allocation fails or \a entry does not comply with the
  88097. * Vorbis comment specification, else \c true.
  88098. */
  88099. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88100. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88101. *
  88102. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88103. * one already.
  88104. *
  88105. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88106. * takes ownership of the \c entry.entry pointer.
  88107. *
  88108. * \note If this function returns \c false, the caller still owns the
  88109. * pointer.
  88110. *
  88111. * \param object A pointer to an existing VORBIS_COMMENT object.
  88112. * \param comment_num The index at which to insert the comment. The comments
  88113. * at and after \a comment_num move right one position.
  88114. * To append a comment to the end, set \a comment_num to
  88115. * \c object->data.vorbis_comment.num_comments .
  88116. * \param entry The comment to insert.
  88117. * \param copy See above.
  88118. * \assert
  88119. * \code object != NULL \endcode
  88120. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88121. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88122. * \code (entry.entry != NULL && entry.length > 0) ||
  88123. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88124. * \retval FLAC__bool
  88125. * \c false if memory allocation fails or \a entry does not comply with the
  88126. * Vorbis comment specification, else \c true.
  88127. */
  88128. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88129. /** Appends a comment to a VORBIS_COMMENT block.
  88130. *
  88131. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88132. * one already.
  88133. *
  88134. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88135. * takes ownership of the \c entry.entry pointer.
  88136. *
  88137. * \note If this function returns \c false, the caller still owns the
  88138. * pointer.
  88139. *
  88140. * \param object A pointer to an existing VORBIS_COMMENT object.
  88141. * \param entry The comment to insert.
  88142. * \param copy See above.
  88143. * \assert
  88144. * \code object != NULL \endcode
  88145. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88146. * \code (entry.entry != NULL && entry.length > 0) ||
  88147. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88148. * \retval FLAC__bool
  88149. * \c false if memory allocation fails or \a entry does not comply with the
  88150. * Vorbis comment specification, else \c true.
  88151. */
  88152. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88153. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88154. *
  88155. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88156. * one already.
  88157. *
  88158. * Depending on the the value of \a all, either all or just the first comment
  88159. * whose field name(s) match the given entry's name will be replaced by the
  88160. * given entry. If no comments match, \a entry will simply be appended.
  88161. *
  88162. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88163. * takes ownership of the \c entry.entry pointer.
  88164. *
  88165. * \note If this function returns \c false, the caller still owns the
  88166. * pointer.
  88167. *
  88168. * \param object A pointer to an existing VORBIS_COMMENT object.
  88169. * \param entry The comment to insert.
  88170. * \param all If \c true, all comments whose field name matches
  88171. * \a entry's field name will be removed, and \a entry will
  88172. * be inserted at the position of the first matching
  88173. * comment. If \c false, only the first comment whose
  88174. * field name matches \a entry's field name will be
  88175. * replaced with \a entry.
  88176. * \param copy See above.
  88177. * \assert
  88178. * \code object != NULL \endcode
  88179. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88180. * \code (entry.entry != NULL && entry.length > 0) ||
  88181. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88182. * \retval FLAC__bool
  88183. * \c false if memory allocation fails or \a entry does not comply with the
  88184. * Vorbis comment specification, else \c true.
  88185. */
  88186. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88187. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88188. *
  88189. * \param object A pointer to an existing VORBIS_COMMENT object.
  88190. * \param comment_num The index of the comment to delete.
  88191. * \assert
  88192. * \code object != NULL \endcode
  88193. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88194. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88195. * \retval FLAC__bool
  88196. * \c false if realloc() fails, else \c true.
  88197. */
  88198. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88199. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88200. *
  88201. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88202. * memory and shall be owned by the caller. For convenience the entry will
  88203. * have a terminating NUL.
  88204. *
  88205. * \param entry A pointer to a Vorbis comment entry. The entry's
  88206. * \c entry pointer should not point to allocated
  88207. * memory as it will be overwritten.
  88208. * \param field_name The field name in ASCII, \c NUL terminated.
  88209. * \param field_value The field value in UTF-8, \c NUL terminated.
  88210. * \assert
  88211. * \code entry != NULL \endcode
  88212. * \code field_name != NULL \endcode
  88213. * \code field_value != NULL \endcode
  88214. * \retval FLAC__bool
  88215. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88216. * not comply with the Vorbis comment specification, else \c true.
  88217. */
  88218. 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);
  88219. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88220. *
  88221. * The returned pointers to name and value will be allocated by malloc()
  88222. * and shall be owned by the caller.
  88223. *
  88224. * \param entry An existing Vorbis comment entry.
  88225. * \param field_name The address of where the returned pointer to the
  88226. * field name will be stored.
  88227. * \param field_value The address of where the returned pointer to the
  88228. * field value will be stored.
  88229. * \assert
  88230. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88231. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88232. * \code field_name != NULL \endcode
  88233. * \code field_value != NULL \endcode
  88234. * \retval FLAC__bool
  88235. * \c false if memory allocation fails or \a entry does not comply with the
  88236. * Vorbis comment specification, else \c true.
  88237. */
  88238. 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);
  88239. /** Check if the given Vorbis comment entry's field name matches the given
  88240. * field name.
  88241. *
  88242. * \param entry An existing Vorbis comment entry.
  88243. * \param field_name The field name to check.
  88244. * \param field_name_length The length of \a field_name, not including the
  88245. * terminating \c NUL.
  88246. * \assert
  88247. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88248. * \retval FLAC__bool
  88249. * \c true if the field names match, else \c false
  88250. */
  88251. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88252. /** Find a Vorbis comment with the given field name.
  88253. *
  88254. * The search begins at entry number \a offset; use an offset of 0 to
  88255. * search from the beginning of the comment array.
  88256. *
  88257. * \param object A pointer to an existing VORBIS_COMMENT object.
  88258. * \param offset The offset into the comment array from where to start
  88259. * the search.
  88260. * \param field_name The field name of the comment to find.
  88261. * \assert
  88262. * \code object != NULL \endcode
  88263. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88264. * \code field_name != NULL \endcode
  88265. * \retval int
  88266. * The offset in the comment array of the first comment whose field
  88267. * name matches \a field_name, or \c -1 if no match was found.
  88268. */
  88269. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88270. /** Remove first Vorbis comment matching the given field name.
  88271. *
  88272. * \param object A pointer to an existing VORBIS_COMMENT object.
  88273. * \param field_name The field name of comment to delete.
  88274. * \assert
  88275. * \code object != NULL \endcode
  88276. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88277. * \retval int
  88278. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88279. * \c 1 for one matching entry deleted.
  88280. */
  88281. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88282. /** Remove all Vorbis comments matching the given field name.
  88283. *
  88284. * \param object A pointer to an existing VORBIS_COMMENT object.
  88285. * \param field_name The field name of comments to delete.
  88286. * \assert
  88287. * \code object != NULL \endcode
  88288. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88289. * \retval int
  88290. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88291. * else the number of matching entries deleted.
  88292. */
  88293. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88294. /** Create a new CUESHEET track instance.
  88295. *
  88296. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88297. *
  88298. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88299. * \c NULL if there was an error allocating memory, else the new instance.
  88300. */
  88301. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88302. /** Create a copy of an existing CUESHEET track object.
  88303. *
  88304. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88305. * object is also copied. The caller takes ownership of the new object and
  88306. * is responsible for freeing it with
  88307. * FLAC__metadata_object_cuesheet_track_delete().
  88308. *
  88309. * \param object Pointer to object to copy.
  88310. * \assert
  88311. * \code object != NULL \endcode
  88312. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88313. * \c NULL if there was an error allocating memory, else the new instance.
  88314. */
  88315. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88316. /** Delete a CUESHEET track object
  88317. *
  88318. * \param object A pointer to an existing CUESHEET track object.
  88319. * \assert
  88320. * \code object != NULL \endcode
  88321. */
  88322. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88323. /** Resize a track's index point array.
  88324. *
  88325. * If the size shrinks, elements will truncated; if it grows, new blank
  88326. * indices will be added to the end.
  88327. *
  88328. * \param object A pointer to an existing CUESHEET object.
  88329. * \param track_num The index of the track to modify. NOTE: this is not
  88330. * necessarily the same as the track's \a number field.
  88331. * \param new_num_indices The desired length of the array; may be \c 0.
  88332. * \assert
  88333. * \code object != NULL \endcode
  88334. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88335. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88336. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88337. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88338. * \retval FLAC__bool
  88339. * \c false if memory allocation error, else \c true.
  88340. */
  88341. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88342. /** Insert an index point in a CUESHEET track at the given index.
  88343. *
  88344. * \param object A pointer to an existing CUESHEET object.
  88345. * \param track_num The index of the track to modify. NOTE: this is not
  88346. * necessarily the same as the track's \a number field.
  88347. * \param index_num The index into the track's index array at which to
  88348. * insert the index point. NOTE: this is not necessarily
  88349. * the same as the index point's \a number field. The
  88350. * indices at and after \a index_num move right one
  88351. * position. To append an index point to the end, set
  88352. * \a index_num to
  88353. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88354. * \param index The index point to insert.
  88355. * \assert
  88356. * \code object != NULL \endcode
  88357. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88358. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88359. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88360. * \retval FLAC__bool
  88361. * \c false if realloc() fails, else \c true.
  88362. */
  88363. 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);
  88364. /** Insert a blank index point in a CUESHEET track at the given index.
  88365. *
  88366. * A blank index point is one in which all field values are zero.
  88367. *
  88368. * \param object A pointer to an existing CUESHEET object.
  88369. * \param track_num The index of the track to modify. NOTE: this is not
  88370. * necessarily the same as the track's \a number field.
  88371. * \param index_num The index into the track's index array at which to
  88372. * insert the index point. NOTE: this is not necessarily
  88373. * the same as the index point's \a number field. The
  88374. * indices at and after \a index_num move right one
  88375. * position. To append an index point to the end, set
  88376. * \a index_num to
  88377. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88378. * \assert
  88379. * \code object != NULL \endcode
  88380. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88381. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88382. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88383. * \retval FLAC__bool
  88384. * \c false if realloc() fails, else \c true.
  88385. */
  88386. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88387. /** Delete an index point in a CUESHEET track at the given index.
  88388. *
  88389. * \param object A pointer to an existing CUESHEET object.
  88390. * \param track_num The index into the track array of the track to
  88391. * modify. NOTE: this is not necessarily the same
  88392. * as the track's \a number field.
  88393. * \param index_num The index into the track's index array of the index
  88394. * to delete. NOTE: this is not necessarily the same
  88395. * as the index's \a number field.
  88396. * \assert
  88397. * \code object != NULL \endcode
  88398. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88399. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88400. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88401. * \retval FLAC__bool
  88402. * \c false if realloc() fails, else \c true.
  88403. */
  88404. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88405. /** Resize the track array.
  88406. *
  88407. * If the size shrinks, elements will truncated; if it grows, new blank
  88408. * tracks will be added to the end.
  88409. *
  88410. * \param object A pointer to an existing CUESHEET object.
  88411. * \param new_num_tracks The desired length of the array; may be \c 0.
  88412. * \assert
  88413. * \code object != NULL \endcode
  88414. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88415. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88416. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88417. * \retval FLAC__bool
  88418. * \c false if memory allocation error, else \c true.
  88419. */
  88420. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88421. /** Sets a track in a CUESHEET block.
  88422. *
  88423. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88424. * takes ownership of the \a track pointer.
  88425. *
  88426. * \param object A pointer to an existing CUESHEET object.
  88427. * \param track_num Index into track array to set. NOTE: this is not
  88428. * necessarily the same as the track's \a number field.
  88429. * \param track The track to set the track to. You may safely pass in
  88430. * a const pointer if \a copy is \c true.
  88431. * \param copy See above.
  88432. * \assert
  88433. * \code object != NULL \endcode
  88434. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88435. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88436. * \code (track->indices != NULL && track->num_indices > 0) ||
  88437. * (track->indices == NULL && track->num_indices == 0)
  88438. * \retval FLAC__bool
  88439. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88440. */
  88441. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88442. /** Insert a track in a CUESHEET block at the given index.
  88443. *
  88444. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88445. * takes ownership of the \a track pointer.
  88446. *
  88447. * \param object A pointer to an existing CUESHEET object.
  88448. * \param track_num The index at which to insert the track. NOTE: this
  88449. * is not necessarily the same as the track's \a number
  88450. * field. The tracks at and after \a track_num move right
  88451. * one position. To append a track to the end, set
  88452. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88453. * \param track The track to insert. You may safely pass in a const
  88454. * pointer if \a copy is \c true.
  88455. * \param copy See above.
  88456. * \assert
  88457. * \code object != NULL \endcode
  88458. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88459. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88460. * \retval FLAC__bool
  88461. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88462. */
  88463. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88464. /** Insert a blank track in a CUESHEET block at the given index.
  88465. *
  88466. * A blank track is one in which all field values are zero.
  88467. *
  88468. * \param object A pointer to an existing CUESHEET object.
  88469. * \param track_num The index at which to insert the track. NOTE: this
  88470. * is not necessarily the same as the track's \a number
  88471. * field. The tracks at and after \a track_num move right
  88472. * one position. To append a track to the end, set
  88473. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88474. * \assert
  88475. * \code object != NULL \endcode
  88476. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88477. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88478. * \retval FLAC__bool
  88479. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88480. */
  88481. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88482. /** Delete a track in a CUESHEET block at the given index.
  88483. *
  88484. * \param object A pointer to an existing CUESHEET object.
  88485. * \param track_num The index into the track array of the track to
  88486. * delete. NOTE: this is not necessarily the same
  88487. * as the track's \a number field.
  88488. * \assert
  88489. * \code object != NULL \endcode
  88490. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88491. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88492. * \retval FLAC__bool
  88493. * \c false if realloc() fails, else \c true.
  88494. */
  88495. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88496. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88497. * See the format specification for limits on the contents of the
  88498. * cue sheet.
  88499. *
  88500. * \param object A pointer to an existing CUESHEET object.
  88501. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88502. * stringent requirements for a CD-DA (audio) disc.
  88503. * \param violation Address of a pointer to a string. If there is a
  88504. * violation, a pointer to a string explanation of the
  88505. * violation will be returned here. \a violation may be
  88506. * \c NULL if you don't need the returned string. Do not
  88507. * free the returned string; it will always point to static
  88508. * data.
  88509. * \assert
  88510. * \code object != NULL \endcode
  88511. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88512. * \retval FLAC__bool
  88513. * \c false if cue sheet is illegal, else \c true.
  88514. */
  88515. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88516. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88517. * assumes the cue sheet corresponds to a CD; the result is undefined
  88518. * if the cuesheet's is_cd bit is not set.
  88519. *
  88520. * \param object A pointer to an existing CUESHEET object.
  88521. * \assert
  88522. * \code object != NULL \endcode
  88523. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88524. * \retval FLAC__uint32
  88525. * The unsigned integer representation of the CDDB/freedb ID
  88526. */
  88527. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88528. /** Sets the MIME type of a PICTURE block.
  88529. *
  88530. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88531. * takes ownership of the pointer. The existing string will be freed if this
  88532. * function is successful, otherwise the original string will remain if \a copy
  88533. * is \c true and malloc() fails.
  88534. *
  88535. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88536. *
  88537. * \param object A pointer to an existing PICTURE object.
  88538. * \param mime_type A pointer to the MIME type string. The string must be
  88539. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88540. * is done.
  88541. * \param copy See above.
  88542. * \assert
  88543. * \code object != NULL \endcode
  88544. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88545. * \code (mime_type != NULL) \endcode
  88546. * \retval FLAC__bool
  88547. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88548. */
  88549. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88550. /** Sets the description of a PICTURE block.
  88551. *
  88552. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88553. * takes ownership of the pointer. The existing string will be freed if this
  88554. * function is successful, otherwise the original string will remain if \a copy
  88555. * is \c true and malloc() fails.
  88556. *
  88557. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88558. *
  88559. * \param object A pointer to an existing PICTURE object.
  88560. * \param description A pointer to the description string. The string must be
  88561. * valid UTF-8, NUL-terminated. No validation is done.
  88562. * \param copy See above.
  88563. * \assert
  88564. * \code object != NULL \endcode
  88565. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88566. * \code (description != NULL) \endcode
  88567. * \retval FLAC__bool
  88568. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88569. */
  88570. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88571. /** Sets the picture data of a PICTURE block.
  88572. *
  88573. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88574. * takes ownership of the pointer. Also sets the \a data_length field of the
  88575. * metadata object to what is passed in as the \a length parameter. The
  88576. * existing data will be freed if this function is successful, otherwise the
  88577. * original data and data_length will remain if \a copy is \c true and
  88578. * malloc() fails.
  88579. *
  88580. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88581. *
  88582. * \param object A pointer to an existing PICTURE object.
  88583. * \param data A pointer to the data to set.
  88584. * \param length The length of \a data in bytes.
  88585. * \param copy See above.
  88586. * \assert
  88587. * \code object != NULL \endcode
  88588. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88589. * \code (data != NULL && length > 0) ||
  88590. * (data == NULL && length == 0 && copy == false) \endcode
  88591. * \retval FLAC__bool
  88592. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88593. */
  88594. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88595. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88596. * See the format specification for limits on the contents of the
  88597. * PICTURE block.
  88598. *
  88599. * \param object A pointer to existing PICTURE block to be checked.
  88600. * \param violation Address of a pointer to a string. If there is a
  88601. * violation, a pointer to a string explanation of the
  88602. * violation will be returned here. \a violation may be
  88603. * \c NULL if you don't need the returned string. Do not
  88604. * free the returned string; it will always point to static
  88605. * data.
  88606. * \assert
  88607. * \code object != NULL \endcode
  88608. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88609. * \retval FLAC__bool
  88610. * \c false if PICTURE block is illegal, else \c true.
  88611. */
  88612. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88613. /* \} */
  88614. #ifdef __cplusplus
  88615. }
  88616. #endif
  88617. #endif
  88618. /*** End of inlined file: metadata.h ***/
  88619. /*** Start of inlined file: stream_decoder.h ***/
  88620. #ifndef FLAC__STREAM_DECODER_H
  88621. #define FLAC__STREAM_DECODER_H
  88622. #include <stdio.h> /* for FILE */
  88623. #ifdef __cplusplus
  88624. extern "C" {
  88625. #endif
  88626. /** \file include/FLAC/stream_decoder.h
  88627. *
  88628. * \brief
  88629. * This module contains the functions which implement the stream
  88630. * decoder.
  88631. *
  88632. * See the detailed documentation in the
  88633. * \link flac_stream_decoder stream decoder \endlink module.
  88634. */
  88635. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88636. * \ingroup flac
  88637. *
  88638. * \brief
  88639. * This module describes the decoder layers provided by libFLAC.
  88640. *
  88641. * The stream decoder can be used to decode complete streams either from
  88642. * the client via callbacks, or directly from a file, depending on how
  88643. * it is initialized. When decoding via callbacks, the client provides
  88644. * callbacks for reading FLAC data and writing decoded samples, and
  88645. * handling metadata and errors. If the client also supplies seek-related
  88646. * callback, the decoder function for sample-accurate seeking within the
  88647. * FLAC input is also available. When decoding from a file, the client
  88648. * needs only supply a filename or open \c FILE* and write/metadata/error
  88649. * callbacks; the rest of the callbacks are supplied internally. For more
  88650. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88651. */
  88652. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88653. * \ingroup flac_decoder
  88654. *
  88655. * \brief
  88656. * This module contains the functions which implement the stream
  88657. * decoder.
  88658. *
  88659. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88660. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88661. *
  88662. * The basic usage of this decoder is as follows:
  88663. * - The program creates an instance of a decoder using
  88664. * FLAC__stream_decoder_new().
  88665. * - The program overrides the default settings using
  88666. * FLAC__stream_decoder_set_*() functions.
  88667. * - The program initializes the instance to validate the settings and
  88668. * prepare for decoding using
  88669. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88670. * or FLAC__stream_decoder_init_file() for native FLAC,
  88671. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88672. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88673. * - The program calls the FLAC__stream_decoder_process_*() functions
  88674. * to decode data, which subsequently calls the callbacks.
  88675. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88676. * which flushes the input and output and resets the decoder to the
  88677. * uninitialized state.
  88678. * - The instance may be used again or deleted with
  88679. * FLAC__stream_decoder_delete().
  88680. *
  88681. * In more detail, the program will create a new instance by calling
  88682. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88683. * functions to override the default decoder options, and call
  88684. * one of the FLAC__stream_decoder_init_*() functions.
  88685. *
  88686. * There are three initialization functions for native FLAC, one for
  88687. * setting up the decoder to decode FLAC data from the client via
  88688. * callbacks, and two for decoding directly from a FLAC file.
  88689. *
  88690. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88691. * You must also supply several callbacks for handling I/O. Some (like
  88692. * seeking) are optional, depending on the capabilities of the input.
  88693. *
  88694. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88695. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88696. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88697. * the other callbacks internally.
  88698. *
  88699. * There are three similarly-named init functions for decoding from Ogg
  88700. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88701. * library has been built with Ogg support.
  88702. *
  88703. * Once the decoder is initialized, your program will call one of several
  88704. * functions to start the decoding process:
  88705. *
  88706. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88707. * most one metadata block or audio frame and return, calling either the
  88708. * metadata callback or write callback, respectively, once. If the decoder
  88709. * loses sync it will return with only the error callback being called.
  88710. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88711. * to process the stream from the current location and stop upon reaching
  88712. * the first audio frame. The client will get one metadata, write, or error
  88713. * callback per metadata block, audio frame, or sync error, respectively.
  88714. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88715. * to process the stream from the current location until the read callback
  88716. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88717. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88718. * write, or error callback per metadata block, audio frame, or sync error,
  88719. * respectively.
  88720. *
  88721. * When the decoder has finished decoding (normally or through an abort),
  88722. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88723. * ensures the decoder is in the correct state and frees memory. Then the
  88724. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88725. * again to decode another stream.
  88726. *
  88727. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88728. * At any point after the stream decoder has been initialized, the client can
  88729. * call this function to seek to an exact sample within the stream.
  88730. * Subsequently, the first time the write callback is called it will be
  88731. * passed a (possibly partial) block starting at that sample.
  88732. *
  88733. * If the client cannot seek via the callback interface provided, but still
  88734. * has another way of seeking, it can flush the decoder using
  88735. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88736. * through the read callback.
  88737. *
  88738. * The stream decoder also provides MD5 signature checking. If this is
  88739. * turned on before initialization, FLAC__stream_decoder_finish() will
  88740. * report when the decoded MD5 signature does not match the one stored
  88741. * in the STREAMINFO block. MD5 checking is automatically turned off
  88742. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88743. * in the STREAMINFO block or when a seek is attempted.
  88744. *
  88745. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88746. * attention. By default, the decoder only calls the metadata_callback for
  88747. * the STREAMINFO block. These functions allow you to tell the decoder
  88748. * explicitly which blocks to parse and return via the metadata_callback
  88749. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88750. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88751. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88752. * which blocks to return. Remember that metadata blocks can potentially
  88753. * be big (for example, cover art) so filtering out the ones you don't
  88754. * use can reduce the memory requirements of the decoder. Also note the
  88755. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88756. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88757. * filtering APPLICATION blocks based on the application ID.
  88758. *
  88759. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88760. * they still can legally be filtered from the metadata_callback.
  88761. *
  88762. * \note
  88763. * The "set" functions may only be called when the decoder is in the
  88764. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88765. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88766. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88767. * return \c true, otherwise \c false.
  88768. *
  88769. * \note
  88770. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88771. * defaults, including the callbacks.
  88772. *
  88773. * \{
  88774. */
  88775. /** State values for a FLAC__StreamDecoder
  88776. *
  88777. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88778. */
  88779. typedef enum {
  88780. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88781. /**< The decoder is ready to search for metadata. */
  88782. FLAC__STREAM_DECODER_READ_METADATA,
  88783. /**< The decoder is ready to or is in the process of reading metadata. */
  88784. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88785. /**< The decoder is ready to or is in the process of searching for the
  88786. * frame sync code.
  88787. */
  88788. FLAC__STREAM_DECODER_READ_FRAME,
  88789. /**< The decoder is ready to or is in the process of reading a frame. */
  88790. FLAC__STREAM_DECODER_END_OF_STREAM,
  88791. /**< The decoder has reached the end of the stream. */
  88792. FLAC__STREAM_DECODER_OGG_ERROR,
  88793. /**< An error occurred in the underlying Ogg layer. */
  88794. FLAC__STREAM_DECODER_SEEK_ERROR,
  88795. /**< An error occurred while seeking. The decoder must be flushed
  88796. * with FLAC__stream_decoder_flush() or reset with
  88797. * FLAC__stream_decoder_reset() before decoding can continue.
  88798. */
  88799. FLAC__STREAM_DECODER_ABORTED,
  88800. /**< The decoder was aborted by the read callback. */
  88801. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88802. /**< An error occurred allocating memory. The decoder is in an invalid
  88803. * state and can no longer be used.
  88804. */
  88805. FLAC__STREAM_DECODER_UNINITIALIZED
  88806. /**< The decoder is in the uninitialized state; one of the
  88807. * FLAC__stream_decoder_init_*() functions must be called before samples
  88808. * can be processed.
  88809. */
  88810. } FLAC__StreamDecoderState;
  88811. /** Maps a FLAC__StreamDecoderState to a C string.
  88812. *
  88813. * Using a FLAC__StreamDecoderState as the index to this array
  88814. * will give the string equivalent. The contents should not be modified.
  88815. */
  88816. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88817. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88818. */
  88819. typedef enum {
  88820. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  88821. /**< Initialization was successful. */
  88822. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  88823. /**< The library was not compiled with support for the given container
  88824. * format.
  88825. */
  88826. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  88827. /**< A required callback was not supplied. */
  88828. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  88829. /**< An error occurred allocating memory. */
  88830. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  88831. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  88832. * FLAC__stream_decoder_init_ogg_file(). */
  88833. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  88834. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  88835. * already initialized, usually because
  88836. * FLAC__stream_decoder_finish() was not called.
  88837. */
  88838. } FLAC__StreamDecoderInitStatus;
  88839. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  88840. *
  88841. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  88842. * will give the string equivalent. The contents should not be modified.
  88843. */
  88844. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  88845. /** Return values for the FLAC__StreamDecoder read callback.
  88846. */
  88847. typedef enum {
  88848. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  88849. /**< The read was OK and decoding can continue. */
  88850. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  88851. /**< The read was attempted while at the end of the stream. Note that
  88852. * the client must only return this value when the read callback was
  88853. * called when already at the end of the stream. Otherwise, if the read
  88854. * itself moves to the end of the stream, the client should still return
  88855. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  88856. * the next read callback it should return
  88857. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  88858. * of \c 0.
  88859. */
  88860. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  88861. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88862. } FLAC__StreamDecoderReadStatus;
  88863. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  88864. *
  88865. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  88866. * will give the string equivalent. The contents should not be modified.
  88867. */
  88868. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  88869. /** Return values for the FLAC__StreamDecoder seek callback.
  88870. */
  88871. typedef enum {
  88872. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  88873. /**< The seek was OK and decoding can continue. */
  88874. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  88875. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88876. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  88877. /**< Client does not support seeking. */
  88878. } FLAC__StreamDecoderSeekStatus;
  88879. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  88880. *
  88881. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  88882. * will give the string equivalent. The contents should not be modified.
  88883. */
  88884. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  88885. /** Return values for the FLAC__StreamDecoder tell callback.
  88886. */
  88887. typedef enum {
  88888. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  88889. /**< The tell was OK and decoding can continue. */
  88890. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  88891. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88892. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  88893. /**< Client does not support telling the position. */
  88894. } FLAC__StreamDecoderTellStatus;
  88895. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  88896. *
  88897. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  88898. * will give the string equivalent. The contents should not be modified.
  88899. */
  88900. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  88901. /** Return values for the FLAC__StreamDecoder length callback.
  88902. */
  88903. typedef enum {
  88904. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  88905. /**< The length call was OK and decoding can continue. */
  88906. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  88907. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88908. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  88909. /**< Client does not support reporting the length. */
  88910. } FLAC__StreamDecoderLengthStatus;
  88911. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  88912. *
  88913. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  88914. * will give the string equivalent. The contents should not be modified.
  88915. */
  88916. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  88917. /** Return values for the FLAC__StreamDecoder write callback.
  88918. */
  88919. typedef enum {
  88920. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  88921. /**< The write was OK and decoding can continue. */
  88922. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  88923. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88924. } FLAC__StreamDecoderWriteStatus;
  88925. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  88926. *
  88927. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  88928. * will give the string equivalent. The contents should not be modified.
  88929. */
  88930. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  88931. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  88932. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  88933. * all. The rest could be caused by bad sync (false synchronization on
  88934. * data that is not the start of a frame) or corrupted data. The error
  88935. * itself is the decoder's best guess at what happened assuming a correct
  88936. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  88937. * could be caused by a correct sync on the start of a frame, but some
  88938. * data in the frame header was corrupted. Or it could be the result of
  88939. * syncing on a point the stream that looked like the starting of a frame
  88940. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88941. * could be because the decoder encountered a valid frame made by a future
  88942. * version of the encoder which it cannot parse, or because of a false
  88943. * sync making it appear as though an encountered frame was generated by
  88944. * a future encoder.
  88945. */
  88946. typedef enum {
  88947. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  88948. /**< An error in the stream caused the decoder to lose synchronization. */
  88949. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  88950. /**< The decoder encountered a corrupted frame header. */
  88951. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  88952. /**< The frame's data did not match the CRC in the footer. */
  88953. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88954. /**< The decoder encountered reserved fields in use in the stream. */
  88955. } FLAC__StreamDecoderErrorStatus;
  88956. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  88957. *
  88958. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  88959. * will give the string equivalent. The contents should not be modified.
  88960. */
  88961. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  88962. /***********************************************************************
  88963. *
  88964. * class FLAC__StreamDecoder
  88965. *
  88966. ***********************************************************************/
  88967. struct FLAC__StreamDecoderProtected;
  88968. struct FLAC__StreamDecoderPrivate;
  88969. /** The opaque structure definition for the stream decoder type.
  88970. * See the \link flac_stream_decoder stream decoder module \endlink
  88971. * for a detailed description.
  88972. */
  88973. typedef struct {
  88974. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88975. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88976. } FLAC__StreamDecoder;
  88977. /** Signature for the read callback.
  88978. *
  88979. * A function pointer matching this signature must be passed to
  88980. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88981. * called when the decoder needs more input data. The address of the
  88982. * buffer to be filled is supplied, along with the number of bytes the
  88983. * buffer can hold. The callback may choose to supply less data and
  88984. * modify the byte count but must be careful not to overflow the buffer.
  88985. * The callback then returns a status code chosen from
  88986. * FLAC__StreamDecoderReadStatus.
  88987. *
  88988. * Here is an example of a read callback for stdio streams:
  88989. * \code
  88990. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88991. * {
  88992. * FILE *file = ((MyClientData*)client_data)->file;
  88993. * if(*bytes > 0) {
  88994. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88995. * if(ferror(file))
  88996. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88997. * else if(*bytes == 0)
  88998. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  88999. * else
  89000. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89001. * }
  89002. * else
  89003. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89004. * }
  89005. * \endcode
  89006. *
  89007. * \note In general, FLAC__StreamDecoder functions which change the
  89008. * state should not be called on the \a decoder while in the callback.
  89009. *
  89010. * \param decoder The decoder instance calling the callback.
  89011. * \param buffer A pointer to a location for the callee to store
  89012. * data to be decoded.
  89013. * \param bytes A pointer to the size of the buffer. On entry
  89014. * to the callback, it contains the maximum number
  89015. * of bytes that may be stored in \a buffer. The
  89016. * callee must set it to the actual number of bytes
  89017. * stored (0 in case of error or end-of-stream) before
  89018. * returning.
  89019. * \param client_data The callee's client data set through
  89020. * FLAC__stream_decoder_init_*().
  89021. * \retval FLAC__StreamDecoderReadStatus
  89022. * The callee's return status. Note that the callback should return
  89023. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89024. * zero bytes were read and there is no more data to be read.
  89025. */
  89026. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89027. /** Signature for the seek callback.
  89028. *
  89029. * A function pointer matching this signature may be passed to
  89030. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89031. * called when the decoder needs to seek the input stream. The decoder
  89032. * will pass the absolute byte offset to seek to, 0 meaning the
  89033. * beginning of the stream.
  89034. *
  89035. * Here is an example of a seek callback for stdio streams:
  89036. * \code
  89037. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89038. * {
  89039. * FILE *file = ((MyClientData*)client_data)->file;
  89040. * if(file == stdin)
  89041. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89042. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89043. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89044. * else
  89045. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89046. * }
  89047. * \endcode
  89048. *
  89049. * \note In general, FLAC__StreamDecoder functions which change the
  89050. * state should not be called on the \a decoder while in the callback.
  89051. *
  89052. * \param decoder The decoder instance calling the callback.
  89053. * \param absolute_byte_offset The offset from the beginning of the stream
  89054. * to seek to.
  89055. * \param client_data The callee's client data set through
  89056. * FLAC__stream_decoder_init_*().
  89057. * \retval FLAC__StreamDecoderSeekStatus
  89058. * The callee's return status.
  89059. */
  89060. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89061. /** Signature for the tell callback.
  89062. *
  89063. * A function pointer matching this signature may be passed to
  89064. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89065. * called when the decoder wants to know the current position of the
  89066. * stream. The callback should return the byte offset from the
  89067. * beginning of the stream.
  89068. *
  89069. * Here is an example of a tell callback for stdio streams:
  89070. * \code
  89071. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89072. * {
  89073. * FILE *file = ((MyClientData*)client_data)->file;
  89074. * off_t pos;
  89075. * if(file == stdin)
  89076. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89077. * else if((pos = ftello(file)) < 0)
  89078. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89079. * else {
  89080. * *absolute_byte_offset = (FLAC__uint64)pos;
  89081. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89082. * }
  89083. * }
  89084. * \endcode
  89085. *
  89086. * \note In general, FLAC__StreamDecoder functions which change the
  89087. * state should not be called on the \a decoder while in the callback.
  89088. *
  89089. * \param decoder The decoder instance calling the callback.
  89090. * \param absolute_byte_offset A pointer to storage for the current offset
  89091. * from the beginning of the stream.
  89092. * \param client_data The callee's client data set through
  89093. * FLAC__stream_decoder_init_*().
  89094. * \retval FLAC__StreamDecoderTellStatus
  89095. * The callee's return status.
  89096. */
  89097. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89098. /** Signature for the length callback.
  89099. *
  89100. * A function pointer matching this signature may be passed to
  89101. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89102. * called when the decoder wants to know the total length of the stream
  89103. * in bytes.
  89104. *
  89105. * Here is an example of a length callback for stdio streams:
  89106. * \code
  89107. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89108. * {
  89109. * FILE *file = ((MyClientData*)client_data)->file;
  89110. * struct stat filestats;
  89111. *
  89112. * if(file == stdin)
  89113. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89114. * else if(fstat(fileno(file), &filestats) != 0)
  89115. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89116. * else {
  89117. * *stream_length = (FLAC__uint64)filestats.st_size;
  89118. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89119. * }
  89120. * }
  89121. * \endcode
  89122. *
  89123. * \note In general, FLAC__StreamDecoder functions which change the
  89124. * state should not be called on the \a decoder while in the callback.
  89125. *
  89126. * \param decoder The decoder instance calling the callback.
  89127. * \param stream_length A pointer to storage for the length of the stream
  89128. * in bytes.
  89129. * \param client_data The callee's client data set through
  89130. * FLAC__stream_decoder_init_*().
  89131. * \retval FLAC__StreamDecoderLengthStatus
  89132. * The callee's return status.
  89133. */
  89134. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89135. /** Signature for the EOF callback.
  89136. *
  89137. * A function pointer matching this signature may be passed to
  89138. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89139. * called when the decoder needs to know if the end of the stream has
  89140. * been reached.
  89141. *
  89142. * Here is an example of a EOF callback for stdio streams:
  89143. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89144. * \code
  89145. * {
  89146. * FILE *file = ((MyClientData*)client_data)->file;
  89147. * return feof(file)? true : false;
  89148. * }
  89149. * \endcode
  89150. *
  89151. * \note In general, FLAC__StreamDecoder functions which change the
  89152. * state should not be called on the \a decoder while in the callback.
  89153. *
  89154. * \param decoder The decoder instance calling the callback.
  89155. * \param client_data The callee's client data set through
  89156. * FLAC__stream_decoder_init_*().
  89157. * \retval FLAC__bool
  89158. * \c true if the currently at the end of the stream, else \c false.
  89159. */
  89160. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89161. /** Signature for the write callback.
  89162. *
  89163. * A function pointer matching this signature must be passed to one of
  89164. * the FLAC__stream_decoder_init_*() functions.
  89165. * The supplied function will be called when the decoder has decoded a
  89166. * single audio frame. The decoder will pass the frame metadata as well
  89167. * as an array of pointers (one for each channel) pointing to the
  89168. * decoded audio.
  89169. *
  89170. * \note In general, FLAC__StreamDecoder functions which change the
  89171. * state should not be called on the \a decoder while in the callback.
  89172. *
  89173. * \param decoder The decoder instance calling the callback.
  89174. * \param frame The description of the decoded frame. See
  89175. * FLAC__Frame.
  89176. * \param buffer An array of pointers to decoded channels of data.
  89177. * Each pointer will point to an array of signed
  89178. * samples of length \a frame->header.blocksize.
  89179. * Channels will be ordered according to the FLAC
  89180. * specification; see the documentation for the
  89181. * <A HREF="../format.html#frame_header">frame header</A>.
  89182. * \param client_data The callee's client data set through
  89183. * FLAC__stream_decoder_init_*().
  89184. * \retval FLAC__StreamDecoderWriteStatus
  89185. * The callee's return status.
  89186. */
  89187. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89188. /** Signature for the metadata callback.
  89189. *
  89190. * A function pointer matching this signature must be passed to one of
  89191. * the FLAC__stream_decoder_init_*() functions.
  89192. * The supplied function will be called when the decoder has decoded a
  89193. * metadata block. In a valid FLAC file there will always be one
  89194. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89195. * These will be supplied by the decoder in the same order as they
  89196. * appear in the stream and always before the first audio frame (i.e.
  89197. * write callback). The metadata block that is passed in must not be
  89198. * modified, and it doesn't live beyond the callback, so you should make
  89199. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89200. * elsewhere. Since metadata blocks can potentially be large, by
  89201. * default the decoder only calls the metadata callback for the
  89202. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89203. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89204. *
  89205. * \note In general, FLAC__StreamDecoder functions which change the
  89206. * state should not be called on the \a decoder while in the callback.
  89207. *
  89208. * \param decoder The decoder instance calling the callback.
  89209. * \param metadata The decoded metadata block.
  89210. * \param client_data The callee's client data set through
  89211. * FLAC__stream_decoder_init_*().
  89212. */
  89213. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89214. /** Signature for the error callback.
  89215. *
  89216. * A function pointer matching this signature must be passed to one of
  89217. * the FLAC__stream_decoder_init_*() functions.
  89218. * The supplied function will be called whenever an error occurs during
  89219. * decoding.
  89220. *
  89221. * \note In general, FLAC__StreamDecoder functions which change the
  89222. * state should not be called on the \a decoder while in the callback.
  89223. *
  89224. * \param decoder The decoder instance calling the callback.
  89225. * \param status The error encountered by the decoder.
  89226. * \param client_data The callee's client data set through
  89227. * FLAC__stream_decoder_init_*().
  89228. */
  89229. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89230. /***********************************************************************
  89231. *
  89232. * Class constructor/destructor
  89233. *
  89234. ***********************************************************************/
  89235. /** Create a new stream decoder instance. The instance is created with
  89236. * default settings; see the individual FLAC__stream_decoder_set_*()
  89237. * functions for each setting's default.
  89238. *
  89239. * \retval FLAC__StreamDecoder*
  89240. * \c NULL if there was an error allocating memory, else the new instance.
  89241. */
  89242. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89243. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89244. *
  89245. * \param decoder A pointer to an existing decoder.
  89246. * \assert
  89247. * \code decoder != NULL \endcode
  89248. */
  89249. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89250. /***********************************************************************
  89251. *
  89252. * Public class method prototypes
  89253. *
  89254. ***********************************************************************/
  89255. /** Set the serial number for the FLAC stream within the Ogg container.
  89256. * The default behavior is to use the serial number of the first Ogg
  89257. * page. Setting a serial number here will explicitly specify which
  89258. * stream is to be decoded.
  89259. *
  89260. * \note
  89261. * This does not need to be set for native FLAC decoding.
  89262. *
  89263. * \default \c use serial number of first page
  89264. * \param decoder A decoder instance to set.
  89265. * \param serial_number See above.
  89266. * \assert
  89267. * \code decoder != NULL \endcode
  89268. * \retval FLAC__bool
  89269. * \c false if the decoder is already initialized, else \c true.
  89270. */
  89271. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89272. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89273. * compute the MD5 signature of the unencoded audio data while decoding
  89274. * and compare it to the signature from the STREAMINFO block, if it
  89275. * exists, during FLAC__stream_decoder_finish().
  89276. *
  89277. * MD5 signature checking will be turned off (until the next
  89278. * FLAC__stream_decoder_reset()) if there is no signature in the
  89279. * STREAMINFO block or when a seek is attempted.
  89280. *
  89281. * Clients that do not use the MD5 check should leave this off to speed
  89282. * up decoding.
  89283. *
  89284. * \default \c false
  89285. * \param decoder A decoder instance to set.
  89286. * \param value Flag value (see above).
  89287. * \assert
  89288. * \code decoder != NULL \endcode
  89289. * \retval FLAC__bool
  89290. * \c false if the decoder is already initialized, else \c true.
  89291. */
  89292. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89293. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89294. *
  89295. * \default By default, only the \c STREAMINFO block is returned via the
  89296. * metadata callback.
  89297. * \param decoder A decoder instance to set.
  89298. * \param type See above.
  89299. * \assert
  89300. * \code decoder != NULL \endcode
  89301. * \a type is valid
  89302. * \retval FLAC__bool
  89303. * \c false if the decoder is already initialized, else \c true.
  89304. */
  89305. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89306. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89307. * given \a id.
  89308. *
  89309. * \default By default, only the \c STREAMINFO block is returned via the
  89310. * metadata callback.
  89311. * \param decoder A decoder instance to set.
  89312. * \param id See above.
  89313. * \assert
  89314. * \code decoder != NULL \endcode
  89315. * \code id != NULL \endcode
  89316. * \retval FLAC__bool
  89317. * \c false if the decoder is already initialized, else \c true.
  89318. */
  89319. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89320. /** Direct the decoder to pass on all metadata blocks of any type.
  89321. *
  89322. * \default By default, only the \c STREAMINFO block is returned via the
  89323. * metadata callback.
  89324. * \param decoder A decoder instance to set.
  89325. * \assert
  89326. * \code decoder != NULL \endcode
  89327. * \retval FLAC__bool
  89328. * \c false if the decoder is already initialized, else \c true.
  89329. */
  89330. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89331. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89332. *
  89333. * \default By default, only the \c STREAMINFO block is returned via the
  89334. * metadata callback.
  89335. * \param decoder A decoder instance to set.
  89336. * \param type See above.
  89337. * \assert
  89338. * \code decoder != NULL \endcode
  89339. * \a type is valid
  89340. * \retval FLAC__bool
  89341. * \c false if the decoder is already initialized, else \c true.
  89342. */
  89343. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89344. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89345. * the given \a id.
  89346. *
  89347. * \default By default, only the \c STREAMINFO block is returned via the
  89348. * metadata callback.
  89349. * \param decoder A decoder instance to set.
  89350. * \param id See above.
  89351. * \assert
  89352. * \code decoder != NULL \endcode
  89353. * \code id != NULL \endcode
  89354. * \retval FLAC__bool
  89355. * \c false if the decoder is already initialized, else \c true.
  89356. */
  89357. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89358. /** Direct the decoder to filter out all metadata blocks of any type.
  89359. *
  89360. * \default By default, only the \c STREAMINFO block is returned via the
  89361. * metadata callback.
  89362. * \param decoder A decoder instance to set.
  89363. * \assert
  89364. * \code decoder != NULL \endcode
  89365. * \retval FLAC__bool
  89366. * \c false if the decoder is already initialized, else \c true.
  89367. */
  89368. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89369. /** Get the current decoder state.
  89370. *
  89371. * \param decoder A decoder instance to query.
  89372. * \assert
  89373. * \code decoder != NULL \endcode
  89374. * \retval FLAC__StreamDecoderState
  89375. * The current decoder state.
  89376. */
  89377. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89378. /** Get the current decoder state as a C string.
  89379. *
  89380. * \param decoder A decoder instance to query.
  89381. * \assert
  89382. * \code decoder != NULL \endcode
  89383. * \retval const char *
  89384. * The decoder state as a C string. Do not modify the contents.
  89385. */
  89386. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89387. /** Get the "MD5 signature checking" flag.
  89388. * This is the value of the setting, not whether or not the decoder is
  89389. * currently checking the MD5 (remember, it can be turned off automatically
  89390. * by a seek). When the decoder is reset the flag will be restored to the
  89391. * value returned by this function.
  89392. *
  89393. * \param decoder A decoder instance to query.
  89394. * \assert
  89395. * \code decoder != NULL \endcode
  89396. * \retval FLAC__bool
  89397. * See above.
  89398. */
  89399. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89400. /** Get the total number of samples in the stream being decoded.
  89401. * Will only be valid after decoding has started and will contain the
  89402. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89403. *
  89404. * \param decoder A decoder instance to query.
  89405. * \assert
  89406. * \code decoder != NULL \endcode
  89407. * \retval unsigned
  89408. * See above.
  89409. */
  89410. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89411. /** Get the current number of channels in the stream being decoded.
  89412. * Will only be valid after decoding has started and will contain the
  89413. * value from the most recently decoded frame header.
  89414. *
  89415. * \param decoder A decoder instance to query.
  89416. * \assert
  89417. * \code decoder != NULL \endcode
  89418. * \retval unsigned
  89419. * See above.
  89420. */
  89421. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89422. /** Get the current channel assignment in the stream being decoded.
  89423. * Will only be valid after decoding has started and will contain the
  89424. * value from the most recently decoded frame header.
  89425. *
  89426. * \param decoder A decoder instance to query.
  89427. * \assert
  89428. * \code decoder != NULL \endcode
  89429. * \retval FLAC__ChannelAssignment
  89430. * See above.
  89431. */
  89432. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89433. /** Get the current sample resolution in the stream being decoded.
  89434. * Will only be valid after decoding has started and will contain the
  89435. * value from the most recently decoded frame header.
  89436. *
  89437. * \param decoder A decoder instance to query.
  89438. * \assert
  89439. * \code decoder != NULL \endcode
  89440. * \retval unsigned
  89441. * See above.
  89442. */
  89443. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89444. /** Get the current sample rate in Hz of the stream being decoded.
  89445. * Will only be valid after decoding has started and will contain the
  89446. * value from the most recently decoded frame header.
  89447. *
  89448. * \param decoder A decoder instance to query.
  89449. * \assert
  89450. * \code decoder != NULL \endcode
  89451. * \retval unsigned
  89452. * See above.
  89453. */
  89454. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89455. /** Get the current blocksize of the stream being decoded.
  89456. * Will only be valid after decoding has started and will contain the
  89457. * value from the most recently decoded frame header.
  89458. *
  89459. * \param decoder A decoder instance to query.
  89460. * \assert
  89461. * \code decoder != NULL \endcode
  89462. * \retval unsigned
  89463. * See above.
  89464. */
  89465. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89466. /** Returns the decoder's current read position within the stream.
  89467. * The position is the byte offset from the start of the stream.
  89468. * Bytes before this position have been fully decoded. Note that
  89469. * there may still be undecoded bytes in the decoder's read FIFO.
  89470. * The returned position is correct even after a seek.
  89471. *
  89472. * \warning This function currently only works for native FLAC,
  89473. * not Ogg FLAC streams.
  89474. *
  89475. * \param decoder A decoder instance to query.
  89476. * \param position Address at which to return the desired position.
  89477. * \assert
  89478. * \code decoder != NULL \endcode
  89479. * \code position != NULL \endcode
  89480. * \retval FLAC__bool
  89481. * \c true if successful, \c false if the stream is not native FLAC,
  89482. * or there was an error from the 'tell' callback or it returned
  89483. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89484. */
  89485. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89486. /** Initialize the decoder instance to decode native FLAC streams.
  89487. *
  89488. * This flavor of initialization sets up the decoder to decode from a
  89489. * native FLAC stream. I/O is performed via callbacks to the client.
  89490. * For decoding from a plain file via filename or open FILE*,
  89491. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89492. * provide a simpler interface.
  89493. *
  89494. * This function should be called after FLAC__stream_decoder_new() and
  89495. * FLAC__stream_decoder_set_*() but before any of the
  89496. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89497. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89498. * if initialization succeeded.
  89499. *
  89500. * \param decoder An uninitialized decoder instance.
  89501. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89502. * pointer must not be \c NULL.
  89503. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89504. * pointer may be \c NULL if seeking is not
  89505. * supported. If \a seek_callback is not \c NULL then a
  89506. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89507. * Alternatively, a dummy seek callback that just
  89508. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89509. * may also be supplied, all though this is slightly
  89510. * less efficient for the decoder.
  89511. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89512. * pointer may be \c NULL if not supported by the client. If
  89513. * \a seek_callback is not \c NULL then a
  89514. * \a tell_callback must also be supplied.
  89515. * Alternatively, a dummy tell callback that just
  89516. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89517. * may also be supplied, all though this is slightly
  89518. * less efficient for the decoder.
  89519. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89520. * pointer may be \c NULL if not supported by the client. If
  89521. * \a seek_callback is not \c NULL then a
  89522. * \a length_callback must also be supplied.
  89523. * Alternatively, a dummy length callback that just
  89524. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89525. * may also be supplied, all though this is slightly
  89526. * less efficient for the decoder.
  89527. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89528. * pointer may be \c NULL if not supported by the client. If
  89529. * \a seek_callback is not \c NULL then a
  89530. * \a eof_callback must also be supplied.
  89531. * Alternatively, a dummy length callback that just
  89532. * returns \c false
  89533. * may also be supplied, all though this is slightly
  89534. * less efficient for the decoder.
  89535. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89536. * pointer must not be \c NULL.
  89537. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89538. * pointer may be \c NULL if the callback is not
  89539. * desired.
  89540. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89541. * pointer must not be \c NULL.
  89542. * \param client_data This value will be supplied to callbacks in their
  89543. * \a client_data argument.
  89544. * \assert
  89545. * \code decoder != NULL \endcode
  89546. * \retval FLAC__StreamDecoderInitStatus
  89547. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89548. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89549. */
  89550. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89551. FLAC__StreamDecoder *decoder,
  89552. FLAC__StreamDecoderReadCallback read_callback,
  89553. FLAC__StreamDecoderSeekCallback seek_callback,
  89554. FLAC__StreamDecoderTellCallback tell_callback,
  89555. FLAC__StreamDecoderLengthCallback length_callback,
  89556. FLAC__StreamDecoderEofCallback eof_callback,
  89557. FLAC__StreamDecoderWriteCallback write_callback,
  89558. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89559. FLAC__StreamDecoderErrorCallback error_callback,
  89560. void *client_data
  89561. );
  89562. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89563. *
  89564. * This flavor of initialization sets up the decoder to decode from a
  89565. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89566. * client. For decoding from a plain file via filename or open FILE*,
  89567. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89568. * provide a simpler interface.
  89569. *
  89570. * This function should be called after FLAC__stream_decoder_new() and
  89571. * FLAC__stream_decoder_set_*() but before any of the
  89572. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89573. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89574. * if initialization succeeded.
  89575. *
  89576. * \note Support for Ogg FLAC in the library is optional. If this
  89577. * library has been built without support for Ogg FLAC, this function
  89578. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89579. *
  89580. * \param decoder An uninitialized decoder instance.
  89581. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89582. * pointer must not be \c NULL.
  89583. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89584. * pointer may be \c NULL if seeking is not
  89585. * supported. If \a seek_callback is not \c NULL then a
  89586. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89587. * Alternatively, a dummy seek callback that just
  89588. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89589. * may also be supplied, all though this is slightly
  89590. * less efficient for the decoder.
  89591. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89592. * pointer may be \c NULL if not supported by the client. If
  89593. * \a seek_callback is not \c NULL then a
  89594. * \a tell_callback must also be supplied.
  89595. * Alternatively, a dummy tell callback that just
  89596. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89597. * may also be supplied, all though this is slightly
  89598. * less efficient for the decoder.
  89599. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89600. * pointer may be \c NULL if not supported by the client. If
  89601. * \a seek_callback is not \c NULL then a
  89602. * \a length_callback must also be supplied.
  89603. * Alternatively, a dummy length callback that just
  89604. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89605. * may also be supplied, all though this is slightly
  89606. * less efficient for the decoder.
  89607. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89608. * pointer may be \c NULL if not supported by the client. If
  89609. * \a seek_callback is not \c NULL then a
  89610. * \a eof_callback must also be supplied.
  89611. * Alternatively, a dummy length callback that just
  89612. * returns \c false
  89613. * may also be supplied, all though this is slightly
  89614. * less efficient for the decoder.
  89615. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89616. * pointer must not be \c NULL.
  89617. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89618. * pointer may be \c NULL if the callback is not
  89619. * desired.
  89620. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89621. * pointer must not be \c NULL.
  89622. * \param client_data This value will be supplied to callbacks in their
  89623. * \a client_data argument.
  89624. * \assert
  89625. * \code decoder != NULL \endcode
  89626. * \retval FLAC__StreamDecoderInitStatus
  89627. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89628. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89629. */
  89630. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89631. FLAC__StreamDecoder *decoder,
  89632. FLAC__StreamDecoderReadCallback read_callback,
  89633. FLAC__StreamDecoderSeekCallback seek_callback,
  89634. FLAC__StreamDecoderTellCallback tell_callback,
  89635. FLAC__StreamDecoderLengthCallback length_callback,
  89636. FLAC__StreamDecoderEofCallback eof_callback,
  89637. FLAC__StreamDecoderWriteCallback write_callback,
  89638. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89639. FLAC__StreamDecoderErrorCallback error_callback,
  89640. void *client_data
  89641. );
  89642. /** Initialize the decoder instance to decode native FLAC files.
  89643. *
  89644. * This flavor of initialization sets up the decoder to decode from a
  89645. * plain native FLAC file. For non-stdio streams, you must use
  89646. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89647. *
  89648. * This function should be called after FLAC__stream_decoder_new() and
  89649. * FLAC__stream_decoder_set_*() but before any of the
  89650. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89651. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89652. * if initialization succeeded.
  89653. *
  89654. * \param decoder An uninitialized decoder instance.
  89655. * \param file An open FLAC file. The file should have been
  89656. * opened with mode \c "rb" and rewound. The file
  89657. * becomes owned by the decoder and should not be
  89658. * manipulated by the client while decoding.
  89659. * Unless \a file is \c stdin, it will be closed
  89660. * when FLAC__stream_decoder_finish() is called.
  89661. * Note however that seeking will not work when
  89662. * decoding from \c stdout since it is not seekable.
  89663. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89664. * pointer must not be \c NULL.
  89665. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89666. * pointer may be \c NULL if the callback is not
  89667. * desired.
  89668. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89669. * pointer must not be \c NULL.
  89670. * \param client_data This value will be supplied to callbacks in their
  89671. * \a client_data argument.
  89672. * \assert
  89673. * \code decoder != NULL \endcode
  89674. * \code file != NULL \endcode
  89675. * \retval FLAC__StreamDecoderInitStatus
  89676. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89677. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89678. */
  89679. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89680. FLAC__StreamDecoder *decoder,
  89681. FILE *file,
  89682. FLAC__StreamDecoderWriteCallback write_callback,
  89683. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89684. FLAC__StreamDecoderErrorCallback error_callback,
  89685. void *client_data
  89686. );
  89687. /** Initialize the decoder instance to decode Ogg FLAC files.
  89688. *
  89689. * This flavor of initialization sets up the decoder to decode from a
  89690. * plain Ogg FLAC file. For non-stdio streams, you must use
  89691. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89692. *
  89693. * This function should be called after FLAC__stream_decoder_new() and
  89694. * FLAC__stream_decoder_set_*() but before any of the
  89695. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89696. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89697. * if initialization succeeded.
  89698. *
  89699. * \note Support for Ogg FLAC in the library is optional. If this
  89700. * library has been built without support for Ogg FLAC, this function
  89701. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89702. *
  89703. * \param decoder An uninitialized decoder instance.
  89704. * \param file An open FLAC file. The file should have been
  89705. * opened with mode \c "rb" and rewound. The file
  89706. * becomes owned by the decoder and should not be
  89707. * manipulated by the client while decoding.
  89708. * Unless \a file is \c stdin, it will be closed
  89709. * when FLAC__stream_decoder_finish() is called.
  89710. * Note however that seeking will not work when
  89711. * decoding from \c stdout since it is not seekable.
  89712. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89713. * pointer must not be \c NULL.
  89714. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89715. * pointer may be \c NULL if the callback is not
  89716. * desired.
  89717. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89718. * pointer must not be \c NULL.
  89719. * \param client_data This value will be supplied to callbacks in their
  89720. * \a client_data argument.
  89721. * \assert
  89722. * \code decoder != NULL \endcode
  89723. * \code file != NULL \endcode
  89724. * \retval FLAC__StreamDecoderInitStatus
  89725. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89726. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89727. */
  89728. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89729. FLAC__StreamDecoder *decoder,
  89730. FILE *file,
  89731. FLAC__StreamDecoderWriteCallback write_callback,
  89732. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89733. FLAC__StreamDecoderErrorCallback error_callback,
  89734. void *client_data
  89735. );
  89736. /** Initialize the decoder instance to decode native FLAC files.
  89737. *
  89738. * This flavor of initialization sets up the decoder to decode from a plain
  89739. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89740. * example, with Unicode filenames on Windows), you must use
  89741. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89742. * and provide callbacks for the I/O.
  89743. *
  89744. * This function should be called after FLAC__stream_decoder_new() and
  89745. * FLAC__stream_decoder_set_*() but before any of the
  89746. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89747. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89748. * if initialization succeeded.
  89749. *
  89750. * \param decoder An uninitialized decoder instance.
  89751. * \param filename The name of the file to decode from. The file will
  89752. * be opened with fopen(). Use \c NULL to decode from
  89753. * \c stdin. Note that \c stdin is not seekable.
  89754. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89755. * pointer must not be \c NULL.
  89756. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89757. * pointer may be \c NULL if the callback is not
  89758. * desired.
  89759. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89760. * pointer must not be \c NULL.
  89761. * \param client_data This value will be supplied to callbacks in their
  89762. * \a client_data argument.
  89763. * \assert
  89764. * \code decoder != NULL \endcode
  89765. * \retval FLAC__StreamDecoderInitStatus
  89766. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89767. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89768. */
  89769. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89770. FLAC__StreamDecoder *decoder,
  89771. const char *filename,
  89772. FLAC__StreamDecoderWriteCallback write_callback,
  89773. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89774. FLAC__StreamDecoderErrorCallback error_callback,
  89775. void *client_data
  89776. );
  89777. /** Initialize the decoder instance to decode Ogg FLAC files.
  89778. *
  89779. * This flavor of initialization sets up the decoder to decode from a plain
  89780. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89781. * example, with Unicode filenames on Windows), you must use
  89782. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89783. * and provide callbacks for the I/O.
  89784. *
  89785. * This function should be called after FLAC__stream_decoder_new() and
  89786. * FLAC__stream_decoder_set_*() but before any of the
  89787. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89788. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89789. * if initialization succeeded.
  89790. *
  89791. * \note Support for Ogg FLAC in the library is optional. If this
  89792. * library has been built without support for Ogg FLAC, this function
  89793. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89794. *
  89795. * \param decoder An uninitialized decoder instance.
  89796. * \param filename The name of the file to decode from. The file will
  89797. * be opened with fopen(). Use \c NULL to decode from
  89798. * \c stdin. Note that \c stdin is not seekable.
  89799. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89800. * pointer must not be \c NULL.
  89801. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89802. * pointer may be \c NULL if the callback is not
  89803. * desired.
  89804. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89805. * pointer must not be \c NULL.
  89806. * \param client_data This value will be supplied to callbacks in their
  89807. * \a client_data argument.
  89808. * \assert
  89809. * \code decoder != NULL \endcode
  89810. * \retval FLAC__StreamDecoderInitStatus
  89811. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89812. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89813. */
  89814. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89815. FLAC__StreamDecoder *decoder,
  89816. const char *filename,
  89817. FLAC__StreamDecoderWriteCallback write_callback,
  89818. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89819. FLAC__StreamDecoderErrorCallback error_callback,
  89820. void *client_data
  89821. );
  89822. /** Finish the decoding process.
  89823. * Flushes the decoding buffer, releases resources, resets the decoder
  89824. * settings to their defaults, and returns the decoder state to
  89825. * FLAC__STREAM_DECODER_UNINITIALIZED.
  89826. *
  89827. * In the event of a prematurely-terminated decode, it is not strictly
  89828. * necessary to call this immediately before FLAC__stream_decoder_delete()
  89829. * but it is good practice to match every FLAC__stream_decoder_init_*()
  89830. * with a FLAC__stream_decoder_finish().
  89831. *
  89832. * \param decoder An uninitialized decoder instance.
  89833. * \assert
  89834. * \code decoder != NULL \endcode
  89835. * \retval FLAC__bool
  89836. * \c false if MD5 checking is on AND a STREAMINFO block was available
  89837. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  89838. * signature does not match the one computed by the decoder; else
  89839. * \c true.
  89840. */
  89841. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  89842. /** Flush the stream input.
  89843. * The decoder's input buffer will be cleared and the state set to
  89844. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  89845. * off MD5 checking.
  89846. *
  89847. * \param decoder A decoder instance.
  89848. * \assert
  89849. * \code decoder != NULL \endcode
  89850. * \retval FLAC__bool
  89851. * \c true if successful, else \c false if a memory allocation
  89852. * error occurs (in which case the state will be set to
  89853. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  89854. */
  89855. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  89856. /** Reset the decoding process.
  89857. * The decoder's input buffer will be cleared and the state set to
  89858. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  89859. * FLAC__stream_decoder_finish() except that the settings are
  89860. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  89861. * before decoding again. MD5 checking will be restored to its original
  89862. * setting.
  89863. *
  89864. * If the decoder is seekable, or was initialized with
  89865. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  89866. * the decoder will also attempt to seek to the beginning of the file.
  89867. * If this rewind fails, this function will return \c false. It follows
  89868. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  89869. * \c stdin.
  89870. *
  89871. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  89872. * and is not seekable (i.e. no seek callback was provided or the seek
  89873. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  89874. * is the duty of the client to start feeding data from the beginning of
  89875. * the stream on the next FLAC__stream_decoder_process() or
  89876. * FLAC__stream_decoder_process_interleaved() call.
  89877. *
  89878. * \param decoder A decoder instance.
  89879. * \assert
  89880. * \code decoder != NULL \endcode
  89881. * \retval FLAC__bool
  89882. * \c true if successful, else \c false if a memory allocation occurs
  89883. * (in which case the state will be set to
  89884. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  89885. * occurs (the state will be unchanged).
  89886. */
  89887. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  89888. /** Decode one metadata block or audio frame.
  89889. * This version instructs the decoder to decode a either a single metadata
  89890. * block or a single frame and stop, unless the callbacks return a fatal
  89891. * error or the read callback returns
  89892. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89893. *
  89894. * As the decoder needs more input it will call the read callback.
  89895. * Depending on what was decoded, the metadata or write callback will be
  89896. * called with the decoded metadata block or audio frame.
  89897. *
  89898. * Unless there is a fatal read error or end of stream, this function
  89899. * will return once one whole frame is decoded. In other words, if the
  89900. * stream is not synchronized or points to a corrupt frame header, the
  89901. * decoder will continue to try and resync until it gets to a valid
  89902. * frame, then decode one frame, then return. If the decoder points to
  89903. * a frame whose frame CRC in the frame footer does not match the
  89904. * computed frame CRC, this function will issue a
  89905. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  89906. * error callback, and return, having decoded one complete, although
  89907. * corrupt, frame. (Such corrupted frames are sent as silence of the
  89908. * correct length to the write callback.)
  89909. *
  89910. * \param decoder An initialized decoder instance.
  89911. * \assert
  89912. * \code decoder != NULL \endcode
  89913. * \retval FLAC__bool
  89914. * \c false if any fatal read, write, or memory allocation error
  89915. * occurred (meaning decoding must stop), else \c true; for more
  89916. * information about the decoder, check the decoder state with
  89917. * FLAC__stream_decoder_get_state().
  89918. */
  89919. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  89920. /** Decode until the end of the metadata.
  89921. * This version instructs the decoder to decode from the current position
  89922. * and continue until all the metadata has been read, or until the
  89923. * callbacks return a fatal error or the read callback returns
  89924. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89925. *
  89926. * As the decoder needs more input it will call the read callback.
  89927. * As each metadata block is decoded, the metadata callback will be called
  89928. * with the decoded metadata.
  89929. *
  89930. * \param decoder An initialized decoder instance.
  89931. * \assert
  89932. * \code decoder != NULL \endcode
  89933. * \retval FLAC__bool
  89934. * \c false if any fatal read, write, or memory allocation error
  89935. * occurred (meaning decoding must stop), else \c true; for more
  89936. * information about the decoder, check the decoder state with
  89937. * FLAC__stream_decoder_get_state().
  89938. */
  89939. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  89940. /** Decode until the end of the stream.
  89941. * This version instructs the decoder to decode from the current position
  89942. * and continue until the end of stream (the read callback returns
  89943. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  89944. * callbacks return a fatal error.
  89945. *
  89946. * As the decoder needs more input it will call the read callback.
  89947. * As each metadata block and frame is decoded, the metadata or write
  89948. * callback will be called with the decoded metadata or frame.
  89949. *
  89950. * \param decoder An initialized decoder instance.
  89951. * \assert
  89952. * \code decoder != NULL \endcode
  89953. * \retval FLAC__bool
  89954. * \c false if any fatal read, write, or memory allocation error
  89955. * occurred (meaning decoding must stop), else \c true; for more
  89956. * information about the decoder, check the decoder state with
  89957. * FLAC__stream_decoder_get_state().
  89958. */
  89959. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  89960. /** Skip one audio frame.
  89961. * This version instructs the decoder to 'skip' a single frame and stop,
  89962. * unless the callbacks return a fatal error or the read callback returns
  89963. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89964. *
  89965. * The decoding flow is the same as what occurs when
  89966. * FLAC__stream_decoder_process_single() is called to process an audio
  89967. * frame, except that this function does not decode the parsed data into
  89968. * PCM or call the write callback. The integrity of the frame is still
  89969. * checked the same way as in the other process functions.
  89970. *
  89971. * This function will return once one whole frame is skipped, in the
  89972. * same way that FLAC__stream_decoder_process_single() will return once
  89973. * one whole frame is decoded.
  89974. *
  89975. * This function can be used in more quickly determining FLAC frame
  89976. * boundaries when decoding of the actual data is not needed, for
  89977. * example when an application is separating a FLAC stream into frames
  89978. * for editing or storing in a container. To do this, the application
  89979. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  89980. * to the next frame, then use
  89981. * FLAC__stream_decoder_get_decode_position() to find the new frame
  89982. * boundary.
  89983. *
  89984. * This function should only be called when the stream has advanced
  89985. * past all the metadata, otherwise it will return \c false.
  89986. *
  89987. * \param decoder An initialized decoder instance not in a metadata
  89988. * state.
  89989. * \assert
  89990. * \code decoder != NULL \endcode
  89991. * \retval FLAC__bool
  89992. * \c false if any fatal read, write, or memory allocation error
  89993. * occurred (meaning decoding must stop), or if the decoder
  89994. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  89995. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  89996. * information about the decoder, check the decoder state with
  89997. * FLAC__stream_decoder_get_state().
  89998. */
  89999. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90000. /** Flush the input and seek to an absolute sample.
  90001. * Decoding will resume at the given sample. Note that because of
  90002. * this, the next write callback may contain a partial block. The
  90003. * client must support seeking the input or this function will fail
  90004. * and return \c false. Furthermore, if the decoder state is
  90005. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90006. * with FLAC__stream_decoder_flush() or reset with
  90007. * FLAC__stream_decoder_reset() before decoding can continue.
  90008. *
  90009. * \param decoder A decoder instance.
  90010. * \param sample The target sample number to seek to.
  90011. * \assert
  90012. * \code decoder != NULL \endcode
  90013. * \retval FLAC__bool
  90014. * \c true if successful, else \c false.
  90015. */
  90016. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90017. /* \} */
  90018. #ifdef __cplusplus
  90019. }
  90020. #endif
  90021. #endif
  90022. /*** End of inlined file: stream_decoder.h ***/
  90023. /*** Start of inlined file: stream_encoder.h ***/
  90024. #ifndef FLAC__STREAM_ENCODER_H
  90025. #define FLAC__STREAM_ENCODER_H
  90026. #include <stdio.h> /* for FILE */
  90027. #ifdef __cplusplus
  90028. extern "C" {
  90029. #endif
  90030. /** \file include/FLAC/stream_encoder.h
  90031. *
  90032. * \brief
  90033. * This module contains the functions which implement the stream
  90034. * encoder.
  90035. *
  90036. * See the detailed documentation in the
  90037. * \link flac_stream_encoder stream encoder \endlink module.
  90038. */
  90039. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90040. * \ingroup flac
  90041. *
  90042. * \brief
  90043. * This module describes the encoder layers provided by libFLAC.
  90044. *
  90045. * The stream encoder can be used to encode complete streams either to the
  90046. * client via callbacks, or directly to a file, depending on how it is
  90047. * initialized. When encoding via callbacks, the client provides a write
  90048. * callback which will be called whenever FLAC data is ready to be written.
  90049. * If the client also supplies a seek callback, the encoder will also
  90050. * automatically handle the writing back of metadata discovered while
  90051. * encoding, like stream info, seek points offsets, etc. When encoding to
  90052. * a file, the client needs only supply a filename or open \c FILE* and an
  90053. * optional progress callback for periodic notification of progress; the
  90054. * write and seek callbacks are supplied internally. For more info see the
  90055. * \link flac_stream_encoder stream encoder \endlink module.
  90056. */
  90057. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90058. * \ingroup flac_encoder
  90059. *
  90060. * \brief
  90061. * This module contains the functions which implement the stream
  90062. * encoder.
  90063. *
  90064. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90065. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90066. *
  90067. * The basic usage of this encoder is as follows:
  90068. * - The program creates an instance of an encoder using
  90069. * FLAC__stream_encoder_new().
  90070. * - The program overrides the default settings using
  90071. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90072. * functions should be called:
  90073. * - FLAC__stream_encoder_set_channels()
  90074. * - FLAC__stream_encoder_set_bits_per_sample()
  90075. * - FLAC__stream_encoder_set_sample_rate()
  90076. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90077. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90078. * - If the application wants to control the compression level or set its own
  90079. * metadata, then the following should also be called:
  90080. * - FLAC__stream_encoder_set_compression_level()
  90081. * - FLAC__stream_encoder_set_verify()
  90082. * - FLAC__stream_encoder_set_metadata()
  90083. * - The rest of the set functions should only be called if the client needs
  90084. * exact control over how the audio is compressed; thorough understanding
  90085. * of the FLAC format is necessary to achieve good results.
  90086. * - The program initializes the instance to validate the settings and
  90087. * prepare for encoding using
  90088. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90089. * or FLAC__stream_encoder_init_file() for native FLAC
  90090. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90091. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90092. * - The program calls FLAC__stream_encoder_process() or
  90093. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90094. * subsequently calls the callbacks when there is encoder data ready
  90095. * to be written.
  90096. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90097. * which causes the encoder to encode any data still in its input pipe,
  90098. * update the metadata with the final encoding statistics if output
  90099. * seeking is possible, and finally reset the encoder to the
  90100. * uninitialized state.
  90101. * - The instance may be used again or deleted with
  90102. * FLAC__stream_encoder_delete().
  90103. *
  90104. * In more detail, the stream encoder functions similarly to the
  90105. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90106. * callbacks and more options. Typically the client will create a new
  90107. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90108. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90109. * calling one of the FLAC__stream_encoder_init_*() functions.
  90110. *
  90111. * Unlike the decoders, the stream encoder has many options that can
  90112. * affect the speed and compression ratio. When setting these parameters
  90113. * you should have some basic knowledge of the format (see the
  90114. * <A HREF="../documentation.html#format">user-level documentation</A>
  90115. * or the <A HREF="../format.html">formal description</A>). The
  90116. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90117. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90118. * functions will do this, so make sure to pay attention to the state
  90119. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90120. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90121. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90122. * the constructor.
  90123. *
  90124. * There are three initialization functions for native FLAC, one for
  90125. * setting up the encoder to encode FLAC data to the client via
  90126. * callbacks, and two for encoding directly to a file.
  90127. *
  90128. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90129. * You must also supply a write callback which will be called anytime
  90130. * there is raw encoded data to write. If the client can seek the output
  90131. * it is best to also supply seek and tell callbacks, as this allows the
  90132. * encoder to go back after encoding is finished to write back
  90133. * information that was collected while encoding, like seek point offsets,
  90134. * frame sizes, etc.
  90135. *
  90136. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90137. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90138. * filename or open \c FILE*; the encoder will handle all the callbacks
  90139. * internally. You may also supply a progress callback for periodic
  90140. * notification of the encoding progress.
  90141. *
  90142. * There are three similarly-named init functions for encoding to Ogg
  90143. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90144. * library has been built with Ogg support.
  90145. *
  90146. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90147. * call the write callback several times, once with the \c fLaC signature,
  90148. * and once for each encoded metadata block. Note that for Ogg FLAC
  90149. * encoding you will usually get at least twice the number of callbacks than
  90150. * with native FLAC, one for the Ogg page header and one for the page body.
  90151. *
  90152. * After initializing the instance, the client may feed audio data to the
  90153. * encoder in one of two ways:
  90154. *
  90155. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90156. * will pass an array of pointers to buffers, one for each channel, to
  90157. * the encoder, each of the same length. The samples need not be
  90158. * block-aligned, but each channel should have the same number of samples.
  90159. * - Channel interleaved, through
  90160. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90161. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90162. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90163. * Again, the samples need not be block-aligned but they must be
  90164. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90165. * the last value channelN_sampleM.
  90166. *
  90167. * Note that for either process call, each sample in the buffers should be a
  90168. * signed integer, right-justified to the resolution set by
  90169. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90170. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90171. *
  90172. * When the client is finished encoding data, it calls
  90173. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90174. * data still in its input pipe, and call the metadata callback with the
  90175. * final encoding statistics. Then the instance may be deleted with
  90176. * FLAC__stream_encoder_delete() or initialized again to encode another
  90177. * stream.
  90178. *
  90179. * For programs that write their own metadata, but that do not know the
  90180. * actual metadata until after encoding, it is advantageous to instruct
  90181. * the encoder to write a PADDING block of the correct size, so that
  90182. * instead of rewriting the whole stream after encoding, the program can
  90183. * just overwrite the PADDING block. If only the maximum size of the
  90184. * metadata is known, the program can write a slightly larger padding
  90185. * block, then split it after encoding.
  90186. *
  90187. * Make sure you understand how lengths are calculated. All FLAC metadata
  90188. * blocks have a 4 byte header which contains the type and length. This
  90189. * length does not include the 4 bytes of the header. See the format page
  90190. * for the specification of metadata blocks and their lengths.
  90191. *
  90192. * \note
  90193. * If you are writing the FLAC data to a file via callbacks, make sure it
  90194. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90195. * after the first encoding pass, the encoder will try to seek back to the
  90196. * beginning of the stream, to the STREAMINFO block, to write some data
  90197. * there. (If using FLAC__stream_encoder_init*_file() or
  90198. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90199. *
  90200. * \note
  90201. * The "set" functions may only be called when the encoder is in the
  90202. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90203. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90204. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90205. * return \c true, otherwise \c false.
  90206. *
  90207. * \note
  90208. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90209. * defaults.
  90210. *
  90211. * \{
  90212. */
  90213. /** State values for a FLAC__StreamEncoder.
  90214. *
  90215. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90216. *
  90217. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90218. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90219. * must be deleted with FLAC__stream_encoder_delete().
  90220. */
  90221. typedef enum {
  90222. FLAC__STREAM_ENCODER_OK = 0,
  90223. /**< The encoder is in the normal OK state and samples can be processed. */
  90224. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90225. /**< The encoder is in the uninitialized state; one of the
  90226. * FLAC__stream_encoder_init_*() functions must be called before samples
  90227. * can be processed.
  90228. */
  90229. FLAC__STREAM_ENCODER_OGG_ERROR,
  90230. /**< An error occurred in the underlying Ogg layer. */
  90231. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90232. /**< An error occurred in the underlying verify stream decoder;
  90233. * check FLAC__stream_encoder_get_verify_decoder_state().
  90234. */
  90235. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90236. /**< The verify decoder detected a mismatch between the original
  90237. * audio signal and the decoded audio signal.
  90238. */
  90239. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90240. /**< One of the callbacks returned a fatal error. */
  90241. FLAC__STREAM_ENCODER_IO_ERROR,
  90242. /**< An I/O error occurred while opening/reading/writing a file.
  90243. * Check \c errno.
  90244. */
  90245. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90246. /**< An error occurred while writing the stream; usually, the
  90247. * write_callback returned an error.
  90248. */
  90249. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90250. /**< Memory allocation failed. */
  90251. } FLAC__StreamEncoderState;
  90252. /** Maps a FLAC__StreamEncoderState to a C string.
  90253. *
  90254. * Using a FLAC__StreamEncoderState as the index to this array
  90255. * will give the string equivalent. The contents should not be modified.
  90256. */
  90257. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90258. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90259. */
  90260. typedef enum {
  90261. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90262. /**< Initialization was successful. */
  90263. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90264. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90265. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90266. /**< The library was not compiled with support for the given container
  90267. * format.
  90268. */
  90269. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90270. /**< A required callback was not supplied. */
  90271. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90272. /**< The encoder has an invalid setting for number of channels. */
  90273. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90274. /**< The encoder has an invalid setting for bits-per-sample.
  90275. * FLAC supports 4-32 bps but the reference encoder currently supports
  90276. * only up to 24 bps.
  90277. */
  90278. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90279. /**< The encoder has an invalid setting for the input sample rate. */
  90280. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90281. /**< The encoder has an invalid setting for the block size. */
  90282. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90283. /**< The encoder has an invalid setting for the maximum LPC order. */
  90284. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90285. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90286. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90287. /**< The specified block size is less than the maximum LPC order. */
  90288. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90289. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90290. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90291. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90292. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90293. * - One of the metadata blocks contains an undefined type
  90294. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90295. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90296. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90297. */
  90298. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90299. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90300. * already initialized, usually because
  90301. * FLAC__stream_encoder_finish() was not called.
  90302. */
  90303. } FLAC__StreamEncoderInitStatus;
  90304. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90305. *
  90306. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90307. * will give the string equivalent. The contents should not be modified.
  90308. */
  90309. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90310. /** Return values for the FLAC__StreamEncoder read callback.
  90311. */
  90312. typedef enum {
  90313. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90314. /**< The read was OK and decoding can continue. */
  90315. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90316. /**< The read was attempted at the end of the stream. */
  90317. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90318. /**< An unrecoverable error occurred. */
  90319. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90320. /**< Client does not support reading back from the output. */
  90321. } FLAC__StreamEncoderReadStatus;
  90322. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90323. *
  90324. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90325. * will give the string equivalent. The contents should not be modified.
  90326. */
  90327. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90328. /** Return values for the FLAC__StreamEncoder write callback.
  90329. */
  90330. typedef enum {
  90331. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90332. /**< The write was OK and encoding can continue. */
  90333. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90334. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90335. } FLAC__StreamEncoderWriteStatus;
  90336. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90337. *
  90338. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90339. * will give the string equivalent. The contents should not be modified.
  90340. */
  90341. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90342. /** Return values for the FLAC__StreamEncoder seek callback.
  90343. */
  90344. typedef enum {
  90345. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90346. /**< The seek was OK and encoding can continue. */
  90347. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90348. /**< An unrecoverable error occurred. */
  90349. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90350. /**< Client does not support seeking. */
  90351. } FLAC__StreamEncoderSeekStatus;
  90352. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90353. *
  90354. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90355. * will give the string equivalent. The contents should not be modified.
  90356. */
  90357. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90358. /** Return values for the FLAC__StreamEncoder tell callback.
  90359. */
  90360. typedef enum {
  90361. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90362. /**< The tell was OK and encoding can continue. */
  90363. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90364. /**< An unrecoverable error occurred. */
  90365. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90366. /**< Client does not support seeking. */
  90367. } FLAC__StreamEncoderTellStatus;
  90368. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90369. *
  90370. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90371. * will give the string equivalent. The contents should not be modified.
  90372. */
  90373. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90374. /***********************************************************************
  90375. *
  90376. * class FLAC__StreamEncoder
  90377. *
  90378. ***********************************************************************/
  90379. struct FLAC__StreamEncoderProtected;
  90380. struct FLAC__StreamEncoderPrivate;
  90381. /** The opaque structure definition for the stream encoder type.
  90382. * See the \link flac_stream_encoder stream encoder module \endlink
  90383. * for a detailed description.
  90384. */
  90385. typedef struct {
  90386. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90387. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90388. } FLAC__StreamEncoder;
  90389. /** Signature for the read callback.
  90390. *
  90391. * A function pointer matching this signature must be passed to
  90392. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90393. * The supplied function will be called when the encoder needs to read back
  90394. * encoded data. This happens during the metadata callback, when the encoder
  90395. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90396. * while encoding. The address of the buffer to be filled is supplied, along
  90397. * with the number of bytes the buffer can hold. The callback may choose to
  90398. * supply less data and modify the byte count but must be careful not to
  90399. * overflow the buffer. The callback then returns a status code chosen from
  90400. * FLAC__StreamEncoderReadStatus.
  90401. *
  90402. * Here is an example of a read callback for stdio streams:
  90403. * \code
  90404. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90405. * {
  90406. * FILE *file = ((MyClientData*)client_data)->file;
  90407. * if(*bytes > 0) {
  90408. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90409. * if(ferror(file))
  90410. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90411. * else if(*bytes == 0)
  90412. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90413. * else
  90414. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90415. * }
  90416. * else
  90417. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90418. * }
  90419. * \endcode
  90420. *
  90421. * \note In general, FLAC__StreamEncoder functions which change the
  90422. * state should not be called on the \a encoder while in the callback.
  90423. *
  90424. * \param encoder The encoder instance calling the callback.
  90425. * \param buffer A pointer to a location for the callee to store
  90426. * data to be encoded.
  90427. * \param bytes A pointer to the size of the buffer. On entry
  90428. * to the callback, it contains the maximum number
  90429. * of bytes that may be stored in \a buffer. The
  90430. * callee must set it to the actual number of bytes
  90431. * stored (0 in case of error or end-of-stream) before
  90432. * returning.
  90433. * \param client_data The callee's client data set through
  90434. * FLAC__stream_encoder_set_client_data().
  90435. * \retval FLAC__StreamEncoderReadStatus
  90436. * The callee's return status.
  90437. */
  90438. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90439. /** Signature for the write callback.
  90440. *
  90441. * A function pointer matching this signature must be passed to
  90442. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90443. * by the encoder anytime there is raw encoded data ready to write. It may
  90444. * include metadata mixed with encoded audio frames and the data is not
  90445. * guaranteed to be aligned on frame or metadata block boundaries.
  90446. *
  90447. * The only duty of the callback is to write out the \a bytes worth of data
  90448. * in \a buffer to the current position in the output stream. The arguments
  90449. * \a samples and \a current_frame are purely informational. If \a samples
  90450. * is greater than \c 0, then \a current_frame will hold the current frame
  90451. * number that is being written; otherwise it indicates that the write
  90452. * callback is being called to write metadata.
  90453. *
  90454. * \note
  90455. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90456. * write callback will be called twice when writing each audio
  90457. * frame; once for the page header, and once for the page body.
  90458. * When writing the page header, the \a samples argument to the
  90459. * write callback will be \c 0.
  90460. *
  90461. * \note In general, FLAC__StreamEncoder functions which change the
  90462. * state should not be called on the \a encoder while in the callback.
  90463. *
  90464. * \param encoder The encoder instance calling the callback.
  90465. * \param buffer An array of encoded data of length \a bytes.
  90466. * \param bytes The byte length of \a buffer.
  90467. * \param samples The number of samples encoded by \a buffer.
  90468. * \c 0 has a special meaning; see above.
  90469. * \param current_frame The number of the current frame being encoded.
  90470. * \param client_data The callee's client data set through
  90471. * FLAC__stream_encoder_init_*().
  90472. * \retval FLAC__StreamEncoderWriteStatus
  90473. * The callee's return status.
  90474. */
  90475. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90476. /** Signature for the seek callback.
  90477. *
  90478. * A function pointer matching this signature may be passed to
  90479. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90480. * when the encoder needs to seek the output stream. The encoder will pass
  90481. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90482. *
  90483. * Here is an example of a seek callback for stdio streams:
  90484. * \code
  90485. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90486. * {
  90487. * FILE *file = ((MyClientData*)client_data)->file;
  90488. * if(file == stdin)
  90489. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90490. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90491. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90492. * else
  90493. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90494. * }
  90495. * \endcode
  90496. *
  90497. * \note In general, FLAC__StreamEncoder functions which change the
  90498. * state should not be called on the \a encoder while in the callback.
  90499. *
  90500. * \param encoder The encoder instance calling the callback.
  90501. * \param absolute_byte_offset The offset from the beginning of the stream
  90502. * to seek to.
  90503. * \param client_data The callee's client data set through
  90504. * FLAC__stream_encoder_init_*().
  90505. * \retval FLAC__StreamEncoderSeekStatus
  90506. * The callee's return status.
  90507. */
  90508. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90509. /** Signature for the tell callback.
  90510. *
  90511. * A function pointer matching this signature may be passed to
  90512. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90513. * when the encoder needs to know the current position of the output stream.
  90514. *
  90515. * \warning
  90516. * The callback must return the true current byte offset of the output to
  90517. * which the encoder is writing. If you are buffering the output, make
  90518. * sure and take this into account. If you are writing directly to a
  90519. * FILE* from your write callback, ftell() is sufficient. If you are
  90520. * writing directly to a file descriptor from your write callback, you
  90521. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90522. * these points to rewrite metadata after encoding.
  90523. *
  90524. * Here is an example of a tell callback for stdio streams:
  90525. * \code
  90526. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90527. * {
  90528. * FILE *file = ((MyClientData*)client_data)->file;
  90529. * off_t pos;
  90530. * if(file == stdin)
  90531. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90532. * else if((pos = ftello(file)) < 0)
  90533. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90534. * else {
  90535. * *absolute_byte_offset = (FLAC__uint64)pos;
  90536. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90537. * }
  90538. * }
  90539. * \endcode
  90540. *
  90541. * \note In general, FLAC__StreamEncoder functions which change the
  90542. * state should not be called on the \a encoder while in the callback.
  90543. *
  90544. * \param encoder The encoder instance calling the callback.
  90545. * \param absolute_byte_offset The address at which to store the current
  90546. * position of the output.
  90547. * \param client_data The callee's client data set through
  90548. * FLAC__stream_encoder_init_*().
  90549. * \retval FLAC__StreamEncoderTellStatus
  90550. * The callee's return status.
  90551. */
  90552. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90553. /** Signature for the metadata callback.
  90554. *
  90555. * A function pointer matching this signature may be passed to
  90556. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90557. * once at the end of encoding with the populated STREAMINFO structure. This
  90558. * is so the client can seek back to the beginning of the file and write the
  90559. * STREAMINFO block with the correct statistics after encoding (like
  90560. * minimum/maximum frame size and total samples).
  90561. *
  90562. * \note In general, FLAC__StreamEncoder functions which change the
  90563. * state should not be called on the \a encoder while in the callback.
  90564. *
  90565. * \param encoder The encoder instance calling the callback.
  90566. * \param metadata The final populated STREAMINFO block.
  90567. * \param client_data The callee's client data set through
  90568. * FLAC__stream_encoder_init_*().
  90569. */
  90570. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90571. /** Signature for the progress callback.
  90572. *
  90573. * A function pointer matching this signature may be passed to
  90574. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90575. * The supplied function will be called when the encoder has finished
  90576. * writing a frame. The \c total_frames_estimate argument to the
  90577. * callback will be based on the value from
  90578. * FLAC__stream_encoder_set_total_samples_estimate().
  90579. *
  90580. * \note In general, FLAC__StreamEncoder functions which change the
  90581. * state should not be called on the \a encoder while in the callback.
  90582. *
  90583. * \param encoder The encoder instance calling the callback.
  90584. * \param bytes_written Bytes written so far.
  90585. * \param samples_written Samples written so far.
  90586. * \param frames_written Frames written so far.
  90587. * \param total_frames_estimate The estimate of the total number of
  90588. * frames to be written.
  90589. * \param client_data The callee's client data set through
  90590. * FLAC__stream_encoder_init_*().
  90591. */
  90592. 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);
  90593. /***********************************************************************
  90594. *
  90595. * Class constructor/destructor
  90596. *
  90597. ***********************************************************************/
  90598. /** Create a new stream encoder instance. The instance is created with
  90599. * default settings; see the individual FLAC__stream_encoder_set_*()
  90600. * functions for each setting's default.
  90601. *
  90602. * \retval FLAC__StreamEncoder*
  90603. * \c NULL if there was an error allocating memory, else the new instance.
  90604. */
  90605. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90606. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90607. *
  90608. * \param encoder A pointer to an existing encoder.
  90609. * \assert
  90610. * \code encoder != NULL \endcode
  90611. */
  90612. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90613. /***********************************************************************
  90614. *
  90615. * Public class method prototypes
  90616. *
  90617. ***********************************************************************/
  90618. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90619. *
  90620. * \note
  90621. * This does not need to be set for native FLAC encoding.
  90622. *
  90623. * \note
  90624. * It is recommended to set a serial number explicitly as the default of '0'
  90625. * may collide with other streams.
  90626. *
  90627. * \default \c 0
  90628. * \param encoder An encoder instance to set.
  90629. * \param serial_number See above.
  90630. * \assert
  90631. * \code encoder != NULL \endcode
  90632. * \retval FLAC__bool
  90633. * \c false if the encoder is already initialized, else \c true.
  90634. */
  90635. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90636. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90637. * encoded output by feeding it through an internal decoder and comparing
  90638. * the original signal against the decoded signal. If a mismatch occurs,
  90639. * the process call will return \c false. Note that this will slow the
  90640. * encoding process by the extra time required for decoding and comparison.
  90641. *
  90642. * \default \c false
  90643. * \param encoder An encoder instance to set.
  90644. * \param value Flag value (see above).
  90645. * \assert
  90646. * \code encoder != NULL \endcode
  90647. * \retval FLAC__bool
  90648. * \c false if the encoder is already initialized, else \c true.
  90649. */
  90650. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90651. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90652. * the encoder will comply with the Subset and will check the
  90653. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90654. * comply. If \c false, the settings may take advantage of the full
  90655. * range that the format allows.
  90656. *
  90657. * Make sure you know what it entails before setting this to \c false.
  90658. *
  90659. * \default \c true
  90660. * \param encoder An encoder instance to set.
  90661. * \param value Flag value (see above).
  90662. * \assert
  90663. * \code encoder != NULL \endcode
  90664. * \retval FLAC__bool
  90665. * \c false if the encoder is already initialized, else \c true.
  90666. */
  90667. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90668. /** Set the number of channels to be encoded.
  90669. *
  90670. * \default \c 2
  90671. * \param encoder An encoder instance to set.
  90672. * \param value See above.
  90673. * \assert
  90674. * \code encoder != NULL \endcode
  90675. * \retval FLAC__bool
  90676. * \c false if the encoder is already initialized, else \c true.
  90677. */
  90678. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90679. /** Set the sample resolution of the input to be encoded.
  90680. *
  90681. * \warning
  90682. * Do not feed the encoder data that is wider than the value you
  90683. * set here or you will generate an invalid stream.
  90684. *
  90685. * \default \c 16
  90686. * \param encoder An encoder instance to set.
  90687. * \param value See above.
  90688. * \assert
  90689. * \code encoder != NULL \endcode
  90690. * \retval FLAC__bool
  90691. * \c false if the encoder is already initialized, else \c true.
  90692. */
  90693. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90694. /** Set the sample rate (in Hz) of the input to be encoded.
  90695. *
  90696. * \default \c 44100
  90697. * \param encoder An encoder instance to set.
  90698. * \param value See above.
  90699. * \assert
  90700. * \code encoder != NULL \endcode
  90701. * \retval FLAC__bool
  90702. * \c false if the encoder is already initialized, else \c true.
  90703. */
  90704. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90705. /** Set the compression level
  90706. *
  90707. * The compression level is roughly proportional to the amount of effort
  90708. * the encoder expends to compress the file. A higher level usually
  90709. * means more computation but higher compression. The default level is
  90710. * suitable for most applications.
  90711. *
  90712. * Currently the levels range from \c 0 (fastest, least compression) to
  90713. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90714. * treated as \c 8.
  90715. *
  90716. * This function automatically calls the following other \c _set_
  90717. * functions with appropriate values, so the client does not need to
  90718. * unless it specifically wants to override them:
  90719. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90720. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90721. * - FLAC__stream_encoder_set_apodization()
  90722. * - FLAC__stream_encoder_set_max_lpc_order()
  90723. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90724. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90725. * - FLAC__stream_encoder_set_do_escape_coding()
  90726. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90727. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90728. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90729. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90730. *
  90731. * The actual values set for each level are:
  90732. * <table>
  90733. * <tr>
  90734. * <td><b>level</b><td>
  90735. * <td>do mid-side stereo<td>
  90736. * <td>loose mid-side stereo<td>
  90737. * <td>apodization<td>
  90738. * <td>max lpc order<td>
  90739. * <td>qlp coeff precision<td>
  90740. * <td>qlp coeff prec search<td>
  90741. * <td>escape coding<td>
  90742. * <td>exhaustive model search<td>
  90743. * <td>min residual partition order<td>
  90744. * <td>max residual partition order<td>
  90745. * <td>rice parameter search dist<td>
  90746. * </tr>
  90747. * <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>
  90748. * <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>
  90749. * <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>
  90750. * <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>
  90751. * <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>
  90752. * <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>
  90753. * <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>
  90754. * <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>
  90755. * <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>
  90756. * </table>
  90757. *
  90758. * \default \c 5
  90759. * \param encoder An encoder instance to set.
  90760. * \param value See above.
  90761. * \assert
  90762. * \code encoder != NULL \endcode
  90763. * \retval FLAC__bool
  90764. * \c false if the encoder is already initialized, else \c true.
  90765. */
  90766. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90767. /** Set the blocksize to use while encoding.
  90768. *
  90769. * The number of samples to use per frame. Use \c 0 to let the encoder
  90770. * estimate a blocksize; this is usually best.
  90771. *
  90772. * \default \c 0
  90773. * \param encoder An encoder instance to set.
  90774. * \param value See above.
  90775. * \assert
  90776. * \code encoder != NULL \endcode
  90777. * \retval FLAC__bool
  90778. * \c false if the encoder is already initialized, else \c true.
  90779. */
  90780. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90781. /** Set to \c true to enable mid-side encoding on stereo input. The
  90782. * number of channels must be 2 for this to have any effect. Set to
  90783. * \c false to use only independent channel coding.
  90784. *
  90785. * \default \c false
  90786. * \param encoder An encoder instance to set.
  90787. * \param value Flag value (see above).
  90788. * \assert
  90789. * \code encoder != NULL \endcode
  90790. * \retval FLAC__bool
  90791. * \c false if the encoder is already initialized, else \c true.
  90792. */
  90793. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90794. /** Set to \c true to enable adaptive switching between mid-side and
  90795. * left-right encoding on stereo input. Set to \c false to use
  90796. * exhaustive searching. Setting this to \c true requires
  90797. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90798. * \c true in order to have any effect.
  90799. *
  90800. * \default \c false
  90801. * \param encoder An encoder instance to set.
  90802. * \param value Flag value (see above).
  90803. * \assert
  90804. * \code encoder != NULL \endcode
  90805. * \retval FLAC__bool
  90806. * \c false if the encoder is already initialized, else \c true.
  90807. */
  90808. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90809. /** Sets the apodization function(s) the encoder will use when windowing
  90810. * audio data for LPC analysis.
  90811. *
  90812. * The \a specification is a plain ASCII string which specifies exactly
  90813. * which functions to use. There may be more than one (up to 32),
  90814. * separated by \c ';' characters. Some functions take one or more
  90815. * comma-separated arguments in parentheses.
  90816. *
  90817. * The available functions are \c bartlett, \c bartlett_hann,
  90818. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90819. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  90820. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  90821. *
  90822. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  90823. * (0<STDDEV<=0.5).
  90824. *
  90825. * For \c tukey(P), P specifies the fraction of the window that is
  90826. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  90827. * corresponds to \c hann.
  90828. *
  90829. * Example specifications are \c "blackman" or
  90830. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  90831. *
  90832. * Any function that is specified erroneously is silently dropped. Up
  90833. * to 32 functions are kept, the rest are dropped. If the specification
  90834. * is empty the encoder defaults to \c "tukey(0.5)".
  90835. *
  90836. * When more than one function is specified, then for every subframe the
  90837. * encoder will try each of them separately and choose the window that
  90838. * results in the smallest compressed subframe.
  90839. *
  90840. * Note that each function specified causes the encoder to occupy a
  90841. * floating point array in which to store the window.
  90842. *
  90843. * \default \c "tukey(0.5)"
  90844. * \param encoder An encoder instance to set.
  90845. * \param specification See above.
  90846. * \assert
  90847. * \code encoder != NULL \endcode
  90848. * \code specification != NULL \endcode
  90849. * \retval FLAC__bool
  90850. * \c false if the encoder is already initialized, else \c true.
  90851. */
  90852. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  90853. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  90854. *
  90855. * \default \c 0
  90856. * \param encoder An encoder instance to set.
  90857. * \param value See above.
  90858. * \assert
  90859. * \code encoder != NULL \endcode
  90860. * \retval FLAC__bool
  90861. * \c false if the encoder is already initialized, else \c true.
  90862. */
  90863. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  90864. /** Set the precision, in bits, of the quantized linear predictor
  90865. * coefficients, or \c 0 to let the encoder select it based on the
  90866. * blocksize.
  90867. *
  90868. * \note
  90869. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  90870. * be less than 32.
  90871. *
  90872. * \default \c 0
  90873. * \param encoder An encoder instance to set.
  90874. * \param value See above.
  90875. * \assert
  90876. * \code encoder != NULL \endcode
  90877. * \retval FLAC__bool
  90878. * \c false if the encoder is already initialized, else \c true.
  90879. */
  90880. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  90881. /** Set to \c false to use only the specified quantized linear predictor
  90882. * coefficient precision, or \c true to search neighboring precision
  90883. * values and use the best one.
  90884. *
  90885. * \default \c false
  90886. * \param encoder An encoder instance to set.
  90887. * \param value See above.
  90888. * \assert
  90889. * \code encoder != NULL \endcode
  90890. * \retval FLAC__bool
  90891. * \c false if the encoder is already initialized, else \c true.
  90892. */
  90893. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90894. /** Deprecated. Setting this value has no effect.
  90895. *
  90896. * \default \c false
  90897. * \param encoder An encoder instance to set.
  90898. * \param value See above.
  90899. * \assert
  90900. * \code encoder != NULL \endcode
  90901. * \retval FLAC__bool
  90902. * \c false if the encoder is already initialized, else \c true.
  90903. */
  90904. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90905. /** Set to \c false to let the encoder estimate the best model order
  90906. * based on the residual signal energy, or \c true to force the
  90907. * encoder to evaluate all order models and select the best.
  90908. *
  90909. * \default \c false
  90910. * \param encoder An encoder instance to set.
  90911. * \param value See above.
  90912. * \assert
  90913. * \code encoder != NULL \endcode
  90914. * \retval FLAC__bool
  90915. * \c false if the encoder is already initialized, else \c true.
  90916. */
  90917. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90918. /** Set the minimum partition order to search when coding the residual.
  90919. * This is used in tandem with
  90920. * FLAC__stream_encoder_set_max_residual_partition_order().
  90921. *
  90922. * The partition order determines the context size in the residual.
  90923. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90924. *
  90925. * Set both min and max values to \c 0 to force a single context,
  90926. * whose Rice parameter is based on the residual signal variance.
  90927. * Otherwise, set a min and max order, and the encoder will search
  90928. * all orders, using the mean of each context for its Rice parameter,
  90929. * and use the best.
  90930. *
  90931. * \default \c 0
  90932. * \param encoder An encoder instance to set.
  90933. * \param value See above.
  90934. * \assert
  90935. * \code encoder != NULL \endcode
  90936. * \retval FLAC__bool
  90937. * \c false if the encoder is already initialized, else \c true.
  90938. */
  90939. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90940. /** Set the maximum partition order to search when coding the residual.
  90941. * This is used in tandem with
  90942. * FLAC__stream_encoder_set_min_residual_partition_order().
  90943. *
  90944. * The partition order determines the context size in the residual.
  90945. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90946. *
  90947. * Set both min and max values to \c 0 to force a single context,
  90948. * whose Rice parameter is based on the residual signal variance.
  90949. * Otherwise, set a min and max order, and the encoder will search
  90950. * all orders, using the mean of each context for its Rice parameter,
  90951. * and use the best.
  90952. *
  90953. * \default \c 0
  90954. * \param encoder An encoder instance to set.
  90955. * \param value See above.
  90956. * \assert
  90957. * \code encoder != NULL \endcode
  90958. * \retval FLAC__bool
  90959. * \c false if the encoder is already initialized, else \c true.
  90960. */
  90961. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90962. /** Deprecated. Setting this value has no effect.
  90963. *
  90964. * \default \c 0
  90965. * \param encoder An encoder instance to set.
  90966. * \param value See above.
  90967. * \assert
  90968. * \code encoder != NULL \endcode
  90969. * \retval FLAC__bool
  90970. * \c false if the encoder is already initialized, else \c true.
  90971. */
  90972. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  90973. /** Set an estimate of the total samples that will be encoded.
  90974. * This is merely an estimate and may be set to \c 0 if unknown.
  90975. * This value will be written to the STREAMINFO block before encoding,
  90976. * and can remove the need for the caller to rewrite the value later
  90977. * if the value is known before encoding.
  90978. *
  90979. * \default \c 0
  90980. * \param encoder An encoder instance to set.
  90981. * \param value See above.
  90982. * \assert
  90983. * \code encoder != NULL \endcode
  90984. * \retval FLAC__bool
  90985. * \c false if the encoder is already initialized, else \c true.
  90986. */
  90987. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  90988. /** Set the metadata blocks to be emitted to the stream before encoding.
  90989. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  90990. * array of pointers to metadata blocks. The array is non-const since
  90991. * the encoder may need to change the \a is_last flag inside them, and
  90992. * in some cases update seek point offsets. Otherwise, the encoder will
  90993. * not modify or free the blocks. It is up to the caller to free the
  90994. * metadata blocks after encoding finishes.
  90995. *
  90996. * \note
  90997. * The encoder stores only copies of the pointers in the \a metadata array;
  90998. * the metadata blocks themselves must survive at least until after
  90999. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91000. *
  91001. * \note
  91002. * The STREAMINFO block is always written and no STREAMINFO block may
  91003. * occur in the supplied array.
  91004. *
  91005. * \note
  91006. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91007. * in the \a metadata array, but the client has specified that it does not
  91008. * support seeking, then the SEEKTABLE will be written verbatim. However
  91009. * by itself this is not very useful as the client will not know the stream
  91010. * offsets for the seekpoints ahead of time. In order to get a proper
  91011. * seektable the client must support seeking. See next note.
  91012. *
  91013. * \note
  91014. * SEEKTABLE blocks are handled specially. Since you will not know
  91015. * the values for the seek point stream offsets, you should pass in
  91016. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91017. * required sample numbers (or placeholder points), with \c 0 for the
  91018. * \a frame_samples and \a stream_offset fields for each point. If the
  91019. * client has specified that it supports seeking by providing a seek
  91020. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91021. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91022. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91023. * then while it is encoding the encoder will fill the stream offsets in
  91024. * for you and when encoding is finished, it will seek back and write the
  91025. * real values into the SEEKTABLE block in the stream. There are helper
  91026. * routines for manipulating seektable template blocks; see metadata.h:
  91027. * FLAC__metadata_object_seektable_template_*(). If the client does
  91028. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91029. * will slow down or remove the ability to seek in the FLAC stream.
  91030. *
  91031. * \note
  91032. * The encoder instance \b will modify the first \c SEEKTABLE block
  91033. * as it transforms the template to a valid seektable while encoding,
  91034. * but it is still up to the caller to free all metadata blocks after
  91035. * encoding.
  91036. *
  91037. * \note
  91038. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91039. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91040. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91041. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91042. * block is present in the \a metadata array, libFLAC will write an
  91043. * empty one, containing only the vendor string.
  91044. *
  91045. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91046. * the second metadata block of the stream. The encoder already supplies
  91047. * the STREAMINFO block automatically. If \a metadata does not contain a
  91048. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91049. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91050. * first, the init function will reorder \a metadata by moving the
  91051. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91052. * blocks will remain as they were.
  91053. *
  91054. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91055. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91056. * return \c false.
  91057. *
  91058. * \default \c NULL, 0
  91059. * \param encoder An encoder instance to set.
  91060. * \param metadata See above.
  91061. * \param num_blocks See above.
  91062. * \assert
  91063. * \code encoder != NULL \endcode
  91064. * \retval FLAC__bool
  91065. * \c false if the encoder is already initialized, else \c true.
  91066. * \c false if the encoder is already initialized, or if
  91067. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91068. */
  91069. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91070. /** Get the current encoder state.
  91071. *
  91072. * \param encoder An encoder instance to query.
  91073. * \assert
  91074. * \code encoder != NULL \endcode
  91075. * \retval FLAC__StreamEncoderState
  91076. * The current encoder state.
  91077. */
  91078. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91079. /** Get the state of the verify stream decoder.
  91080. * Useful when the stream encoder state is
  91081. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91082. *
  91083. * \param encoder An encoder instance to query.
  91084. * \assert
  91085. * \code encoder != NULL \endcode
  91086. * \retval FLAC__StreamDecoderState
  91087. * The verify stream decoder state.
  91088. */
  91089. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91090. /** Get the current encoder state as a C string.
  91091. * This version automatically resolves
  91092. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91093. * verify decoder's state.
  91094. *
  91095. * \param encoder A encoder instance to query.
  91096. * \assert
  91097. * \code encoder != NULL \endcode
  91098. * \retval const char *
  91099. * The encoder state as a C string. Do not modify the contents.
  91100. */
  91101. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91102. /** Get relevant values about the nature of a verify decoder error.
  91103. * Useful when the stream encoder state is
  91104. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91105. * be addresses in which the stats will be returned, or NULL if value
  91106. * is not desired.
  91107. *
  91108. * \param encoder An encoder instance to query.
  91109. * \param absolute_sample The absolute sample number of the mismatch.
  91110. * \param frame_number The number of the frame in which the mismatch occurred.
  91111. * \param channel The channel in which the mismatch occurred.
  91112. * \param sample The number of the sample (relative to the frame) in
  91113. * which the mismatch occurred.
  91114. * \param expected The expected value for the sample in question.
  91115. * \param got The actual value returned by the decoder.
  91116. * \assert
  91117. * \code encoder != NULL \endcode
  91118. */
  91119. 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);
  91120. /** Get the "verify" flag.
  91121. *
  91122. * \param encoder An encoder instance to query.
  91123. * \assert
  91124. * \code encoder != NULL \endcode
  91125. * \retval FLAC__bool
  91126. * See FLAC__stream_encoder_set_verify().
  91127. */
  91128. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91129. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91130. *
  91131. * \param encoder An encoder instance to query.
  91132. * \assert
  91133. * \code encoder != NULL \endcode
  91134. * \retval FLAC__bool
  91135. * See FLAC__stream_encoder_set_streamable_subset().
  91136. */
  91137. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91138. /** Get the number of input channels being processed.
  91139. *
  91140. * \param encoder An encoder instance to query.
  91141. * \assert
  91142. * \code encoder != NULL \endcode
  91143. * \retval unsigned
  91144. * See FLAC__stream_encoder_set_channels().
  91145. */
  91146. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91147. /** Get the input sample resolution setting.
  91148. *
  91149. * \param encoder An encoder instance to query.
  91150. * \assert
  91151. * \code encoder != NULL \endcode
  91152. * \retval unsigned
  91153. * See FLAC__stream_encoder_set_bits_per_sample().
  91154. */
  91155. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91156. /** Get the input sample rate setting.
  91157. *
  91158. * \param encoder An encoder instance to query.
  91159. * \assert
  91160. * \code encoder != NULL \endcode
  91161. * \retval unsigned
  91162. * See FLAC__stream_encoder_set_sample_rate().
  91163. */
  91164. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91165. /** Get the blocksize setting.
  91166. *
  91167. * \param encoder An encoder instance to query.
  91168. * \assert
  91169. * \code encoder != NULL \endcode
  91170. * \retval unsigned
  91171. * See FLAC__stream_encoder_set_blocksize().
  91172. */
  91173. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91174. /** Get the "mid/side stereo coding" flag.
  91175. *
  91176. * \param encoder An encoder instance to query.
  91177. * \assert
  91178. * \code encoder != NULL \endcode
  91179. * \retval FLAC__bool
  91180. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91181. */
  91182. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91183. /** Get the "adaptive mid/side switching" flag.
  91184. *
  91185. * \param encoder An encoder instance to query.
  91186. * \assert
  91187. * \code encoder != NULL \endcode
  91188. * \retval FLAC__bool
  91189. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91190. */
  91191. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91192. /** Get the maximum LPC order setting.
  91193. *
  91194. * \param encoder An encoder instance to query.
  91195. * \assert
  91196. * \code encoder != NULL \endcode
  91197. * \retval unsigned
  91198. * See FLAC__stream_encoder_set_max_lpc_order().
  91199. */
  91200. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91201. /** Get the quantized linear predictor coefficient precision setting.
  91202. *
  91203. * \param encoder An encoder instance to query.
  91204. * \assert
  91205. * \code encoder != NULL \endcode
  91206. * \retval unsigned
  91207. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91208. */
  91209. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91210. /** Get the qlp coefficient precision search flag.
  91211. *
  91212. * \param encoder An encoder instance to query.
  91213. * \assert
  91214. * \code encoder != NULL \endcode
  91215. * \retval FLAC__bool
  91216. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91217. */
  91218. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91219. /** Get the "escape coding" flag.
  91220. *
  91221. * \param encoder An encoder instance to query.
  91222. * \assert
  91223. * \code encoder != NULL \endcode
  91224. * \retval FLAC__bool
  91225. * See FLAC__stream_encoder_set_do_escape_coding().
  91226. */
  91227. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91228. /** Get the exhaustive model search flag.
  91229. *
  91230. * \param encoder An encoder instance to query.
  91231. * \assert
  91232. * \code encoder != NULL \endcode
  91233. * \retval FLAC__bool
  91234. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91235. */
  91236. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91237. /** Get the minimum residual partition order setting.
  91238. *
  91239. * \param encoder An encoder instance to query.
  91240. * \assert
  91241. * \code encoder != NULL \endcode
  91242. * \retval unsigned
  91243. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91244. */
  91245. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91246. /** Get maximum residual partition order setting.
  91247. *
  91248. * \param encoder An encoder instance to query.
  91249. * \assert
  91250. * \code encoder != NULL \endcode
  91251. * \retval unsigned
  91252. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91253. */
  91254. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91255. /** Get the Rice parameter search distance setting.
  91256. *
  91257. * \param encoder An encoder instance to query.
  91258. * \assert
  91259. * \code encoder != NULL \endcode
  91260. * \retval unsigned
  91261. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91262. */
  91263. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91264. /** Get the previously set estimate of the total samples to be encoded.
  91265. * The encoder merely mimics back the value given to
  91266. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91267. * other way of knowing how many samples the client will encode.
  91268. *
  91269. * \param encoder An encoder instance to set.
  91270. * \assert
  91271. * \code encoder != NULL \endcode
  91272. * \retval FLAC__uint64
  91273. * See FLAC__stream_encoder_get_total_samples_estimate().
  91274. */
  91275. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91276. /** Initialize the encoder instance to encode native FLAC streams.
  91277. *
  91278. * This flavor of initialization sets up the encoder to encode to a
  91279. * native FLAC stream. I/O is performed via callbacks to the client.
  91280. * For encoding to a plain file via filename or open \c FILE*,
  91281. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91282. * provide a simpler interface.
  91283. *
  91284. * This function should be called after FLAC__stream_encoder_new() and
  91285. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91286. * or FLAC__stream_encoder_process_interleaved().
  91287. * initialization succeeded.
  91288. *
  91289. * The call to FLAC__stream_encoder_init_stream() currently will also
  91290. * immediately call the write callback several times, once with the \c fLaC
  91291. * signature, and once for each encoded metadata block.
  91292. *
  91293. * \param encoder An uninitialized encoder instance.
  91294. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91295. * pointer must not be \c NULL.
  91296. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91297. * pointer may be \c NULL if seeking is not
  91298. * supported. The encoder uses seeking to go back
  91299. * and write some some stream statistics to the
  91300. * STREAMINFO block; this is recommended but not
  91301. * necessary to create a valid FLAC stream. If
  91302. * \a seek_callback is not \c NULL then a
  91303. * \a tell_callback must also be supplied.
  91304. * Alternatively, a dummy seek callback that just
  91305. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91306. * may also be supplied, all though this is slightly
  91307. * less efficient for the encoder.
  91308. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91309. * pointer may be \c NULL if seeking is not
  91310. * supported. If \a seek_callback is \c NULL then
  91311. * this argument will be ignored. If
  91312. * \a seek_callback is not \c NULL then a
  91313. * \a tell_callback must also be supplied.
  91314. * Alternatively, a dummy tell callback that just
  91315. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91316. * may also be supplied, all though this is slightly
  91317. * less efficient for the encoder.
  91318. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91319. * pointer may be \c NULL if the callback is not
  91320. * desired. If the client provides a seek callback,
  91321. * this function is not necessary as the encoder
  91322. * will automatically seek back and update the
  91323. * STREAMINFO block. It may also be \c NULL if the
  91324. * client does not support seeking, since it will
  91325. * have no way of going back to update the
  91326. * STREAMINFO. However the client can still supply
  91327. * a callback if it would like to know the details
  91328. * from the STREAMINFO.
  91329. * \param client_data This value will be supplied to callbacks in their
  91330. * \a client_data argument.
  91331. * \assert
  91332. * \code encoder != NULL \endcode
  91333. * \retval FLAC__StreamEncoderInitStatus
  91334. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91335. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91336. */
  91337. 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);
  91338. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91339. *
  91340. * This flavor of initialization sets up the encoder to encode to a FLAC
  91341. * stream in an Ogg container. I/O is performed via callbacks to the
  91342. * client. For encoding to a plain file via filename or open \c FILE*,
  91343. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91344. * provide a simpler interface.
  91345. *
  91346. * This function should be called after FLAC__stream_encoder_new() and
  91347. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91348. * or FLAC__stream_encoder_process_interleaved().
  91349. * initialization succeeded.
  91350. *
  91351. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91352. * immediately call the write callback several times to write the metadata
  91353. * packets.
  91354. *
  91355. * \param encoder An uninitialized encoder instance.
  91356. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91357. * pointer must not be \c NULL if \a seek_callback
  91358. * is non-NULL since they are both needed to be
  91359. * able to write data back to the Ogg FLAC stream
  91360. * in the post-encode phase.
  91361. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91362. * pointer must not be \c NULL.
  91363. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91364. * pointer may be \c NULL if seeking is not
  91365. * supported. The encoder uses seeking to go back
  91366. * and write some some stream statistics to the
  91367. * STREAMINFO block; this is recommended but not
  91368. * necessary to create a valid FLAC stream. If
  91369. * \a seek_callback is not \c NULL then a
  91370. * \a tell_callback must also be supplied.
  91371. * Alternatively, a dummy seek callback that just
  91372. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91373. * may also be supplied, all though this is slightly
  91374. * less efficient for the encoder.
  91375. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91376. * pointer may be \c NULL if seeking is not
  91377. * supported. If \a seek_callback is \c NULL then
  91378. * this argument will be ignored. If
  91379. * \a seek_callback is not \c NULL then a
  91380. * \a tell_callback must also be supplied.
  91381. * Alternatively, a dummy tell callback that just
  91382. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91383. * may also be supplied, all though this is slightly
  91384. * less efficient for the encoder.
  91385. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91386. * pointer may be \c NULL if the callback is not
  91387. * desired. If the client provides a seek callback,
  91388. * this function is not necessary as the encoder
  91389. * will automatically seek back and update the
  91390. * STREAMINFO block. It may also be \c NULL if the
  91391. * client does not support seeking, since it will
  91392. * have no way of going back to update the
  91393. * STREAMINFO. However the client can still supply
  91394. * a callback if it would like to know the details
  91395. * from the STREAMINFO.
  91396. * \param client_data This value will be supplied to callbacks in their
  91397. * \a client_data argument.
  91398. * \assert
  91399. * \code encoder != NULL \endcode
  91400. * \retval FLAC__StreamEncoderInitStatus
  91401. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91402. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91403. */
  91404. 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);
  91405. /** Initialize the encoder instance to encode native FLAC files.
  91406. *
  91407. * This flavor of initialization sets up the encoder to encode to a
  91408. * plain native FLAC file. For non-stdio streams, you must use
  91409. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91410. *
  91411. * This function should be called after FLAC__stream_encoder_new() and
  91412. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91413. * or FLAC__stream_encoder_process_interleaved().
  91414. * initialization succeeded.
  91415. *
  91416. * \param encoder An uninitialized encoder instance.
  91417. * \param file An open file. The file should have been opened
  91418. * with mode \c "w+b" and rewound. The file
  91419. * becomes owned by the encoder and should not be
  91420. * manipulated by the client while encoding.
  91421. * Unless \a file is \c stdout, it will be closed
  91422. * when FLAC__stream_encoder_finish() is called.
  91423. * Note however that a proper SEEKTABLE cannot be
  91424. * created when encoding to \c stdout since it is
  91425. * not seekable.
  91426. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91427. * pointer may be \c NULL if the callback is not
  91428. * desired.
  91429. * \param client_data This value will be supplied to callbacks in their
  91430. * \a client_data argument.
  91431. * \assert
  91432. * \code encoder != NULL \endcode
  91433. * \code file != NULL \endcode
  91434. * \retval FLAC__StreamEncoderInitStatus
  91435. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91436. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91437. */
  91438. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91439. /** Initialize the encoder instance to encode Ogg FLAC files.
  91440. *
  91441. * This flavor of initialization sets up the encoder to encode to a
  91442. * plain Ogg FLAC file. For non-stdio streams, you must use
  91443. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91444. *
  91445. * This function should be called after FLAC__stream_encoder_new() and
  91446. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91447. * or FLAC__stream_encoder_process_interleaved().
  91448. * initialization succeeded.
  91449. *
  91450. * \param encoder An uninitialized encoder instance.
  91451. * \param file An open file. The file should have been opened
  91452. * with mode \c "w+b" and rewound. The file
  91453. * becomes owned by the encoder and should not be
  91454. * manipulated by the client while encoding.
  91455. * Unless \a file is \c stdout, it will be closed
  91456. * when FLAC__stream_encoder_finish() is called.
  91457. * Note however that a proper SEEKTABLE cannot be
  91458. * created when encoding to \c stdout since it is
  91459. * not seekable.
  91460. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91461. * pointer may be \c NULL if the callback is not
  91462. * desired.
  91463. * \param client_data This value will be supplied to callbacks in their
  91464. * \a client_data argument.
  91465. * \assert
  91466. * \code encoder != NULL \endcode
  91467. * \code file != NULL \endcode
  91468. * \retval FLAC__StreamEncoderInitStatus
  91469. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91470. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91471. */
  91472. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91473. /** Initialize the encoder instance to encode native FLAC files.
  91474. *
  91475. * This flavor of initialization sets up the encoder to encode to a plain
  91476. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91477. * with Unicode filenames on Windows), you must use
  91478. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91479. * and provide callbacks for the I/O.
  91480. *
  91481. * This function should be called after FLAC__stream_encoder_new() and
  91482. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91483. * or FLAC__stream_encoder_process_interleaved().
  91484. * initialization succeeded.
  91485. *
  91486. * \param encoder An uninitialized encoder instance.
  91487. * \param filename The name of the file to encode to. The file will
  91488. * be opened with fopen(). Use \c NULL to encode to
  91489. * \c stdout. Note however that a proper SEEKTABLE
  91490. * cannot be created when encoding to \c stdout since
  91491. * it is not seekable.
  91492. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91493. * pointer may be \c NULL if the callback is not
  91494. * desired.
  91495. * \param client_data This value will be supplied to callbacks in their
  91496. * \a client_data argument.
  91497. * \assert
  91498. * \code encoder != NULL \endcode
  91499. * \retval FLAC__StreamEncoderInitStatus
  91500. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91501. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91502. */
  91503. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91504. /** Initialize the encoder instance to encode Ogg FLAC files.
  91505. *
  91506. * This flavor of initialization sets up the encoder to encode to a plain
  91507. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91508. * with Unicode filenames on Windows), you must use
  91509. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91510. * and provide callbacks for the I/O.
  91511. *
  91512. * This function should be called after FLAC__stream_encoder_new() and
  91513. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91514. * or FLAC__stream_encoder_process_interleaved().
  91515. * initialization succeeded.
  91516. *
  91517. * \param encoder An uninitialized encoder instance.
  91518. * \param filename The name of the file to encode to. The file will
  91519. * be opened with fopen(). Use \c NULL to encode to
  91520. * \c stdout. Note however that a proper SEEKTABLE
  91521. * cannot be created when encoding to \c stdout since
  91522. * it is not seekable.
  91523. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91524. * pointer may be \c NULL if the callback is not
  91525. * desired.
  91526. * \param client_data This value will be supplied to callbacks in their
  91527. * \a client_data argument.
  91528. * \assert
  91529. * \code encoder != NULL \endcode
  91530. * \retval FLAC__StreamEncoderInitStatus
  91531. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91532. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91533. */
  91534. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91535. /** Finish the encoding process.
  91536. * Flushes the encoding buffer, releases resources, resets the encoder
  91537. * settings to their defaults, and returns the encoder state to
  91538. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91539. * one or more write callbacks before returning, and will generate
  91540. * a metadata callback.
  91541. *
  91542. * Note that in the course of processing the last frame, errors can
  91543. * occur, so the caller should be sure to check the return value to
  91544. * ensure the file was encoded properly.
  91545. *
  91546. * In the event of a prematurely-terminated encode, it is not strictly
  91547. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91548. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91549. * with a FLAC__stream_encoder_finish().
  91550. *
  91551. * \param encoder An uninitialized encoder instance.
  91552. * \assert
  91553. * \code encoder != NULL \endcode
  91554. * \retval FLAC__bool
  91555. * \c false if an error occurred processing the last frame; or if verify
  91556. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91557. * verify mismatch; else \c true. If \c false, caller should check the
  91558. * state with FLAC__stream_encoder_get_state() for more information
  91559. * about the error.
  91560. */
  91561. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91562. /** Submit data for encoding.
  91563. * This version allows you to supply the input data via an array of
  91564. * pointers, each pointer pointing to an array of \a samples samples
  91565. * representing one channel. The samples need not be block-aligned,
  91566. * but each channel should have the same number of samples. Each sample
  91567. * should be a signed integer, right-justified to the resolution set by
  91568. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91569. * resolution is 16 bits per sample, the samples should all be in the
  91570. * range [-32768,32767].
  91571. *
  91572. * For applications where channel order is important, channels must
  91573. * follow the order as described in the
  91574. * <A HREF="../format.html#frame_header">frame header</A>.
  91575. *
  91576. * \param encoder An initialized encoder instance in the OK state.
  91577. * \param buffer An array of pointers to each channel's signal.
  91578. * \param samples The number of samples in one channel.
  91579. * \assert
  91580. * \code encoder != NULL \endcode
  91581. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91582. * \retval FLAC__bool
  91583. * \c true if successful, else \c false; in this case, check the
  91584. * encoder state with FLAC__stream_encoder_get_state() to see what
  91585. * went wrong.
  91586. */
  91587. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91588. /** Submit data for encoding.
  91589. * This version allows you to supply the input data where the channels
  91590. * are interleaved into a single array (i.e. channel0_sample0,
  91591. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91592. * The samples need not be block-aligned but they must be
  91593. * sample-aligned, i.e. the first value should be channel0_sample0
  91594. * and the last value channelN_sampleM. Each sample should be a signed
  91595. * integer, right-justified to the resolution set by
  91596. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91597. * resolution is 16 bits per sample, the samples should all be in the
  91598. * range [-32768,32767].
  91599. *
  91600. * For applications where channel order is important, channels must
  91601. * follow the order as described in the
  91602. * <A HREF="../format.html#frame_header">frame header</A>.
  91603. *
  91604. * \param encoder An initialized encoder instance in the OK state.
  91605. * \param buffer An array of channel-interleaved data (see above).
  91606. * \param samples The number of samples in one channel, the same as for
  91607. * FLAC__stream_encoder_process(). For example, if
  91608. * encoding two channels, \c 1000 \a samples corresponds
  91609. * to a \a buffer of 2000 values.
  91610. * \assert
  91611. * \code encoder != NULL \endcode
  91612. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91613. * \retval FLAC__bool
  91614. * \c true if successful, else \c false; in this case, check the
  91615. * encoder state with FLAC__stream_encoder_get_state() to see what
  91616. * went wrong.
  91617. */
  91618. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91619. /* \} */
  91620. #ifdef __cplusplus
  91621. }
  91622. #endif
  91623. #endif
  91624. /*** End of inlined file: stream_encoder.h ***/
  91625. #ifdef _MSC_VER
  91626. /* OPT: an MSVC built-in would be better */
  91627. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91628. {
  91629. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91630. return (x>>16) | (x<<16);
  91631. }
  91632. #endif
  91633. #if defined(_MSC_VER) && defined(_X86_)
  91634. /* OPT: an MSVC built-in would be better */
  91635. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91636. {
  91637. __asm {
  91638. mov edx, start
  91639. mov ecx, len
  91640. test ecx, ecx
  91641. loop1:
  91642. jz done1
  91643. mov eax, [edx]
  91644. bswap eax
  91645. mov [edx], eax
  91646. add edx, 4
  91647. dec ecx
  91648. jmp short loop1
  91649. done1:
  91650. }
  91651. }
  91652. #endif
  91653. /** \mainpage
  91654. *
  91655. * \section intro Introduction
  91656. *
  91657. * This is the documentation for the FLAC C and C++ APIs. It is
  91658. * highly interconnected; this introduction should give you a top
  91659. * level idea of the structure and how to find the information you
  91660. * need. As a prerequisite you should have at least a basic
  91661. * knowledge of the FLAC format, documented
  91662. * <A HREF="../format.html">here</A>.
  91663. *
  91664. * \section c_api FLAC C API
  91665. *
  91666. * The FLAC C API is the interface to libFLAC, a set of structures
  91667. * describing the components of FLAC streams, and functions for
  91668. * encoding and decoding streams, as well as manipulating FLAC
  91669. * metadata in files. The public include files will be installed
  91670. * in your include area (for example /usr/include/FLAC/...).
  91671. *
  91672. * By writing a little code and linking against libFLAC, it is
  91673. * relatively easy to add FLAC support to another program. The
  91674. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91675. * Complete source code of libFLAC as well as the command-line
  91676. * encoder and plugins is available and is a useful source of
  91677. * examples.
  91678. *
  91679. * Aside from encoders and decoders, libFLAC provides a powerful
  91680. * metadata interface for manipulating metadata in FLAC files. It
  91681. * allows the user to add, delete, and modify FLAC metadata blocks
  91682. * and it can automatically take advantage of PADDING blocks to avoid
  91683. * rewriting the entire FLAC file when changing the size of the
  91684. * metadata.
  91685. *
  91686. * libFLAC usually only requires the standard C library and C math
  91687. * library. In particular, threading is not used so there is no
  91688. * dependency on a thread library. However, libFLAC does not use
  91689. * global variables and should be thread-safe.
  91690. *
  91691. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91692. * However the metadata editing interfaces currently have limited
  91693. * read-only support for Ogg FLAC files.
  91694. *
  91695. * \section cpp_api FLAC C++ API
  91696. *
  91697. * The FLAC C++ API is a set of classes that encapsulate the
  91698. * structures and functions in libFLAC. They provide slightly more
  91699. * functionality with respect to metadata but are otherwise
  91700. * equivalent. For the most part, they share the same usage as
  91701. * their counterparts in libFLAC, and the FLAC C API documentation
  91702. * can be used as a supplement. The public include files
  91703. * for the C++ API will be installed in your include area (for
  91704. * example /usr/include/FLAC++/...).
  91705. *
  91706. * libFLAC++ is also licensed under
  91707. * <A HREF="../license.html">Xiph's BSD license</A>.
  91708. *
  91709. * \section getting_started Getting Started
  91710. *
  91711. * A good starting point for learning the API is to browse through
  91712. * the <A HREF="modules.html">modules</A>. Modules are logical
  91713. * groupings of related functions or classes, which correspond roughly
  91714. * to header files or sections of header files. Each module includes a
  91715. * detailed description of the general usage of its functions or
  91716. * classes.
  91717. *
  91718. * From there you can go on to look at the documentation of
  91719. * individual functions. You can see different views of the individual
  91720. * functions through the links in top bar across this page.
  91721. *
  91722. * If you prefer a more hands-on approach, you can jump right to some
  91723. * <A HREF="../documentation_example_code.html">example code</A>.
  91724. *
  91725. * \section porting_guide Porting Guide
  91726. *
  91727. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91728. * has been introduced which gives detailed instructions on how to
  91729. * port your code to newer versions of FLAC.
  91730. *
  91731. * \section embedded_developers Embedded Developers
  91732. *
  91733. * libFLAC has grown larger over time as more functionality has been
  91734. * included, but much of it may be unnecessary for a particular embedded
  91735. * implementation. Unused parts may be pruned by some simple editing of
  91736. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91737. * metadata interface are all independent from each other.
  91738. *
  91739. * It is easiest to just describe the dependencies:
  91740. *
  91741. * - All modules depend on the \link flac_format Format \endlink module.
  91742. * - The decoders and encoders depend on the bitbuffer.
  91743. * - The decoder is independent of the encoder. The encoder uses the
  91744. * decoder because of the verify feature, but this can be removed if
  91745. * not needed.
  91746. * - Parts of the metadata interface require the stream decoder (but not
  91747. * the encoder).
  91748. * - Ogg support is selectable through the compile time macro
  91749. * \c FLAC__HAS_OGG.
  91750. *
  91751. * For example, if your application only requires the stream decoder, no
  91752. * encoder, and no metadata interface, you can remove the stream encoder
  91753. * and the metadata interface, which will greatly reduce the size of the
  91754. * library.
  91755. *
  91756. * Also, there are several places in the libFLAC code with comments marked
  91757. * with "OPT:" where a #define can be changed to enable code that might be
  91758. * faster on a specific platform. Experimenting with these can yield faster
  91759. * binaries.
  91760. */
  91761. /** \defgroup porting Porting Guide for New Versions
  91762. *
  91763. * This module describes differences in the library interfaces from
  91764. * version to version. It assists in the porting of code that uses
  91765. * the libraries to newer versions of FLAC.
  91766. *
  91767. * One simple facility for making porting easier that has been added
  91768. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91769. * library's includes (e.g. \c include/FLAC/export.h). The
  91770. * \c #defines mirror the libraries'
  91771. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91772. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91773. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91774. * These can be used to support multiple versions of an API during the
  91775. * transition phase, e.g.
  91776. *
  91777. * \code
  91778. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91779. * legacy code
  91780. * #else
  91781. * new code
  91782. * #endif
  91783. * \endcode
  91784. *
  91785. * The the source will work for multiple versions and the legacy code can
  91786. * easily be removed when the transition is complete.
  91787. *
  91788. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91789. * include/FLAC/export.h), which can be used to determine whether or not
  91790. * the library has been compiled with support for Ogg FLAC. This is
  91791. * simpler than trying to call an Ogg init function and catching the
  91792. * error.
  91793. */
  91794. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91795. * \ingroup porting
  91796. *
  91797. * \brief
  91798. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91799. *
  91800. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91801. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91802. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91803. * decoding layers and three encoding layers have been merged into a
  91804. * single stream decoder and stream encoder. That is, the functionality
  91805. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91806. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91807. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91808. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91809. * is there is now a single API that can be used to encode or decode
  91810. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91811. * on both seekable and non-seekable streams.
  91812. *
  91813. * Instead of creating an encoder or decoder of a certain layer, now the
  91814. * client will always create a FLAC__StreamEncoder or
  91815. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91816. * initialization function. For example, for the decoder,
  91817. * FLAC__stream_decoder_init() has been replaced by
  91818. * FLAC__stream_decoder_init_stream(). This init function takes
  91819. * callbacks for the I/O, and the seeking callbacks are optional. This
  91820. * allows the client to use the same object for seekable and
  91821. * non-seekable streams. For decoding a FLAC file directly, the client
  91822. * can use FLAC__stream_decoder_init_file() and pass just a filename
  91823. * and fewer callbacks; most of the other callbacks are supplied
  91824. * internally. For situations where fopen()ing by filename is not
  91825. * possible (e.g. Unicode filenames on Windows) the client can instead
  91826. * open the file itself and supply the FILE* to
  91827. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  91828. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  91829. * Since the callbacks and client data are now passed to the init
  91830. * function, the FLAC__stream_decoder_set_*_callback() functions and
  91831. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  91832. * rest of the calls to the decoder are the same as before.
  91833. *
  91834. * There are counterpart init functions for Ogg FLAC, e.g.
  91835. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  91836. * and callbacks are the same as for native FLAC.
  91837. *
  91838. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  91839. * been set up like so:
  91840. *
  91841. * \code
  91842. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  91843. * if(decoder == NULL) do_something;
  91844. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  91845. * [... other settings ...]
  91846. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  91847. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  91848. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  91849. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  91850. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  91851. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  91852. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  91853. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  91854. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  91855. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  91856. * \endcode
  91857. *
  91858. * In FLAC 1.1.3 it is like this:
  91859. *
  91860. * \code
  91861. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  91862. * if(decoder == NULL) do_something;
  91863. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  91864. * [... other settings ...]
  91865. * if(FLAC__stream_decoder_init_stream(
  91866. * decoder,
  91867. * my_read_callback,
  91868. * my_seek_callback, // or NULL
  91869. * my_tell_callback, // or NULL
  91870. * my_length_callback, // or NULL
  91871. * my_eof_callback, // or NULL
  91872. * my_write_callback,
  91873. * my_metadata_callback, // or NULL
  91874. * my_error_callback,
  91875. * my_client_data
  91876. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91877. * \endcode
  91878. *
  91879. * or you could do;
  91880. *
  91881. * \code
  91882. * [...]
  91883. * FILE *file = fopen("somefile.flac","rb");
  91884. * if(file == NULL) do_somthing;
  91885. * if(FLAC__stream_decoder_init_FILE(
  91886. * decoder,
  91887. * file,
  91888. * my_write_callback,
  91889. * my_metadata_callback, // or NULL
  91890. * my_error_callback,
  91891. * my_client_data
  91892. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91893. * \endcode
  91894. *
  91895. * or just:
  91896. *
  91897. * \code
  91898. * [...]
  91899. * if(FLAC__stream_decoder_init_file(
  91900. * decoder,
  91901. * "somefile.flac",
  91902. * my_write_callback,
  91903. * my_metadata_callback, // or NULL
  91904. * my_error_callback,
  91905. * my_client_data
  91906. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91907. * \endcode
  91908. *
  91909. * Another small change to the decoder is in how it handles unparseable
  91910. * streams. Before, when the decoder found an unparseable stream
  91911. * (reserved for when the decoder encounters a stream from a future
  91912. * encoder that it can't parse), it changed the state to
  91913. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  91914. * drops sync and calls the error callback with a new error code
  91915. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  91916. * more robust. If your error callback does not discriminate on the the
  91917. * error state, your code does not need to be changed.
  91918. *
  91919. * The encoder now has a new setting:
  91920. * FLAC__stream_encoder_set_apodization(). This is for setting the
  91921. * method used to window the data before LPC analysis. You only need to
  91922. * add a call to this function if the default is not suitable. There
  91923. * are also two new convenience functions that may be useful:
  91924. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  91925. * FLAC__metadata_get_cuesheet().
  91926. *
  91927. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  91928. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  91929. * is now \c size_t instead of \c unsigned.
  91930. */
  91931. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  91932. * \ingroup porting
  91933. *
  91934. * \brief
  91935. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  91936. *
  91937. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  91938. * There was a slight change in the implementation of
  91939. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  91940. * of the \a metadata array of pointers so the client no longer needs
  91941. * to maintain it after the call. The objects themselves that are
  91942. * pointed to by the array are still not copied though and must be
  91943. * maintained until the call to FLAC__stream_encoder_finish().
  91944. */
  91945. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  91946. * \ingroup porting
  91947. *
  91948. * \brief
  91949. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  91950. *
  91951. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  91952. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  91953. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  91954. *
  91955. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  91956. * has changed to reflect the conversion of one of the reserved bits
  91957. * into active use. It used to be \c 2 and now is \c 1. However the
  91958. * FLAC frame header length has not changed, so to skip the proper
  91959. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  91960. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  91961. */
  91962. /** \defgroup flac FLAC C API
  91963. *
  91964. * The FLAC C API is the interface to libFLAC, a set of structures
  91965. * describing the components of FLAC streams, and functions for
  91966. * encoding and decoding streams, as well as manipulating FLAC
  91967. * metadata in files.
  91968. *
  91969. * You should start with the format components as all other modules
  91970. * are dependent on it.
  91971. */
  91972. #endif
  91973. /*** End of inlined file: all.h ***/
  91974. /*** Start of inlined file: bitmath.c ***/
  91975. /*** Start of inlined file: juce_FlacHeader.h ***/
  91976. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91977. // tasks..
  91978. #define VERSION "1.2.1"
  91979. #define FLAC__NO_DLL 1
  91980. #if JUCE_MSVC
  91981. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91982. #endif
  91983. #if JUCE_MAC
  91984. #define FLAC__SYS_DARWIN 1
  91985. #endif
  91986. /*** End of inlined file: juce_FlacHeader.h ***/
  91987. #if JUCE_USE_FLAC
  91988. #if HAVE_CONFIG_H
  91989. # include <config.h>
  91990. #endif
  91991. /*** Start of inlined file: bitmath.h ***/
  91992. #ifndef FLAC__PRIVATE__BITMATH_H
  91993. #define FLAC__PRIVATE__BITMATH_H
  91994. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  91995. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  91996. unsigned FLAC__bitmath_silog2(int v);
  91997. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  91998. #endif
  91999. /*** End of inlined file: bitmath.h ***/
  92000. /* An example of what FLAC__bitmath_ilog2() computes:
  92001. *
  92002. * ilog2( 0) = assertion failure
  92003. * ilog2( 1) = 0
  92004. * ilog2( 2) = 1
  92005. * ilog2( 3) = 1
  92006. * ilog2( 4) = 2
  92007. * ilog2( 5) = 2
  92008. * ilog2( 6) = 2
  92009. * ilog2( 7) = 2
  92010. * ilog2( 8) = 3
  92011. * ilog2( 9) = 3
  92012. * ilog2(10) = 3
  92013. * ilog2(11) = 3
  92014. * ilog2(12) = 3
  92015. * ilog2(13) = 3
  92016. * ilog2(14) = 3
  92017. * ilog2(15) = 3
  92018. * ilog2(16) = 4
  92019. * ilog2(17) = 4
  92020. * ilog2(18) = 4
  92021. */
  92022. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92023. {
  92024. unsigned l = 0;
  92025. FLAC__ASSERT(v > 0);
  92026. while(v >>= 1)
  92027. l++;
  92028. return l;
  92029. }
  92030. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92031. {
  92032. unsigned l = 0;
  92033. FLAC__ASSERT(v > 0);
  92034. while(v >>= 1)
  92035. l++;
  92036. return l;
  92037. }
  92038. /* An example of what FLAC__bitmath_silog2() computes:
  92039. *
  92040. * silog2(-10) = 5
  92041. * silog2(- 9) = 5
  92042. * silog2(- 8) = 4
  92043. * silog2(- 7) = 4
  92044. * silog2(- 6) = 4
  92045. * silog2(- 5) = 4
  92046. * silog2(- 4) = 3
  92047. * silog2(- 3) = 3
  92048. * silog2(- 2) = 2
  92049. * silog2(- 1) = 2
  92050. * silog2( 0) = 0
  92051. * silog2( 1) = 2
  92052. * silog2( 2) = 3
  92053. * silog2( 3) = 3
  92054. * silog2( 4) = 4
  92055. * silog2( 5) = 4
  92056. * silog2( 6) = 4
  92057. * silog2( 7) = 4
  92058. * silog2( 8) = 5
  92059. * silog2( 9) = 5
  92060. * silog2( 10) = 5
  92061. */
  92062. unsigned FLAC__bitmath_silog2(int v)
  92063. {
  92064. while(1) {
  92065. if(v == 0) {
  92066. return 0;
  92067. }
  92068. else if(v > 0) {
  92069. unsigned l = 0;
  92070. while(v) {
  92071. l++;
  92072. v >>= 1;
  92073. }
  92074. return l+1;
  92075. }
  92076. else if(v == -1) {
  92077. return 2;
  92078. }
  92079. else {
  92080. v++;
  92081. v = -v;
  92082. }
  92083. }
  92084. }
  92085. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92086. {
  92087. while(1) {
  92088. if(v == 0) {
  92089. return 0;
  92090. }
  92091. else if(v > 0) {
  92092. unsigned l = 0;
  92093. while(v) {
  92094. l++;
  92095. v >>= 1;
  92096. }
  92097. return l+1;
  92098. }
  92099. else if(v == -1) {
  92100. return 2;
  92101. }
  92102. else {
  92103. v++;
  92104. v = -v;
  92105. }
  92106. }
  92107. }
  92108. #endif
  92109. /*** End of inlined file: bitmath.c ***/
  92110. /*** Start of inlined file: bitreader.c ***/
  92111. /*** Start of inlined file: juce_FlacHeader.h ***/
  92112. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92113. // tasks..
  92114. #define VERSION "1.2.1"
  92115. #define FLAC__NO_DLL 1
  92116. #if JUCE_MSVC
  92117. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92118. #endif
  92119. #if JUCE_MAC
  92120. #define FLAC__SYS_DARWIN 1
  92121. #endif
  92122. /*** End of inlined file: juce_FlacHeader.h ***/
  92123. #if JUCE_USE_FLAC
  92124. #if HAVE_CONFIG_H
  92125. # include <config.h>
  92126. #endif
  92127. #include <stdlib.h> /* for malloc() */
  92128. #include <string.h> /* for memcpy(), memset() */
  92129. #ifdef _MSC_VER
  92130. #include <winsock.h> /* for ntohl() */
  92131. #elif defined FLAC__SYS_DARWIN
  92132. #include <machine/endian.h> /* for ntohl() */
  92133. #elif defined __MINGW32__
  92134. #include <winsock.h> /* for ntohl() */
  92135. #else
  92136. #include <netinet/in.h> /* for ntohl() */
  92137. #endif
  92138. /*** Start of inlined file: bitreader.h ***/
  92139. #ifndef FLAC__PRIVATE__BITREADER_H
  92140. #define FLAC__PRIVATE__BITREADER_H
  92141. #include <stdio.h> /* for FILE */
  92142. /*** Start of inlined file: cpu.h ***/
  92143. #ifndef FLAC__PRIVATE__CPU_H
  92144. #define FLAC__PRIVATE__CPU_H
  92145. #ifdef HAVE_CONFIG_H
  92146. #include <config.h>
  92147. #endif
  92148. typedef enum {
  92149. FLAC__CPUINFO_TYPE_IA32,
  92150. FLAC__CPUINFO_TYPE_PPC,
  92151. FLAC__CPUINFO_TYPE_UNKNOWN
  92152. } FLAC__CPUInfo_Type;
  92153. typedef struct {
  92154. FLAC__bool cpuid;
  92155. FLAC__bool bswap;
  92156. FLAC__bool cmov;
  92157. FLAC__bool mmx;
  92158. FLAC__bool fxsr;
  92159. FLAC__bool sse;
  92160. FLAC__bool sse2;
  92161. FLAC__bool sse3;
  92162. FLAC__bool ssse3;
  92163. FLAC__bool _3dnow;
  92164. FLAC__bool ext3dnow;
  92165. FLAC__bool extmmx;
  92166. } FLAC__CPUInfo_IA32;
  92167. typedef struct {
  92168. FLAC__bool altivec;
  92169. FLAC__bool ppc64;
  92170. } FLAC__CPUInfo_PPC;
  92171. typedef struct {
  92172. FLAC__bool use_asm;
  92173. FLAC__CPUInfo_Type type;
  92174. union {
  92175. FLAC__CPUInfo_IA32 ia32;
  92176. FLAC__CPUInfo_PPC ppc;
  92177. } data;
  92178. } FLAC__CPUInfo;
  92179. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92180. #ifndef FLAC__NO_ASM
  92181. #ifdef FLAC__CPU_IA32
  92182. #ifdef FLAC__HAS_NASM
  92183. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92184. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92185. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92186. #endif
  92187. #endif
  92188. #endif
  92189. #endif
  92190. /*** End of inlined file: cpu.h ***/
  92191. /*
  92192. * opaque structure definition
  92193. */
  92194. struct FLAC__BitReader;
  92195. typedef struct FLAC__BitReader FLAC__BitReader;
  92196. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92197. /*
  92198. * construction, deletion, initialization, etc functions
  92199. */
  92200. FLAC__BitReader *FLAC__bitreader_new(void);
  92201. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92202. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92203. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92204. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92205. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92206. /*
  92207. * CRC functions
  92208. */
  92209. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92210. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92211. /*
  92212. * info functions
  92213. */
  92214. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92215. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92216. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92217. /*
  92218. * read functions
  92219. */
  92220. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92221. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92222. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92223. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92224. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92225. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92226. 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! */
  92227. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92228. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92229. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92230. #ifndef FLAC__NO_ASM
  92231. # ifdef FLAC__CPU_IA32
  92232. # ifdef FLAC__HAS_NASM
  92233. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92234. # endif
  92235. # endif
  92236. #endif
  92237. #if 0 /* UNUSED */
  92238. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92239. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92240. #endif
  92241. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92242. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92243. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92244. #endif
  92245. /*** End of inlined file: bitreader.h ***/
  92246. /*** Start of inlined file: crc.h ***/
  92247. #ifndef FLAC__PRIVATE__CRC_H
  92248. #define FLAC__PRIVATE__CRC_H
  92249. /* 8 bit CRC generator, MSB shifted first
  92250. ** polynomial = x^8 + x^2 + x^1 + x^0
  92251. ** init = 0
  92252. */
  92253. extern FLAC__byte const FLAC__crc8_table[256];
  92254. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92255. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92256. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92257. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92258. /* 16 bit CRC generator, MSB shifted first
  92259. ** polynomial = x^16 + x^15 + x^2 + x^0
  92260. ** init = 0
  92261. */
  92262. extern unsigned FLAC__crc16_table[256];
  92263. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92264. /* this alternate may be faster on some systems/compilers */
  92265. #if 0
  92266. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92267. #endif
  92268. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92269. #endif
  92270. /*** End of inlined file: crc.h ***/
  92271. /* Things should be fastest when this matches the machine word size */
  92272. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92273. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92274. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92275. typedef FLAC__uint32 brword;
  92276. #define FLAC__BYTES_PER_WORD 4
  92277. #define FLAC__BITS_PER_WORD 32
  92278. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92279. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92280. #if WORDS_BIGENDIAN
  92281. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92282. #else
  92283. #if defined (_MSC_VER) && defined (_X86_)
  92284. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92285. #else
  92286. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92287. #endif
  92288. #endif
  92289. /* counts the # of zero MSBs in a word */
  92290. #define COUNT_ZERO_MSBS(word) ( \
  92291. (word) <= 0xffff ? \
  92292. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92293. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92294. )
  92295. /* this alternate might be slightly faster on some systems/compilers: */
  92296. #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])) )
  92297. /*
  92298. * This should be at least twice as large as the largest number of words
  92299. * required to represent any 'number' (in any encoding) you are going to
  92300. * read. With FLAC this is on the order of maybe a few hundred bits.
  92301. * If the buffer is smaller than that, the decoder won't be able to read
  92302. * in a whole number that is in a variable length encoding (e.g. Rice).
  92303. * But to be practical it should be at least 1K bytes.
  92304. *
  92305. * Increase this number to decrease the number of read callbacks, at the
  92306. * expense of using more memory. Or decrease for the reverse effect,
  92307. * keeping in mind the limit from the first paragraph. The optimal size
  92308. * also depends on the CPU cache size and other factors; some twiddling
  92309. * may be necessary to squeeze out the best performance.
  92310. */
  92311. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92312. static const unsigned char byte_to_unary_table[] = {
  92313. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92314. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92315. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92316. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92317. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92318. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92319. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92320. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92329. };
  92330. #ifdef min
  92331. #undef min
  92332. #endif
  92333. #define min(x,y) ((x)<(y)?(x):(y))
  92334. #ifdef max
  92335. #undef max
  92336. #endif
  92337. #define max(x,y) ((x)>(y)?(x):(y))
  92338. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92339. #ifdef _MSC_VER
  92340. #define FLAC__U64L(x) x
  92341. #else
  92342. #define FLAC__U64L(x) x##LLU
  92343. #endif
  92344. #ifndef FLaC__INLINE
  92345. #define FLaC__INLINE
  92346. #endif
  92347. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92348. struct FLAC__BitReader {
  92349. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92350. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92351. brword *buffer;
  92352. unsigned capacity; /* in words */
  92353. unsigned words; /* # of completed words in buffer */
  92354. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92355. unsigned consumed_words; /* #words ... */
  92356. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92357. unsigned read_crc16; /* the running frame CRC */
  92358. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92359. FLAC__BitReaderReadCallback read_callback;
  92360. void *client_data;
  92361. FLAC__CPUInfo cpu_info;
  92362. };
  92363. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92364. {
  92365. register unsigned crc = br->read_crc16;
  92366. #if FLAC__BYTES_PER_WORD == 4
  92367. switch(br->crc16_align) {
  92368. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92369. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92370. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92371. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92372. }
  92373. #elif FLAC__BYTES_PER_WORD == 8
  92374. switch(br->crc16_align) {
  92375. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92376. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92377. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92378. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92379. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92380. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92381. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92382. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92383. }
  92384. #else
  92385. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92386. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92387. br->read_crc16 = crc;
  92388. #endif
  92389. br->crc16_align = 0;
  92390. }
  92391. /* would be static except it needs to be called by asm routines */
  92392. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92393. {
  92394. unsigned start, end;
  92395. size_t bytes;
  92396. FLAC__byte *target;
  92397. /* first shift the unconsumed buffer data toward the front as much as possible */
  92398. if(br->consumed_words > 0) {
  92399. start = br->consumed_words;
  92400. end = br->words + (br->bytes? 1:0);
  92401. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92402. br->words -= start;
  92403. br->consumed_words = 0;
  92404. }
  92405. /*
  92406. * set the target for reading, taking into account word alignment and endianness
  92407. */
  92408. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92409. if(bytes == 0)
  92410. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92411. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92412. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92413. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92414. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92415. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92416. * ^^-------target, bytes=3
  92417. * on LE machines, have to byteswap the odd tail word so nothing is
  92418. * overwritten:
  92419. */
  92420. #if WORDS_BIGENDIAN
  92421. #else
  92422. if(br->bytes)
  92423. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92424. #endif
  92425. /* now it looks like:
  92426. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92427. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92428. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92429. * ^^-------target, bytes=3
  92430. */
  92431. /* read in the data; note that the callback may return a smaller number of bytes */
  92432. if(!br->read_callback(target, &bytes, br->client_data))
  92433. return false;
  92434. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92435. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92436. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92437. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92438. * now have to byteswap on LE machines:
  92439. */
  92440. #if WORDS_BIGENDIAN
  92441. #else
  92442. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92443. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92444. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92445. start = br->words;
  92446. local_swap32_block_(br->buffer + start, end - start);
  92447. }
  92448. else
  92449. # endif
  92450. for(start = br->words; start < end; start++)
  92451. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92452. #endif
  92453. /* now it looks like:
  92454. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92455. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92456. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92457. * finally we'll update the reader values:
  92458. */
  92459. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92460. br->words = end / FLAC__BYTES_PER_WORD;
  92461. br->bytes = end % FLAC__BYTES_PER_WORD;
  92462. return true;
  92463. }
  92464. /***********************************************************************
  92465. *
  92466. * Class constructor/destructor
  92467. *
  92468. ***********************************************************************/
  92469. FLAC__BitReader *FLAC__bitreader_new(void)
  92470. {
  92471. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92472. /* calloc() implies:
  92473. memset(br, 0, sizeof(FLAC__BitReader));
  92474. br->buffer = 0;
  92475. br->capacity = 0;
  92476. br->words = br->bytes = 0;
  92477. br->consumed_words = br->consumed_bits = 0;
  92478. br->read_callback = 0;
  92479. br->client_data = 0;
  92480. */
  92481. return br;
  92482. }
  92483. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92484. {
  92485. FLAC__ASSERT(0 != br);
  92486. FLAC__bitreader_free(br);
  92487. free(br);
  92488. }
  92489. /***********************************************************************
  92490. *
  92491. * Public class methods
  92492. *
  92493. ***********************************************************************/
  92494. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92495. {
  92496. FLAC__ASSERT(0 != br);
  92497. br->words = br->bytes = 0;
  92498. br->consumed_words = br->consumed_bits = 0;
  92499. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92500. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92501. if(br->buffer == 0)
  92502. return false;
  92503. br->read_callback = rcb;
  92504. br->client_data = cd;
  92505. br->cpu_info = cpu;
  92506. return true;
  92507. }
  92508. void FLAC__bitreader_free(FLAC__BitReader *br)
  92509. {
  92510. FLAC__ASSERT(0 != br);
  92511. if(0 != br->buffer)
  92512. free(br->buffer);
  92513. br->buffer = 0;
  92514. br->capacity = 0;
  92515. br->words = br->bytes = 0;
  92516. br->consumed_words = br->consumed_bits = 0;
  92517. br->read_callback = 0;
  92518. br->client_data = 0;
  92519. }
  92520. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92521. {
  92522. br->words = br->bytes = 0;
  92523. br->consumed_words = br->consumed_bits = 0;
  92524. return true;
  92525. }
  92526. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92527. {
  92528. unsigned i, j;
  92529. if(br == 0) {
  92530. fprintf(out, "bitreader is NULL\n");
  92531. }
  92532. else {
  92533. 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);
  92534. for(i = 0; i < br->words; i++) {
  92535. fprintf(out, "%08X: ", i);
  92536. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92537. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92538. fprintf(out, ".");
  92539. else
  92540. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92541. fprintf(out, "\n");
  92542. }
  92543. if(br->bytes > 0) {
  92544. fprintf(out, "%08X: ", i);
  92545. for(j = 0; j < br->bytes*8; j++)
  92546. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92547. fprintf(out, ".");
  92548. else
  92549. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92550. fprintf(out, "\n");
  92551. }
  92552. }
  92553. }
  92554. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92555. {
  92556. FLAC__ASSERT(0 != br);
  92557. FLAC__ASSERT(0 != br->buffer);
  92558. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92559. br->read_crc16 = (unsigned)seed;
  92560. br->crc16_align = br->consumed_bits;
  92561. }
  92562. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92563. {
  92564. FLAC__ASSERT(0 != br);
  92565. FLAC__ASSERT(0 != br->buffer);
  92566. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92567. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92568. /* CRC any tail bytes in a partially-consumed word */
  92569. if(br->consumed_bits) {
  92570. const brword tail = br->buffer[br->consumed_words];
  92571. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92572. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92573. }
  92574. return br->read_crc16;
  92575. }
  92576. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92577. {
  92578. return ((br->consumed_bits & 7) == 0);
  92579. }
  92580. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92581. {
  92582. return 8 - (br->consumed_bits & 7);
  92583. }
  92584. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92585. {
  92586. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92587. }
  92588. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92589. {
  92590. FLAC__ASSERT(0 != br);
  92591. FLAC__ASSERT(0 != br->buffer);
  92592. FLAC__ASSERT(bits <= 32);
  92593. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92594. FLAC__ASSERT(br->consumed_words <= br->words);
  92595. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92596. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92597. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92598. *val = 0;
  92599. return true;
  92600. }
  92601. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92602. if(!bitreader_read_from_client_(br))
  92603. return false;
  92604. }
  92605. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92606. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92607. if(br->consumed_bits) {
  92608. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92609. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92610. const brword word = br->buffer[br->consumed_words];
  92611. if(bits < n) {
  92612. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92613. br->consumed_bits += bits;
  92614. return true;
  92615. }
  92616. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92617. bits -= n;
  92618. crc16_update_word_(br, word);
  92619. br->consumed_words++;
  92620. br->consumed_bits = 0;
  92621. 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 */
  92622. *val <<= bits;
  92623. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92624. br->consumed_bits = bits;
  92625. }
  92626. return true;
  92627. }
  92628. else {
  92629. const brword word = br->buffer[br->consumed_words];
  92630. if(bits < FLAC__BITS_PER_WORD) {
  92631. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92632. br->consumed_bits = bits;
  92633. return true;
  92634. }
  92635. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92636. *val = word;
  92637. crc16_update_word_(br, word);
  92638. br->consumed_words++;
  92639. return true;
  92640. }
  92641. }
  92642. else {
  92643. /* in this case we're starting our read at a partial tail word;
  92644. * the reader has guaranteed that we have at least 'bits' bits
  92645. * available to read, which makes this case simpler.
  92646. */
  92647. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92648. if(br->consumed_bits) {
  92649. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92650. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92651. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92652. br->consumed_bits += bits;
  92653. return true;
  92654. }
  92655. else {
  92656. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92657. br->consumed_bits += bits;
  92658. return true;
  92659. }
  92660. }
  92661. }
  92662. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92663. {
  92664. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92665. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92666. return false;
  92667. /* sign-extend: */
  92668. *val <<= (32-bits);
  92669. *val >>= (32-bits);
  92670. return true;
  92671. }
  92672. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92673. {
  92674. FLAC__uint32 hi, lo;
  92675. if(bits > 32) {
  92676. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92677. return false;
  92678. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92679. return false;
  92680. *val = hi;
  92681. *val <<= 32;
  92682. *val |= lo;
  92683. }
  92684. else {
  92685. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92686. return false;
  92687. *val = lo;
  92688. }
  92689. return true;
  92690. }
  92691. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92692. {
  92693. FLAC__uint32 x8, x32 = 0;
  92694. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92695. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92696. return false;
  92697. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92698. return false;
  92699. x32 |= (x8 << 8);
  92700. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92701. return false;
  92702. x32 |= (x8 << 16);
  92703. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92704. return false;
  92705. x32 |= (x8 << 24);
  92706. *val = x32;
  92707. return true;
  92708. }
  92709. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92710. {
  92711. /*
  92712. * OPT: a faster implementation is possible but probably not that useful
  92713. * since this is only called a couple of times in the metadata readers.
  92714. */
  92715. FLAC__ASSERT(0 != br);
  92716. FLAC__ASSERT(0 != br->buffer);
  92717. if(bits > 0) {
  92718. const unsigned n = br->consumed_bits & 7;
  92719. unsigned m;
  92720. FLAC__uint32 x;
  92721. if(n != 0) {
  92722. m = min(8-n, bits);
  92723. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92724. return false;
  92725. bits -= m;
  92726. }
  92727. m = bits / 8;
  92728. if(m > 0) {
  92729. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92730. return false;
  92731. bits %= 8;
  92732. }
  92733. if(bits > 0) {
  92734. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92735. return false;
  92736. }
  92737. }
  92738. return true;
  92739. }
  92740. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92741. {
  92742. FLAC__uint32 x;
  92743. FLAC__ASSERT(0 != br);
  92744. FLAC__ASSERT(0 != br->buffer);
  92745. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92746. /* step 1: skip over partial head word to get word aligned */
  92747. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92748. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92749. return false;
  92750. nvals--;
  92751. }
  92752. if(0 == nvals)
  92753. return true;
  92754. /* step 2: skip whole words in chunks */
  92755. while(nvals >= FLAC__BYTES_PER_WORD) {
  92756. if(br->consumed_words < br->words) {
  92757. br->consumed_words++;
  92758. nvals -= FLAC__BYTES_PER_WORD;
  92759. }
  92760. else if(!bitreader_read_from_client_(br))
  92761. return false;
  92762. }
  92763. /* step 3: skip any remainder from partial tail bytes */
  92764. while(nvals) {
  92765. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92766. return false;
  92767. nvals--;
  92768. }
  92769. return true;
  92770. }
  92771. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92772. {
  92773. FLAC__uint32 x;
  92774. FLAC__ASSERT(0 != br);
  92775. FLAC__ASSERT(0 != br->buffer);
  92776. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92777. /* step 1: read from partial head word to get word aligned */
  92778. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92779. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92780. return false;
  92781. *val++ = (FLAC__byte)x;
  92782. nvals--;
  92783. }
  92784. if(0 == nvals)
  92785. return true;
  92786. /* step 2: read whole words in chunks */
  92787. while(nvals >= FLAC__BYTES_PER_WORD) {
  92788. if(br->consumed_words < br->words) {
  92789. const brword word = br->buffer[br->consumed_words++];
  92790. #if FLAC__BYTES_PER_WORD == 4
  92791. val[0] = (FLAC__byte)(word >> 24);
  92792. val[1] = (FLAC__byte)(word >> 16);
  92793. val[2] = (FLAC__byte)(word >> 8);
  92794. val[3] = (FLAC__byte)word;
  92795. #elif FLAC__BYTES_PER_WORD == 8
  92796. val[0] = (FLAC__byte)(word >> 56);
  92797. val[1] = (FLAC__byte)(word >> 48);
  92798. val[2] = (FLAC__byte)(word >> 40);
  92799. val[3] = (FLAC__byte)(word >> 32);
  92800. val[4] = (FLAC__byte)(word >> 24);
  92801. val[5] = (FLAC__byte)(word >> 16);
  92802. val[6] = (FLAC__byte)(word >> 8);
  92803. val[7] = (FLAC__byte)word;
  92804. #else
  92805. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92806. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92807. #endif
  92808. val += FLAC__BYTES_PER_WORD;
  92809. nvals -= FLAC__BYTES_PER_WORD;
  92810. }
  92811. else if(!bitreader_read_from_client_(br))
  92812. return false;
  92813. }
  92814. /* step 3: read any remainder from partial tail bytes */
  92815. while(nvals) {
  92816. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92817. return false;
  92818. *val++ = (FLAC__byte)x;
  92819. nvals--;
  92820. }
  92821. return true;
  92822. }
  92823. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  92824. #if 0 /* slow but readable version */
  92825. {
  92826. unsigned bit;
  92827. FLAC__ASSERT(0 != br);
  92828. FLAC__ASSERT(0 != br->buffer);
  92829. *val = 0;
  92830. while(1) {
  92831. if(!FLAC__bitreader_read_bit(br, &bit))
  92832. return false;
  92833. if(bit)
  92834. break;
  92835. else
  92836. *val++;
  92837. }
  92838. return true;
  92839. }
  92840. #else
  92841. {
  92842. unsigned i;
  92843. FLAC__ASSERT(0 != br);
  92844. FLAC__ASSERT(0 != br->buffer);
  92845. *val = 0;
  92846. while(1) {
  92847. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92848. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  92849. if(b) {
  92850. i = COUNT_ZERO_MSBS(b);
  92851. *val += i;
  92852. i++;
  92853. br->consumed_bits += i;
  92854. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  92855. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92856. br->consumed_words++;
  92857. br->consumed_bits = 0;
  92858. }
  92859. return true;
  92860. }
  92861. else {
  92862. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  92863. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92864. br->consumed_words++;
  92865. br->consumed_bits = 0;
  92866. /* didn't find stop bit yet, have to keep going... */
  92867. }
  92868. }
  92869. /* at this point we've eaten up all the whole words; have to try
  92870. * reading through any tail bytes before calling the read callback.
  92871. * this is a repeat of the above logic adjusted for the fact we
  92872. * don't have a whole word. note though if the client is feeding
  92873. * us data a byte at a time (unlikely), br->consumed_bits may not
  92874. * be zero.
  92875. */
  92876. if(br->bytes) {
  92877. const unsigned end = br->bytes * 8;
  92878. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  92879. if(b) {
  92880. i = COUNT_ZERO_MSBS(b);
  92881. *val += i;
  92882. i++;
  92883. br->consumed_bits += i;
  92884. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92885. return true;
  92886. }
  92887. else {
  92888. *val += end - br->consumed_bits;
  92889. br->consumed_bits += end;
  92890. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92891. /* didn't find stop bit yet, have to keep going... */
  92892. }
  92893. }
  92894. if(!bitreader_read_from_client_(br))
  92895. return false;
  92896. }
  92897. }
  92898. #endif
  92899. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92900. {
  92901. FLAC__uint32 lsbs = 0, msbs = 0;
  92902. unsigned uval;
  92903. FLAC__ASSERT(0 != br);
  92904. FLAC__ASSERT(0 != br->buffer);
  92905. FLAC__ASSERT(parameter <= 31);
  92906. /* read the unary MSBs and end bit */
  92907. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  92908. return false;
  92909. /* read the binary LSBs */
  92910. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  92911. return false;
  92912. /* compose the value */
  92913. uval = (msbs << parameter) | lsbs;
  92914. if(uval & 1)
  92915. *val = -((int)(uval >> 1)) - 1;
  92916. else
  92917. *val = (int)(uval >> 1);
  92918. return true;
  92919. }
  92920. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  92921. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  92922. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  92923. /* OPT: possibly faster version for use with MSVC */
  92924. #ifdef _MSC_VER
  92925. {
  92926. unsigned i;
  92927. unsigned uval = 0;
  92928. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  92929. /* try and get br->consumed_words and br->consumed_bits into register;
  92930. * must remember to flush them back to *br before calling other
  92931. * bitwriter functions that use them, and before returning */
  92932. register unsigned cwords;
  92933. register unsigned cbits;
  92934. FLAC__ASSERT(0 != br);
  92935. FLAC__ASSERT(0 != br->buffer);
  92936. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92937. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92938. FLAC__ASSERT(parameter < 32);
  92939. /* 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 */
  92940. if(nvals == 0)
  92941. return true;
  92942. cbits = br->consumed_bits;
  92943. cwords = br->consumed_words;
  92944. while(1) {
  92945. /* read unary part */
  92946. while(1) {
  92947. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92948. brword b = br->buffer[cwords] << cbits;
  92949. if(b) {
  92950. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  92951. __asm {
  92952. bsr eax, b
  92953. not eax
  92954. and eax, 31
  92955. mov i, eax
  92956. }
  92957. #else
  92958. i = COUNT_ZERO_MSBS(b);
  92959. #endif
  92960. uval += i;
  92961. bits = parameter;
  92962. i++;
  92963. cbits += i;
  92964. if(cbits == FLAC__BITS_PER_WORD) {
  92965. crc16_update_word_(br, br->buffer[cwords]);
  92966. cwords++;
  92967. cbits = 0;
  92968. }
  92969. goto break1;
  92970. }
  92971. else {
  92972. uval += FLAC__BITS_PER_WORD - cbits;
  92973. crc16_update_word_(br, br->buffer[cwords]);
  92974. cwords++;
  92975. cbits = 0;
  92976. /* didn't find stop bit yet, have to keep going... */
  92977. }
  92978. }
  92979. /* at this point we've eaten up all the whole words; have to try
  92980. * reading through any tail bytes before calling the read callback.
  92981. * this is a repeat of the above logic adjusted for the fact we
  92982. * don't have a whole word. note though if the client is feeding
  92983. * us data a byte at a time (unlikely), br->consumed_bits may not
  92984. * be zero.
  92985. */
  92986. if(br->bytes) {
  92987. const unsigned end = br->bytes * 8;
  92988. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  92989. if(b) {
  92990. i = COUNT_ZERO_MSBS(b);
  92991. uval += i;
  92992. bits = parameter;
  92993. i++;
  92994. cbits += i;
  92995. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92996. goto break1;
  92997. }
  92998. else {
  92999. uval += end - cbits;
  93000. cbits += end;
  93001. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93002. /* didn't find stop bit yet, have to keep going... */
  93003. }
  93004. }
  93005. /* flush registers and read; bitreader_read_from_client_() does
  93006. * not touch br->consumed_bits at all but we still need to set
  93007. * it in case it fails and we have to return false.
  93008. */
  93009. br->consumed_bits = cbits;
  93010. br->consumed_words = cwords;
  93011. if(!bitreader_read_from_client_(br))
  93012. return false;
  93013. cwords = br->consumed_words;
  93014. }
  93015. break1:
  93016. /* read binary part */
  93017. FLAC__ASSERT(cwords <= br->words);
  93018. if(bits) {
  93019. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93020. /* flush registers and read; bitreader_read_from_client_() does
  93021. * not touch br->consumed_bits at all but we still need to set
  93022. * it in case it fails and we have to return false.
  93023. */
  93024. br->consumed_bits = cbits;
  93025. br->consumed_words = cwords;
  93026. if(!bitreader_read_from_client_(br))
  93027. return false;
  93028. cwords = br->consumed_words;
  93029. }
  93030. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93031. if(cbits) {
  93032. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93033. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93034. const brword word = br->buffer[cwords];
  93035. if(bits < n) {
  93036. uval <<= bits;
  93037. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93038. cbits += bits;
  93039. goto break2;
  93040. }
  93041. uval <<= n;
  93042. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93043. bits -= n;
  93044. crc16_update_word_(br, word);
  93045. cwords++;
  93046. cbits = 0;
  93047. 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 */
  93048. uval <<= bits;
  93049. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93050. cbits = bits;
  93051. }
  93052. goto break2;
  93053. }
  93054. else {
  93055. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93056. uval <<= bits;
  93057. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93058. cbits = bits;
  93059. goto break2;
  93060. }
  93061. }
  93062. else {
  93063. /* in this case we're starting our read at a partial tail word;
  93064. * the reader has guaranteed that we have at least 'bits' bits
  93065. * available to read, which makes this case simpler.
  93066. */
  93067. uval <<= bits;
  93068. if(cbits) {
  93069. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93070. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93071. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93072. cbits += bits;
  93073. goto break2;
  93074. }
  93075. else {
  93076. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93077. cbits += bits;
  93078. goto break2;
  93079. }
  93080. }
  93081. }
  93082. break2:
  93083. /* compose the value */
  93084. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93085. /* are we done? */
  93086. --nvals;
  93087. if(nvals == 0) {
  93088. br->consumed_bits = cbits;
  93089. br->consumed_words = cwords;
  93090. return true;
  93091. }
  93092. uval = 0;
  93093. ++vals;
  93094. }
  93095. }
  93096. #else
  93097. {
  93098. unsigned i;
  93099. unsigned uval = 0;
  93100. /* try and get br->consumed_words and br->consumed_bits into register;
  93101. * must remember to flush them back to *br before calling other
  93102. * bitwriter functions that use them, and before returning */
  93103. register unsigned cwords;
  93104. register unsigned cbits;
  93105. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93106. FLAC__ASSERT(0 != br);
  93107. FLAC__ASSERT(0 != br->buffer);
  93108. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93109. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93110. FLAC__ASSERT(parameter < 32);
  93111. /* 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 */
  93112. if(nvals == 0)
  93113. return true;
  93114. cbits = br->consumed_bits;
  93115. cwords = br->consumed_words;
  93116. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93117. while(1) {
  93118. /* read unary part */
  93119. while(1) {
  93120. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93121. brword b = br->buffer[cwords] << cbits;
  93122. if(b) {
  93123. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93124. asm volatile (
  93125. "bsrl %1, %0;"
  93126. "notl %0;"
  93127. "andl $31, %0;"
  93128. : "=r"(i)
  93129. : "r"(b)
  93130. );
  93131. #else
  93132. i = COUNT_ZERO_MSBS(b);
  93133. #endif
  93134. uval += i;
  93135. cbits += i;
  93136. cbits++; /* skip over stop bit */
  93137. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93138. crc16_update_word_(br, br->buffer[cwords]);
  93139. cwords++;
  93140. cbits = 0;
  93141. }
  93142. goto break1;
  93143. }
  93144. else {
  93145. uval += FLAC__BITS_PER_WORD - cbits;
  93146. crc16_update_word_(br, br->buffer[cwords]);
  93147. cwords++;
  93148. cbits = 0;
  93149. /* didn't find stop bit yet, have to keep going... */
  93150. }
  93151. }
  93152. /* at this point we've eaten up all the whole words; have to try
  93153. * reading through any tail bytes before calling the read callback.
  93154. * this is a repeat of the above logic adjusted for the fact we
  93155. * don't have a whole word. note though if the client is feeding
  93156. * us data a byte at a time (unlikely), br->consumed_bits may not
  93157. * be zero.
  93158. */
  93159. if(br->bytes) {
  93160. const unsigned end = br->bytes * 8;
  93161. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93162. if(b) {
  93163. i = COUNT_ZERO_MSBS(b);
  93164. uval += i;
  93165. cbits += i;
  93166. cbits++; /* skip over stop bit */
  93167. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93168. goto break1;
  93169. }
  93170. else {
  93171. uval += end - cbits;
  93172. cbits += end;
  93173. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93174. /* didn't find stop bit yet, have to keep going... */
  93175. }
  93176. }
  93177. /* flush registers and read; bitreader_read_from_client_() does
  93178. * not touch br->consumed_bits at all but we still need to set
  93179. * it in case it fails and we have to return false.
  93180. */
  93181. br->consumed_bits = cbits;
  93182. br->consumed_words = cwords;
  93183. if(!bitreader_read_from_client_(br))
  93184. return false;
  93185. cwords = br->consumed_words;
  93186. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93187. /* + uval to offset our count by the # of unary bits already
  93188. * consumed before the read, because we will add these back
  93189. * in all at once at break1
  93190. */
  93191. }
  93192. break1:
  93193. ucbits -= uval;
  93194. ucbits--; /* account for stop bit */
  93195. /* read binary part */
  93196. FLAC__ASSERT(cwords <= br->words);
  93197. if(parameter) {
  93198. while(ucbits < parameter) {
  93199. /* flush registers and read; bitreader_read_from_client_() does
  93200. * not touch br->consumed_bits at all but we still need to set
  93201. * it in case it fails and we have to return false.
  93202. */
  93203. br->consumed_bits = cbits;
  93204. br->consumed_words = cwords;
  93205. if(!bitreader_read_from_client_(br))
  93206. return false;
  93207. cwords = br->consumed_words;
  93208. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93209. }
  93210. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93211. if(cbits) {
  93212. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93213. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93214. const brword word = br->buffer[cwords];
  93215. if(parameter < n) {
  93216. uval <<= parameter;
  93217. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93218. cbits += parameter;
  93219. }
  93220. else {
  93221. uval <<= n;
  93222. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93223. crc16_update_word_(br, word);
  93224. cwords++;
  93225. cbits = parameter - n;
  93226. 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 */
  93227. uval <<= cbits;
  93228. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93229. }
  93230. }
  93231. }
  93232. else {
  93233. cbits = parameter;
  93234. uval <<= parameter;
  93235. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93236. }
  93237. }
  93238. else {
  93239. /* in this case we're starting our read at a partial tail word;
  93240. * the reader has guaranteed that we have at least 'parameter'
  93241. * bits available to read, which makes this case simpler.
  93242. */
  93243. uval <<= parameter;
  93244. if(cbits) {
  93245. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93246. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93247. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93248. cbits += parameter;
  93249. }
  93250. else {
  93251. cbits = parameter;
  93252. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93253. }
  93254. }
  93255. }
  93256. ucbits -= parameter;
  93257. /* compose the value */
  93258. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93259. /* are we done? */
  93260. --nvals;
  93261. if(nvals == 0) {
  93262. br->consumed_bits = cbits;
  93263. br->consumed_words = cwords;
  93264. return true;
  93265. }
  93266. uval = 0;
  93267. ++vals;
  93268. }
  93269. }
  93270. #endif
  93271. #if 0 /* UNUSED */
  93272. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93273. {
  93274. FLAC__uint32 lsbs = 0, msbs = 0;
  93275. unsigned bit, uval, k;
  93276. FLAC__ASSERT(0 != br);
  93277. FLAC__ASSERT(0 != br->buffer);
  93278. k = FLAC__bitmath_ilog2(parameter);
  93279. /* read the unary MSBs and end bit */
  93280. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93281. return false;
  93282. /* read the binary LSBs */
  93283. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93284. return false;
  93285. if(parameter == 1u<<k) {
  93286. /* compose the value */
  93287. uval = (msbs << k) | lsbs;
  93288. }
  93289. else {
  93290. unsigned d = (1 << (k+1)) - parameter;
  93291. if(lsbs >= d) {
  93292. if(!FLAC__bitreader_read_bit(br, &bit))
  93293. return false;
  93294. lsbs <<= 1;
  93295. lsbs |= bit;
  93296. lsbs -= d;
  93297. }
  93298. /* compose the value */
  93299. uval = msbs * parameter + lsbs;
  93300. }
  93301. /* unfold unsigned to signed */
  93302. if(uval & 1)
  93303. *val = -((int)(uval >> 1)) - 1;
  93304. else
  93305. *val = (int)(uval >> 1);
  93306. return true;
  93307. }
  93308. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93309. {
  93310. FLAC__uint32 lsbs, msbs = 0;
  93311. unsigned bit, k;
  93312. FLAC__ASSERT(0 != br);
  93313. FLAC__ASSERT(0 != br->buffer);
  93314. k = FLAC__bitmath_ilog2(parameter);
  93315. /* read the unary MSBs and end bit */
  93316. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93317. return false;
  93318. /* read the binary LSBs */
  93319. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93320. return false;
  93321. if(parameter == 1u<<k) {
  93322. /* compose the value */
  93323. *val = (msbs << k) | lsbs;
  93324. }
  93325. else {
  93326. unsigned d = (1 << (k+1)) - parameter;
  93327. if(lsbs >= d) {
  93328. if(!FLAC__bitreader_read_bit(br, &bit))
  93329. return false;
  93330. lsbs <<= 1;
  93331. lsbs |= bit;
  93332. lsbs -= d;
  93333. }
  93334. /* compose the value */
  93335. *val = msbs * parameter + lsbs;
  93336. }
  93337. return true;
  93338. }
  93339. #endif /* UNUSED */
  93340. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93341. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93342. {
  93343. FLAC__uint32 v = 0;
  93344. FLAC__uint32 x;
  93345. unsigned i;
  93346. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93347. return false;
  93348. if(raw)
  93349. raw[(*rawlen)++] = (FLAC__byte)x;
  93350. if(!(x & 0x80)) { /* 0xxxxxxx */
  93351. v = x;
  93352. i = 0;
  93353. }
  93354. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93355. v = x & 0x1F;
  93356. i = 1;
  93357. }
  93358. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93359. v = x & 0x0F;
  93360. i = 2;
  93361. }
  93362. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93363. v = x & 0x07;
  93364. i = 3;
  93365. }
  93366. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93367. v = x & 0x03;
  93368. i = 4;
  93369. }
  93370. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93371. v = x & 0x01;
  93372. i = 5;
  93373. }
  93374. else {
  93375. *val = 0xffffffff;
  93376. return true;
  93377. }
  93378. for( ; i; i--) {
  93379. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93380. return false;
  93381. if(raw)
  93382. raw[(*rawlen)++] = (FLAC__byte)x;
  93383. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93384. *val = 0xffffffff;
  93385. return true;
  93386. }
  93387. v <<= 6;
  93388. v |= (x & 0x3F);
  93389. }
  93390. *val = v;
  93391. return true;
  93392. }
  93393. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93394. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93395. {
  93396. FLAC__uint64 v = 0;
  93397. FLAC__uint32 x;
  93398. unsigned i;
  93399. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93400. return false;
  93401. if(raw)
  93402. raw[(*rawlen)++] = (FLAC__byte)x;
  93403. if(!(x & 0x80)) { /* 0xxxxxxx */
  93404. v = x;
  93405. i = 0;
  93406. }
  93407. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93408. v = x & 0x1F;
  93409. i = 1;
  93410. }
  93411. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93412. v = x & 0x0F;
  93413. i = 2;
  93414. }
  93415. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93416. v = x & 0x07;
  93417. i = 3;
  93418. }
  93419. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93420. v = x & 0x03;
  93421. i = 4;
  93422. }
  93423. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93424. v = x & 0x01;
  93425. i = 5;
  93426. }
  93427. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93428. v = 0;
  93429. i = 6;
  93430. }
  93431. else {
  93432. *val = FLAC__U64L(0xffffffffffffffff);
  93433. return true;
  93434. }
  93435. for( ; i; i--) {
  93436. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93437. return false;
  93438. if(raw)
  93439. raw[(*rawlen)++] = (FLAC__byte)x;
  93440. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93441. *val = FLAC__U64L(0xffffffffffffffff);
  93442. return true;
  93443. }
  93444. v <<= 6;
  93445. v |= (x & 0x3F);
  93446. }
  93447. *val = v;
  93448. return true;
  93449. }
  93450. #endif
  93451. /*** End of inlined file: bitreader.c ***/
  93452. /*** Start of inlined file: bitwriter.c ***/
  93453. /*** Start of inlined file: juce_FlacHeader.h ***/
  93454. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93455. // tasks..
  93456. #define VERSION "1.2.1"
  93457. #define FLAC__NO_DLL 1
  93458. #if JUCE_MSVC
  93459. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93460. #endif
  93461. #if JUCE_MAC
  93462. #define FLAC__SYS_DARWIN 1
  93463. #endif
  93464. /*** End of inlined file: juce_FlacHeader.h ***/
  93465. #if JUCE_USE_FLAC
  93466. #if HAVE_CONFIG_H
  93467. # include <config.h>
  93468. #endif
  93469. #include <stdlib.h> /* for malloc() */
  93470. #include <string.h> /* for memcpy(), memset() */
  93471. #ifdef _MSC_VER
  93472. #include <winsock.h> /* for ntohl() */
  93473. #elif defined FLAC__SYS_DARWIN
  93474. #include <machine/endian.h> /* for ntohl() */
  93475. #elif defined __MINGW32__
  93476. #include <winsock.h> /* for ntohl() */
  93477. #else
  93478. #include <netinet/in.h> /* for ntohl() */
  93479. #endif
  93480. #if 0 /* UNUSED */
  93481. #endif
  93482. /*** Start of inlined file: bitwriter.h ***/
  93483. #ifndef FLAC__PRIVATE__BITWRITER_H
  93484. #define FLAC__PRIVATE__BITWRITER_H
  93485. #include <stdio.h> /* for FILE */
  93486. /*
  93487. * opaque structure definition
  93488. */
  93489. struct FLAC__BitWriter;
  93490. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93491. /*
  93492. * construction, deletion, initialization, etc functions
  93493. */
  93494. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93495. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93496. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93497. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93498. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93499. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93500. /*
  93501. * CRC functions
  93502. *
  93503. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93504. */
  93505. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93506. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93507. /*
  93508. * info functions
  93509. */
  93510. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93511. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93512. /*
  93513. * direct buffer access
  93514. *
  93515. * there may be no calls on the bitwriter between get and release.
  93516. * the bitwriter continues to own the returned buffer.
  93517. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93518. */
  93519. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93520. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93521. /*
  93522. * write functions
  93523. */
  93524. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93525. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93526. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93527. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93528. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93529. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93530. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93531. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93532. #if 0 /* UNUSED */
  93533. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93534. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93535. #endif
  93536. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93537. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93538. #if 0 /* UNUSED */
  93539. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93540. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93541. #endif
  93542. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93543. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93544. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93545. #endif
  93546. /*** End of inlined file: bitwriter.h ***/
  93547. /*** Start of inlined file: alloc.h ***/
  93548. #ifndef FLAC__SHARE__ALLOC_H
  93549. #define FLAC__SHARE__ALLOC_H
  93550. #if HAVE_CONFIG_H
  93551. # include <config.h>
  93552. #endif
  93553. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93554. * before #including this file, otherwise SIZE_MAX might not be defined
  93555. */
  93556. #include <limits.h> /* for SIZE_MAX */
  93557. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93558. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93559. #endif
  93560. #include <stdlib.h> /* for size_t, malloc(), etc */
  93561. #ifndef SIZE_MAX
  93562. # ifndef SIZE_T_MAX
  93563. # ifdef _MSC_VER
  93564. # define SIZE_T_MAX UINT_MAX
  93565. # else
  93566. # error
  93567. # endif
  93568. # endif
  93569. # define SIZE_MAX SIZE_T_MAX
  93570. #endif
  93571. #ifndef FLaC__INLINE
  93572. #define FLaC__INLINE
  93573. #endif
  93574. /* avoid malloc()ing 0 bytes, see:
  93575. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93576. */
  93577. static FLaC__INLINE void *safe_malloc_(size_t size)
  93578. {
  93579. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93580. if(!size)
  93581. size++;
  93582. return malloc(size);
  93583. }
  93584. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93585. {
  93586. if(!nmemb || !size)
  93587. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93588. return calloc(nmemb, size);
  93589. }
  93590. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93591. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93592. {
  93593. size2 += size1;
  93594. if(size2 < size1)
  93595. return 0;
  93596. return safe_malloc_(size2);
  93597. }
  93598. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93599. {
  93600. size2 += size1;
  93601. if(size2 < size1)
  93602. return 0;
  93603. size3 += size2;
  93604. if(size3 < size2)
  93605. return 0;
  93606. return safe_malloc_(size3);
  93607. }
  93608. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93609. {
  93610. size2 += size1;
  93611. if(size2 < size1)
  93612. return 0;
  93613. size3 += size2;
  93614. if(size3 < size2)
  93615. return 0;
  93616. size4 += size3;
  93617. if(size4 < size3)
  93618. return 0;
  93619. return safe_malloc_(size4);
  93620. }
  93621. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93622. #if 0
  93623. needs support for cases where sizeof(size_t) != 4
  93624. {
  93625. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93626. if(sizeof(size_t) == 4) {
  93627. if ((double)size1 * (double)size2 < 4294967296.0)
  93628. return malloc(size1*size2);
  93629. }
  93630. return 0;
  93631. }
  93632. #else
  93633. /* better? */
  93634. {
  93635. if(!size1 || !size2)
  93636. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93637. if(size1 > SIZE_MAX / size2)
  93638. return 0;
  93639. return malloc(size1*size2);
  93640. }
  93641. #endif
  93642. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93643. {
  93644. if(!size1 || !size2 || !size3)
  93645. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93646. if(size1 > SIZE_MAX / size2)
  93647. return 0;
  93648. size1 *= size2;
  93649. if(size1 > SIZE_MAX / size3)
  93650. return 0;
  93651. return malloc(size1*size3);
  93652. }
  93653. /* size1*size2 + size3 */
  93654. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93655. {
  93656. if(!size1 || !size2)
  93657. return safe_malloc_(size3);
  93658. if(size1 > SIZE_MAX / size2)
  93659. return 0;
  93660. return safe_malloc_add_2op_(size1*size2, size3);
  93661. }
  93662. /* size1 * (size2 + size3) */
  93663. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93664. {
  93665. if(!size1 || (!size2 && !size3))
  93666. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93667. size2 += size3;
  93668. if(size2 < size3)
  93669. return 0;
  93670. return safe_malloc_mul_2op_(size1, size2);
  93671. }
  93672. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93673. {
  93674. size2 += size1;
  93675. if(size2 < size1)
  93676. return 0;
  93677. return realloc(ptr, size2);
  93678. }
  93679. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93680. {
  93681. size2 += size1;
  93682. if(size2 < size1)
  93683. return 0;
  93684. size3 += size2;
  93685. if(size3 < size2)
  93686. return 0;
  93687. return realloc(ptr, size3);
  93688. }
  93689. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93690. {
  93691. size2 += size1;
  93692. if(size2 < size1)
  93693. return 0;
  93694. size3 += size2;
  93695. if(size3 < size2)
  93696. return 0;
  93697. size4 += size3;
  93698. if(size4 < size3)
  93699. return 0;
  93700. return realloc(ptr, size4);
  93701. }
  93702. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93703. {
  93704. if(!size1 || !size2)
  93705. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93706. if(size1 > SIZE_MAX / size2)
  93707. return 0;
  93708. return realloc(ptr, size1*size2);
  93709. }
  93710. /* size1 * (size2 + size3) */
  93711. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93712. {
  93713. if(!size1 || (!size2 && !size3))
  93714. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93715. size2 += size3;
  93716. if(size2 < size3)
  93717. return 0;
  93718. return safe_realloc_mul_2op_(ptr, size1, size2);
  93719. }
  93720. #endif
  93721. /*** End of inlined file: alloc.h ***/
  93722. /* Things should be fastest when this matches the machine word size */
  93723. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93724. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93725. typedef FLAC__uint32 bwword;
  93726. #define FLAC__BYTES_PER_WORD 4
  93727. #define FLAC__BITS_PER_WORD 32
  93728. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93729. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93730. #if WORDS_BIGENDIAN
  93731. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93732. #else
  93733. #ifdef _MSC_VER
  93734. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93735. #else
  93736. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93737. #endif
  93738. #endif
  93739. /*
  93740. * The default capacity here doesn't matter too much. The buffer always grows
  93741. * to hold whatever is written to it. Usually the encoder will stop adding at
  93742. * a frame or metadata block, then write that out and clear the buffer for the
  93743. * next one.
  93744. */
  93745. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93746. /* When growing, increment 4K at a time */
  93747. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93748. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93749. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93750. #ifdef min
  93751. #undef min
  93752. #endif
  93753. #define min(x,y) ((x)<(y)?(x):(y))
  93754. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93755. #ifdef _MSC_VER
  93756. #define FLAC__U64L(x) x
  93757. #else
  93758. #define FLAC__U64L(x) x##LLU
  93759. #endif
  93760. #ifndef FLaC__INLINE
  93761. #define FLaC__INLINE
  93762. #endif
  93763. struct FLAC__BitWriter {
  93764. bwword *buffer;
  93765. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93766. unsigned capacity; /* capacity of buffer in words */
  93767. unsigned words; /* # of complete words in buffer */
  93768. unsigned bits; /* # of used bits in accum */
  93769. };
  93770. /* * WATCHOUT: The current implementation only grows the buffer. */
  93771. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93772. {
  93773. unsigned new_capacity;
  93774. bwword *new_buffer;
  93775. FLAC__ASSERT(0 != bw);
  93776. FLAC__ASSERT(0 != bw->buffer);
  93777. /* calculate total words needed to store 'bits_to_add' additional bits */
  93778. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93779. /* it's possible (due to pessimism in the growth estimation that
  93780. * leads to this call) that we don't actually need to grow
  93781. */
  93782. if(bw->capacity >= new_capacity)
  93783. return true;
  93784. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93785. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93786. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93787. /* make sure we got everything right */
  93788. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93789. FLAC__ASSERT(new_capacity > bw->capacity);
  93790. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93791. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93792. if(new_buffer == 0)
  93793. return false;
  93794. bw->buffer = new_buffer;
  93795. bw->capacity = new_capacity;
  93796. return true;
  93797. }
  93798. /***********************************************************************
  93799. *
  93800. * Class constructor/destructor
  93801. *
  93802. ***********************************************************************/
  93803. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93804. {
  93805. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93806. /* note that calloc() sets all members to 0 for us */
  93807. return bw;
  93808. }
  93809. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93810. {
  93811. FLAC__ASSERT(0 != bw);
  93812. FLAC__bitwriter_free(bw);
  93813. free(bw);
  93814. }
  93815. /***********************************************************************
  93816. *
  93817. * Public class methods
  93818. *
  93819. ***********************************************************************/
  93820. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  93821. {
  93822. FLAC__ASSERT(0 != bw);
  93823. bw->words = bw->bits = 0;
  93824. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  93825. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  93826. if(bw->buffer == 0)
  93827. return false;
  93828. return true;
  93829. }
  93830. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  93831. {
  93832. FLAC__ASSERT(0 != bw);
  93833. if(0 != bw->buffer)
  93834. free(bw->buffer);
  93835. bw->buffer = 0;
  93836. bw->capacity = 0;
  93837. bw->words = bw->bits = 0;
  93838. }
  93839. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  93840. {
  93841. bw->words = bw->bits = 0;
  93842. }
  93843. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  93844. {
  93845. unsigned i, j;
  93846. if(bw == 0) {
  93847. fprintf(out, "bitwriter is NULL\n");
  93848. }
  93849. else {
  93850. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  93851. for(i = 0; i < bw->words; i++) {
  93852. fprintf(out, "%08X: ", i);
  93853. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93854. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93855. fprintf(out, "\n");
  93856. }
  93857. if(bw->bits > 0) {
  93858. fprintf(out, "%08X: ", i);
  93859. for(j = 0; j < bw->bits; j++)
  93860. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  93861. fprintf(out, "\n");
  93862. }
  93863. }
  93864. }
  93865. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  93866. {
  93867. const FLAC__byte *buffer;
  93868. size_t bytes;
  93869. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93870. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93871. return false;
  93872. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  93873. FLAC__bitwriter_release_buffer(bw);
  93874. return true;
  93875. }
  93876. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  93877. {
  93878. const FLAC__byte *buffer;
  93879. size_t bytes;
  93880. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93881. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93882. return false;
  93883. *crc = FLAC__crc8(buffer, bytes);
  93884. FLAC__bitwriter_release_buffer(bw);
  93885. return true;
  93886. }
  93887. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  93888. {
  93889. return ((bw->bits & 7) == 0);
  93890. }
  93891. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  93892. {
  93893. return FLAC__TOTAL_BITS(bw);
  93894. }
  93895. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  93896. {
  93897. FLAC__ASSERT((bw->bits & 7) == 0);
  93898. /* double protection */
  93899. if(bw->bits & 7)
  93900. return false;
  93901. /* if we have bits in the accumulator we have to flush those to the buffer first */
  93902. if(bw->bits) {
  93903. FLAC__ASSERT(bw->words <= bw->capacity);
  93904. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  93905. return false;
  93906. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  93907. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  93908. }
  93909. /* now we can just return what we have */
  93910. *buffer = (FLAC__byte*)bw->buffer;
  93911. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  93912. return true;
  93913. }
  93914. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  93915. {
  93916. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  93917. * get-mode' flag could be added everywhere and then cleared here
  93918. */
  93919. (void)bw;
  93920. }
  93921. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  93922. {
  93923. unsigned n;
  93924. FLAC__ASSERT(0 != bw);
  93925. FLAC__ASSERT(0 != bw->buffer);
  93926. if(bits == 0)
  93927. return true;
  93928. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93929. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93930. return false;
  93931. /* first part gets to word alignment */
  93932. if(bw->bits) {
  93933. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  93934. bw->accum <<= n;
  93935. bits -= n;
  93936. bw->bits += n;
  93937. if(bw->bits == FLAC__BITS_PER_WORD) {
  93938. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93939. bw->bits = 0;
  93940. }
  93941. else
  93942. return true;
  93943. }
  93944. /* do whole words */
  93945. while(bits >= FLAC__BITS_PER_WORD) {
  93946. bw->buffer[bw->words++] = 0;
  93947. bits -= FLAC__BITS_PER_WORD;
  93948. }
  93949. /* do any leftovers */
  93950. if(bits > 0) {
  93951. bw->accum = 0;
  93952. bw->bits = bits;
  93953. }
  93954. return true;
  93955. }
  93956. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  93957. {
  93958. register unsigned left;
  93959. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93960. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93961. FLAC__ASSERT(0 != bw);
  93962. FLAC__ASSERT(0 != bw->buffer);
  93963. FLAC__ASSERT(bits <= 32);
  93964. if(bits == 0)
  93965. return true;
  93966. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93967. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93968. return false;
  93969. left = FLAC__BITS_PER_WORD - bw->bits;
  93970. if(bits < left) {
  93971. bw->accum <<= bits;
  93972. bw->accum |= val;
  93973. bw->bits += bits;
  93974. }
  93975. 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 */
  93976. bw->accum <<= left;
  93977. bw->accum |= val >> (bw->bits = bits - left);
  93978. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93979. bw->accum = val;
  93980. }
  93981. else {
  93982. bw->accum = val;
  93983. bw->bits = 0;
  93984. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  93985. }
  93986. return true;
  93987. }
  93988. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  93989. {
  93990. /* zero-out unused bits */
  93991. if(bits < 32)
  93992. val &= (~(0xffffffff << bits));
  93993. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93994. }
  93995. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  93996. {
  93997. /* this could be a little faster but it's not used for much */
  93998. if(bits > 32) {
  93999. return
  94000. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94001. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94002. }
  94003. else
  94004. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94005. }
  94006. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94007. {
  94008. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94009. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94010. return false;
  94011. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94012. return false;
  94013. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94014. return false;
  94015. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94016. return false;
  94017. return true;
  94018. }
  94019. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94020. {
  94021. unsigned i;
  94022. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94023. for(i = 0; i < nvals; i++) {
  94024. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94025. return false;
  94026. }
  94027. return true;
  94028. }
  94029. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94030. {
  94031. if(val < 32)
  94032. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94033. else
  94034. return
  94035. FLAC__bitwriter_write_zeroes(bw, val) &&
  94036. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94037. }
  94038. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94039. {
  94040. FLAC__uint32 uval;
  94041. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94042. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94043. uval = (val<<1) ^ (val>>31);
  94044. return 1 + parameter + (uval >> parameter);
  94045. }
  94046. #if 0 /* UNUSED */
  94047. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94048. {
  94049. unsigned bits, msbs, uval;
  94050. unsigned k;
  94051. FLAC__ASSERT(parameter > 0);
  94052. /* fold signed to unsigned */
  94053. if(val < 0)
  94054. uval = (unsigned)(((-(++val)) << 1) + 1);
  94055. else
  94056. uval = (unsigned)(val << 1);
  94057. k = FLAC__bitmath_ilog2(parameter);
  94058. if(parameter == 1u<<k) {
  94059. FLAC__ASSERT(k <= 30);
  94060. msbs = uval >> k;
  94061. bits = 1 + k + msbs;
  94062. }
  94063. else {
  94064. unsigned q, r, d;
  94065. d = (1 << (k+1)) - parameter;
  94066. q = uval / parameter;
  94067. r = uval - (q * parameter);
  94068. bits = 1 + q + k;
  94069. if(r >= d)
  94070. bits++;
  94071. }
  94072. return bits;
  94073. }
  94074. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94075. {
  94076. unsigned bits, msbs;
  94077. unsigned k;
  94078. FLAC__ASSERT(parameter > 0);
  94079. k = FLAC__bitmath_ilog2(parameter);
  94080. if(parameter == 1u<<k) {
  94081. FLAC__ASSERT(k <= 30);
  94082. msbs = uval >> k;
  94083. bits = 1 + k + msbs;
  94084. }
  94085. else {
  94086. unsigned q, r, d;
  94087. d = (1 << (k+1)) - parameter;
  94088. q = uval / parameter;
  94089. r = uval - (q * parameter);
  94090. bits = 1 + q + k;
  94091. if(r >= d)
  94092. bits++;
  94093. }
  94094. return bits;
  94095. }
  94096. #endif /* UNUSED */
  94097. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94098. {
  94099. unsigned total_bits, interesting_bits, msbs;
  94100. FLAC__uint32 uval, pattern;
  94101. FLAC__ASSERT(0 != bw);
  94102. FLAC__ASSERT(0 != bw->buffer);
  94103. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94104. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94105. uval = (val<<1) ^ (val>>31);
  94106. msbs = uval >> parameter;
  94107. interesting_bits = 1 + parameter;
  94108. total_bits = interesting_bits + msbs;
  94109. pattern = 1 << parameter; /* the unary end bit */
  94110. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94111. if(total_bits <= 32)
  94112. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94113. else
  94114. return
  94115. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94116. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94117. }
  94118. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94119. {
  94120. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94121. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94122. FLAC__uint32 uval;
  94123. unsigned left;
  94124. const unsigned lsbits = 1 + parameter;
  94125. unsigned msbits;
  94126. FLAC__ASSERT(0 != bw);
  94127. FLAC__ASSERT(0 != bw->buffer);
  94128. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94129. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94130. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94131. while(nvals) {
  94132. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94133. uval = (*vals<<1) ^ (*vals>>31);
  94134. msbits = uval >> parameter;
  94135. #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) */
  94136. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94137. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94138. bw->bits = bw->bits + msbits + lsbits;
  94139. uval |= mask1; /* set stop bit */
  94140. uval &= mask2; /* mask off unused top bits */
  94141. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94142. bw->accum <<= msbits;
  94143. bw->accum <<= lsbits;
  94144. bw->accum |= uval;
  94145. if(bw->bits == FLAC__BITS_PER_WORD) {
  94146. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94147. bw->bits = 0;
  94148. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94149. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94150. FLAC__ASSERT(bw->capacity == bw->words);
  94151. return false;
  94152. }
  94153. }
  94154. }
  94155. else {
  94156. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94157. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94158. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94159. bw->bits = bw->bits + msbits + lsbits;
  94160. uval |= mask1; /* set stop bit */
  94161. uval &= mask2; /* mask off unused top bits */
  94162. bw->accum <<= msbits + lsbits;
  94163. bw->accum |= uval;
  94164. }
  94165. else {
  94166. #endif
  94167. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94168. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94169. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94170. return false;
  94171. if(msbits) {
  94172. /* first part gets to word alignment */
  94173. if(bw->bits) {
  94174. left = FLAC__BITS_PER_WORD - bw->bits;
  94175. if(msbits < left) {
  94176. bw->accum <<= msbits;
  94177. bw->bits += msbits;
  94178. goto break1;
  94179. }
  94180. else {
  94181. bw->accum <<= left;
  94182. msbits -= left;
  94183. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94184. bw->bits = 0;
  94185. }
  94186. }
  94187. /* do whole words */
  94188. while(msbits >= FLAC__BITS_PER_WORD) {
  94189. bw->buffer[bw->words++] = 0;
  94190. msbits -= FLAC__BITS_PER_WORD;
  94191. }
  94192. /* do any leftovers */
  94193. if(msbits > 0) {
  94194. bw->accum = 0;
  94195. bw->bits = msbits;
  94196. }
  94197. }
  94198. break1:
  94199. uval |= mask1; /* set stop bit */
  94200. uval &= mask2; /* mask off unused top bits */
  94201. left = FLAC__BITS_PER_WORD - bw->bits;
  94202. if(lsbits < left) {
  94203. bw->accum <<= lsbits;
  94204. bw->accum |= uval;
  94205. bw->bits += lsbits;
  94206. }
  94207. else {
  94208. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94209. * be > lsbits (because of previous assertions) so it would have
  94210. * triggered the (lsbits<left) case above.
  94211. */
  94212. FLAC__ASSERT(bw->bits);
  94213. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94214. bw->accum <<= left;
  94215. bw->accum |= uval >> (bw->bits = lsbits - left);
  94216. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94217. bw->accum = uval;
  94218. }
  94219. #if 1
  94220. }
  94221. #endif
  94222. vals++;
  94223. nvals--;
  94224. }
  94225. return true;
  94226. }
  94227. #if 0 /* UNUSED */
  94228. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94229. {
  94230. unsigned total_bits, msbs, uval;
  94231. unsigned k;
  94232. FLAC__ASSERT(0 != bw);
  94233. FLAC__ASSERT(0 != bw->buffer);
  94234. FLAC__ASSERT(parameter > 0);
  94235. /* fold signed to unsigned */
  94236. if(val < 0)
  94237. uval = (unsigned)(((-(++val)) << 1) + 1);
  94238. else
  94239. uval = (unsigned)(val << 1);
  94240. k = FLAC__bitmath_ilog2(parameter);
  94241. if(parameter == 1u<<k) {
  94242. unsigned pattern;
  94243. FLAC__ASSERT(k <= 30);
  94244. msbs = uval >> k;
  94245. total_bits = 1 + k + msbs;
  94246. pattern = 1 << k; /* the unary end bit */
  94247. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94248. if(total_bits <= 32) {
  94249. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94250. return false;
  94251. }
  94252. else {
  94253. /* write the unary MSBs */
  94254. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94255. return false;
  94256. /* write the unary end bit and binary LSBs */
  94257. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94258. return false;
  94259. }
  94260. }
  94261. else {
  94262. unsigned q, r, d;
  94263. d = (1 << (k+1)) - parameter;
  94264. q = uval / parameter;
  94265. r = uval - (q * parameter);
  94266. /* write the unary MSBs */
  94267. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94268. return false;
  94269. /* write the unary end bit */
  94270. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94271. return false;
  94272. /* write the binary LSBs */
  94273. if(r >= d) {
  94274. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94275. return false;
  94276. }
  94277. else {
  94278. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94279. return false;
  94280. }
  94281. }
  94282. return true;
  94283. }
  94284. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94285. {
  94286. unsigned total_bits, msbs;
  94287. unsigned k;
  94288. FLAC__ASSERT(0 != bw);
  94289. FLAC__ASSERT(0 != bw->buffer);
  94290. FLAC__ASSERT(parameter > 0);
  94291. k = FLAC__bitmath_ilog2(parameter);
  94292. if(parameter == 1u<<k) {
  94293. unsigned pattern;
  94294. FLAC__ASSERT(k <= 30);
  94295. msbs = uval >> k;
  94296. total_bits = 1 + k + msbs;
  94297. pattern = 1 << k; /* the unary end bit */
  94298. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94299. if(total_bits <= 32) {
  94300. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94301. return false;
  94302. }
  94303. else {
  94304. /* write the unary MSBs */
  94305. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94306. return false;
  94307. /* write the unary end bit and binary LSBs */
  94308. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94309. return false;
  94310. }
  94311. }
  94312. else {
  94313. unsigned q, r, d;
  94314. d = (1 << (k+1)) - parameter;
  94315. q = uval / parameter;
  94316. r = uval - (q * parameter);
  94317. /* write the unary MSBs */
  94318. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94319. return false;
  94320. /* write the unary end bit */
  94321. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94322. return false;
  94323. /* write the binary LSBs */
  94324. if(r >= d) {
  94325. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94326. return false;
  94327. }
  94328. else {
  94329. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94330. return false;
  94331. }
  94332. }
  94333. return true;
  94334. }
  94335. #endif /* UNUSED */
  94336. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94337. {
  94338. FLAC__bool ok = 1;
  94339. FLAC__ASSERT(0 != bw);
  94340. FLAC__ASSERT(0 != bw->buffer);
  94341. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94342. if(val < 0x80) {
  94343. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94344. }
  94345. else if(val < 0x800) {
  94346. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94347. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94348. }
  94349. else if(val < 0x10000) {
  94350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94351. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94352. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94353. }
  94354. else if(val < 0x200000) {
  94355. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94356. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94357. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94358. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94359. }
  94360. else if(val < 0x4000000) {
  94361. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94362. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94363. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94364. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94365. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94366. }
  94367. else {
  94368. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94369. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94370. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94371. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94372. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94373. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94374. }
  94375. return ok;
  94376. }
  94377. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94378. {
  94379. FLAC__bool ok = 1;
  94380. FLAC__ASSERT(0 != bw);
  94381. FLAC__ASSERT(0 != bw->buffer);
  94382. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94383. if(val < 0x80) {
  94384. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94385. }
  94386. else if(val < 0x800) {
  94387. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94388. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94389. }
  94390. else if(val < 0x10000) {
  94391. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94392. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94393. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94394. }
  94395. else if(val < 0x200000) {
  94396. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94397. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94398. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94399. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94400. }
  94401. else if(val < 0x4000000) {
  94402. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94403. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94404. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94405. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94406. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94407. }
  94408. else if(val < 0x80000000) {
  94409. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94410. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94411. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94412. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94413. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94414. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94415. }
  94416. else {
  94417. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94418. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94419. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94420. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94421. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94422. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94423. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94424. }
  94425. return ok;
  94426. }
  94427. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94428. {
  94429. /* 0-pad to byte boundary */
  94430. if(bw->bits & 7u)
  94431. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94432. else
  94433. return true;
  94434. }
  94435. #endif
  94436. /*** End of inlined file: bitwriter.c ***/
  94437. /*** Start of inlined file: cpu.c ***/
  94438. /*** Start of inlined file: juce_FlacHeader.h ***/
  94439. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94440. // tasks..
  94441. #define VERSION "1.2.1"
  94442. #define FLAC__NO_DLL 1
  94443. #if JUCE_MSVC
  94444. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94445. #endif
  94446. #if JUCE_MAC
  94447. #define FLAC__SYS_DARWIN 1
  94448. #endif
  94449. /*** End of inlined file: juce_FlacHeader.h ***/
  94450. #if JUCE_USE_FLAC
  94451. #if HAVE_CONFIG_H
  94452. # include <config.h>
  94453. #endif
  94454. #include <stdlib.h>
  94455. #include <stdio.h>
  94456. #if defined FLAC__CPU_IA32
  94457. # include <signal.h>
  94458. #elif defined FLAC__CPU_PPC
  94459. # if !defined FLAC__NO_ASM
  94460. # if defined FLAC__SYS_DARWIN
  94461. # include <sys/sysctl.h>
  94462. # include <mach/mach.h>
  94463. # include <mach/mach_host.h>
  94464. # include <mach/host_info.h>
  94465. # include <mach/machine.h>
  94466. # ifndef CPU_SUBTYPE_POWERPC_970
  94467. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94468. # endif
  94469. # else /* FLAC__SYS_DARWIN */
  94470. # include <signal.h>
  94471. # include <setjmp.h>
  94472. static sigjmp_buf jmpbuf;
  94473. static volatile sig_atomic_t canjump = 0;
  94474. static void sigill_handler (int sig)
  94475. {
  94476. if (!canjump) {
  94477. signal (sig, SIG_DFL);
  94478. raise (sig);
  94479. }
  94480. canjump = 0;
  94481. siglongjmp (jmpbuf, 1);
  94482. }
  94483. # endif /* FLAC__SYS_DARWIN */
  94484. # endif /* FLAC__NO_ASM */
  94485. #endif /* FLAC__CPU_PPC */
  94486. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94487. #include <sys/param.h>
  94488. #include <sys/sysctl.h>
  94489. #include <machine/cpu.h>
  94490. #endif
  94491. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94492. #include <sys/types.h>
  94493. #include <sys/sysctl.h>
  94494. #endif
  94495. #if defined(__APPLE__)
  94496. /* how to get sysctlbyname()? */
  94497. #endif
  94498. /* these are flags in EDX of CPUID AX=00000001 */
  94499. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94500. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94501. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94502. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94503. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94504. /* these are flags in ECX of CPUID AX=00000001 */
  94505. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94506. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94507. /* these are flags in EDX of CPUID AX=80000001 */
  94508. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94509. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94510. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94511. /*
  94512. * Extra stuff needed for detection of OS support for SSE on IA-32
  94513. */
  94514. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94515. # if defined(__linux__)
  94516. /*
  94517. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94518. * modify the return address to jump over the offending SSE instruction
  94519. * and also the operation following it that indicates the instruction
  94520. * executed successfully. In this way we use no global variables and
  94521. * stay thread-safe.
  94522. *
  94523. * 3 + 3 + 6:
  94524. * 3 bytes for "xorps xmm0,xmm0"
  94525. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94526. * 6 bytes extra in case our estimate is wrong
  94527. * 12 bytes puts us in the NOP "landing zone"
  94528. */
  94529. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94530. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94531. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94532. {
  94533. (void)signal;
  94534. sc.eip += 3 + 3 + 6;
  94535. }
  94536. # else
  94537. # include <sys/ucontext.h>
  94538. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94539. {
  94540. (void)signal, (void)si;
  94541. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94542. }
  94543. # endif
  94544. # elif defined(_MSC_VER)
  94545. # include <windows.h>
  94546. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94547. # ifdef USE_TRY_CATCH_FLAVOR
  94548. # else
  94549. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94550. {
  94551. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94552. ep->ContextRecord->Eip += 3 + 3 + 6;
  94553. return EXCEPTION_CONTINUE_EXECUTION;
  94554. }
  94555. return EXCEPTION_CONTINUE_SEARCH;
  94556. }
  94557. # endif
  94558. # endif
  94559. #endif
  94560. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94561. {
  94562. /*
  94563. * IA32-specific
  94564. */
  94565. #ifdef FLAC__CPU_IA32
  94566. info->type = FLAC__CPUINFO_TYPE_IA32;
  94567. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94568. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94569. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94570. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94571. info->data.ia32.cmov = false;
  94572. info->data.ia32.mmx = false;
  94573. info->data.ia32.fxsr = false;
  94574. info->data.ia32.sse = false;
  94575. info->data.ia32.sse2 = false;
  94576. info->data.ia32.sse3 = false;
  94577. info->data.ia32.ssse3 = false;
  94578. info->data.ia32._3dnow = false;
  94579. info->data.ia32.ext3dnow = false;
  94580. info->data.ia32.extmmx = false;
  94581. if(info->data.ia32.cpuid) {
  94582. /* http://www.sandpile.org/ia32/cpuid.htm */
  94583. FLAC__uint32 flags_edx, flags_ecx;
  94584. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94585. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94586. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94587. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94588. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94589. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94590. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94591. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94592. #ifdef FLAC__USE_3DNOW
  94593. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94594. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94595. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94596. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94597. #else
  94598. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94599. #endif
  94600. #ifdef DEBUG
  94601. fprintf(stderr, "CPU info (IA-32):\n");
  94602. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94603. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94604. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94605. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94606. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94607. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94608. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94609. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94610. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94611. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94612. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94613. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94614. #endif
  94615. /*
  94616. * now have to check for OS support of SSE/SSE2
  94617. */
  94618. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94619. #if defined FLAC__NO_SSE_OS
  94620. /* assume user knows better than us; turn it off */
  94621. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94622. #elif defined FLAC__SSE_OS
  94623. /* assume user knows better than us; leave as detected above */
  94624. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94625. int sse = 0;
  94626. size_t len;
  94627. /* at least one of these must work: */
  94628. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94629. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94630. if(!sse)
  94631. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94632. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94633. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94634. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94635. size_t len = sizeof(val);
  94636. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94637. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94638. else { /* double-check SSE2 */
  94639. mib[1] = CPU_SSE2;
  94640. len = sizeof(val);
  94641. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94642. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94643. }
  94644. # else
  94645. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94646. # endif
  94647. #elif defined(__linux__)
  94648. int sse = 0;
  94649. struct sigaction sigill_save;
  94650. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94651. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94652. #else
  94653. struct sigaction sigill_sse;
  94654. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94655. __sigemptyset(&sigill_sse.sa_mask);
  94656. 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 */
  94657. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94658. #endif
  94659. {
  94660. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94661. /* see sigill_handler_sse_os() for an explanation of the following: */
  94662. asm volatile (
  94663. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94664. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94665. "incl %0\n\t" /* SIGILL handler will jump over this */
  94666. /* landing zone */
  94667. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94668. "nop\n\t"
  94669. "nop\n\t"
  94670. "nop\n\t"
  94671. "nop\n\t"
  94672. "nop\n\t"
  94673. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94674. "nop\n\t"
  94675. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94676. : "=r"(sse)
  94677. : "r"(sse)
  94678. );
  94679. sigaction(SIGILL, &sigill_save, NULL);
  94680. }
  94681. if(!sse)
  94682. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94683. #elif defined(_MSC_VER)
  94684. # ifdef USE_TRY_CATCH_FLAVOR
  94685. _try {
  94686. __asm {
  94687. # if _MSC_VER <= 1200
  94688. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94689. _emit 0x0F
  94690. _emit 0x57
  94691. _emit 0xC0
  94692. # else
  94693. xorps xmm0,xmm0
  94694. # endif
  94695. }
  94696. }
  94697. _except(EXCEPTION_EXECUTE_HANDLER) {
  94698. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94699. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94700. }
  94701. # else
  94702. int sse = 0;
  94703. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94704. /* see GCC version above for explanation */
  94705. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94706. /* http://www.codeproject.com/cpp/gccasm.asp */
  94707. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94708. __asm {
  94709. # if _MSC_VER <= 1200
  94710. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94711. _emit 0x0F
  94712. _emit 0x57
  94713. _emit 0xC0
  94714. # else
  94715. xorps xmm0,xmm0
  94716. # endif
  94717. inc sse
  94718. nop
  94719. nop
  94720. nop
  94721. nop
  94722. nop
  94723. nop
  94724. nop
  94725. nop
  94726. nop
  94727. }
  94728. SetUnhandledExceptionFilter(save);
  94729. if(!sse)
  94730. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94731. # endif
  94732. #else
  94733. /* no way to test, disable to be safe */
  94734. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94735. #endif
  94736. #ifdef DEBUG
  94737. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94738. #endif
  94739. }
  94740. }
  94741. #else
  94742. info->use_asm = false;
  94743. #endif
  94744. /*
  94745. * PPC-specific
  94746. */
  94747. #elif defined FLAC__CPU_PPC
  94748. info->type = FLAC__CPUINFO_TYPE_PPC;
  94749. # if !defined FLAC__NO_ASM
  94750. info->use_asm = true;
  94751. # ifdef FLAC__USE_ALTIVEC
  94752. # if defined FLAC__SYS_DARWIN
  94753. {
  94754. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94755. size_t len = sizeof(val);
  94756. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94757. }
  94758. {
  94759. host_basic_info_data_t hostInfo;
  94760. mach_msg_type_number_t infoCount;
  94761. infoCount = HOST_BASIC_INFO_COUNT;
  94762. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94763. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94764. }
  94765. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94766. {
  94767. /* no Darwin, do it the brute-force way */
  94768. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94769. info->data.ppc.altivec = 0;
  94770. info->data.ppc.ppc64 = 0;
  94771. signal (SIGILL, sigill_handler);
  94772. canjump = 0;
  94773. if (!sigsetjmp (jmpbuf, 1)) {
  94774. canjump = 1;
  94775. asm volatile (
  94776. "mtspr 256, %0\n\t"
  94777. "vand %%v0, %%v0, %%v0"
  94778. :
  94779. : "r" (-1)
  94780. );
  94781. info->data.ppc.altivec = 1;
  94782. }
  94783. canjump = 0;
  94784. if (!sigsetjmp (jmpbuf, 1)) {
  94785. int x = 0;
  94786. canjump = 1;
  94787. /* PPC64 hardware implements the cntlzd instruction */
  94788. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94789. info->data.ppc.ppc64 = 1;
  94790. }
  94791. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94792. }
  94793. # endif
  94794. # else /* !FLAC__USE_ALTIVEC */
  94795. info->data.ppc.altivec = 0;
  94796. info->data.ppc.ppc64 = 0;
  94797. # endif
  94798. # else
  94799. info->use_asm = false;
  94800. # endif
  94801. /*
  94802. * unknown CPI
  94803. */
  94804. #else
  94805. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94806. info->use_asm = false;
  94807. #endif
  94808. }
  94809. #endif
  94810. /*** End of inlined file: cpu.c ***/
  94811. /*** Start of inlined file: crc.c ***/
  94812. /*** Start of inlined file: juce_FlacHeader.h ***/
  94813. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94814. // tasks..
  94815. #define VERSION "1.2.1"
  94816. #define FLAC__NO_DLL 1
  94817. #if JUCE_MSVC
  94818. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94819. #endif
  94820. #if JUCE_MAC
  94821. #define FLAC__SYS_DARWIN 1
  94822. #endif
  94823. /*** End of inlined file: juce_FlacHeader.h ***/
  94824. #if JUCE_USE_FLAC
  94825. #if HAVE_CONFIG_H
  94826. # include <config.h>
  94827. #endif
  94828. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  94829. FLAC__byte const FLAC__crc8_table[256] = {
  94830. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  94831. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  94832. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  94833. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  94834. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  94835. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  94836. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  94837. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  94838. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  94839. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  94840. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  94841. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  94842. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  94843. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  94844. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  94845. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  94846. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  94847. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  94848. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  94849. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  94850. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  94851. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  94852. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  94853. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  94854. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  94855. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  94856. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  94857. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  94858. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  94859. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  94860. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  94861. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  94862. };
  94863. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  94864. unsigned FLAC__crc16_table[256] = {
  94865. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  94866. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  94867. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  94868. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  94869. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  94870. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  94871. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  94872. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  94873. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  94874. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  94875. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  94876. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  94877. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  94878. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  94879. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  94880. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  94881. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  94882. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  94883. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  94884. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  94885. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  94886. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  94887. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  94888. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  94889. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  94890. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  94891. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  94892. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  94893. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  94894. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  94895. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  94896. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  94897. };
  94898. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  94899. {
  94900. *crc = FLAC__crc8_table[*crc ^ data];
  94901. }
  94902. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  94903. {
  94904. while(len--)
  94905. *crc = FLAC__crc8_table[*crc ^ *data++];
  94906. }
  94907. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  94908. {
  94909. FLAC__uint8 crc = 0;
  94910. while(len--)
  94911. crc = FLAC__crc8_table[crc ^ *data++];
  94912. return crc;
  94913. }
  94914. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  94915. {
  94916. unsigned crc = 0;
  94917. while(len--)
  94918. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  94919. return crc;
  94920. }
  94921. #endif
  94922. /*** End of inlined file: crc.c ***/
  94923. /*** Start of inlined file: fixed.c ***/
  94924. /*** Start of inlined file: juce_FlacHeader.h ***/
  94925. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94926. // tasks..
  94927. #define VERSION "1.2.1"
  94928. #define FLAC__NO_DLL 1
  94929. #if JUCE_MSVC
  94930. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94931. #endif
  94932. #if JUCE_MAC
  94933. #define FLAC__SYS_DARWIN 1
  94934. #endif
  94935. /*** End of inlined file: juce_FlacHeader.h ***/
  94936. #if JUCE_USE_FLAC
  94937. #if HAVE_CONFIG_H
  94938. # include <config.h>
  94939. #endif
  94940. #include <math.h>
  94941. #include <string.h>
  94942. /*** Start of inlined file: fixed.h ***/
  94943. #ifndef FLAC__PRIVATE__FIXED_H
  94944. #define FLAC__PRIVATE__FIXED_H
  94945. #ifdef HAVE_CONFIG_H
  94946. #include <config.h>
  94947. #endif
  94948. /*** Start of inlined file: float.h ***/
  94949. #ifndef FLAC__PRIVATE__FLOAT_H
  94950. #define FLAC__PRIVATE__FLOAT_H
  94951. #ifdef HAVE_CONFIG_H
  94952. #include <config.h>
  94953. #endif
  94954. /*
  94955. * These typedefs make it easier to ensure that integer versions of
  94956. * the library really only contain integer operations. All the code
  94957. * in libFLAC should use FLAC__float and FLAC__double in place of
  94958. * float and double, and be protected by checks of the macro
  94959. * FLAC__INTEGER_ONLY_LIBRARY.
  94960. *
  94961. * FLAC__real is the basic floating point type used in LPC analysis.
  94962. */
  94963. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94964. typedef double FLAC__double;
  94965. typedef float FLAC__float;
  94966. /*
  94967. * WATCHOUT: changing FLAC__real will change the signatures of many
  94968. * functions that have assembly language equivalents and break them.
  94969. */
  94970. typedef float FLAC__real;
  94971. #else
  94972. /*
  94973. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  94974. * for the integer part and lower 16 bits for the fractional part.
  94975. */
  94976. typedef FLAC__int32 FLAC__fixedpoint;
  94977. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  94978. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  94979. extern const FLAC__fixedpoint FLAC__FP_ONE;
  94980. extern const FLAC__fixedpoint FLAC__FP_LN2;
  94981. extern const FLAC__fixedpoint FLAC__FP_E;
  94982. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  94983. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  94984. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  94985. /*
  94986. * FLAC__fixedpoint_log2()
  94987. * --------------------------------------------------------------------
  94988. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  94989. * algorithm by Knuth for x >= 1.0
  94990. *
  94991. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  94992. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  94993. *
  94994. * 'precision' roughly limits the number of iterations that are done;
  94995. * use (unsigned)(-1) for maximum precision.
  94996. *
  94997. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  94998. * function will punt and return 0.
  94999. *
  95000. * The return value will also have 'fracbits' fractional bits.
  95001. */
  95002. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95003. #endif
  95004. #endif
  95005. /*** End of inlined file: float.h ***/
  95006. /*** Start of inlined file: format.h ***/
  95007. #ifndef FLAC__PRIVATE__FORMAT_H
  95008. #define FLAC__PRIVATE__FORMAT_H
  95009. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95010. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95011. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95012. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95013. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95014. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95015. #endif
  95016. /*** End of inlined file: format.h ***/
  95017. /*
  95018. * FLAC__fixed_compute_best_predictor()
  95019. * --------------------------------------------------------------------
  95020. * Compute the best fixed predictor and the expected bits-per-sample
  95021. * of the residual signal for each order. The _wide() version uses
  95022. * 64-bit integers which is statistically necessary when bits-per-
  95023. * sample + log2(blocksize) > 30
  95024. *
  95025. * IN data[0,data_len-1]
  95026. * IN data_len
  95027. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95028. */
  95029. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95030. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95031. # ifndef FLAC__NO_ASM
  95032. # ifdef FLAC__CPU_IA32
  95033. # ifdef FLAC__HAS_NASM
  95034. 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]);
  95035. # endif
  95036. # endif
  95037. # endif
  95038. 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]);
  95039. #else
  95040. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95041. 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]);
  95042. #endif
  95043. /*
  95044. * FLAC__fixed_compute_residual()
  95045. * --------------------------------------------------------------------
  95046. * Compute the residual signal obtained from sutracting the predicted
  95047. * signal from the original.
  95048. *
  95049. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95050. * IN data_len length of original signal
  95051. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95052. * OUT residual[0,data_len-1] residual signal
  95053. */
  95054. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95055. /*
  95056. * FLAC__fixed_restore_signal()
  95057. * --------------------------------------------------------------------
  95058. * Restore the original signal by summing the residual and the
  95059. * predictor.
  95060. *
  95061. * IN residual[0,data_len-1] residual signal
  95062. * IN data_len length of original signal
  95063. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95064. * *** IMPORTANT: the caller must pass in the historical samples:
  95065. * IN data[-order,-1] previously-reconstructed historical samples
  95066. * OUT data[0,data_len-1] original signal
  95067. */
  95068. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95069. #endif
  95070. /*** End of inlined file: fixed.h ***/
  95071. #ifndef M_LN2
  95072. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95073. #define M_LN2 0.69314718055994530942
  95074. #endif
  95075. #ifdef min
  95076. #undef min
  95077. #endif
  95078. #define min(x,y) ((x) < (y)? (x) : (y))
  95079. #ifdef local_abs
  95080. #undef local_abs
  95081. #endif
  95082. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95083. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95084. /* rbps stands for residual bits per sample
  95085. *
  95086. * (ln(2) * err)
  95087. * rbps = log (-----------)
  95088. * 2 ( n )
  95089. */
  95090. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95091. {
  95092. FLAC__uint32 rbps;
  95093. unsigned bits; /* the number of bits required to represent a number */
  95094. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95095. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95096. FLAC__ASSERT(err > 0);
  95097. FLAC__ASSERT(n > 0);
  95098. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95099. if(err <= n)
  95100. return 0;
  95101. /*
  95102. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95103. * These allow us later to know we won't lose too much precision in the
  95104. * fixed-point division (err<<fracbits)/n.
  95105. */
  95106. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95107. err <<= fracbits;
  95108. err /= n;
  95109. /* err now holds err/n with fracbits fractional bits */
  95110. /*
  95111. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95112. * our purposes.
  95113. */
  95114. FLAC__ASSERT(err > 0);
  95115. bits = FLAC__bitmath_ilog2(err)+1;
  95116. if(bits > 16) {
  95117. err >>= (bits-16);
  95118. fracbits -= (bits-16);
  95119. }
  95120. rbps = (FLAC__uint32)err;
  95121. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95122. rbps *= FLAC__FP_LN2;
  95123. fracbits += 16;
  95124. FLAC__ASSERT(fracbits >= 0);
  95125. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95126. {
  95127. const int f = fracbits & 3;
  95128. if(f) {
  95129. rbps >>= f;
  95130. fracbits -= f;
  95131. }
  95132. }
  95133. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95134. if(rbps == 0)
  95135. return 0;
  95136. /*
  95137. * The return value must have 16 fractional bits. Since the whole part
  95138. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95139. * must be >= -3, these assertion allows us to be able to shift rbps
  95140. * left if necessary to get 16 fracbits without losing any bits of the
  95141. * whole part of rbps.
  95142. *
  95143. * There is a slight chance due to accumulated error that the whole part
  95144. * will require 6 bits, so we use 6 in the assertion. Really though as
  95145. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95146. */
  95147. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95148. FLAC__ASSERT(fracbits >= -3);
  95149. /* now shift the decimal point into place */
  95150. if(fracbits < 16)
  95151. return rbps << (16-fracbits);
  95152. else if(fracbits > 16)
  95153. return rbps >> (fracbits-16);
  95154. else
  95155. return rbps;
  95156. }
  95157. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95158. {
  95159. FLAC__uint32 rbps;
  95160. unsigned bits; /* the number of bits required to represent a number */
  95161. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95162. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95163. FLAC__ASSERT(err > 0);
  95164. FLAC__ASSERT(n > 0);
  95165. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95166. if(err <= n)
  95167. return 0;
  95168. /*
  95169. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95170. * These allow us later to know we won't lose too much precision in the
  95171. * fixed-point division (err<<fracbits)/n.
  95172. */
  95173. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95174. err <<= fracbits;
  95175. err /= n;
  95176. /* err now holds err/n with fracbits fractional bits */
  95177. /*
  95178. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95179. * our purposes.
  95180. */
  95181. FLAC__ASSERT(err > 0);
  95182. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95183. if(bits > 16) {
  95184. err >>= (bits-16);
  95185. fracbits -= (bits-16);
  95186. }
  95187. rbps = (FLAC__uint32)err;
  95188. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95189. rbps *= FLAC__FP_LN2;
  95190. fracbits += 16;
  95191. FLAC__ASSERT(fracbits >= 0);
  95192. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95193. {
  95194. const int f = fracbits & 3;
  95195. if(f) {
  95196. rbps >>= f;
  95197. fracbits -= f;
  95198. }
  95199. }
  95200. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95201. if(rbps == 0)
  95202. return 0;
  95203. /*
  95204. * The return value must have 16 fractional bits. Since the whole part
  95205. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95206. * must be >= -3, these assertion allows us to be able to shift rbps
  95207. * left if necessary to get 16 fracbits without losing any bits of the
  95208. * whole part of rbps.
  95209. *
  95210. * There is a slight chance due to accumulated error that the whole part
  95211. * will require 6 bits, so we use 6 in the assertion. Really though as
  95212. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95213. */
  95214. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95215. FLAC__ASSERT(fracbits >= -3);
  95216. /* now shift the decimal point into place */
  95217. if(fracbits < 16)
  95218. return rbps << (16-fracbits);
  95219. else if(fracbits > 16)
  95220. return rbps >> (fracbits-16);
  95221. else
  95222. return rbps;
  95223. }
  95224. #endif
  95225. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95226. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95227. #else
  95228. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95229. #endif
  95230. {
  95231. FLAC__int32 last_error_0 = data[-1];
  95232. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95233. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95234. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95235. FLAC__int32 error, save;
  95236. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95237. unsigned i, order;
  95238. for(i = 0; i < data_len; i++) {
  95239. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95240. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95241. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95242. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95243. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95244. }
  95245. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95246. order = 0;
  95247. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95248. order = 1;
  95249. else if(total_error_2 < min(total_error_3, total_error_4))
  95250. order = 2;
  95251. else if(total_error_3 < total_error_4)
  95252. order = 3;
  95253. else
  95254. order = 4;
  95255. /* Estimate the expected number of bits per residual signal sample. */
  95256. /* 'total_error*' is linearly related to the variance of the residual */
  95257. /* signal, so we use it directly to compute E(|x|) */
  95258. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95259. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95260. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95261. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95262. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95263. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95264. 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);
  95265. 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);
  95266. 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);
  95267. 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);
  95268. 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);
  95269. #else
  95270. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95271. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95272. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95273. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95274. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95275. #endif
  95276. return order;
  95277. }
  95278. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95279. 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])
  95280. #else
  95281. 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])
  95282. #endif
  95283. {
  95284. FLAC__int32 last_error_0 = data[-1];
  95285. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95286. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95287. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95288. FLAC__int32 error, save;
  95289. /* total_error_* are 64-bits to avoid overflow when encoding
  95290. * erratic signals when the bits-per-sample and blocksize are
  95291. * large.
  95292. */
  95293. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95294. unsigned i, order;
  95295. for(i = 0; i < data_len; i++) {
  95296. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95297. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95298. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95299. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95300. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95301. }
  95302. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95303. order = 0;
  95304. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95305. order = 1;
  95306. else if(total_error_2 < min(total_error_3, total_error_4))
  95307. order = 2;
  95308. else if(total_error_3 < total_error_4)
  95309. order = 3;
  95310. else
  95311. order = 4;
  95312. /* Estimate the expected number of bits per residual signal sample. */
  95313. /* 'total_error*' is linearly related to the variance of the residual */
  95314. /* signal, so we use it directly to compute E(|x|) */
  95315. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95316. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95317. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95318. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95319. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95320. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95321. #if defined _MSC_VER || defined __MINGW32__
  95322. /* with MSVC you have to spoon feed it the casting */
  95323. 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);
  95324. 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);
  95325. 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);
  95326. 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);
  95327. 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);
  95328. #else
  95329. 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);
  95330. 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);
  95331. 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);
  95332. 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);
  95333. 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);
  95334. #endif
  95335. #else
  95336. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95337. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95338. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95339. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95340. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95341. #endif
  95342. return order;
  95343. }
  95344. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95345. {
  95346. const int idata_len = (int)data_len;
  95347. int i;
  95348. switch(order) {
  95349. case 0:
  95350. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95351. memcpy(residual, data, sizeof(residual[0])*data_len);
  95352. break;
  95353. case 1:
  95354. for(i = 0; i < idata_len; i++)
  95355. residual[i] = data[i] - data[i-1];
  95356. break;
  95357. case 2:
  95358. for(i = 0; i < idata_len; i++)
  95359. #if 1 /* OPT: may be faster with some compilers on some systems */
  95360. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95361. #else
  95362. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95363. #endif
  95364. break;
  95365. case 3:
  95366. for(i = 0; i < idata_len; i++)
  95367. #if 1 /* OPT: may be faster with some compilers on some systems */
  95368. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95369. #else
  95370. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95371. #endif
  95372. break;
  95373. case 4:
  95374. for(i = 0; i < idata_len; i++)
  95375. #if 1 /* OPT: may be faster with some compilers on some systems */
  95376. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95377. #else
  95378. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95379. #endif
  95380. break;
  95381. default:
  95382. FLAC__ASSERT(0);
  95383. }
  95384. }
  95385. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95386. {
  95387. int i, idata_len = (int)data_len;
  95388. switch(order) {
  95389. case 0:
  95390. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95391. memcpy(data, residual, sizeof(residual[0])*data_len);
  95392. break;
  95393. case 1:
  95394. for(i = 0; i < idata_len; i++)
  95395. data[i] = residual[i] + data[i-1];
  95396. break;
  95397. case 2:
  95398. for(i = 0; i < idata_len; i++)
  95399. #if 1 /* OPT: may be faster with some compilers on some systems */
  95400. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95401. #else
  95402. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95403. #endif
  95404. break;
  95405. case 3:
  95406. for(i = 0; i < idata_len; i++)
  95407. #if 1 /* OPT: may be faster with some compilers on some systems */
  95408. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95409. #else
  95410. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95411. #endif
  95412. break;
  95413. case 4:
  95414. for(i = 0; i < idata_len; i++)
  95415. #if 1 /* OPT: may be faster with some compilers on some systems */
  95416. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95417. #else
  95418. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95419. #endif
  95420. break;
  95421. default:
  95422. FLAC__ASSERT(0);
  95423. }
  95424. }
  95425. #endif
  95426. /*** End of inlined file: fixed.c ***/
  95427. /*** Start of inlined file: float.c ***/
  95428. /*** Start of inlined file: juce_FlacHeader.h ***/
  95429. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95430. // tasks..
  95431. #define VERSION "1.2.1"
  95432. #define FLAC__NO_DLL 1
  95433. #if JUCE_MSVC
  95434. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95435. #endif
  95436. #if JUCE_MAC
  95437. #define FLAC__SYS_DARWIN 1
  95438. #endif
  95439. /*** End of inlined file: juce_FlacHeader.h ***/
  95440. #if JUCE_USE_FLAC
  95441. #if HAVE_CONFIG_H
  95442. # include <config.h>
  95443. #endif
  95444. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95445. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95446. #ifdef _MSC_VER
  95447. #define FLAC__U64L(x) x
  95448. #else
  95449. #define FLAC__U64L(x) x##LLU
  95450. #endif
  95451. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95452. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95453. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95454. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95455. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95456. /* Lookup tables for Knuth's logarithm algorithm */
  95457. #define LOG2_LOOKUP_PRECISION 16
  95458. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95459. {
  95460. /*
  95461. * 0 fraction bits
  95462. */
  95463. /* undefined */ 0x00000000,
  95464. /* lg(2/1) = */ 0x00000001,
  95465. /* lg(4/3) = */ 0x00000000,
  95466. /* lg(8/7) = */ 0x00000000,
  95467. /* lg(16/15) = */ 0x00000000,
  95468. /* lg(32/31) = */ 0x00000000,
  95469. /* lg(64/63) = */ 0x00000000,
  95470. /* lg(128/127) = */ 0x00000000,
  95471. /* lg(256/255) = */ 0x00000000,
  95472. /* lg(512/511) = */ 0x00000000,
  95473. /* lg(1024/1023) = */ 0x00000000,
  95474. /* lg(2048/2047) = */ 0x00000000,
  95475. /* lg(4096/4095) = */ 0x00000000,
  95476. /* lg(8192/8191) = */ 0x00000000,
  95477. /* lg(16384/16383) = */ 0x00000000,
  95478. /* lg(32768/32767) = */ 0x00000000
  95479. },
  95480. {
  95481. /*
  95482. * 4 fraction bits
  95483. */
  95484. /* undefined */ 0x00000000,
  95485. /* lg(2/1) = */ 0x00000010,
  95486. /* lg(4/3) = */ 0x00000007,
  95487. /* lg(8/7) = */ 0x00000003,
  95488. /* lg(16/15) = */ 0x00000001,
  95489. /* lg(32/31) = */ 0x00000001,
  95490. /* lg(64/63) = */ 0x00000000,
  95491. /* lg(128/127) = */ 0x00000000,
  95492. /* lg(256/255) = */ 0x00000000,
  95493. /* lg(512/511) = */ 0x00000000,
  95494. /* lg(1024/1023) = */ 0x00000000,
  95495. /* lg(2048/2047) = */ 0x00000000,
  95496. /* lg(4096/4095) = */ 0x00000000,
  95497. /* lg(8192/8191) = */ 0x00000000,
  95498. /* lg(16384/16383) = */ 0x00000000,
  95499. /* lg(32768/32767) = */ 0x00000000
  95500. },
  95501. {
  95502. /*
  95503. * 8 fraction bits
  95504. */
  95505. /* undefined */ 0x00000000,
  95506. /* lg(2/1) = */ 0x00000100,
  95507. /* lg(4/3) = */ 0x0000006a,
  95508. /* lg(8/7) = */ 0x00000031,
  95509. /* lg(16/15) = */ 0x00000018,
  95510. /* lg(32/31) = */ 0x0000000c,
  95511. /* lg(64/63) = */ 0x00000006,
  95512. /* lg(128/127) = */ 0x00000003,
  95513. /* lg(256/255) = */ 0x00000001,
  95514. /* lg(512/511) = */ 0x00000001,
  95515. /* lg(1024/1023) = */ 0x00000000,
  95516. /* lg(2048/2047) = */ 0x00000000,
  95517. /* lg(4096/4095) = */ 0x00000000,
  95518. /* lg(8192/8191) = */ 0x00000000,
  95519. /* lg(16384/16383) = */ 0x00000000,
  95520. /* lg(32768/32767) = */ 0x00000000
  95521. },
  95522. {
  95523. /*
  95524. * 12 fraction bits
  95525. */
  95526. /* undefined */ 0x00000000,
  95527. /* lg(2/1) = */ 0x00001000,
  95528. /* lg(4/3) = */ 0x000006a4,
  95529. /* lg(8/7) = */ 0x00000315,
  95530. /* lg(16/15) = */ 0x0000017d,
  95531. /* lg(32/31) = */ 0x000000bc,
  95532. /* lg(64/63) = */ 0x0000005d,
  95533. /* lg(128/127) = */ 0x0000002e,
  95534. /* lg(256/255) = */ 0x00000017,
  95535. /* lg(512/511) = */ 0x0000000c,
  95536. /* lg(1024/1023) = */ 0x00000006,
  95537. /* lg(2048/2047) = */ 0x00000003,
  95538. /* lg(4096/4095) = */ 0x00000001,
  95539. /* lg(8192/8191) = */ 0x00000001,
  95540. /* lg(16384/16383) = */ 0x00000000,
  95541. /* lg(32768/32767) = */ 0x00000000
  95542. },
  95543. {
  95544. /*
  95545. * 16 fraction bits
  95546. */
  95547. /* undefined */ 0x00000000,
  95548. /* lg(2/1) = */ 0x00010000,
  95549. /* lg(4/3) = */ 0x00006a40,
  95550. /* lg(8/7) = */ 0x00003151,
  95551. /* lg(16/15) = */ 0x000017d6,
  95552. /* lg(32/31) = */ 0x00000bba,
  95553. /* lg(64/63) = */ 0x000005d1,
  95554. /* lg(128/127) = */ 0x000002e6,
  95555. /* lg(256/255) = */ 0x00000172,
  95556. /* lg(512/511) = */ 0x000000b9,
  95557. /* lg(1024/1023) = */ 0x0000005c,
  95558. /* lg(2048/2047) = */ 0x0000002e,
  95559. /* lg(4096/4095) = */ 0x00000017,
  95560. /* lg(8192/8191) = */ 0x0000000c,
  95561. /* lg(16384/16383) = */ 0x00000006,
  95562. /* lg(32768/32767) = */ 0x00000003
  95563. },
  95564. {
  95565. /*
  95566. * 20 fraction bits
  95567. */
  95568. /* undefined */ 0x00000000,
  95569. /* lg(2/1) = */ 0x00100000,
  95570. /* lg(4/3) = */ 0x0006a3fe,
  95571. /* lg(8/7) = */ 0x00031513,
  95572. /* lg(16/15) = */ 0x00017d60,
  95573. /* lg(32/31) = */ 0x0000bb9d,
  95574. /* lg(64/63) = */ 0x00005d10,
  95575. /* lg(128/127) = */ 0x00002e59,
  95576. /* lg(256/255) = */ 0x00001721,
  95577. /* lg(512/511) = */ 0x00000b8e,
  95578. /* lg(1024/1023) = */ 0x000005c6,
  95579. /* lg(2048/2047) = */ 0x000002e3,
  95580. /* lg(4096/4095) = */ 0x00000171,
  95581. /* lg(8192/8191) = */ 0x000000b9,
  95582. /* lg(16384/16383) = */ 0x0000005c,
  95583. /* lg(32768/32767) = */ 0x0000002e
  95584. },
  95585. {
  95586. /*
  95587. * 24 fraction bits
  95588. */
  95589. /* undefined */ 0x00000000,
  95590. /* lg(2/1) = */ 0x01000000,
  95591. /* lg(4/3) = */ 0x006a3fe6,
  95592. /* lg(8/7) = */ 0x00315130,
  95593. /* lg(16/15) = */ 0x0017d605,
  95594. /* lg(32/31) = */ 0x000bb9ca,
  95595. /* lg(64/63) = */ 0x0005d0fc,
  95596. /* lg(128/127) = */ 0x0002e58f,
  95597. /* lg(256/255) = */ 0x0001720e,
  95598. /* lg(512/511) = */ 0x0000b8d8,
  95599. /* lg(1024/1023) = */ 0x00005c61,
  95600. /* lg(2048/2047) = */ 0x00002e2d,
  95601. /* lg(4096/4095) = */ 0x00001716,
  95602. /* lg(8192/8191) = */ 0x00000b8b,
  95603. /* lg(16384/16383) = */ 0x000005c5,
  95604. /* lg(32768/32767) = */ 0x000002e3
  95605. },
  95606. {
  95607. /*
  95608. * 28 fraction bits
  95609. */
  95610. /* undefined */ 0x00000000,
  95611. /* lg(2/1) = */ 0x10000000,
  95612. /* lg(4/3) = */ 0x06a3fe5c,
  95613. /* lg(8/7) = */ 0x03151301,
  95614. /* lg(16/15) = */ 0x017d6049,
  95615. /* lg(32/31) = */ 0x00bb9ca6,
  95616. /* lg(64/63) = */ 0x005d0fba,
  95617. /* lg(128/127) = */ 0x002e58f7,
  95618. /* lg(256/255) = */ 0x001720da,
  95619. /* lg(512/511) = */ 0x000b8d87,
  95620. /* lg(1024/1023) = */ 0x0005c60b,
  95621. /* lg(2048/2047) = */ 0x0002e2d7,
  95622. /* lg(4096/4095) = */ 0x00017160,
  95623. /* lg(8192/8191) = */ 0x0000b8ad,
  95624. /* lg(16384/16383) = */ 0x00005c56,
  95625. /* lg(32768/32767) = */ 0x00002e2b
  95626. }
  95627. };
  95628. #if 0
  95629. static const FLAC__uint64 log2_lookup_wide[] = {
  95630. {
  95631. /*
  95632. * 32 fraction bits
  95633. */
  95634. /* undefined */ 0x00000000,
  95635. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95636. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95637. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95638. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95639. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95640. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95641. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95642. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95643. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95644. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95645. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95646. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95647. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95648. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95649. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95650. },
  95651. {
  95652. /*
  95653. * 48 fraction bits
  95654. */
  95655. /* undefined */ 0x00000000,
  95656. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95657. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95658. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95659. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95660. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95661. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95662. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95663. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95664. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95665. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95666. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95667. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95668. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95669. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95670. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95671. }
  95672. };
  95673. #endif
  95674. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95675. {
  95676. const FLAC__uint32 ONE = (1u << fracbits);
  95677. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95678. FLAC__ASSERT(fracbits < 32);
  95679. FLAC__ASSERT((fracbits & 0x3) == 0);
  95680. if(x < ONE)
  95681. return 0;
  95682. if(precision > LOG2_LOOKUP_PRECISION)
  95683. precision = LOG2_LOOKUP_PRECISION;
  95684. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95685. {
  95686. FLAC__uint32 y = 0;
  95687. FLAC__uint32 z = x >> 1, k = 1;
  95688. while (x > ONE && k < precision) {
  95689. if (x - z >= ONE) {
  95690. x -= z;
  95691. z = x >> k;
  95692. y += table[k];
  95693. }
  95694. else {
  95695. z >>= 1;
  95696. k++;
  95697. }
  95698. }
  95699. return y;
  95700. }
  95701. }
  95702. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95703. #endif
  95704. /*** End of inlined file: float.c ***/
  95705. /*** Start of inlined file: format.c ***/
  95706. /*** Start of inlined file: juce_FlacHeader.h ***/
  95707. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95708. // tasks..
  95709. #define VERSION "1.2.1"
  95710. #define FLAC__NO_DLL 1
  95711. #if JUCE_MSVC
  95712. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95713. #endif
  95714. #if JUCE_MAC
  95715. #define FLAC__SYS_DARWIN 1
  95716. #endif
  95717. /*** End of inlined file: juce_FlacHeader.h ***/
  95718. #if JUCE_USE_FLAC
  95719. #if HAVE_CONFIG_H
  95720. # include <config.h>
  95721. #endif
  95722. #include <stdio.h>
  95723. #include <stdlib.h> /* for qsort() */
  95724. #include <string.h> /* for memset() */
  95725. #ifndef FLaC__INLINE
  95726. #define FLaC__INLINE
  95727. #endif
  95728. #ifdef min
  95729. #undef min
  95730. #endif
  95731. #define min(a,b) ((a)<(b)?(a):(b))
  95732. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95733. #ifdef _MSC_VER
  95734. #define FLAC__U64L(x) x
  95735. #else
  95736. #define FLAC__U64L(x) x##LLU
  95737. #endif
  95738. /* VERSION should come from configure */
  95739. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95740. ;
  95741. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95742. /* yet one more hack because of MSVC6: */
  95743. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95744. #else
  95745. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95746. #endif
  95747. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95748. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95749. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95750. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95751. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95752. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95753. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95754. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95755. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95756. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95757. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95758. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95759. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95760. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95761. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95762. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95763. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95764. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95765. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95766. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95767. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95768. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95769. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95770. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95771. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95772. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95773. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95774. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95775. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95776. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95777. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95778. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95779. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95780. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95781. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95782. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95783. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95784. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95785. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95786. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95787. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95788. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95789. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95790. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95791. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95792. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95793. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95794. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95795. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95796. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95797. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95798. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95799. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95800. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95801. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95802. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95803. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95804. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95805. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95806. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95807. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95808. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95809. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95810. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95811. "PARTITIONED_RICE",
  95812. "PARTITIONED_RICE2"
  95813. };
  95814. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95815. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95816. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95817. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95818. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95819. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  95820. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  95821. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  95822. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  95823. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  95824. "CONSTANT",
  95825. "VERBATIM",
  95826. "FIXED",
  95827. "LPC"
  95828. };
  95829. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  95830. "INDEPENDENT",
  95831. "LEFT_SIDE",
  95832. "RIGHT_SIDE",
  95833. "MID_SIDE"
  95834. };
  95835. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  95836. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  95837. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  95838. };
  95839. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  95840. "STREAMINFO",
  95841. "PADDING",
  95842. "APPLICATION",
  95843. "SEEKTABLE",
  95844. "VORBIS_COMMENT",
  95845. "CUESHEET",
  95846. "PICTURE"
  95847. };
  95848. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  95849. "Other",
  95850. "32x32 pixels 'file icon' (PNG only)",
  95851. "Other file icon",
  95852. "Cover (front)",
  95853. "Cover (back)",
  95854. "Leaflet page",
  95855. "Media (e.g. label side of CD)",
  95856. "Lead artist/lead performer/soloist",
  95857. "Artist/performer",
  95858. "Conductor",
  95859. "Band/Orchestra",
  95860. "Composer",
  95861. "Lyricist/text writer",
  95862. "Recording Location",
  95863. "During recording",
  95864. "During performance",
  95865. "Movie/video screen capture",
  95866. "A bright coloured fish",
  95867. "Illustration",
  95868. "Band/artist logotype",
  95869. "Publisher/Studio logotype"
  95870. };
  95871. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  95872. {
  95873. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  95874. return false;
  95875. }
  95876. else
  95877. return true;
  95878. }
  95879. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  95880. {
  95881. if(
  95882. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  95883. (
  95884. sample_rate >= (1u << 16) &&
  95885. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  95886. )
  95887. ) {
  95888. return false;
  95889. }
  95890. else
  95891. return true;
  95892. }
  95893. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95894. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  95895. {
  95896. unsigned i;
  95897. FLAC__uint64 prev_sample_number = 0;
  95898. FLAC__bool got_prev = false;
  95899. FLAC__ASSERT(0 != seek_table);
  95900. for(i = 0; i < seek_table->num_points; i++) {
  95901. if(got_prev) {
  95902. if(
  95903. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95904. seek_table->points[i].sample_number <= prev_sample_number
  95905. )
  95906. return false;
  95907. }
  95908. prev_sample_number = seek_table->points[i].sample_number;
  95909. got_prev = true;
  95910. }
  95911. return true;
  95912. }
  95913. /* used as the sort predicate for qsort() */
  95914. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  95915. {
  95916. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  95917. if(l->sample_number == r->sample_number)
  95918. return 0;
  95919. else if(l->sample_number < r->sample_number)
  95920. return -1;
  95921. else
  95922. return 1;
  95923. }
  95924. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95925. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  95926. {
  95927. unsigned i, j;
  95928. FLAC__bool first;
  95929. FLAC__ASSERT(0 != seek_table);
  95930. /* sort the seekpoints */
  95931. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  95932. /* uniquify the seekpoints */
  95933. first = true;
  95934. for(i = j = 0; i < seek_table->num_points; i++) {
  95935. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  95936. if(!first) {
  95937. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  95938. continue;
  95939. }
  95940. }
  95941. first = false;
  95942. seek_table->points[j++] = seek_table->points[i];
  95943. }
  95944. for(i = j; i < seek_table->num_points; i++) {
  95945. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  95946. seek_table->points[i].stream_offset = 0;
  95947. seek_table->points[i].frame_samples = 0;
  95948. }
  95949. return j;
  95950. }
  95951. /*
  95952. * also disallows non-shortest-form encodings, c.f.
  95953. * http://www.unicode.org/versions/corrigendum1.html
  95954. * and a more clear explanation at the end of this section:
  95955. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  95956. */
  95957. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  95958. {
  95959. FLAC__ASSERT(0 != utf8);
  95960. if ((utf8[0] & 0x80) == 0) {
  95961. return 1;
  95962. }
  95963. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  95964. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  95965. return 0;
  95966. return 2;
  95967. }
  95968. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  95969. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  95970. return 0;
  95971. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  95972. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  95973. return 0;
  95974. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  95975. return 0;
  95976. return 3;
  95977. }
  95978. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  95979. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  95980. return 0;
  95981. return 4;
  95982. }
  95983. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  95984. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  95985. return 0;
  95986. return 5;
  95987. }
  95988. 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) {
  95989. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  95990. return 0;
  95991. return 6;
  95992. }
  95993. else {
  95994. return 0;
  95995. }
  95996. }
  95997. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  95998. {
  95999. char c;
  96000. for(c = *name; c; c = *(++name))
  96001. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96002. return false;
  96003. return true;
  96004. }
  96005. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96006. {
  96007. if(length == (unsigned)(-1)) {
  96008. while(*value) {
  96009. unsigned n = utf8len_(value);
  96010. if(n == 0)
  96011. return false;
  96012. value += n;
  96013. }
  96014. }
  96015. else {
  96016. const FLAC__byte *end = value + length;
  96017. while(value < end) {
  96018. unsigned n = utf8len_(value);
  96019. if(n == 0)
  96020. return false;
  96021. value += n;
  96022. }
  96023. if(value != end)
  96024. return false;
  96025. }
  96026. return true;
  96027. }
  96028. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96029. {
  96030. const FLAC__byte *s, *end;
  96031. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96032. if(*s < 0x20 || *s > 0x7D)
  96033. return false;
  96034. }
  96035. if(s == end)
  96036. return false;
  96037. s++; /* skip '=' */
  96038. while(s < end) {
  96039. unsigned n = utf8len_(s);
  96040. if(n == 0)
  96041. return false;
  96042. s += n;
  96043. }
  96044. if(s != end)
  96045. return false;
  96046. return true;
  96047. }
  96048. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96049. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96050. {
  96051. unsigned i, j;
  96052. if(check_cd_da_subset) {
  96053. if(cue_sheet->lead_in < 2 * 44100) {
  96054. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96055. return false;
  96056. }
  96057. if(cue_sheet->lead_in % 588 != 0) {
  96058. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96059. return false;
  96060. }
  96061. }
  96062. if(cue_sheet->num_tracks == 0) {
  96063. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96064. return false;
  96065. }
  96066. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96067. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96068. return false;
  96069. }
  96070. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96071. if(cue_sheet->tracks[i].number == 0) {
  96072. if(violation) *violation = "cue sheet may not have a track number 0";
  96073. return false;
  96074. }
  96075. if(check_cd_da_subset) {
  96076. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96077. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96078. return false;
  96079. }
  96080. }
  96081. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96082. if(violation) {
  96083. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96084. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96085. else
  96086. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96087. }
  96088. return false;
  96089. }
  96090. if(i < cue_sheet->num_tracks - 1) {
  96091. if(cue_sheet->tracks[i].num_indices == 0) {
  96092. if(violation) *violation = "cue sheet track must have at least one index point";
  96093. return false;
  96094. }
  96095. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96096. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96097. return false;
  96098. }
  96099. }
  96100. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96101. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96102. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96103. return false;
  96104. }
  96105. if(j > 0) {
  96106. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96107. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96108. return false;
  96109. }
  96110. }
  96111. }
  96112. }
  96113. return true;
  96114. }
  96115. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96116. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96117. {
  96118. char *p;
  96119. FLAC__byte *b;
  96120. for(p = picture->mime_type; *p; p++) {
  96121. if(*p < 0x20 || *p > 0x7e) {
  96122. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96123. return false;
  96124. }
  96125. }
  96126. for(b = picture->description; *b; ) {
  96127. unsigned n = utf8len_(b);
  96128. if(n == 0) {
  96129. if(violation) *violation = "description string must be valid UTF-8";
  96130. return false;
  96131. }
  96132. b += n;
  96133. }
  96134. return true;
  96135. }
  96136. /*
  96137. * These routines are private to libFLAC
  96138. */
  96139. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96140. {
  96141. return
  96142. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96143. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96144. blocksize,
  96145. predictor_order
  96146. );
  96147. }
  96148. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96149. {
  96150. unsigned max_rice_partition_order = 0;
  96151. while(!(blocksize & 1)) {
  96152. max_rice_partition_order++;
  96153. blocksize >>= 1;
  96154. }
  96155. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96156. }
  96157. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96158. {
  96159. unsigned max_rice_partition_order = limit;
  96160. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96161. max_rice_partition_order--;
  96162. FLAC__ASSERT(
  96163. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96164. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96165. );
  96166. return max_rice_partition_order;
  96167. }
  96168. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96169. {
  96170. FLAC__ASSERT(0 != object);
  96171. object->parameters = 0;
  96172. object->raw_bits = 0;
  96173. object->capacity_by_order = 0;
  96174. }
  96175. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96176. {
  96177. FLAC__ASSERT(0 != object);
  96178. if(0 != object->parameters)
  96179. free(object->parameters);
  96180. if(0 != object->raw_bits)
  96181. free(object->raw_bits);
  96182. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96183. }
  96184. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96185. {
  96186. FLAC__ASSERT(0 != object);
  96187. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96188. if(object->capacity_by_order < max_partition_order) {
  96189. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96190. return false;
  96191. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96192. return false;
  96193. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96194. object->capacity_by_order = max_partition_order;
  96195. }
  96196. return true;
  96197. }
  96198. #endif
  96199. /*** End of inlined file: format.c ***/
  96200. /*** Start of inlined file: lpc_flac.c ***/
  96201. /*** Start of inlined file: juce_FlacHeader.h ***/
  96202. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96203. // tasks..
  96204. #define VERSION "1.2.1"
  96205. #define FLAC__NO_DLL 1
  96206. #if JUCE_MSVC
  96207. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96208. #endif
  96209. #if JUCE_MAC
  96210. #define FLAC__SYS_DARWIN 1
  96211. #endif
  96212. /*** End of inlined file: juce_FlacHeader.h ***/
  96213. #if JUCE_USE_FLAC
  96214. #if HAVE_CONFIG_H
  96215. # include <config.h>
  96216. #endif
  96217. #include <math.h>
  96218. /*** Start of inlined file: lpc.h ***/
  96219. #ifndef FLAC__PRIVATE__LPC_H
  96220. #define FLAC__PRIVATE__LPC_H
  96221. #ifdef HAVE_CONFIG_H
  96222. #include <config.h>
  96223. #endif
  96224. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96225. /*
  96226. * FLAC__lpc_window_data()
  96227. * --------------------------------------------------------------------
  96228. * Applies the given window to the data.
  96229. * OPT: asm implementation
  96230. *
  96231. * IN in[0,data_len-1]
  96232. * IN window[0,data_len-1]
  96233. * OUT out[0,lag-1]
  96234. * IN data_len
  96235. */
  96236. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96237. /*
  96238. * FLAC__lpc_compute_autocorrelation()
  96239. * --------------------------------------------------------------------
  96240. * Compute the autocorrelation for lags between 0 and lag-1.
  96241. * Assumes data[] outside of [0,data_len-1] == 0.
  96242. * Asserts that lag > 0.
  96243. *
  96244. * IN data[0,data_len-1]
  96245. * IN data_len
  96246. * IN 0 < lag <= data_len
  96247. * OUT autoc[0,lag-1]
  96248. */
  96249. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96250. #ifndef FLAC__NO_ASM
  96251. # ifdef FLAC__CPU_IA32
  96252. # ifdef FLAC__HAS_NASM
  96253. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96254. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96255. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96256. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96257. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96258. # endif
  96259. # endif
  96260. #endif
  96261. /*
  96262. * FLAC__lpc_compute_lp_coefficients()
  96263. * --------------------------------------------------------------------
  96264. * Computes LP coefficients for orders 1..max_order.
  96265. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96266. * and there is no point in calculating a predictor.
  96267. *
  96268. * IN autoc[0,max_order] autocorrelation values
  96269. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96270. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96271. * *** IMPORTANT:
  96272. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96273. * OUT error[0,max_order-1] error for each order (more
  96274. * specifically, the variance of
  96275. * the error signal times # of
  96276. * samples in the signal)
  96277. *
  96278. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96279. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96280. * in lp_coeff[7][0,7], etc.
  96281. */
  96282. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96283. /*
  96284. * FLAC__lpc_quantize_coefficients()
  96285. * --------------------------------------------------------------------
  96286. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96287. * must be less than 32 (sizeof(FLAC__int32)*8).
  96288. *
  96289. * IN lp_coeff[0,order-1] LP coefficients
  96290. * IN order LP order
  96291. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96292. * desired precision (in bits, including sign
  96293. * bit) of largest coefficient
  96294. * OUT qlp_coeff[0,order-1] quantized coefficients
  96295. * OUT shift # of bits to shift right to get approximated
  96296. * LP coefficients. NOTE: could be negative.
  96297. * RETURN 0 => quantization OK
  96298. * 1 => coefficients require too much shifting for *shift to
  96299. * fit in the LPC subframe header. 'shift' is unset.
  96300. * 2 => coefficients are all zero, which is bad. 'shift' is
  96301. * unset.
  96302. */
  96303. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96304. /*
  96305. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96306. * --------------------------------------------------------------------
  96307. * Compute the residual signal obtained from sutracting the predicted
  96308. * signal from the original.
  96309. *
  96310. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96311. * IN data_len length of original signal
  96312. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96313. * IN order > 0 LP order
  96314. * IN lp_quantization quantization of LP coefficients in bits
  96315. * OUT residual[0,data_len-1] residual signal
  96316. */
  96317. 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[]);
  96318. 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[]);
  96319. #ifndef FLAC__NO_ASM
  96320. # ifdef FLAC__CPU_IA32
  96321. # ifdef FLAC__HAS_NASM
  96322. 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[]);
  96323. 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[]);
  96324. # endif
  96325. # endif
  96326. #endif
  96327. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96328. /*
  96329. * FLAC__lpc_restore_signal()
  96330. * --------------------------------------------------------------------
  96331. * Restore the original signal by summing the residual and the
  96332. * predictor.
  96333. *
  96334. * IN residual[0,data_len-1] residual signal
  96335. * IN data_len length of original signal
  96336. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96337. * IN order > 0 LP order
  96338. * IN lp_quantization quantization of LP coefficients in bits
  96339. * *** IMPORTANT: the caller must pass in the historical samples:
  96340. * IN data[-order,-1] previously-reconstructed historical samples
  96341. * OUT data[0,data_len-1] original signal
  96342. */
  96343. 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[]);
  96344. 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[]);
  96345. #ifndef FLAC__NO_ASM
  96346. # ifdef FLAC__CPU_IA32
  96347. # ifdef FLAC__HAS_NASM
  96348. 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[]);
  96349. 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[]);
  96350. # endif /* FLAC__HAS_NASM */
  96351. # elif defined FLAC__CPU_PPC
  96352. 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[]);
  96353. 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[]);
  96354. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96355. #endif /* FLAC__NO_ASM */
  96356. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96357. /*
  96358. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96359. * --------------------------------------------------------------------
  96360. * Compute the expected number of bits per residual signal sample
  96361. * based on the LP error (which is related to the residual variance).
  96362. *
  96363. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96364. * IN total_samples > 0 # of samples in residual signal
  96365. * RETURN expected bits per sample
  96366. */
  96367. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96368. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96369. /*
  96370. * FLAC__lpc_compute_best_order()
  96371. * --------------------------------------------------------------------
  96372. * Compute the best order from the array of signal errors returned
  96373. * during coefficient computation.
  96374. *
  96375. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96376. * IN max_order > 0 max LP order
  96377. * IN total_samples > 0 # of samples in residual signal
  96378. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96379. * (includes warmup sample size and quantized LP coefficient)
  96380. * RETURN [1,max_order] best order
  96381. */
  96382. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96383. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96384. #endif
  96385. /*** End of inlined file: lpc.h ***/
  96386. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96387. #include <stdio.h>
  96388. #endif
  96389. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96390. #ifndef M_LN2
  96391. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96392. #define M_LN2 0.69314718055994530942
  96393. #endif
  96394. /* OPT: #undef'ing this may improve the speed on some architectures */
  96395. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96396. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96397. {
  96398. unsigned i;
  96399. for(i = 0; i < data_len; i++)
  96400. out[i] = in[i] * window[i];
  96401. }
  96402. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96403. {
  96404. /* a readable, but slower, version */
  96405. #if 0
  96406. FLAC__real d;
  96407. unsigned i;
  96408. FLAC__ASSERT(lag > 0);
  96409. FLAC__ASSERT(lag <= data_len);
  96410. /*
  96411. * Technically we should subtract the mean first like so:
  96412. * for(i = 0; i < data_len; i++)
  96413. * data[i] -= mean;
  96414. * but it appears not to make enough of a difference to matter, and
  96415. * most signals are already closely centered around zero
  96416. */
  96417. while(lag--) {
  96418. for(i = lag, d = 0.0; i < data_len; i++)
  96419. d += data[i] * data[i - lag];
  96420. autoc[lag] = d;
  96421. }
  96422. #endif
  96423. /*
  96424. * this version tends to run faster because of better data locality
  96425. * ('data_len' is usually much larger than 'lag')
  96426. */
  96427. FLAC__real d;
  96428. unsigned sample, coeff;
  96429. const unsigned limit = data_len - lag;
  96430. FLAC__ASSERT(lag > 0);
  96431. FLAC__ASSERT(lag <= data_len);
  96432. for(coeff = 0; coeff < lag; coeff++)
  96433. autoc[coeff] = 0.0;
  96434. for(sample = 0; sample <= limit; sample++) {
  96435. d = data[sample];
  96436. for(coeff = 0; coeff < lag; coeff++)
  96437. autoc[coeff] += d * data[sample+coeff];
  96438. }
  96439. for(; sample < data_len; sample++) {
  96440. d = data[sample];
  96441. for(coeff = 0; coeff < data_len - sample; coeff++)
  96442. autoc[coeff] += d * data[sample+coeff];
  96443. }
  96444. }
  96445. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96446. {
  96447. unsigned i, j;
  96448. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96449. FLAC__ASSERT(0 != max_order);
  96450. FLAC__ASSERT(0 < *max_order);
  96451. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96452. FLAC__ASSERT(autoc[0] != 0.0);
  96453. err = autoc[0];
  96454. for(i = 0; i < *max_order; i++) {
  96455. /* Sum up this iteration's reflection coefficient. */
  96456. r = -autoc[i+1];
  96457. for(j = 0; j < i; j++)
  96458. r -= lpc[j] * autoc[i-j];
  96459. ref[i] = (r/=err);
  96460. /* Update LPC coefficients and total error. */
  96461. lpc[i]=r;
  96462. for(j = 0; j < (i>>1); j++) {
  96463. FLAC__double tmp = lpc[j];
  96464. lpc[j] += r * lpc[i-1-j];
  96465. lpc[i-1-j] += r * tmp;
  96466. }
  96467. if(i & 1)
  96468. lpc[j] += lpc[j] * r;
  96469. err *= (1.0 - r * r);
  96470. /* save this order */
  96471. for(j = 0; j <= i; j++)
  96472. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96473. error[i] = err;
  96474. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96475. if(err == 0.0) {
  96476. *max_order = i+1;
  96477. return;
  96478. }
  96479. }
  96480. }
  96481. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96482. {
  96483. unsigned i;
  96484. FLAC__double cmax;
  96485. FLAC__int32 qmax, qmin;
  96486. FLAC__ASSERT(precision > 0);
  96487. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96488. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96489. precision--;
  96490. qmax = 1 << precision;
  96491. qmin = -qmax;
  96492. qmax--;
  96493. /* calc cmax = max( |lp_coeff[i]| ) */
  96494. cmax = 0.0;
  96495. for(i = 0; i < order; i++) {
  96496. const FLAC__double d = fabs(lp_coeff[i]);
  96497. if(d > cmax)
  96498. cmax = d;
  96499. }
  96500. if(cmax <= 0.0) {
  96501. /* => coefficients are all 0, which means our constant-detect didn't work */
  96502. return 2;
  96503. }
  96504. else {
  96505. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96506. const int min_shiftlimit = -max_shiftlimit - 1;
  96507. int log2cmax;
  96508. (void)frexp(cmax, &log2cmax);
  96509. log2cmax--;
  96510. *shift = (int)precision - log2cmax - 1;
  96511. if(*shift > max_shiftlimit)
  96512. *shift = max_shiftlimit;
  96513. else if(*shift < min_shiftlimit)
  96514. return 1;
  96515. }
  96516. if(*shift >= 0) {
  96517. FLAC__double error = 0.0;
  96518. FLAC__int32 q;
  96519. for(i = 0; i < order; i++) {
  96520. error += lp_coeff[i] * (1 << *shift);
  96521. #if 1 /* unfortunately lround() is C99 */
  96522. if(error >= 0.0)
  96523. q = (FLAC__int32)(error + 0.5);
  96524. else
  96525. q = (FLAC__int32)(error - 0.5);
  96526. #else
  96527. q = lround(error);
  96528. #endif
  96529. #ifdef FLAC__OVERFLOW_DETECT
  96530. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96531. 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]);
  96532. else if(q < qmin)
  96533. 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]);
  96534. #endif
  96535. if(q > qmax)
  96536. q = qmax;
  96537. else if(q < qmin)
  96538. q = qmin;
  96539. error -= q;
  96540. qlp_coeff[i] = q;
  96541. }
  96542. }
  96543. /* negative shift is very rare but due to design flaw, negative shift is
  96544. * a NOP in the decoder, so it must be handled specially by scaling down
  96545. * coeffs
  96546. */
  96547. else {
  96548. const int nshift = -(*shift);
  96549. FLAC__double error = 0.0;
  96550. FLAC__int32 q;
  96551. #ifdef DEBUG
  96552. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96553. #endif
  96554. for(i = 0; i < order; i++) {
  96555. error += lp_coeff[i] / (1 << nshift);
  96556. #if 1 /* unfortunately lround() is C99 */
  96557. if(error >= 0.0)
  96558. q = (FLAC__int32)(error + 0.5);
  96559. else
  96560. q = (FLAC__int32)(error - 0.5);
  96561. #else
  96562. q = lround(error);
  96563. #endif
  96564. #ifdef FLAC__OVERFLOW_DETECT
  96565. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96566. 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]);
  96567. else if(q < qmin)
  96568. 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]);
  96569. #endif
  96570. if(q > qmax)
  96571. q = qmax;
  96572. else if(q < qmin)
  96573. q = qmin;
  96574. error -= q;
  96575. qlp_coeff[i] = q;
  96576. }
  96577. *shift = 0;
  96578. }
  96579. return 0;
  96580. }
  96581. 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[])
  96582. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96583. {
  96584. FLAC__int64 sumo;
  96585. unsigned i, j;
  96586. FLAC__int32 sum;
  96587. const FLAC__int32 *history;
  96588. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96589. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96590. for(i=0;i<order;i++)
  96591. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96592. fprintf(stderr,"\n");
  96593. #endif
  96594. FLAC__ASSERT(order > 0);
  96595. for(i = 0; i < data_len; i++) {
  96596. sumo = 0;
  96597. sum = 0;
  96598. history = data;
  96599. for(j = 0; j < order; j++) {
  96600. sum += qlp_coeff[j] * (*(--history));
  96601. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96602. #if defined _MSC_VER
  96603. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96604. 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);
  96605. #else
  96606. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96607. 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);
  96608. #endif
  96609. }
  96610. *(residual++) = *(data++) - (sum >> lp_quantization);
  96611. }
  96612. /* Here's a slower but clearer version:
  96613. for(i = 0; i < data_len; i++) {
  96614. sum = 0;
  96615. for(j = 0; j < order; j++)
  96616. sum += qlp_coeff[j] * data[i-j-1];
  96617. residual[i] = data[i] - (sum >> lp_quantization);
  96618. }
  96619. */
  96620. }
  96621. #else /* fully unrolled version for normal use */
  96622. {
  96623. int i;
  96624. FLAC__int32 sum;
  96625. FLAC__ASSERT(order > 0);
  96626. FLAC__ASSERT(order <= 32);
  96627. /*
  96628. * We do unique versions up to 12th order since that's the subset limit.
  96629. * Also they are roughly ordered to match frequency of occurrence to
  96630. * minimize branching.
  96631. */
  96632. if(order <= 12) {
  96633. if(order > 8) {
  96634. if(order > 10) {
  96635. if(order == 12) {
  96636. for(i = 0; i < (int)data_len; i++) {
  96637. sum = 0;
  96638. sum += qlp_coeff[11] * data[i-12];
  96639. sum += qlp_coeff[10] * data[i-11];
  96640. sum += qlp_coeff[9] * data[i-10];
  96641. sum += qlp_coeff[8] * data[i-9];
  96642. sum += qlp_coeff[7] * data[i-8];
  96643. sum += qlp_coeff[6] * data[i-7];
  96644. sum += qlp_coeff[5] * data[i-6];
  96645. sum += qlp_coeff[4] * data[i-5];
  96646. sum += qlp_coeff[3] * data[i-4];
  96647. sum += qlp_coeff[2] * data[i-3];
  96648. sum += qlp_coeff[1] * data[i-2];
  96649. sum += qlp_coeff[0] * data[i-1];
  96650. residual[i] = data[i] - (sum >> lp_quantization);
  96651. }
  96652. }
  96653. else { /* order == 11 */
  96654. for(i = 0; i < (int)data_len; i++) {
  96655. sum = 0;
  96656. sum += qlp_coeff[10] * data[i-11];
  96657. sum += qlp_coeff[9] * data[i-10];
  96658. sum += qlp_coeff[8] * data[i-9];
  96659. sum += qlp_coeff[7] * data[i-8];
  96660. sum += qlp_coeff[6] * data[i-7];
  96661. sum += qlp_coeff[5] * data[i-6];
  96662. sum += qlp_coeff[4] * data[i-5];
  96663. sum += qlp_coeff[3] * data[i-4];
  96664. sum += qlp_coeff[2] * data[i-3];
  96665. sum += qlp_coeff[1] * data[i-2];
  96666. sum += qlp_coeff[0] * data[i-1];
  96667. residual[i] = data[i] - (sum >> lp_quantization);
  96668. }
  96669. }
  96670. }
  96671. else {
  96672. if(order == 10) {
  96673. for(i = 0; i < (int)data_len; i++) {
  96674. sum = 0;
  96675. sum += qlp_coeff[9] * data[i-10];
  96676. sum += qlp_coeff[8] * data[i-9];
  96677. sum += qlp_coeff[7] * data[i-8];
  96678. sum += qlp_coeff[6] * data[i-7];
  96679. sum += qlp_coeff[5] * data[i-6];
  96680. sum += qlp_coeff[4] * data[i-5];
  96681. sum += qlp_coeff[3] * data[i-4];
  96682. sum += qlp_coeff[2] * data[i-3];
  96683. sum += qlp_coeff[1] * data[i-2];
  96684. sum += qlp_coeff[0] * data[i-1];
  96685. residual[i] = data[i] - (sum >> lp_quantization);
  96686. }
  96687. }
  96688. else { /* order == 9 */
  96689. for(i = 0; i < (int)data_len; i++) {
  96690. sum = 0;
  96691. sum += qlp_coeff[8] * data[i-9];
  96692. sum += qlp_coeff[7] * data[i-8];
  96693. sum += qlp_coeff[6] * data[i-7];
  96694. sum += qlp_coeff[5] * data[i-6];
  96695. sum += qlp_coeff[4] * data[i-5];
  96696. sum += qlp_coeff[3] * data[i-4];
  96697. sum += qlp_coeff[2] * data[i-3];
  96698. sum += qlp_coeff[1] * data[i-2];
  96699. sum += qlp_coeff[0] * data[i-1];
  96700. residual[i] = data[i] - (sum >> lp_quantization);
  96701. }
  96702. }
  96703. }
  96704. }
  96705. else if(order > 4) {
  96706. if(order > 6) {
  96707. if(order == 8) {
  96708. for(i = 0; i < (int)data_len; i++) {
  96709. sum = 0;
  96710. sum += qlp_coeff[7] * data[i-8];
  96711. sum += qlp_coeff[6] * data[i-7];
  96712. sum += qlp_coeff[5] * data[i-6];
  96713. sum += qlp_coeff[4] * data[i-5];
  96714. sum += qlp_coeff[3] * data[i-4];
  96715. sum += qlp_coeff[2] * data[i-3];
  96716. sum += qlp_coeff[1] * data[i-2];
  96717. sum += qlp_coeff[0] * data[i-1];
  96718. residual[i] = data[i] - (sum >> lp_quantization);
  96719. }
  96720. }
  96721. else { /* order == 7 */
  96722. for(i = 0; i < (int)data_len; i++) {
  96723. sum = 0;
  96724. sum += qlp_coeff[6] * data[i-7];
  96725. sum += qlp_coeff[5] * data[i-6];
  96726. sum += qlp_coeff[4] * data[i-5];
  96727. sum += qlp_coeff[3] * data[i-4];
  96728. sum += qlp_coeff[2] * data[i-3];
  96729. sum += qlp_coeff[1] * data[i-2];
  96730. sum += qlp_coeff[0] * data[i-1];
  96731. residual[i] = data[i] - (sum >> lp_quantization);
  96732. }
  96733. }
  96734. }
  96735. else {
  96736. if(order == 6) {
  96737. for(i = 0; i < (int)data_len; i++) {
  96738. sum = 0;
  96739. sum += qlp_coeff[5] * data[i-6];
  96740. sum += qlp_coeff[4] * data[i-5];
  96741. sum += qlp_coeff[3] * data[i-4];
  96742. sum += qlp_coeff[2] * data[i-3];
  96743. sum += qlp_coeff[1] * data[i-2];
  96744. sum += qlp_coeff[0] * data[i-1];
  96745. residual[i] = data[i] - (sum >> lp_quantization);
  96746. }
  96747. }
  96748. else { /* order == 5 */
  96749. for(i = 0; i < (int)data_len; i++) {
  96750. sum = 0;
  96751. sum += qlp_coeff[4] * data[i-5];
  96752. sum += qlp_coeff[3] * data[i-4];
  96753. sum += qlp_coeff[2] * data[i-3];
  96754. sum += qlp_coeff[1] * data[i-2];
  96755. sum += qlp_coeff[0] * data[i-1];
  96756. residual[i] = data[i] - (sum >> lp_quantization);
  96757. }
  96758. }
  96759. }
  96760. }
  96761. else {
  96762. if(order > 2) {
  96763. if(order == 4) {
  96764. for(i = 0; i < (int)data_len; i++) {
  96765. sum = 0;
  96766. sum += qlp_coeff[3] * data[i-4];
  96767. sum += qlp_coeff[2] * data[i-3];
  96768. sum += qlp_coeff[1] * data[i-2];
  96769. sum += qlp_coeff[0] * data[i-1];
  96770. residual[i] = data[i] - (sum >> lp_quantization);
  96771. }
  96772. }
  96773. else { /* order == 3 */
  96774. for(i = 0; i < (int)data_len; i++) {
  96775. sum = 0;
  96776. sum += qlp_coeff[2] * data[i-3];
  96777. sum += qlp_coeff[1] * data[i-2];
  96778. sum += qlp_coeff[0] * data[i-1];
  96779. residual[i] = data[i] - (sum >> lp_quantization);
  96780. }
  96781. }
  96782. }
  96783. else {
  96784. if(order == 2) {
  96785. for(i = 0; i < (int)data_len; i++) {
  96786. sum = 0;
  96787. sum += qlp_coeff[1] * data[i-2];
  96788. sum += qlp_coeff[0] * data[i-1];
  96789. residual[i] = data[i] - (sum >> lp_quantization);
  96790. }
  96791. }
  96792. else { /* order == 1 */
  96793. for(i = 0; i < (int)data_len; i++)
  96794. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96795. }
  96796. }
  96797. }
  96798. }
  96799. else { /* order > 12 */
  96800. for(i = 0; i < (int)data_len; i++) {
  96801. sum = 0;
  96802. switch(order) {
  96803. case 32: sum += qlp_coeff[31] * data[i-32];
  96804. case 31: sum += qlp_coeff[30] * data[i-31];
  96805. case 30: sum += qlp_coeff[29] * data[i-30];
  96806. case 29: sum += qlp_coeff[28] * data[i-29];
  96807. case 28: sum += qlp_coeff[27] * data[i-28];
  96808. case 27: sum += qlp_coeff[26] * data[i-27];
  96809. case 26: sum += qlp_coeff[25] * data[i-26];
  96810. case 25: sum += qlp_coeff[24] * data[i-25];
  96811. case 24: sum += qlp_coeff[23] * data[i-24];
  96812. case 23: sum += qlp_coeff[22] * data[i-23];
  96813. case 22: sum += qlp_coeff[21] * data[i-22];
  96814. case 21: sum += qlp_coeff[20] * data[i-21];
  96815. case 20: sum += qlp_coeff[19] * data[i-20];
  96816. case 19: sum += qlp_coeff[18] * data[i-19];
  96817. case 18: sum += qlp_coeff[17] * data[i-18];
  96818. case 17: sum += qlp_coeff[16] * data[i-17];
  96819. case 16: sum += qlp_coeff[15] * data[i-16];
  96820. case 15: sum += qlp_coeff[14] * data[i-15];
  96821. case 14: sum += qlp_coeff[13] * data[i-14];
  96822. case 13: sum += qlp_coeff[12] * data[i-13];
  96823. sum += qlp_coeff[11] * data[i-12];
  96824. sum += qlp_coeff[10] * data[i-11];
  96825. sum += qlp_coeff[ 9] * data[i-10];
  96826. sum += qlp_coeff[ 8] * data[i- 9];
  96827. sum += qlp_coeff[ 7] * data[i- 8];
  96828. sum += qlp_coeff[ 6] * data[i- 7];
  96829. sum += qlp_coeff[ 5] * data[i- 6];
  96830. sum += qlp_coeff[ 4] * data[i- 5];
  96831. sum += qlp_coeff[ 3] * data[i- 4];
  96832. sum += qlp_coeff[ 2] * data[i- 3];
  96833. sum += qlp_coeff[ 1] * data[i- 2];
  96834. sum += qlp_coeff[ 0] * data[i- 1];
  96835. }
  96836. residual[i] = data[i] - (sum >> lp_quantization);
  96837. }
  96838. }
  96839. }
  96840. #endif
  96841. 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[])
  96842. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96843. {
  96844. unsigned i, j;
  96845. FLAC__int64 sum;
  96846. const FLAC__int32 *history;
  96847. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96848. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96849. for(i=0;i<order;i++)
  96850. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96851. fprintf(stderr,"\n");
  96852. #endif
  96853. FLAC__ASSERT(order > 0);
  96854. for(i = 0; i < data_len; i++) {
  96855. sum = 0;
  96856. history = data;
  96857. for(j = 0; j < order; j++)
  96858. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  96859. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  96860. #if defined _MSC_VER
  96861. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  96862. #else
  96863. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  96864. #endif
  96865. break;
  96866. }
  96867. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  96868. #if defined _MSC_VER
  96869. 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));
  96870. #else
  96871. 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)));
  96872. #endif
  96873. break;
  96874. }
  96875. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  96876. }
  96877. }
  96878. #else /* fully unrolled version for normal use */
  96879. {
  96880. int i;
  96881. FLAC__int64 sum;
  96882. FLAC__ASSERT(order > 0);
  96883. FLAC__ASSERT(order <= 32);
  96884. /*
  96885. * We do unique versions up to 12th order since that's the subset limit.
  96886. * Also they are roughly ordered to match frequency of occurrence to
  96887. * minimize branching.
  96888. */
  96889. if(order <= 12) {
  96890. if(order > 8) {
  96891. if(order > 10) {
  96892. if(order == 12) {
  96893. for(i = 0; i < (int)data_len; i++) {
  96894. sum = 0;
  96895. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96896. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96897. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96898. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96899. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96900. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96901. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96902. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96903. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96904. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96905. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96906. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96907. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96908. }
  96909. }
  96910. else { /* order == 11 */
  96911. for(i = 0; i < (int)data_len; i++) {
  96912. sum = 0;
  96913. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96914. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96915. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96916. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96917. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96918. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96919. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96920. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96921. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96922. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96923. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96924. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96925. }
  96926. }
  96927. }
  96928. else {
  96929. if(order == 10) {
  96930. for(i = 0; i < (int)data_len; i++) {
  96931. sum = 0;
  96932. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96933. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96934. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96935. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96936. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96937. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96938. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96939. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96940. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96941. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96942. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96943. }
  96944. }
  96945. else { /* order == 9 */
  96946. for(i = 0; i < (int)data_len; i++) {
  96947. sum = 0;
  96948. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96949. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96950. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96951. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96952. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96953. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96954. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96955. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96956. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96957. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96958. }
  96959. }
  96960. }
  96961. }
  96962. else if(order > 4) {
  96963. if(order > 6) {
  96964. if(order == 8) {
  96965. for(i = 0; i < (int)data_len; i++) {
  96966. sum = 0;
  96967. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96968. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96969. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96970. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96971. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96972. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96973. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96974. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96975. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96976. }
  96977. }
  96978. else { /* order == 7 */
  96979. for(i = 0; i < (int)data_len; i++) {
  96980. sum = 0;
  96981. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96982. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96983. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96984. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96985. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96986. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96987. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96988. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96989. }
  96990. }
  96991. }
  96992. else {
  96993. if(order == 6) {
  96994. for(i = 0; i < (int)data_len; i++) {
  96995. sum = 0;
  96996. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96997. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96998. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96999. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97000. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97001. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97002. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97003. }
  97004. }
  97005. else { /* order == 5 */
  97006. for(i = 0; i < (int)data_len; i++) {
  97007. sum = 0;
  97008. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97009. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97010. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97011. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97012. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97013. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97014. }
  97015. }
  97016. }
  97017. }
  97018. else {
  97019. if(order > 2) {
  97020. if(order == 4) {
  97021. for(i = 0; i < (int)data_len; i++) {
  97022. sum = 0;
  97023. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97024. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97025. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97026. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97027. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97028. }
  97029. }
  97030. else { /* order == 3 */
  97031. for(i = 0; i < (int)data_len; i++) {
  97032. sum = 0;
  97033. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97034. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97035. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97036. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97037. }
  97038. }
  97039. }
  97040. else {
  97041. if(order == 2) {
  97042. for(i = 0; i < (int)data_len; i++) {
  97043. sum = 0;
  97044. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97045. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97046. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97047. }
  97048. }
  97049. else { /* order == 1 */
  97050. for(i = 0; i < (int)data_len; i++)
  97051. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97052. }
  97053. }
  97054. }
  97055. }
  97056. else { /* order > 12 */
  97057. for(i = 0; i < (int)data_len; i++) {
  97058. sum = 0;
  97059. switch(order) {
  97060. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97061. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97062. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97063. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97064. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97065. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97066. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97067. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97068. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97069. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97070. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97071. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97072. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97073. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97074. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97075. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97076. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97077. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97078. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97079. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97080. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97081. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97082. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97083. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97084. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97085. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97086. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97087. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97088. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97089. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97090. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97091. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97092. }
  97093. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97094. }
  97095. }
  97096. }
  97097. #endif
  97098. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97099. 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[])
  97100. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97101. {
  97102. FLAC__int64 sumo;
  97103. unsigned i, j;
  97104. FLAC__int32 sum;
  97105. const FLAC__int32 *r = residual, *history;
  97106. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97107. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97108. for(i=0;i<order;i++)
  97109. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97110. fprintf(stderr,"\n");
  97111. #endif
  97112. FLAC__ASSERT(order > 0);
  97113. for(i = 0; i < data_len; i++) {
  97114. sumo = 0;
  97115. sum = 0;
  97116. history = data;
  97117. for(j = 0; j < order; j++) {
  97118. sum += qlp_coeff[j] * (*(--history));
  97119. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97120. #if defined _MSC_VER
  97121. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97122. 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);
  97123. #else
  97124. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97125. 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);
  97126. #endif
  97127. }
  97128. *(data++) = *(r++) + (sum >> lp_quantization);
  97129. }
  97130. /* Here's a slower but clearer version:
  97131. for(i = 0; i < data_len; i++) {
  97132. sum = 0;
  97133. for(j = 0; j < order; j++)
  97134. sum += qlp_coeff[j] * data[i-j-1];
  97135. data[i] = residual[i] + (sum >> lp_quantization);
  97136. }
  97137. */
  97138. }
  97139. #else /* fully unrolled version for normal use */
  97140. {
  97141. int i;
  97142. FLAC__int32 sum;
  97143. FLAC__ASSERT(order > 0);
  97144. FLAC__ASSERT(order <= 32);
  97145. /*
  97146. * We do unique versions up to 12th order since that's the subset limit.
  97147. * Also they are roughly ordered to match frequency of occurrence to
  97148. * minimize branching.
  97149. */
  97150. if(order <= 12) {
  97151. if(order > 8) {
  97152. if(order > 10) {
  97153. if(order == 12) {
  97154. for(i = 0; i < (int)data_len; i++) {
  97155. sum = 0;
  97156. sum += qlp_coeff[11] * data[i-12];
  97157. sum += qlp_coeff[10] * data[i-11];
  97158. sum += qlp_coeff[9] * data[i-10];
  97159. sum += qlp_coeff[8] * data[i-9];
  97160. sum += qlp_coeff[7] * data[i-8];
  97161. sum += qlp_coeff[6] * data[i-7];
  97162. sum += qlp_coeff[5] * data[i-6];
  97163. sum += qlp_coeff[4] * data[i-5];
  97164. sum += qlp_coeff[3] * data[i-4];
  97165. sum += qlp_coeff[2] * data[i-3];
  97166. sum += qlp_coeff[1] * data[i-2];
  97167. sum += qlp_coeff[0] * data[i-1];
  97168. data[i] = residual[i] + (sum >> lp_quantization);
  97169. }
  97170. }
  97171. else { /* order == 11 */
  97172. for(i = 0; i < (int)data_len; i++) {
  97173. sum = 0;
  97174. sum += qlp_coeff[10] * data[i-11];
  97175. sum += qlp_coeff[9] * data[i-10];
  97176. sum += qlp_coeff[8] * data[i-9];
  97177. sum += qlp_coeff[7] * data[i-8];
  97178. sum += qlp_coeff[6] * data[i-7];
  97179. sum += qlp_coeff[5] * data[i-6];
  97180. sum += qlp_coeff[4] * data[i-5];
  97181. sum += qlp_coeff[3] * data[i-4];
  97182. sum += qlp_coeff[2] * data[i-3];
  97183. sum += qlp_coeff[1] * data[i-2];
  97184. sum += qlp_coeff[0] * data[i-1];
  97185. data[i] = residual[i] + (sum >> lp_quantization);
  97186. }
  97187. }
  97188. }
  97189. else {
  97190. if(order == 10) {
  97191. for(i = 0; i < (int)data_len; i++) {
  97192. sum = 0;
  97193. sum += qlp_coeff[9] * data[i-10];
  97194. sum += qlp_coeff[8] * data[i-9];
  97195. sum += qlp_coeff[7] * data[i-8];
  97196. sum += qlp_coeff[6] * data[i-7];
  97197. sum += qlp_coeff[5] * data[i-6];
  97198. sum += qlp_coeff[4] * data[i-5];
  97199. sum += qlp_coeff[3] * data[i-4];
  97200. sum += qlp_coeff[2] * data[i-3];
  97201. sum += qlp_coeff[1] * data[i-2];
  97202. sum += qlp_coeff[0] * data[i-1];
  97203. data[i] = residual[i] + (sum >> lp_quantization);
  97204. }
  97205. }
  97206. else { /* order == 9 */
  97207. for(i = 0; i < (int)data_len; i++) {
  97208. sum = 0;
  97209. sum += qlp_coeff[8] * data[i-9];
  97210. sum += qlp_coeff[7] * data[i-8];
  97211. sum += qlp_coeff[6] * data[i-7];
  97212. sum += qlp_coeff[5] * data[i-6];
  97213. sum += qlp_coeff[4] * data[i-5];
  97214. sum += qlp_coeff[3] * data[i-4];
  97215. sum += qlp_coeff[2] * data[i-3];
  97216. sum += qlp_coeff[1] * data[i-2];
  97217. sum += qlp_coeff[0] * data[i-1];
  97218. data[i] = residual[i] + (sum >> lp_quantization);
  97219. }
  97220. }
  97221. }
  97222. }
  97223. else if(order > 4) {
  97224. if(order > 6) {
  97225. if(order == 8) {
  97226. for(i = 0; i < (int)data_len; i++) {
  97227. sum = 0;
  97228. sum += qlp_coeff[7] * data[i-8];
  97229. sum += qlp_coeff[6] * data[i-7];
  97230. sum += qlp_coeff[5] * data[i-6];
  97231. sum += qlp_coeff[4] * data[i-5];
  97232. sum += qlp_coeff[3] * data[i-4];
  97233. sum += qlp_coeff[2] * data[i-3];
  97234. sum += qlp_coeff[1] * data[i-2];
  97235. sum += qlp_coeff[0] * data[i-1];
  97236. data[i] = residual[i] + (sum >> lp_quantization);
  97237. }
  97238. }
  97239. else { /* order == 7 */
  97240. for(i = 0; i < (int)data_len; i++) {
  97241. sum = 0;
  97242. sum += qlp_coeff[6] * data[i-7];
  97243. sum += qlp_coeff[5] * data[i-6];
  97244. sum += qlp_coeff[4] * data[i-5];
  97245. sum += qlp_coeff[3] * data[i-4];
  97246. sum += qlp_coeff[2] * data[i-3];
  97247. sum += qlp_coeff[1] * data[i-2];
  97248. sum += qlp_coeff[0] * data[i-1];
  97249. data[i] = residual[i] + (sum >> lp_quantization);
  97250. }
  97251. }
  97252. }
  97253. else {
  97254. if(order == 6) {
  97255. for(i = 0; i < (int)data_len; i++) {
  97256. sum = 0;
  97257. sum += qlp_coeff[5] * data[i-6];
  97258. sum += qlp_coeff[4] * data[i-5];
  97259. sum += qlp_coeff[3] * data[i-4];
  97260. sum += qlp_coeff[2] * data[i-3];
  97261. sum += qlp_coeff[1] * data[i-2];
  97262. sum += qlp_coeff[0] * data[i-1];
  97263. data[i] = residual[i] + (sum >> lp_quantization);
  97264. }
  97265. }
  97266. else { /* order == 5 */
  97267. for(i = 0; i < (int)data_len; i++) {
  97268. sum = 0;
  97269. sum += qlp_coeff[4] * data[i-5];
  97270. sum += qlp_coeff[3] * data[i-4];
  97271. sum += qlp_coeff[2] * data[i-3];
  97272. sum += qlp_coeff[1] * data[i-2];
  97273. sum += qlp_coeff[0] * data[i-1];
  97274. data[i] = residual[i] + (sum >> lp_quantization);
  97275. }
  97276. }
  97277. }
  97278. }
  97279. else {
  97280. if(order > 2) {
  97281. if(order == 4) {
  97282. for(i = 0; i < (int)data_len; i++) {
  97283. sum = 0;
  97284. sum += qlp_coeff[3] * data[i-4];
  97285. sum += qlp_coeff[2] * data[i-3];
  97286. sum += qlp_coeff[1] * data[i-2];
  97287. sum += qlp_coeff[0] * data[i-1];
  97288. data[i] = residual[i] + (sum >> lp_quantization);
  97289. }
  97290. }
  97291. else { /* order == 3 */
  97292. for(i = 0; i < (int)data_len; i++) {
  97293. sum = 0;
  97294. sum += qlp_coeff[2] * data[i-3];
  97295. sum += qlp_coeff[1] * data[i-2];
  97296. sum += qlp_coeff[0] * data[i-1];
  97297. data[i] = residual[i] + (sum >> lp_quantization);
  97298. }
  97299. }
  97300. }
  97301. else {
  97302. if(order == 2) {
  97303. for(i = 0; i < (int)data_len; i++) {
  97304. sum = 0;
  97305. sum += qlp_coeff[1] * data[i-2];
  97306. sum += qlp_coeff[0] * data[i-1];
  97307. data[i] = residual[i] + (sum >> lp_quantization);
  97308. }
  97309. }
  97310. else { /* order == 1 */
  97311. for(i = 0; i < (int)data_len; i++)
  97312. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97313. }
  97314. }
  97315. }
  97316. }
  97317. else { /* order > 12 */
  97318. for(i = 0; i < (int)data_len; i++) {
  97319. sum = 0;
  97320. switch(order) {
  97321. case 32: sum += qlp_coeff[31] * data[i-32];
  97322. case 31: sum += qlp_coeff[30] * data[i-31];
  97323. case 30: sum += qlp_coeff[29] * data[i-30];
  97324. case 29: sum += qlp_coeff[28] * data[i-29];
  97325. case 28: sum += qlp_coeff[27] * data[i-28];
  97326. case 27: sum += qlp_coeff[26] * data[i-27];
  97327. case 26: sum += qlp_coeff[25] * data[i-26];
  97328. case 25: sum += qlp_coeff[24] * data[i-25];
  97329. case 24: sum += qlp_coeff[23] * data[i-24];
  97330. case 23: sum += qlp_coeff[22] * data[i-23];
  97331. case 22: sum += qlp_coeff[21] * data[i-22];
  97332. case 21: sum += qlp_coeff[20] * data[i-21];
  97333. case 20: sum += qlp_coeff[19] * data[i-20];
  97334. case 19: sum += qlp_coeff[18] * data[i-19];
  97335. case 18: sum += qlp_coeff[17] * data[i-18];
  97336. case 17: sum += qlp_coeff[16] * data[i-17];
  97337. case 16: sum += qlp_coeff[15] * data[i-16];
  97338. case 15: sum += qlp_coeff[14] * data[i-15];
  97339. case 14: sum += qlp_coeff[13] * data[i-14];
  97340. case 13: sum += qlp_coeff[12] * data[i-13];
  97341. sum += qlp_coeff[11] * data[i-12];
  97342. sum += qlp_coeff[10] * data[i-11];
  97343. sum += qlp_coeff[ 9] * data[i-10];
  97344. sum += qlp_coeff[ 8] * data[i- 9];
  97345. sum += qlp_coeff[ 7] * data[i- 8];
  97346. sum += qlp_coeff[ 6] * data[i- 7];
  97347. sum += qlp_coeff[ 5] * data[i- 6];
  97348. sum += qlp_coeff[ 4] * data[i- 5];
  97349. sum += qlp_coeff[ 3] * data[i- 4];
  97350. sum += qlp_coeff[ 2] * data[i- 3];
  97351. sum += qlp_coeff[ 1] * data[i- 2];
  97352. sum += qlp_coeff[ 0] * data[i- 1];
  97353. }
  97354. data[i] = residual[i] + (sum >> lp_quantization);
  97355. }
  97356. }
  97357. }
  97358. #endif
  97359. 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[])
  97360. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97361. {
  97362. unsigned i, j;
  97363. FLAC__int64 sum;
  97364. const FLAC__int32 *r = residual, *history;
  97365. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97366. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97367. for(i=0;i<order;i++)
  97368. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97369. fprintf(stderr,"\n");
  97370. #endif
  97371. FLAC__ASSERT(order > 0);
  97372. for(i = 0; i < data_len; i++) {
  97373. sum = 0;
  97374. history = data;
  97375. for(j = 0; j < order; j++)
  97376. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97377. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97378. #ifdef _MSC_VER
  97379. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97380. #else
  97381. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97382. #endif
  97383. break;
  97384. }
  97385. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97386. #ifdef _MSC_VER
  97387. 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));
  97388. #else
  97389. 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)));
  97390. #endif
  97391. break;
  97392. }
  97393. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97394. }
  97395. }
  97396. #else /* fully unrolled version for normal use */
  97397. {
  97398. int i;
  97399. FLAC__int64 sum;
  97400. FLAC__ASSERT(order > 0);
  97401. FLAC__ASSERT(order <= 32);
  97402. /*
  97403. * We do unique versions up to 12th order since that's the subset limit.
  97404. * Also they are roughly ordered to match frequency of occurrence to
  97405. * minimize branching.
  97406. */
  97407. if(order <= 12) {
  97408. if(order > 8) {
  97409. if(order > 10) {
  97410. if(order == 12) {
  97411. for(i = 0; i < (int)data_len; i++) {
  97412. sum = 0;
  97413. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97414. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97415. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97416. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97417. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97418. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97419. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97420. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97421. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97422. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97423. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97424. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97425. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97426. }
  97427. }
  97428. else { /* order == 11 */
  97429. for(i = 0; i < (int)data_len; i++) {
  97430. sum = 0;
  97431. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97432. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97433. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97434. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97435. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97436. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97437. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97438. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97439. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97440. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97441. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97442. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97443. }
  97444. }
  97445. }
  97446. else {
  97447. if(order == 10) {
  97448. for(i = 0; i < (int)data_len; i++) {
  97449. sum = 0;
  97450. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97451. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97452. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97453. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97454. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97455. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97456. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97457. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97458. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97459. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97460. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97461. }
  97462. }
  97463. else { /* order == 9 */
  97464. for(i = 0; i < (int)data_len; i++) {
  97465. sum = 0;
  97466. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97467. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97468. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97469. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97470. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97471. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97472. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97473. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97474. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97475. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97476. }
  97477. }
  97478. }
  97479. }
  97480. else if(order > 4) {
  97481. if(order > 6) {
  97482. if(order == 8) {
  97483. for(i = 0; i < (int)data_len; i++) {
  97484. sum = 0;
  97485. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97486. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97487. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97488. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97489. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97490. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97491. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97492. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97493. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97494. }
  97495. }
  97496. else { /* order == 7 */
  97497. for(i = 0; i < (int)data_len; i++) {
  97498. sum = 0;
  97499. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97500. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97501. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97502. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97503. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97504. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97505. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97506. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97507. }
  97508. }
  97509. }
  97510. else {
  97511. if(order == 6) {
  97512. for(i = 0; i < (int)data_len; i++) {
  97513. sum = 0;
  97514. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97515. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97516. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97517. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97518. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97519. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97520. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97521. }
  97522. }
  97523. else { /* order == 5 */
  97524. for(i = 0; i < (int)data_len; i++) {
  97525. sum = 0;
  97526. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97527. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97528. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97529. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97530. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97531. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97532. }
  97533. }
  97534. }
  97535. }
  97536. else {
  97537. if(order > 2) {
  97538. if(order == 4) {
  97539. for(i = 0; i < (int)data_len; i++) {
  97540. sum = 0;
  97541. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97542. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97543. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97544. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97545. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97546. }
  97547. }
  97548. else { /* order == 3 */
  97549. for(i = 0; i < (int)data_len; i++) {
  97550. sum = 0;
  97551. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97552. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97553. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97554. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97555. }
  97556. }
  97557. }
  97558. else {
  97559. if(order == 2) {
  97560. for(i = 0; i < (int)data_len; i++) {
  97561. sum = 0;
  97562. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97563. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97564. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97565. }
  97566. }
  97567. else { /* order == 1 */
  97568. for(i = 0; i < (int)data_len; i++)
  97569. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97570. }
  97571. }
  97572. }
  97573. }
  97574. else { /* order > 12 */
  97575. for(i = 0; i < (int)data_len; i++) {
  97576. sum = 0;
  97577. switch(order) {
  97578. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97579. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97580. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97581. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97582. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97583. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97584. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97585. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97586. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97587. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97588. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97589. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97590. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97591. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97592. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97593. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97594. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97595. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97596. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97597. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97598. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97599. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97600. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97601. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97602. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97603. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97604. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97605. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97606. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97607. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97608. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97609. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97610. }
  97611. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97612. }
  97613. }
  97614. }
  97615. #endif
  97616. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97617. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97618. {
  97619. FLAC__double error_scale;
  97620. FLAC__ASSERT(total_samples > 0);
  97621. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97622. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97623. }
  97624. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97625. {
  97626. if(lpc_error > 0.0) {
  97627. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97628. if(bps >= 0.0)
  97629. return bps;
  97630. else
  97631. return 0.0;
  97632. }
  97633. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97634. return 1e32;
  97635. }
  97636. else {
  97637. return 0.0;
  97638. }
  97639. }
  97640. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97641. {
  97642. 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 */
  97643. FLAC__double bits, best_bits, error_scale;
  97644. FLAC__ASSERT(max_order > 0);
  97645. FLAC__ASSERT(total_samples > 0);
  97646. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97647. best_index = 0;
  97648. best_bits = (unsigned)(-1);
  97649. for(index = 0, order = 1; index < max_order; index++, order++) {
  97650. 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);
  97651. if(bits < best_bits) {
  97652. best_index = index;
  97653. best_bits = bits;
  97654. }
  97655. }
  97656. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97657. }
  97658. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97659. #endif
  97660. /*** End of inlined file: lpc_flac.c ***/
  97661. /*** Start of inlined file: md5.c ***/
  97662. /*** Start of inlined file: juce_FlacHeader.h ***/
  97663. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97664. // tasks..
  97665. #define VERSION "1.2.1"
  97666. #define FLAC__NO_DLL 1
  97667. #if JUCE_MSVC
  97668. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97669. #endif
  97670. #if JUCE_MAC
  97671. #define FLAC__SYS_DARWIN 1
  97672. #endif
  97673. /*** End of inlined file: juce_FlacHeader.h ***/
  97674. #if JUCE_USE_FLAC
  97675. #if HAVE_CONFIG_H
  97676. # include <config.h>
  97677. #endif
  97678. #include <stdlib.h> /* for malloc() */
  97679. #include <string.h> /* for memcpy() */
  97680. /*** Start of inlined file: md5.h ***/
  97681. #ifndef FLAC__PRIVATE__MD5_H
  97682. #define FLAC__PRIVATE__MD5_H
  97683. /*
  97684. * This is the header file for the MD5 message-digest algorithm.
  97685. * The algorithm is due to Ron Rivest. This code was
  97686. * written by Colin Plumb in 1993, no copyright is claimed.
  97687. * This code is in the public domain; do with it what you wish.
  97688. *
  97689. * Equivalent code is available from RSA Data Security, Inc.
  97690. * This code has been tested against that, and is equivalent,
  97691. * except that you don't need to include two pages of legalese
  97692. * with every copy.
  97693. *
  97694. * To compute the message digest of a chunk of bytes, declare an
  97695. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97696. * needed on buffers full of bytes, and then call MD5Final, which
  97697. * will fill a supplied 16-byte array with the digest.
  97698. *
  97699. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97700. * header definitions; now uses stuff from dpkg's config.h
  97701. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97702. * Still in the public domain.
  97703. *
  97704. * Josh Coalson: made some changes to integrate with libFLAC.
  97705. * Still in the public domain, with no warranty.
  97706. */
  97707. typedef struct {
  97708. FLAC__uint32 in[16];
  97709. FLAC__uint32 buf[4];
  97710. FLAC__uint32 bytes[2];
  97711. FLAC__byte *internal_buf;
  97712. size_t capacity;
  97713. } FLAC__MD5Context;
  97714. void FLAC__MD5Init(FLAC__MD5Context *context);
  97715. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97716. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97717. #endif
  97718. /*** End of inlined file: md5.h ***/
  97719. #ifndef FLaC__INLINE
  97720. #define FLaC__INLINE
  97721. #endif
  97722. /*
  97723. * This code implements the MD5 message-digest algorithm.
  97724. * The algorithm is due to Ron Rivest. This code was
  97725. * written by Colin Plumb in 1993, no copyright is claimed.
  97726. * This code is in the public domain; do with it what you wish.
  97727. *
  97728. * Equivalent code is available from RSA Data Security, Inc.
  97729. * This code has been tested against that, and is equivalent,
  97730. * except that you don't need to include two pages of legalese
  97731. * with every copy.
  97732. *
  97733. * To compute the message digest of a chunk of bytes, declare an
  97734. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97735. * needed on buffers full of bytes, and then call MD5Final, which
  97736. * will fill a supplied 16-byte array with the digest.
  97737. *
  97738. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97739. * definitions; now uses stuff from dpkg's config.h.
  97740. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97741. * Still in the public domain.
  97742. *
  97743. * Josh Coalson: made some changes to integrate with libFLAC.
  97744. * Still in the public domain.
  97745. */
  97746. /* The four core functions - F1 is optimized somewhat */
  97747. /* #define F1(x, y, z) (x & y | ~x & z) */
  97748. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97749. #define F2(x, y, z) F1(z, x, y)
  97750. #define F3(x, y, z) (x ^ y ^ z)
  97751. #define F4(x, y, z) (y ^ (x | ~z))
  97752. /* This is the central step in the MD5 algorithm. */
  97753. #define MD5STEP(f,w,x,y,z,in,s) \
  97754. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97755. /*
  97756. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97757. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97758. * the data and converts bytes into longwords for this routine.
  97759. */
  97760. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97761. {
  97762. register FLAC__uint32 a, b, c, d;
  97763. a = buf[0];
  97764. b = buf[1];
  97765. c = buf[2];
  97766. d = buf[3];
  97767. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97768. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97769. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97770. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97771. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97772. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97773. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97774. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97775. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97776. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97777. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97778. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97779. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97780. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97781. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97782. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97783. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97784. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97785. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97786. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97787. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97788. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97789. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97790. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97791. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97792. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97793. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97794. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97795. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97796. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97797. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97798. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97799. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97800. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97801. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97802. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97803. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97804. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97805. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97806. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97807. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97808. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97809. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97810. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97811. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97812. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97813. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97814. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97815. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97816. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97817. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97818. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97819. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  97820. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  97821. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  97822. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  97823. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  97824. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  97825. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  97826. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  97827. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  97828. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  97829. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  97830. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  97831. buf[0] += a;
  97832. buf[1] += b;
  97833. buf[2] += c;
  97834. buf[3] += d;
  97835. }
  97836. #if WORDS_BIGENDIAN
  97837. //@@@@@@ OPT: use bswap/intrinsics
  97838. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  97839. {
  97840. register FLAC__uint32 x;
  97841. do {
  97842. x = *buf;
  97843. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  97844. *buf++ = (x >> 16) | (x << 16);
  97845. } while (--words);
  97846. }
  97847. static void byteSwapX16(FLAC__uint32 *buf)
  97848. {
  97849. register FLAC__uint32 x;
  97850. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97851. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97852. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97853. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97854. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97855. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97856. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97857. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97858. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97859. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97860. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97861. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97862. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97863. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97864. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97865. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  97866. }
  97867. #else
  97868. #define byteSwap(buf, words)
  97869. #define byteSwapX16(buf)
  97870. #endif
  97871. /*
  97872. * Update context to reflect the concatenation of another buffer full
  97873. * of bytes.
  97874. */
  97875. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  97876. {
  97877. FLAC__uint32 t;
  97878. /* Update byte count */
  97879. t = ctx->bytes[0];
  97880. if ((ctx->bytes[0] = t + len) < t)
  97881. ctx->bytes[1]++; /* Carry from low to high */
  97882. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  97883. if (t > len) {
  97884. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  97885. return;
  97886. }
  97887. /* First chunk is an odd size */
  97888. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  97889. byteSwapX16(ctx->in);
  97890. FLAC__MD5Transform(ctx->buf, ctx->in);
  97891. buf += t;
  97892. len -= t;
  97893. /* Process data in 64-byte chunks */
  97894. while (len >= 64) {
  97895. memcpy(ctx->in, buf, 64);
  97896. byteSwapX16(ctx->in);
  97897. FLAC__MD5Transform(ctx->buf, ctx->in);
  97898. buf += 64;
  97899. len -= 64;
  97900. }
  97901. /* Handle any remaining bytes of data. */
  97902. memcpy(ctx->in, buf, len);
  97903. }
  97904. /*
  97905. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  97906. * initialization constants.
  97907. */
  97908. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  97909. {
  97910. ctx->buf[0] = 0x67452301;
  97911. ctx->buf[1] = 0xefcdab89;
  97912. ctx->buf[2] = 0x98badcfe;
  97913. ctx->buf[3] = 0x10325476;
  97914. ctx->bytes[0] = 0;
  97915. ctx->bytes[1] = 0;
  97916. ctx->internal_buf = 0;
  97917. ctx->capacity = 0;
  97918. }
  97919. /*
  97920. * Final wrapup - pad to 64-byte boundary with the bit pattern
  97921. * 1 0* (64-bit count of bits processed, MSB-first)
  97922. */
  97923. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  97924. {
  97925. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  97926. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  97927. /* Set the first char of padding to 0x80. There is always room. */
  97928. *p++ = 0x80;
  97929. /* Bytes of padding needed to make 56 bytes (-8..55) */
  97930. count = 56 - 1 - count;
  97931. if (count < 0) { /* Padding forces an extra block */
  97932. memset(p, 0, count + 8);
  97933. byteSwapX16(ctx->in);
  97934. FLAC__MD5Transform(ctx->buf, ctx->in);
  97935. p = (FLAC__byte *)ctx->in;
  97936. count = 56;
  97937. }
  97938. memset(p, 0, count);
  97939. byteSwap(ctx->in, 14);
  97940. /* Append length in bits and transform */
  97941. ctx->in[14] = ctx->bytes[0] << 3;
  97942. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  97943. FLAC__MD5Transform(ctx->buf, ctx->in);
  97944. byteSwap(ctx->buf, 4);
  97945. memcpy(digest, ctx->buf, 16);
  97946. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  97947. if(0 != ctx->internal_buf) {
  97948. free(ctx->internal_buf);
  97949. ctx->internal_buf = 0;
  97950. ctx->capacity = 0;
  97951. }
  97952. }
  97953. /*
  97954. * Convert the incoming audio signal to a byte stream
  97955. */
  97956. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97957. {
  97958. unsigned channel, sample;
  97959. register FLAC__int32 a_word;
  97960. register FLAC__byte *buf_ = buf;
  97961. #if WORDS_BIGENDIAN
  97962. #else
  97963. if(channels == 2 && bytes_per_sample == 2) {
  97964. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  97965. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  97966. for(sample = 0; sample < samples; sample++, buf1_+=2)
  97967. *buf1_ = (FLAC__int16)signal[1][sample];
  97968. }
  97969. else if(channels == 1 && bytes_per_sample == 2) {
  97970. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  97971. for(sample = 0; sample < samples; sample++)
  97972. *buf1_++ = (FLAC__int16)signal[0][sample];
  97973. }
  97974. else
  97975. #endif
  97976. if(bytes_per_sample == 2) {
  97977. if(channels == 2) {
  97978. for(sample = 0; sample < samples; sample++) {
  97979. a_word = signal[0][sample];
  97980. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97981. *buf_++ = (FLAC__byte)a_word;
  97982. a_word = signal[1][sample];
  97983. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97984. *buf_++ = (FLAC__byte)a_word;
  97985. }
  97986. }
  97987. else if(channels == 1) {
  97988. for(sample = 0; sample < samples; sample++) {
  97989. a_word = signal[0][sample];
  97990. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97991. *buf_++ = (FLAC__byte)a_word;
  97992. }
  97993. }
  97994. else {
  97995. for(sample = 0; sample < samples; sample++) {
  97996. for(channel = 0; channel < channels; channel++) {
  97997. a_word = signal[channel][sample];
  97998. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97999. *buf_++ = (FLAC__byte)a_word;
  98000. }
  98001. }
  98002. }
  98003. }
  98004. else if(bytes_per_sample == 3) {
  98005. if(channels == 2) {
  98006. for(sample = 0; sample < samples; sample++) {
  98007. a_word = signal[0][sample];
  98008. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98009. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98010. *buf_++ = (FLAC__byte)a_word;
  98011. a_word = signal[1][sample];
  98012. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98013. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98014. *buf_++ = (FLAC__byte)a_word;
  98015. }
  98016. }
  98017. else if(channels == 1) {
  98018. for(sample = 0; sample < samples; sample++) {
  98019. a_word = signal[0][sample];
  98020. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98021. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98022. *buf_++ = (FLAC__byte)a_word;
  98023. }
  98024. }
  98025. else {
  98026. for(sample = 0; sample < samples; sample++) {
  98027. for(channel = 0; channel < channels; channel++) {
  98028. a_word = signal[channel][sample];
  98029. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98030. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98031. *buf_++ = (FLAC__byte)a_word;
  98032. }
  98033. }
  98034. }
  98035. }
  98036. else if(bytes_per_sample == 1) {
  98037. if(channels == 2) {
  98038. for(sample = 0; sample < samples; sample++) {
  98039. a_word = signal[0][sample];
  98040. *buf_++ = (FLAC__byte)a_word;
  98041. a_word = signal[1][sample];
  98042. *buf_++ = (FLAC__byte)a_word;
  98043. }
  98044. }
  98045. else if(channels == 1) {
  98046. for(sample = 0; sample < samples; sample++) {
  98047. a_word = signal[0][sample];
  98048. *buf_++ = (FLAC__byte)a_word;
  98049. }
  98050. }
  98051. else {
  98052. for(sample = 0; sample < samples; sample++) {
  98053. for(channel = 0; channel < channels; channel++) {
  98054. a_word = signal[channel][sample];
  98055. *buf_++ = (FLAC__byte)a_word;
  98056. }
  98057. }
  98058. }
  98059. }
  98060. else { /* bytes_per_sample == 4, maybe optimize more later */
  98061. for(sample = 0; sample < samples; sample++) {
  98062. for(channel = 0; channel < channels; channel++) {
  98063. a_word = signal[channel][sample];
  98064. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98065. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98066. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98067. *buf_++ = (FLAC__byte)a_word;
  98068. }
  98069. }
  98070. }
  98071. }
  98072. /*
  98073. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98074. */
  98075. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98076. {
  98077. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98078. /* overflow check */
  98079. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98080. return false;
  98081. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98082. return false;
  98083. if(ctx->capacity < bytes_needed) {
  98084. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98085. if(0 == tmp) {
  98086. free(ctx->internal_buf);
  98087. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98088. return false;
  98089. }
  98090. ctx->internal_buf = tmp;
  98091. ctx->capacity = bytes_needed;
  98092. }
  98093. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98094. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98095. return true;
  98096. }
  98097. #endif
  98098. /*** End of inlined file: md5.c ***/
  98099. /*** Start of inlined file: memory.c ***/
  98100. /*** Start of inlined file: juce_FlacHeader.h ***/
  98101. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98102. // tasks..
  98103. #define VERSION "1.2.1"
  98104. #define FLAC__NO_DLL 1
  98105. #if JUCE_MSVC
  98106. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98107. #endif
  98108. #if JUCE_MAC
  98109. #define FLAC__SYS_DARWIN 1
  98110. #endif
  98111. /*** End of inlined file: juce_FlacHeader.h ***/
  98112. #if JUCE_USE_FLAC
  98113. #if HAVE_CONFIG_H
  98114. # include <config.h>
  98115. #endif
  98116. /*** Start of inlined file: memory.h ***/
  98117. #ifndef FLAC__PRIVATE__MEMORY_H
  98118. #define FLAC__PRIVATE__MEMORY_H
  98119. #ifdef HAVE_CONFIG_H
  98120. #include <config.h>
  98121. #endif
  98122. #include <stdlib.h> /* for size_t */
  98123. /* Returns the unaligned address returned by malloc.
  98124. * Use free() on this address to deallocate.
  98125. */
  98126. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98127. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98128. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98129. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98130. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98131. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98132. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98133. #endif
  98134. #endif
  98135. /*** End of inlined file: memory.h ***/
  98136. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98137. {
  98138. void *x;
  98139. FLAC__ASSERT(0 != aligned_address);
  98140. #ifdef FLAC__ALIGN_MALLOC_DATA
  98141. /* align on 32-byte (256-bit) boundary */
  98142. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98143. #ifdef SIZEOF_VOIDP
  98144. #if SIZEOF_VOIDP == 4
  98145. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98146. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98147. #elif SIZEOF_VOIDP == 8
  98148. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98149. #else
  98150. # error Unsupported sizeof(void*)
  98151. #endif
  98152. #else
  98153. /* there's got to be a better way to do this right for all archs */
  98154. if(sizeof(void*) == sizeof(unsigned))
  98155. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98156. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98157. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98158. else
  98159. return 0;
  98160. #endif
  98161. #else
  98162. x = safe_malloc_(bytes);
  98163. *aligned_address = x;
  98164. #endif
  98165. return x;
  98166. }
  98167. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98168. {
  98169. FLAC__int32 *pu; /* unaligned pointer */
  98170. union { /* union needed to comply with C99 pointer aliasing rules */
  98171. FLAC__int32 *pa; /* aligned pointer */
  98172. void *pv; /* aligned pointer alias */
  98173. } u;
  98174. FLAC__ASSERT(elements > 0);
  98175. FLAC__ASSERT(0 != unaligned_pointer);
  98176. FLAC__ASSERT(0 != aligned_pointer);
  98177. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98178. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98179. if(0 == pu) {
  98180. return false;
  98181. }
  98182. else {
  98183. if(*unaligned_pointer != 0)
  98184. free(*unaligned_pointer);
  98185. *unaligned_pointer = pu;
  98186. *aligned_pointer = u.pa;
  98187. return true;
  98188. }
  98189. }
  98190. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98191. {
  98192. FLAC__uint32 *pu; /* unaligned pointer */
  98193. union { /* union needed to comply with C99 pointer aliasing rules */
  98194. FLAC__uint32 *pa; /* aligned pointer */
  98195. void *pv; /* aligned pointer alias */
  98196. } u;
  98197. FLAC__ASSERT(elements > 0);
  98198. FLAC__ASSERT(0 != unaligned_pointer);
  98199. FLAC__ASSERT(0 != aligned_pointer);
  98200. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98201. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98202. if(0 == pu) {
  98203. return false;
  98204. }
  98205. else {
  98206. if(*unaligned_pointer != 0)
  98207. free(*unaligned_pointer);
  98208. *unaligned_pointer = pu;
  98209. *aligned_pointer = u.pa;
  98210. return true;
  98211. }
  98212. }
  98213. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98214. {
  98215. FLAC__uint64 *pu; /* unaligned pointer */
  98216. union { /* union needed to comply with C99 pointer aliasing rules */
  98217. FLAC__uint64 *pa; /* aligned pointer */
  98218. void *pv; /* aligned pointer alias */
  98219. } u;
  98220. FLAC__ASSERT(elements > 0);
  98221. FLAC__ASSERT(0 != unaligned_pointer);
  98222. FLAC__ASSERT(0 != aligned_pointer);
  98223. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98224. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98225. if(0 == pu) {
  98226. return false;
  98227. }
  98228. else {
  98229. if(*unaligned_pointer != 0)
  98230. free(*unaligned_pointer);
  98231. *unaligned_pointer = pu;
  98232. *aligned_pointer = u.pa;
  98233. return true;
  98234. }
  98235. }
  98236. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98237. {
  98238. unsigned *pu; /* unaligned pointer */
  98239. union { /* union needed to comply with C99 pointer aliasing rules */
  98240. unsigned *pa; /* aligned pointer */
  98241. void *pv; /* aligned pointer alias */
  98242. } u;
  98243. FLAC__ASSERT(elements > 0);
  98244. FLAC__ASSERT(0 != unaligned_pointer);
  98245. FLAC__ASSERT(0 != aligned_pointer);
  98246. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98247. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98248. if(0 == pu) {
  98249. return false;
  98250. }
  98251. else {
  98252. if(*unaligned_pointer != 0)
  98253. free(*unaligned_pointer);
  98254. *unaligned_pointer = pu;
  98255. *aligned_pointer = u.pa;
  98256. return true;
  98257. }
  98258. }
  98259. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98260. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98261. {
  98262. FLAC__real *pu; /* unaligned pointer */
  98263. union { /* union needed to comply with C99 pointer aliasing rules */
  98264. FLAC__real *pa; /* aligned pointer */
  98265. void *pv; /* aligned pointer alias */
  98266. } u;
  98267. FLAC__ASSERT(elements > 0);
  98268. FLAC__ASSERT(0 != unaligned_pointer);
  98269. FLAC__ASSERT(0 != aligned_pointer);
  98270. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98271. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98272. if(0 == pu) {
  98273. return false;
  98274. }
  98275. else {
  98276. if(*unaligned_pointer != 0)
  98277. free(*unaligned_pointer);
  98278. *unaligned_pointer = pu;
  98279. *aligned_pointer = u.pa;
  98280. return true;
  98281. }
  98282. }
  98283. #endif
  98284. #endif
  98285. /*** End of inlined file: memory.c ***/
  98286. /*** Start of inlined file: stream_decoder.c ***/
  98287. /*** Start of inlined file: juce_FlacHeader.h ***/
  98288. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98289. // tasks..
  98290. #define VERSION "1.2.1"
  98291. #define FLAC__NO_DLL 1
  98292. #if JUCE_MSVC
  98293. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98294. #endif
  98295. #if JUCE_MAC
  98296. #define FLAC__SYS_DARWIN 1
  98297. #endif
  98298. /*** End of inlined file: juce_FlacHeader.h ***/
  98299. #if JUCE_USE_FLAC
  98300. #if HAVE_CONFIG_H
  98301. # include <config.h>
  98302. #endif
  98303. #if defined _MSC_VER || defined __MINGW32__
  98304. #include <io.h> /* for _setmode() */
  98305. #include <fcntl.h> /* for _O_BINARY */
  98306. #endif
  98307. #if defined __CYGWIN__ || defined __EMX__
  98308. #include <io.h> /* for setmode(), O_BINARY */
  98309. #include <fcntl.h> /* for _O_BINARY */
  98310. #endif
  98311. #include <stdio.h>
  98312. #include <stdlib.h> /* for malloc() */
  98313. #include <string.h> /* for memset/memcpy() */
  98314. #include <sys/stat.h> /* for stat() */
  98315. #include <sys/types.h> /* for off_t */
  98316. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98317. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98318. #define fseeko fseek
  98319. #define ftello ftell
  98320. #endif
  98321. #endif
  98322. /*** Start of inlined file: stream_decoder.h ***/
  98323. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98324. #define FLAC__PROTECTED__STREAM_DECODER_H
  98325. #if FLAC__HAS_OGG
  98326. #include "include/private/ogg_decoder_aspect.h"
  98327. #endif
  98328. typedef struct FLAC__StreamDecoderProtected {
  98329. FLAC__StreamDecoderState state;
  98330. unsigned channels;
  98331. FLAC__ChannelAssignment channel_assignment;
  98332. unsigned bits_per_sample;
  98333. unsigned sample_rate; /* in Hz */
  98334. unsigned blocksize; /* in samples (per channel) */
  98335. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98336. #if FLAC__HAS_OGG
  98337. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98338. #endif
  98339. } FLAC__StreamDecoderProtected;
  98340. /*
  98341. * return the number of input bytes consumed
  98342. */
  98343. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98344. #endif
  98345. /*** End of inlined file: stream_decoder.h ***/
  98346. #ifdef max
  98347. #undef max
  98348. #endif
  98349. #define max(a,b) ((a)>(b)?(a):(b))
  98350. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98351. #ifdef _MSC_VER
  98352. #define FLAC__U64L(x) x
  98353. #else
  98354. #define FLAC__U64L(x) x##LLU
  98355. #endif
  98356. /* technically this should be in an "export.c" but this is convenient enough */
  98357. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98358. #if FLAC__HAS_OGG
  98359. 1
  98360. #else
  98361. 0
  98362. #endif
  98363. ;
  98364. /***********************************************************************
  98365. *
  98366. * Private static data
  98367. *
  98368. ***********************************************************************/
  98369. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98370. /***********************************************************************
  98371. *
  98372. * Private class method prototypes
  98373. *
  98374. ***********************************************************************/
  98375. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98376. static FILE *get_binary_stdin_(void);
  98377. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98378. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98379. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98380. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98381. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98382. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98383. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98384. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98385. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98386. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98387. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98388. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98389. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98390. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98391. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98392. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98393. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98394. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98395. 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);
  98396. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98397. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98398. #if FLAC__HAS_OGG
  98399. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98400. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98401. #endif
  98402. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98403. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98404. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98405. #if FLAC__HAS_OGG
  98406. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98407. #endif
  98408. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98409. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98410. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98411. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98412. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98413. /***********************************************************************
  98414. *
  98415. * Private class data
  98416. *
  98417. ***********************************************************************/
  98418. typedef struct FLAC__StreamDecoderPrivate {
  98419. #if FLAC__HAS_OGG
  98420. FLAC__bool is_ogg;
  98421. #endif
  98422. FLAC__StreamDecoderReadCallback read_callback;
  98423. FLAC__StreamDecoderSeekCallback seek_callback;
  98424. FLAC__StreamDecoderTellCallback tell_callback;
  98425. FLAC__StreamDecoderLengthCallback length_callback;
  98426. FLAC__StreamDecoderEofCallback eof_callback;
  98427. FLAC__StreamDecoderWriteCallback write_callback;
  98428. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98429. FLAC__StreamDecoderErrorCallback error_callback;
  98430. /* generic 32-bit datapath: */
  98431. 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[]);
  98432. /* generic 64-bit datapath: */
  98433. 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[]);
  98434. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98435. 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[]);
  98436. /* 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: */
  98437. 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[]);
  98438. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98439. void *client_data;
  98440. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98441. FLAC__BitReader *input;
  98442. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98443. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98444. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98445. unsigned output_capacity, output_channels;
  98446. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98447. FLAC__uint64 samples_decoded;
  98448. FLAC__bool has_stream_info, has_seek_table;
  98449. FLAC__StreamMetadata stream_info;
  98450. FLAC__StreamMetadata seek_table;
  98451. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98452. FLAC__byte *metadata_filter_ids;
  98453. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98454. FLAC__Frame frame;
  98455. FLAC__bool cached; /* true if there is a byte in lookahead */
  98456. FLAC__CPUInfo cpuinfo;
  98457. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98458. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98459. /* unaligned (original) pointers to allocated data */
  98460. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98461. 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 */
  98462. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98463. FLAC__bool is_seeking;
  98464. FLAC__MD5Context md5context;
  98465. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98466. /* (the rest of these are only used for seeking) */
  98467. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98468. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98469. FLAC__uint64 target_sample;
  98470. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98471. #if FLAC__HAS_OGG
  98472. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98473. #endif
  98474. } FLAC__StreamDecoderPrivate;
  98475. /***********************************************************************
  98476. *
  98477. * Public static class data
  98478. *
  98479. ***********************************************************************/
  98480. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98481. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98482. "FLAC__STREAM_DECODER_READ_METADATA",
  98483. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98484. "FLAC__STREAM_DECODER_READ_FRAME",
  98485. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98486. "FLAC__STREAM_DECODER_OGG_ERROR",
  98487. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98488. "FLAC__STREAM_DECODER_ABORTED",
  98489. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98490. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98491. };
  98492. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98493. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98494. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98495. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98496. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98497. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98498. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98499. };
  98500. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98501. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98502. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98503. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98504. };
  98505. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98506. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98507. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98508. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98509. };
  98510. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98511. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98512. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98513. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98514. };
  98515. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98516. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98517. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98518. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98519. };
  98520. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98521. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98522. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98523. };
  98524. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98525. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98526. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98527. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98528. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98529. };
  98530. /***********************************************************************
  98531. *
  98532. * Class constructor/destructor
  98533. *
  98534. ***********************************************************************/
  98535. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98536. {
  98537. FLAC__StreamDecoder *decoder;
  98538. unsigned i;
  98539. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98540. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98541. if(decoder == 0) {
  98542. return 0;
  98543. }
  98544. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98545. if(decoder->protected_ == 0) {
  98546. free(decoder);
  98547. return 0;
  98548. }
  98549. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98550. if(decoder->private_ == 0) {
  98551. free(decoder->protected_);
  98552. free(decoder);
  98553. return 0;
  98554. }
  98555. decoder->private_->input = FLAC__bitreader_new();
  98556. if(decoder->private_->input == 0) {
  98557. free(decoder->private_);
  98558. free(decoder->protected_);
  98559. free(decoder);
  98560. return 0;
  98561. }
  98562. decoder->private_->metadata_filter_ids_capacity = 16;
  98563. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98564. FLAC__bitreader_delete(decoder->private_->input);
  98565. free(decoder->private_);
  98566. free(decoder->protected_);
  98567. free(decoder);
  98568. return 0;
  98569. }
  98570. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98571. decoder->private_->output[i] = 0;
  98572. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98573. }
  98574. decoder->private_->output_capacity = 0;
  98575. decoder->private_->output_channels = 0;
  98576. decoder->private_->has_seek_table = false;
  98577. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98578. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98579. decoder->private_->file = 0;
  98580. set_defaults_dec(decoder);
  98581. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98582. return decoder;
  98583. }
  98584. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98585. {
  98586. unsigned i;
  98587. FLAC__ASSERT(0 != decoder);
  98588. FLAC__ASSERT(0 != decoder->protected_);
  98589. FLAC__ASSERT(0 != decoder->private_);
  98590. FLAC__ASSERT(0 != decoder->private_->input);
  98591. (void)FLAC__stream_decoder_finish(decoder);
  98592. if(0 != decoder->private_->metadata_filter_ids)
  98593. free(decoder->private_->metadata_filter_ids);
  98594. FLAC__bitreader_delete(decoder->private_->input);
  98595. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98596. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98597. free(decoder->private_);
  98598. free(decoder->protected_);
  98599. free(decoder);
  98600. }
  98601. /***********************************************************************
  98602. *
  98603. * Public class methods
  98604. *
  98605. ***********************************************************************/
  98606. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98607. FLAC__StreamDecoder *decoder,
  98608. FLAC__StreamDecoderReadCallback read_callback,
  98609. FLAC__StreamDecoderSeekCallback seek_callback,
  98610. FLAC__StreamDecoderTellCallback tell_callback,
  98611. FLAC__StreamDecoderLengthCallback length_callback,
  98612. FLAC__StreamDecoderEofCallback eof_callback,
  98613. FLAC__StreamDecoderWriteCallback write_callback,
  98614. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98615. FLAC__StreamDecoderErrorCallback error_callback,
  98616. void *client_data,
  98617. FLAC__bool is_ogg
  98618. )
  98619. {
  98620. FLAC__ASSERT(0 != decoder);
  98621. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98622. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98623. #if !FLAC__HAS_OGG
  98624. if(is_ogg)
  98625. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98626. #endif
  98627. if(
  98628. 0 == read_callback ||
  98629. 0 == write_callback ||
  98630. 0 == error_callback ||
  98631. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98632. )
  98633. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98634. #if FLAC__HAS_OGG
  98635. decoder->private_->is_ogg = is_ogg;
  98636. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98637. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98638. #endif
  98639. /*
  98640. * get the CPU info and set the function pointers
  98641. */
  98642. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98643. /* first default to the non-asm routines */
  98644. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98645. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98646. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98647. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98648. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98649. /* now override with asm where appropriate */
  98650. #ifndef FLAC__NO_ASM
  98651. if(decoder->private_->cpuinfo.use_asm) {
  98652. #ifdef FLAC__CPU_IA32
  98653. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98654. #ifdef FLAC__HAS_NASM
  98655. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98656. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98657. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98658. #endif
  98659. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98660. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98661. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98662. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98663. }
  98664. else {
  98665. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98666. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98667. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98668. }
  98669. #endif
  98670. #elif defined FLAC__CPU_PPC
  98671. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98672. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98673. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98674. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98675. }
  98676. #endif
  98677. }
  98678. #endif
  98679. /* from here on, errors are fatal */
  98680. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98681. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98682. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98683. }
  98684. decoder->private_->read_callback = read_callback;
  98685. decoder->private_->seek_callback = seek_callback;
  98686. decoder->private_->tell_callback = tell_callback;
  98687. decoder->private_->length_callback = length_callback;
  98688. decoder->private_->eof_callback = eof_callback;
  98689. decoder->private_->write_callback = write_callback;
  98690. decoder->private_->metadata_callback = metadata_callback;
  98691. decoder->private_->error_callback = error_callback;
  98692. decoder->private_->client_data = client_data;
  98693. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98694. decoder->private_->samples_decoded = 0;
  98695. decoder->private_->has_stream_info = false;
  98696. decoder->private_->cached = false;
  98697. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98698. decoder->private_->is_seeking = false;
  98699. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98700. if(!FLAC__stream_decoder_reset(decoder)) {
  98701. /* above call sets the state for us */
  98702. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98703. }
  98704. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98705. }
  98706. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98707. FLAC__StreamDecoder *decoder,
  98708. FLAC__StreamDecoderReadCallback read_callback,
  98709. FLAC__StreamDecoderSeekCallback seek_callback,
  98710. FLAC__StreamDecoderTellCallback tell_callback,
  98711. FLAC__StreamDecoderLengthCallback length_callback,
  98712. FLAC__StreamDecoderEofCallback eof_callback,
  98713. FLAC__StreamDecoderWriteCallback write_callback,
  98714. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98715. FLAC__StreamDecoderErrorCallback error_callback,
  98716. void *client_data
  98717. )
  98718. {
  98719. return init_stream_internal_dec(
  98720. decoder,
  98721. read_callback,
  98722. seek_callback,
  98723. tell_callback,
  98724. length_callback,
  98725. eof_callback,
  98726. write_callback,
  98727. metadata_callback,
  98728. error_callback,
  98729. client_data,
  98730. /*is_ogg=*/false
  98731. );
  98732. }
  98733. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98734. FLAC__StreamDecoder *decoder,
  98735. FLAC__StreamDecoderReadCallback read_callback,
  98736. FLAC__StreamDecoderSeekCallback seek_callback,
  98737. FLAC__StreamDecoderTellCallback tell_callback,
  98738. FLAC__StreamDecoderLengthCallback length_callback,
  98739. FLAC__StreamDecoderEofCallback eof_callback,
  98740. FLAC__StreamDecoderWriteCallback write_callback,
  98741. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98742. FLAC__StreamDecoderErrorCallback error_callback,
  98743. void *client_data
  98744. )
  98745. {
  98746. return init_stream_internal_dec(
  98747. decoder,
  98748. read_callback,
  98749. seek_callback,
  98750. tell_callback,
  98751. length_callback,
  98752. eof_callback,
  98753. write_callback,
  98754. metadata_callback,
  98755. error_callback,
  98756. client_data,
  98757. /*is_ogg=*/true
  98758. );
  98759. }
  98760. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98761. FLAC__StreamDecoder *decoder,
  98762. FILE *file,
  98763. FLAC__StreamDecoderWriteCallback write_callback,
  98764. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98765. FLAC__StreamDecoderErrorCallback error_callback,
  98766. void *client_data,
  98767. FLAC__bool is_ogg
  98768. )
  98769. {
  98770. FLAC__ASSERT(0 != decoder);
  98771. FLAC__ASSERT(0 != file);
  98772. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98773. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98774. if(0 == write_callback || 0 == error_callback)
  98775. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98776. /*
  98777. * To make sure that our file does not go unclosed after an error, we
  98778. * must assign the FILE pointer before any further error can occur in
  98779. * this routine.
  98780. */
  98781. if(file == stdin)
  98782. file = get_binary_stdin_(); /* just to be safe */
  98783. decoder->private_->file = file;
  98784. return init_stream_internal_dec(
  98785. decoder,
  98786. file_read_callback_dec,
  98787. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98788. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98789. decoder->private_->file == stdin? 0: file_length_callback_,
  98790. file_eof_callback_,
  98791. write_callback,
  98792. metadata_callback,
  98793. error_callback,
  98794. client_data,
  98795. is_ogg
  98796. );
  98797. }
  98798. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98799. FLAC__StreamDecoder *decoder,
  98800. FILE *file,
  98801. FLAC__StreamDecoderWriteCallback write_callback,
  98802. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98803. FLAC__StreamDecoderErrorCallback error_callback,
  98804. void *client_data
  98805. )
  98806. {
  98807. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98808. }
  98809. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98810. FLAC__StreamDecoder *decoder,
  98811. FILE *file,
  98812. FLAC__StreamDecoderWriteCallback write_callback,
  98813. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98814. FLAC__StreamDecoderErrorCallback error_callback,
  98815. void *client_data
  98816. )
  98817. {
  98818. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98819. }
  98820. static FLAC__StreamDecoderInitStatus init_file_internal_(
  98821. FLAC__StreamDecoder *decoder,
  98822. const char *filename,
  98823. FLAC__StreamDecoderWriteCallback write_callback,
  98824. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98825. FLAC__StreamDecoderErrorCallback error_callback,
  98826. void *client_data,
  98827. FLAC__bool is_ogg
  98828. )
  98829. {
  98830. FILE *file;
  98831. FLAC__ASSERT(0 != decoder);
  98832. /*
  98833. * To make sure that our file does not go unclosed after an error, we
  98834. * have to do the same entrance checks here that are later performed
  98835. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  98836. */
  98837. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98838. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98839. if(0 == write_callback || 0 == error_callback)
  98840. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98841. file = filename? fopen(filename, "rb") : stdin;
  98842. if(0 == file)
  98843. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  98844. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  98845. }
  98846. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  98847. FLAC__StreamDecoder *decoder,
  98848. const char *filename,
  98849. FLAC__StreamDecoderWriteCallback write_callback,
  98850. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98851. FLAC__StreamDecoderErrorCallback error_callback,
  98852. void *client_data
  98853. )
  98854. {
  98855. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98856. }
  98857. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  98858. FLAC__StreamDecoder *decoder,
  98859. const char *filename,
  98860. FLAC__StreamDecoderWriteCallback write_callback,
  98861. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98862. FLAC__StreamDecoderErrorCallback error_callback,
  98863. void *client_data
  98864. )
  98865. {
  98866. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98867. }
  98868. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  98869. {
  98870. FLAC__bool md5_failed = false;
  98871. unsigned i;
  98872. FLAC__ASSERT(0 != decoder);
  98873. FLAC__ASSERT(0 != decoder->private_);
  98874. FLAC__ASSERT(0 != decoder->protected_);
  98875. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  98876. return true;
  98877. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  98878. * always call FLAC__MD5Final()
  98879. */
  98880. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  98881. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98882. free(decoder->private_->seek_table.data.seek_table.points);
  98883. decoder->private_->seek_table.data.seek_table.points = 0;
  98884. decoder->private_->has_seek_table = false;
  98885. }
  98886. FLAC__bitreader_free(decoder->private_->input);
  98887. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98888. /* WATCHOUT:
  98889. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  98890. * output arrays have a buffer of up to 3 zeroes in front
  98891. * (at negative indices) for alignment purposes; we use 4
  98892. * to keep the data well-aligned.
  98893. */
  98894. if(0 != decoder->private_->output[i]) {
  98895. free(decoder->private_->output[i]-4);
  98896. decoder->private_->output[i] = 0;
  98897. }
  98898. if(0 != decoder->private_->residual_unaligned[i]) {
  98899. free(decoder->private_->residual_unaligned[i]);
  98900. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98901. }
  98902. }
  98903. decoder->private_->output_capacity = 0;
  98904. decoder->private_->output_channels = 0;
  98905. #if FLAC__HAS_OGG
  98906. if(decoder->private_->is_ogg)
  98907. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  98908. #endif
  98909. if(0 != decoder->private_->file) {
  98910. if(decoder->private_->file != stdin)
  98911. fclose(decoder->private_->file);
  98912. decoder->private_->file = 0;
  98913. }
  98914. if(decoder->private_->do_md5_checking) {
  98915. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  98916. md5_failed = true;
  98917. }
  98918. decoder->private_->is_seeking = false;
  98919. set_defaults_dec(decoder);
  98920. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98921. return !md5_failed;
  98922. }
  98923. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  98924. {
  98925. FLAC__ASSERT(0 != decoder);
  98926. FLAC__ASSERT(0 != decoder->private_);
  98927. FLAC__ASSERT(0 != decoder->protected_);
  98928. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98929. return false;
  98930. #if FLAC__HAS_OGG
  98931. /* can't check decoder->private_->is_ogg since that's not set until init time */
  98932. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  98933. return true;
  98934. #else
  98935. (void)value;
  98936. return false;
  98937. #endif
  98938. }
  98939. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  98940. {
  98941. FLAC__ASSERT(0 != decoder);
  98942. FLAC__ASSERT(0 != decoder->protected_);
  98943. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98944. return false;
  98945. decoder->protected_->md5_checking = value;
  98946. return true;
  98947. }
  98948. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98949. {
  98950. FLAC__ASSERT(0 != decoder);
  98951. FLAC__ASSERT(0 != decoder->private_);
  98952. FLAC__ASSERT(0 != decoder->protected_);
  98953. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98954. /* double protection */
  98955. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98956. return false;
  98957. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98958. return false;
  98959. decoder->private_->metadata_filter[type] = true;
  98960. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98961. decoder->private_->metadata_filter_ids_count = 0;
  98962. return true;
  98963. }
  98964. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98965. {
  98966. FLAC__ASSERT(0 != decoder);
  98967. FLAC__ASSERT(0 != decoder->private_);
  98968. FLAC__ASSERT(0 != decoder->protected_);
  98969. FLAC__ASSERT(0 != id);
  98970. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98971. return false;
  98972. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98973. return true;
  98974. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98975. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98976. 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))) {
  98977. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98978. return false;
  98979. }
  98980. decoder->private_->metadata_filter_ids_capacity *= 2;
  98981. }
  98982. 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));
  98983. decoder->private_->metadata_filter_ids_count++;
  98984. return true;
  98985. }
  98986. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  98987. {
  98988. unsigned i;
  98989. FLAC__ASSERT(0 != decoder);
  98990. FLAC__ASSERT(0 != decoder->private_);
  98991. FLAC__ASSERT(0 != decoder->protected_);
  98992. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98993. return false;
  98994. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  98995. decoder->private_->metadata_filter[i] = true;
  98996. decoder->private_->metadata_filter_ids_count = 0;
  98997. return true;
  98998. }
  98999. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99000. {
  99001. FLAC__ASSERT(0 != decoder);
  99002. FLAC__ASSERT(0 != decoder->private_);
  99003. FLAC__ASSERT(0 != decoder->protected_);
  99004. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99005. /* double protection */
  99006. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99007. return false;
  99008. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99009. return false;
  99010. decoder->private_->metadata_filter[type] = false;
  99011. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99012. decoder->private_->metadata_filter_ids_count = 0;
  99013. return true;
  99014. }
  99015. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99016. {
  99017. FLAC__ASSERT(0 != decoder);
  99018. FLAC__ASSERT(0 != decoder->private_);
  99019. FLAC__ASSERT(0 != decoder->protected_);
  99020. FLAC__ASSERT(0 != id);
  99021. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99022. return false;
  99023. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99024. return true;
  99025. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99026. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99027. 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))) {
  99028. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99029. return false;
  99030. }
  99031. decoder->private_->metadata_filter_ids_capacity *= 2;
  99032. }
  99033. 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));
  99034. decoder->private_->metadata_filter_ids_count++;
  99035. return true;
  99036. }
  99037. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99038. {
  99039. FLAC__ASSERT(0 != decoder);
  99040. FLAC__ASSERT(0 != decoder->private_);
  99041. FLAC__ASSERT(0 != decoder->protected_);
  99042. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99043. return false;
  99044. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99045. decoder->private_->metadata_filter_ids_count = 0;
  99046. return true;
  99047. }
  99048. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99049. {
  99050. FLAC__ASSERT(0 != decoder);
  99051. FLAC__ASSERT(0 != decoder->protected_);
  99052. return decoder->protected_->state;
  99053. }
  99054. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99055. {
  99056. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99057. }
  99058. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99059. {
  99060. FLAC__ASSERT(0 != decoder);
  99061. FLAC__ASSERT(0 != decoder->protected_);
  99062. return decoder->protected_->md5_checking;
  99063. }
  99064. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99065. {
  99066. FLAC__ASSERT(0 != decoder);
  99067. FLAC__ASSERT(0 != decoder->protected_);
  99068. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99069. }
  99070. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99071. {
  99072. FLAC__ASSERT(0 != decoder);
  99073. FLAC__ASSERT(0 != decoder->protected_);
  99074. return decoder->protected_->channels;
  99075. }
  99076. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99077. {
  99078. FLAC__ASSERT(0 != decoder);
  99079. FLAC__ASSERT(0 != decoder->protected_);
  99080. return decoder->protected_->channel_assignment;
  99081. }
  99082. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99083. {
  99084. FLAC__ASSERT(0 != decoder);
  99085. FLAC__ASSERT(0 != decoder->protected_);
  99086. return decoder->protected_->bits_per_sample;
  99087. }
  99088. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99089. {
  99090. FLAC__ASSERT(0 != decoder);
  99091. FLAC__ASSERT(0 != decoder->protected_);
  99092. return decoder->protected_->sample_rate;
  99093. }
  99094. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99095. {
  99096. FLAC__ASSERT(0 != decoder);
  99097. FLAC__ASSERT(0 != decoder->protected_);
  99098. return decoder->protected_->blocksize;
  99099. }
  99100. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99101. {
  99102. FLAC__ASSERT(0 != decoder);
  99103. FLAC__ASSERT(0 != decoder->private_);
  99104. FLAC__ASSERT(0 != position);
  99105. #if FLAC__HAS_OGG
  99106. if(decoder->private_->is_ogg)
  99107. return false;
  99108. #endif
  99109. if(0 == decoder->private_->tell_callback)
  99110. return false;
  99111. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99112. return false;
  99113. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99114. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99115. return false;
  99116. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99117. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99118. return true;
  99119. }
  99120. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99121. {
  99122. FLAC__ASSERT(0 != decoder);
  99123. FLAC__ASSERT(0 != decoder->private_);
  99124. FLAC__ASSERT(0 != decoder->protected_);
  99125. decoder->private_->samples_decoded = 0;
  99126. decoder->private_->do_md5_checking = false;
  99127. #if FLAC__HAS_OGG
  99128. if(decoder->private_->is_ogg)
  99129. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99130. #endif
  99131. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99132. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99133. return false;
  99134. }
  99135. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99136. return true;
  99137. }
  99138. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99139. {
  99140. FLAC__ASSERT(0 != decoder);
  99141. FLAC__ASSERT(0 != decoder->private_);
  99142. FLAC__ASSERT(0 != decoder->protected_);
  99143. if(!FLAC__stream_decoder_flush(decoder)) {
  99144. /* above call sets the state for us */
  99145. return false;
  99146. }
  99147. #if FLAC__HAS_OGG
  99148. /*@@@ could go in !internal_reset_hack block below */
  99149. if(decoder->private_->is_ogg)
  99150. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99151. #endif
  99152. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99153. * (internal_reset_hack) don't try to rewind since we are already at
  99154. * the beginning of the stream and don't want to fail if the input is
  99155. * not seekable.
  99156. */
  99157. if(!decoder->private_->internal_reset_hack) {
  99158. if(decoder->private_->file == stdin)
  99159. return false; /* can't rewind stdin, reset fails */
  99160. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99161. return false; /* seekable and seek fails, reset fails */
  99162. }
  99163. else
  99164. decoder->private_->internal_reset_hack = false;
  99165. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99166. decoder->private_->has_stream_info = false;
  99167. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99168. free(decoder->private_->seek_table.data.seek_table.points);
  99169. decoder->private_->seek_table.data.seek_table.points = 0;
  99170. decoder->private_->has_seek_table = false;
  99171. }
  99172. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99173. /*
  99174. * This goes in reset() and not flush() because according to the spec, a
  99175. * fixed-blocksize stream must stay that way through the whole stream.
  99176. */
  99177. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99178. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99179. * is because md5 checking may be turned on to start and then turned off if
  99180. * a seek occurs. So we init the context here and finalize it in
  99181. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99182. * properly.
  99183. */
  99184. FLAC__MD5Init(&decoder->private_->md5context);
  99185. decoder->private_->first_frame_offset = 0;
  99186. decoder->private_->unparseable_frame_count = 0;
  99187. return true;
  99188. }
  99189. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99190. {
  99191. FLAC__bool got_a_frame;
  99192. FLAC__ASSERT(0 != decoder);
  99193. FLAC__ASSERT(0 != decoder->protected_);
  99194. while(1) {
  99195. switch(decoder->protected_->state) {
  99196. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99197. if(!find_metadata_(decoder))
  99198. return false; /* above function sets the status for us */
  99199. break;
  99200. case FLAC__STREAM_DECODER_READ_METADATA:
  99201. if(!read_metadata_(decoder))
  99202. return false; /* above function sets the status for us */
  99203. else
  99204. return true;
  99205. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99206. if(!frame_sync_(decoder))
  99207. return true; /* above function sets the status for us */
  99208. break;
  99209. case FLAC__STREAM_DECODER_READ_FRAME:
  99210. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99211. return false; /* above function sets the status for us */
  99212. if(got_a_frame)
  99213. return true; /* above function sets the status for us */
  99214. break;
  99215. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99216. case FLAC__STREAM_DECODER_ABORTED:
  99217. return true;
  99218. default:
  99219. FLAC__ASSERT(0);
  99220. return false;
  99221. }
  99222. }
  99223. }
  99224. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99225. {
  99226. FLAC__ASSERT(0 != decoder);
  99227. FLAC__ASSERT(0 != decoder->protected_);
  99228. while(1) {
  99229. switch(decoder->protected_->state) {
  99230. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99231. if(!find_metadata_(decoder))
  99232. return false; /* above function sets the status for us */
  99233. break;
  99234. case FLAC__STREAM_DECODER_READ_METADATA:
  99235. if(!read_metadata_(decoder))
  99236. return false; /* above function sets the status for us */
  99237. break;
  99238. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99239. case FLAC__STREAM_DECODER_READ_FRAME:
  99240. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99241. case FLAC__STREAM_DECODER_ABORTED:
  99242. return true;
  99243. default:
  99244. FLAC__ASSERT(0);
  99245. return false;
  99246. }
  99247. }
  99248. }
  99249. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99250. {
  99251. FLAC__bool dummy;
  99252. FLAC__ASSERT(0 != decoder);
  99253. FLAC__ASSERT(0 != decoder->protected_);
  99254. while(1) {
  99255. switch(decoder->protected_->state) {
  99256. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99257. if(!find_metadata_(decoder))
  99258. return false; /* above function sets the status for us */
  99259. break;
  99260. case FLAC__STREAM_DECODER_READ_METADATA:
  99261. if(!read_metadata_(decoder))
  99262. return false; /* above function sets the status for us */
  99263. break;
  99264. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99265. if(!frame_sync_(decoder))
  99266. return true; /* above function sets the status for us */
  99267. break;
  99268. case FLAC__STREAM_DECODER_READ_FRAME:
  99269. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99270. return false; /* above function sets the status for us */
  99271. break;
  99272. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99273. case FLAC__STREAM_DECODER_ABORTED:
  99274. return true;
  99275. default:
  99276. FLAC__ASSERT(0);
  99277. return false;
  99278. }
  99279. }
  99280. }
  99281. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99282. {
  99283. FLAC__bool got_a_frame;
  99284. FLAC__ASSERT(0 != decoder);
  99285. FLAC__ASSERT(0 != decoder->protected_);
  99286. while(1) {
  99287. switch(decoder->protected_->state) {
  99288. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99289. case FLAC__STREAM_DECODER_READ_METADATA:
  99290. return false; /* above function sets the status for us */
  99291. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99292. if(!frame_sync_(decoder))
  99293. return true; /* above function sets the status for us */
  99294. break;
  99295. case FLAC__STREAM_DECODER_READ_FRAME:
  99296. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99297. return false; /* above function sets the status for us */
  99298. if(got_a_frame)
  99299. return true; /* above function sets the status for us */
  99300. break;
  99301. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99302. case FLAC__STREAM_DECODER_ABORTED:
  99303. return true;
  99304. default:
  99305. FLAC__ASSERT(0);
  99306. return false;
  99307. }
  99308. }
  99309. }
  99310. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99311. {
  99312. FLAC__uint64 length;
  99313. FLAC__ASSERT(0 != decoder);
  99314. if(
  99315. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99316. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99317. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99318. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99319. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99320. )
  99321. return false;
  99322. if(0 == decoder->private_->seek_callback)
  99323. return false;
  99324. FLAC__ASSERT(decoder->private_->seek_callback);
  99325. FLAC__ASSERT(decoder->private_->tell_callback);
  99326. FLAC__ASSERT(decoder->private_->length_callback);
  99327. FLAC__ASSERT(decoder->private_->eof_callback);
  99328. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99329. return false;
  99330. decoder->private_->is_seeking = true;
  99331. /* turn off md5 checking if a seek is attempted */
  99332. decoder->private_->do_md5_checking = false;
  99333. /* 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) */
  99334. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99335. decoder->private_->is_seeking = false;
  99336. return false;
  99337. }
  99338. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99339. if(
  99340. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99341. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99342. ) {
  99343. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99344. /* above call sets the state for us */
  99345. decoder->private_->is_seeking = false;
  99346. return false;
  99347. }
  99348. /* check this again in case we didn't know total_samples the first time */
  99349. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99350. decoder->private_->is_seeking = false;
  99351. return false;
  99352. }
  99353. }
  99354. {
  99355. const FLAC__bool ok =
  99356. #if FLAC__HAS_OGG
  99357. decoder->private_->is_ogg?
  99358. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99359. #endif
  99360. seek_to_absolute_sample_(decoder, length, sample)
  99361. ;
  99362. decoder->private_->is_seeking = false;
  99363. return ok;
  99364. }
  99365. }
  99366. /***********************************************************************
  99367. *
  99368. * Protected class methods
  99369. *
  99370. ***********************************************************************/
  99371. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99372. {
  99373. FLAC__ASSERT(0 != decoder);
  99374. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99375. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99376. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99377. }
  99378. /***********************************************************************
  99379. *
  99380. * Private class methods
  99381. *
  99382. ***********************************************************************/
  99383. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99384. {
  99385. #if FLAC__HAS_OGG
  99386. decoder->private_->is_ogg = false;
  99387. #endif
  99388. decoder->private_->read_callback = 0;
  99389. decoder->private_->seek_callback = 0;
  99390. decoder->private_->tell_callback = 0;
  99391. decoder->private_->length_callback = 0;
  99392. decoder->private_->eof_callback = 0;
  99393. decoder->private_->write_callback = 0;
  99394. decoder->private_->metadata_callback = 0;
  99395. decoder->private_->error_callback = 0;
  99396. decoder->private_->client_data = 0;
  99397. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99398. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99399. decoder->private_->metadata_filter_ids_count = 0;
  99400. decoder->protected_->md5_checking = false;
  99401. #if FLAC__HAS_OGG
  99402. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99403. #endif
  99404. }
  99405. /*
  99406. * This will forcibly set stdin to binary mode (for OSes that require it)
  99407. */
  99408. FILE *get_binary_stdin_(void)
  99409. {
  99410. /* if something breaks here it is probably due to the presence or
  99411. * absence of an underscore before the identifiers 'setmode',
  99412. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99413. */
  99414. #if defined _MSC_VER || defined __MINGW32__
  99415. _setmode(_fileno(stdin), _O_BINARY);
  99416. #elif defined __CYGWIN__
  99417. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99418. setmode(_fileno(stdin), _O_BINARY);
  99419. #elif defined __EMX__
  99420. setmode(fileno(stdin), O_BINARY);
  99421. #endif
  99422. return stdin;
  99423. }
  99424. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99425. {
  99426. unsigned i;
  99427. FLAC__int32 *tmp;
  99428. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99429. return true;
  99430. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99431. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99432. if(0 != decoder->private_->output[i]) {
  99433. free(decoder->private_->output[i]-4);
  99434. decoder->private_->output[i] = 0;
  99435. }
  99436. if(0 != decoder->private_->residual_unaligned[i]) {
  99437. free(decoder->private_->residual_unaligned[i]);
  99438. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99439. }
  99440. }
  99441. for(i = 0; i < channels; i++) {
  99442. /* WATCHOUT:
  99443. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99444. * output arrays have a buffer of up to 3 zeroes in front
  99445. * (at negative indices) for alignment purposes; we use 4
  99446. * to keep the data well-aligned.
  99447. */
  99448. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99449. if(tmp == 0) {
  99450. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99451. return false;
  99452. }
  99453. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99454. decoder->private_->output[i] = tmp + 4;
  99455. /* WATCHOUT:
  99456. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99457. */
  99458. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99459. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99460. return false;
  99461. }
  99462. }
  99463. decoder->private_->output_capacity = size;
  99464. decoder->private_->output_channels = channels;
  99465. return true;
  99466. }
  99467. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99468. {
  99469. size_t i;
  99470. FLAC__ASSERT(0 != decoder);
  99471. FLAC__ASSERT(0 != decoder->private_);
  99472. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99473. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99474. return true;
  99475. return false;
  99476. }
  99477. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99478. {
  99479. FLAC__uint32 x;
  99480. unsigned i, id_;
  99481. FLAC__bool first = true;
  99482. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99483. for(i = id_ = 0; i < 4; ) {
  99484. if(decoder->private_->cached) {
  99485. x = (FLAC__uint32)decoder->private_->lookahead;
  99486. decoder->private_->cached = false;
  99487. }
  99488. else {
  99489. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99490. return false; /* read_callback_ sets the state for us */
  99491. }
  99492. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99493. first = true;
  99494. i++;
  99495. id_ = 0;
  99496. continue;
  99497. }
  99498. if(x == ID3V2_TAG_[id_]) {
  99499. id_++;
  99500. i = 0;
  99501. if(id_ == 3) {
  99502. if(!skip_id3v2_tag_(decoder))
  99503. return false; /* skip_id3v2_tag_ sets the state for us */
  99504. }
  99505. continue;
  99506. }
  99507. id_ = 0;
  99508. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99509. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99510. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99511. return false; /* read_callback_ sets the state for us */
  99512. /* 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 */
  99513. /* else we have to check if the second byte is the end of a sync code */
  99514. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99515. decoder->private_->lookahead = (FLAC__byte)x;
  99516. decoder->private_->cached = true;
  99517. }
  99518. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99519. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99520. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99521. return true;
  99522. }
  99523. }
  99524. i = 0;
  99525. if(first) {
  99526. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99527. first = false;
  99528. }
  99529. }
  99530. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99531. return true;
  99532. }
  99533. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99534. {
  99535. FLAC__bool is_last;
  99536. FLAC__uint32 i, x, type, length;
  99537. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99538. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99539. return false; /* read_callback_ sets the state for us */
  99540. is_last = x? true : false;
  99541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99542. return false; /* read_callback_ sets the state for us */
  99543. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99544. return false; /* read_callback_ sets the state for us */
  99545. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99546. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99547. return false;
  99548. decoder->private_->has_stream_info = true;
  99549. 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))
  99550. decoder->private_->do_md5_checking = false;
  99551. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99552. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99553. }
  99554. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99555. if(!read_metadata_seektable_(decoder, is_last, length))
  99556. return false;
  99557. decoder->private_->has_seek_table = true;
  99558. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99559. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99560. }
  99561. else {
  99562. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99563. unsigned real_length = length;
  99564. FLAC__StreamMetadata block;
  99565. block.is_last = is_last;
  99566. block.type = (FLAC__MetadataType)type;
  99567. block.length = length;
  99568. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99569. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99570. return false; /* read_callback_ sets the state for us */
  99571. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99572. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99573. return false;
  99574. }
  99575. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99576. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99577. skip_it = !skip_it;
  99578. }
  99579. if(skip_it) {
  99580. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99581. return false; /* read_callback_ sets the state for us */
  99582. }
  99583. else {
  99584. switch(type) {
  99585. case FLAC__METADATA_TYPE_PADDING:
  99586. /* skip the padding bytes */
  99587. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99588. return false; /* read_callback_ sets the state for us */
  99589. break;
  99590. case FLAC__METADATA_TYPE_APPLICATION:
  99591. /* remember, we read the ID already */
  99592. if(real_length > 0) {
  99593. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99594. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99595. return false;
  99596. }
  99597. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99598. return false; /* read_callback_ sets the state for us */
  99599. }
  99600. else
  99601. block.data.application.data = 0;
  99602. break;
  99603. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99604. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99605. return false;
  99606. break;
  99607. case FLAC__METADATA_TYPE_CUESHEET:
  99608. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99609. return false;
  99610. break;
  99611. case FLAC__METADATA_TYPE_PICTURE:
  99612. if(!read_metadata_picture_(decoder, &block.data.picture))
  99613. return false;
  99614. break;
  99615. case FLAC__METADATA_TYPE_STREAMINFO:
  99616. case FLAC__METADATA_TYPE_SEEKTABLE:
  99617. FLAC__ASSERT(0);
  99618. break;
  99619. default:
  99620. if(real_length > 0) {
  99621. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99622. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99623. return false;
  99624. }
  99625. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99626. return false; /* read_callback_ sets the state for us */
  99627. }
  99628. else
  99629. block.data.unknown.data = 0;
  99630. break;
  99631. }
  99632. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99633. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99634. /* now we have to free any malloc()ed data in the block */
  99635. switch(type) {
  99636. case FLAC__METADATA_TYPE_PADDING:
  99637. break;
  99638. case FLAC__METADATA_TYPE_APPLICATION:
  99639. if(0 != block.data.application.data)
  99640. free(block.data.application.data);
  99641. break;
  99642. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99643. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99644. free(block.data.vorbis_comment.vendor_string.entry);
  99645. if(block.data.vorbis_comment.num_comments > 0)
  99646. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99647. if(0 != block.data.vorbis_comment.comments[i].entry)
  99648. free(block.data.vorbis_comment.comments[i].entry);
  99649. if(0 != block.data.vorbis_comment.comments)
  99650. free(block.data.vorbis_comment.comments);
  99651. break;
  99652. case FLAC__METADATA_TYPE_CUESHEET:
  99653. if(block.data.cue_sheet.num_tracks > 0)
  99654. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99655. if(0 != block.data.cue_sheet.tracks[i].indices)
  99656. free(block.data.cue_sheet.tracks[i].indices);
  99657. if(0 != block.data.cue_sheet.tracks)
  99658. free(block.data.cue_sheet.tracks);
  99659. break;
  99660. case FLAC__METADATA_TYPE_PICTURE:
  99661. if(0 != block.data.picture.mime_type)
  99662. free(block.data.picture.mime_type);
  99663. if(0 != block.data.picture.description)
  99664. free(block.data.picture.description);
  99665. if(0 != block.data.picture.data)
  99666. free(block.data.picture.data);
  99667. break;
  99668. case FLAC__METADATA_TYPE_STREAMINFO:
  99669. case FLAC__METADATA_TYPE_SEEKTABLE:
  99670. FLAC__ASSERT(0);
  99671. default:
  99672. if(0 != block.data.unknown.data)
  99673. free(block.data.unknown.data);
  99674. break;
  99675. }
  99676. }
  99677. }
  99678. if(is_last) {
  99679. /* if this fails, it's OK, it's just a hint for the seek routine */
  99680. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99681. decoder->private_->first_frame_offset = 0;
  99682. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99683. }
  99684. return true;
  99685. }
  99686. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99687. {
  99688. FLAC__uint32 x;
  99689. unsigned bits, used_bits = 0;
  99690. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99691. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99692. decoder->private_->stream_info.is_last = is_last;
  99693. decoder->private_->stream_info.length = length;
  99694. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99695. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99696. return false; /* read_callback_ sets the state for us */
  99697. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99698. used_bits += bits;
  99699. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99701. return false; /* read_callback_ sets the state for us */
  99702. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99703. used_bits += bits;
  99704. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99705. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99706. return false; /* read_callback_ sets the state for us */
  99707. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99708. used_bits += bits;
  99709. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99710. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99711. return false; /* read_callback_ sets the state for us */
  99712. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99713. used_bits += bits;
  99714. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99715. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99716. return false; /* read_callback_ sets the state for us */
  99717. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99718. used_bits += bits;
  99719. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99720. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99721. return false; /* read_callback_ sets the state for us */
  99722. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99723. used_bits += bits;
  99724. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99725. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99726. return false; /* read_callback_ sets the state for us */
  99727. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99728. used_bits += bits;
  99729. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99730. 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))
  99731. return false; /* read_callback_ sets the state for us */
  99732. used_bits += bits;
  99733. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99734. return false; /* read_callback_ sets the state for us */
  99735. used_bits += 16*8;
  99736. /* skip the rest of the block */
  99737. FLAC__ASSERT(used_bits % 8 == 0);
  99738. length -= (used_bits / 8);
  99739. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99740. return false; /* read_callback_ sets the state for us */
  99741. return true;
  99742. }
  99743. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99744. {
  99745. FLAC__uint32 i, x;
  99746. FLAC__uint64 xx;
  99747. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99748. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99749. decoder->private_->seek_table.is_last = is_last;
  99750. decoder->private_->seek_table.length = length;
  99751. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99752. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99753. 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)))) {
  99754. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99755. return false;
  99756. }
  99757. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99758. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99759. return false; /* read_callback_ sets the state for us */
  99760. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99761. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99762. return false; /* read_callback_ sets the state for us */
  99763. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99764. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99765. return false; /* read_callback_ sets the state for us */
  99766. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99767. }
  99768. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99769. /* if there is a partial point left, skip over it */
  99770. if(length > 0) {
  99771. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99772. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99773. return false; /* read_callback_ sets the state for us */
  99774. }
  99775. return true;
  99776. }
  99777. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99778. {
  99779. FLAC__uint32 i;
  99780. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99781. /* read vendor string */
  99782. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99783. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99784. return false; /* read_callback_ sets the state for us */
  99785. if(obj->vendor_string.length > 0) {
  99786. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99787. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99788. return false;
  99789. }
  99790. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99791. return false; /* read_callback_ sets the state for us */
  99792. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99793. }
  99794. else
  99795. obj->vendor_string.entry = 0;
  99796. /* read num comments */
  99797. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99798. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99799. return false; /* read_callback_ sets the state for us */
  99800. /* read comments */
  99801. if(obj->num_comments > 0) {
  99802. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99803. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99804. return false;
  99805. }
  99806. for(i = 0; i < obj->num_comments; i++) {
  99807. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99808. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99809. return false; /* read_callback_ sets the state for us */
  99810. if(obj->comments[i].length > 0) {
  99811. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99812. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99813. return false;
  99814. }
  99815. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99816. return false; /* read_callback_ sets the state for us */
  99817. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99818. }
  99819. else
  99820. obj->comments[i].entry = 0;
  99821. }
  99822. }
  99823. else {
  99824. obj->comments = 0;
  99825. }
  99826. return true;
  99827. }
  99828. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  99829. {
  99830. FLAC__uint32 i, j, x;
  99831. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99832. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  99833. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99834. 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))
  99835. return false; /* read_callback_ sets the state for us */
  99836. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99837. return false; /* read_callback_ sets the state for us */
  99838. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99839. return false; /* read_callback_ sets the state for us */
  99840. obj->is_cd = x? true : false;
  99841. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99842. return false; /* read_callback_ sets the state for us */
  99843. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99844. return false; /* read_callback_ sets the state for us */
  99845. obj->num_tracks = x;
  99846. if(obj->num_tracks > 0) {
  99847. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  99848. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99849. return false;
  99850. }
  99851. for(i = 0; i < obj->num_tracks; i++) {
  99852. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  99853. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99854. return false; /* read_callback_ sets the state for us */
  99855. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99856. return false; /* read_callback_ sets the state for us */
  99857. track->number = (FLAC__byte)x;
  99858. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99859. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99860. return false; /* read_callback_ sets the state for us */
  99861. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99862. return false; /* read_callback_ sets the state for us */
  99863. track->type = x;
  99864. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99865. return false; /* read_callback_ sets the state for us */
  99866. track->pre_emphasis = x;
  99867. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99868. return false; /* read_callback_ sets the state for us */
  99869. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99870. return false; /* read_callback_ sets the state for us */
  99871. track->num_indices = (FLAC__byte)x;
  99872. if(track->num_indices > 0) {
  99873. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  99874. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99875. return false;
  99876. }
  99877. for(j = 0; j < track->num_indices; j++) {
  99878. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  99879. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99880. return false; /* read_callback_ sets the state for us */
  99881. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99882. return false; /* read_callback_ sets the state for us */
  99883. index->number = (FLAC__byte)x;
  99884. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99885. return false; /* read_callback_ sets the state for us */
  99886. }
  99887. }
  99888. }
  99889. }
  99890. return true;
  99891. }
  99892. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  99893. {
  99894. FLAC__uint32 x;
  99895. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99896. /* read type */
  99897. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99898. return false; /* read_callback_ sets the state for us */
  99899. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  99900. /* read MIME type */
  99901. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99902. return false; /* read_callback_ sets the state for us */
  99903. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  99904. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99905. return false;
  99906. }
  99907. if(x > 0) {
  99908. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  99909. return false; /* read_callback_ sets the state for us */
  99910. }
  99911. obj->mime_type[x] = '\0';
  99912. /* read description */
  99913. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99914. return false; /* read_callback_ sets the state for us */
  99915. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  99916. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99917. return false;
  99918. }
  99919. if(x > 0) {
  99920. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  99921. return false; /* read_callback_ sets the state for us */
  99922. }
  99923. obj->description[x] = '\0';
  99924. /* read width */
  99925. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99926. return false; /* read_callback_ sets the state for us */
  99927. /* read height */
  99928. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99929. return false; /* read_callback_ sets the state for us */
  99930. /* read depth */
  99931. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99932. return false; /* read_callback_ sets the state for us */
  99933. /* read colors */
  99934. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99935. return false; /* read_callback_ sets the state for us */
  99936. /* read data */
  99937. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99938. return false; /* read_callback_ sets the state for us */
  99939. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  99940. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99941. return false;
  99942. }
  99943. if(obj->data_length > 0) {
  99944. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  99945. return false; /* read_callback_ sets the state for us */
  99946. }
  99947. return true;
  99948. }
  99949. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  99950. {
  99951. FLAC__uint32 x;
  99952. unsigned i, skip;
  99953. /* skip the version and flags bytes */
  99954. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  99955. return false; /* read_callback_ sets the state for us */
  99956. /* get the size (in bytes) to skip */
  99957. skip = 0;
  99958. for(i = 0; i < 4; i++) {
  99959. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99960. return false; /* read_callback_ sets the state for us */
  99961. skip <<= 7;
  99962. skip |= (x & 0x7f);
  99963. }
  99964. /* skip the rest of the tag */
  99965. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  99966. return false; /* read_callback_ sets the state for us */
  99967. return true;
  99968. }
  99969. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  99970. {
  99971. FLAC__uint32 x;
  99972. FLAC__bool first = true;
  99973. /* If we know the total number of samples in the stream, stop if we've read that many. */
  99974. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  99975. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  99976. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99977. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  99978. return true;
  99979. }
  99980. }
  99981. /* make sure we're byte aligned */
  99982. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  99983. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  99984. return false; /* read_callback_ sets the state for us */
  99985. }
  99986. while(1) {
  99987. if(decoder->private_->cached) {
  99988. x = (FLAC__uint32)decoder->private_->lookahead;
  99989. decoder->private_->cached = false;
  99990. }
  99991. else {
  99992. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99993. return false; /* read_callback_ sets the state for us */
  99994. }
  99995. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99996. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99997. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99998. return false; /* read_callback_ sets the state for us */
  99999. /* 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 */
  100000. /* else we have to check if the second byte is the end of a sync code */
  100001. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100002. decoder->private_->lookahead = (FLAC__byte)x;
  100003. decoder->private_->cached = true;
  100004. }
  100005. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100006. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100007. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100008. return true;
  100009. }
  100010. }
  100011. if(first) {
  100012. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100013. first = false;
  100014. }
  100015. }
  100016. return true;
  100017. }
  100018. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100019. {
  100020. unsigned channel;
  100021. unsigned i;
  100022. FLAC__int32 mid, side;
  100023. unsigned frame_crc; /* the one we calculate from the input stream */
  100024. FLAC__uint32 x;
  100025. *got_a_frame = false;
  100026. /* init the CRC */
  100027. frame_crc = 0;
  100028. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100029. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100030. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100031. if(!read_frame_header_(decoder))
  100032. return false;
  100033. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100034. return true;
  100035. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100036. return false;
  100037. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100038. /*
  100039. * first figure the correct bits-per-sample of the subframe
  100040. */
  100041. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100042. switch(decoder->private_->frame.header.channel_assignment) {
  100043. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100044. /* no adjustment needed */
  100045. break;
  100046. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100047. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100048. if(channel == 1)
  100049. bps++;
  100050. break;
  100051. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100052. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100053. if(channel == 0)
  100054. bps++;
  100055. break;
  100056. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100057. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100058. if(channel == 1)
  100059. bps++;
  100060. break;
  100061. default:
  100062. FLAC__ASSERT(0);
  100063. }
  100064. /*
  100065. * now read it
  100066. */
  100067. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100068. return false;
  100069. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100070. return true;
  100071. }
  100072. if(!read_zero_padding_(decoder))
  100073. return false;
  100074. 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) */
  100075. return true;
  100076. /*
  100077. * Read the frame CRC-16 from the footer and check
  100078. */
  100079. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100080. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100081. return false; /* read_callback_ sets the state for us */
  100082. if(frame_crc == x) {
  100083. if(do_full_decode) {
  100084. /* Undo any special channel coding */
  100085. switch(decoder->private_->frame.header.channel_assignment) {
  100086. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100087. /* do nothing */
  100088. break;
  100089. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100090. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100091. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100092. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100093. break;
  100094. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100095. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100096. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100097. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100098. break;
  100099. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100100. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100101. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100102. #if 1
  100103. mid = decoder->private_->output[0][i];
  100104. side = decoder->private_->output[1][i];
  100105. mid <<= 1;
  100106. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100107. decoder->private_->output[0][i] = (mid + side) >> 1;
  100108. decoder->private_->output[1][i] = (mid - side) >> 1;
  100109. #else
  100110. /* OPT: without 'side' temp variable */
  100111. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100112. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100113. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100114. #endif
  100115. }
  100116. break;
  100117. default:
  100118. FLAC__ASSERT(0);
  100119. break;
  100120. }
  100121. }
  100122. }
  100123. else {
  100124. /* Bad frame, emit error and zero the output signal */
  100125. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100126. if(do_full_decode) {
  100127. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100128. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100129. }
  100130. }
  100131. }
  100132. *got_a_frame = true;
  100133. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100134. if(decoder->private_->next_fixed_block_size)
  100135. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100136. /* put the latest values into the public section of the decoder instance */
  100137. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100138. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100139. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100140. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100141. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100142. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100143. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100144. /* write it */
  100145. if(do_full_decode) {
  100146. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100147. return false;
  100148. }
  100149. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100150. return true;
  100151. }
  100152. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100153. {
  100154. FLAC__uint32 x;
  100155. FLAC__uint64 xx;
  100156. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100157. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100158. unsigned raw_header_len;
  100159. FLAC__bool is_unparseable = false;
  100160. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100161. /* init the raw header with the saved bits from synchronization */
  100162. raw_header[0] = decoder->private_->header_warmup[0];
  100163. raw_header[1] = decoder->private_->header_warmup[1];
  100164. raw_header_len = 2;
  100165. /* check to make sure that reserved bit is 0 */
  100166. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100167. is_unparseable = true;
  100168. /*
  100169. * Note that along the way as we read the header, we look for a sync
  100170. * code inside. If we find one it would indicate that our original
  100171. * sync was bad since there cannot be a sync code in a valid header.
  100172. *
  100173. * Three kinds of things can go wrong when reading the frame header:
  100174. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100175. * If we don't find a sync code, it can end up looking like we read
  100176. * a valid but unparseable header, until getting to the frame header
  100177. * CRC. Even then we could get a false positive on the CRC.
  100178. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100179. * future encoder).
  100180. * 3) We may be on a damaged frame which appears valid but unparseable.
  100181. *
  100182. * For all these reasons, we try and read a complete frame header as
  100183. * long as it seems valid, even if unparseable, up until the frame
  100184. * header CRC.
  100185. */
  100186. /*
  100187. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100188. */
  100189. for(i = 0; i < 2; i++) {
  100190. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100191. return false; /* read_callback_ sets the state for us */
  100192. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100193. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100194. decoder->private_->lookahead = (FLAC__byte)x;
  100195. decoder->private_->cached = true;
  100196. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100197. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100198. return true;
  100199. }
  100200. raw_header[raw_header_len++] = (FLAC__byte)x;
  100201. }
  100202. switch(x = raw_header[2] >> 4) {
  100203. case 0:
  100204. is_unparseable = true;
  100205. break;
  100206. case 1:
  100207. decoder->private_->frame.header.blocksize = 192;
  100208. break;
  100209. case 2:
  100210. case 3:
  100211. case 4:
  100212. case 5:
  100213. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100214. break;
  100215. case 6:
  100216. case 7:
  100217. blocksize_hint = x;
  100218. break;
  100219. case 8:
  100220. case 9:
  100221. case 10:
  100222. case 11:
  100223. case 12:
  100224. case 13:
  100225. case 14:
  100226. case 15:
  100227. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100228. break;
  100229. default:
  100230. FLAC__ASSERT(0);
  100231. break;
  100232. }
  100233. switch(x = raw_header[2] & 0x0f) {
  100234. case 0:
  100235. if(decoder->private_->has_stream_info)
  100236. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100237. else
  100238. is_unparseable = true;
  100239. break;
  100240. case 1:
  100241. decoder->private_->frame.header.sample_rate = 88200;
  100242. break;
  100243. case 2:
  100244. decoder->private_->frame.header.sample_rate = 176400;
  100245. break;
  100246. case 3:
  100247. decoder->private_->frame.header.sample_rate = 192000;
  100248. break;
  100249. case 4:
  100250. decoder->private_->frame.header.sample_rate = 8000;
  100251. break;
  100252. case 5:
  100253. decoder->private_->frame.header.sample_rate = 16000;
  100254. break;
  100255. case 6:
  100256. decoder->private_->frame.header.sample_rate = 22050;
  100257. break;
  100258. case 7:
  100259. decoder->private_->frame.header.sample_rate = 24000;
  100260. break;
  100261. case 8:
  100262. decoder->private_->frame.header.sample_rate = 32000;
  100263. break;
  100264. case 9:
  100265. decoder->private_->frame.header.sample_rate = 44100;
  100266. break;
  100267. case 10:
  100268. decoder->private_->frame.header.sample_rate = 48000;
  100269. break;
  100270. case 11:
  100271. decoder->private_->frame.header.sample_rate = 96000;
  100272. break;
  100273. case 12:
  100274. case 13:
  100275. case 14:
  100276. sample_rate_hint = x;
  100277. break;
  100278. case 15:
  100279. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100280. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100281. return true;
  100282. default:
  100283. FLAC__ASSERT(0);
  100284. }
  100285. x = (unsigned)(raw_header[3] >> 4);
  100286. if(x & 8) {
  100287. decoder->private_->frame.header.channels = 2;
  100288. switch(x & 7) {
  100289. case 0:
  100290. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100291. break;
  100292. case 1:
  100293. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100294. break;
  100295. case 2:
  100296. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100297. break;
  100298. default:
  100299. is_unparseable = true;
  100300. break;
  100301. }
  100302. }
  100303. else {
  100304. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100305. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100306. }
  100307. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100308. case 0:
  100309. if(decoder->private_->has_stream_info)
  100310. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100311. else
  100312. is_unparseable = true;
  100313. break;
  100314. case 1:
  100315. decoder->private_->frame.header.bits_per_sample = 8;
  100316. break;
  100317. case 2:
  100318. decoder->private_->frame.header.bits_per_sample = 12;
  100319. break;
  100320. case 4:
  100321. decoder->private_->frame.header.bits_per_sample = 16;
  100322. break;
  100323. case 5:
  100324. decoder->private_->frame.header.bits_per_sample = 20;
  100325. break;
  100326. case 6:
  100327. decoder->private_->frame.header.bits_per_sample = 24;
  100328. break;
  100329. case 3:
  100330. case 7:
  100331. is_unparseable = true;
  100332. break;
  100333. default:
  100334. FLAC__ASSERT(0);
  100335. break;
  100336. }
  100337. /* check to make sure that reserved bit is 0 */
  100338. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100339. is_unparseable = true;
  100340. /* read the frame's starting sample number (or frame number as the case may be) */
  100341. if(
  100342. raw_header[1] & 0x01 ||
  100343. /*@@@ 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 */
  100344. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100345. ) { /* variable blocksize */
  100346. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100347. return false; /* read_callback_ sets the state for us */
  100348. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100349. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100350. decoder->private_->cached = true;
  100351. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100352. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100353. return true;
  100354. }
  100355. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100356. decoder->private_->frame.header.number.sample_number = xx;
  100357. }
  100358. else { /* fixed blocksize */
  100359. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100360. return false; /* read_callback_ sets the state for us */
  100361. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100362. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100363. decoder->private_->cached = true;
  100364. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100365. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100366. return true;
  100367. }
  100368. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100369. decoder->private_->frame.header.number.frame_number = x;
  100370. }
  100371. if(blocksize_hint) {
  100372. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100373. return false; /* read_callback_ sets the state for us */
  100374. raw_header[raw_header_len++] = (FLAC__byte)x;
  100375. if(blocksize_hint == 7) {
  100376. FLAC__uint32 _x;
  100377. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100378. return false; /* read_callback_ sets the state for us */
  100379. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100380. x = (x << 8) | _x;
  100381. }
  100382. decoder->private_->frame.header.blocksize = x+1;
  100383. }
  100384. if(sample_rate_hint) {
  100385. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100386. return false; /* read_callback_ sets the state for us */
  100387. raw_header[raw_header_len++] = (FLAC__byte)x;
  100388. if(sample_rate_hint != 12) {
  100389. FLAC__uint32 _x;
  100390. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100391. return false; /* read_callback_ sets the state for us */
  100392. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100393. x = (x << 8) | _x;
  100394. }
  100395. if(sample_rate_hint == 12)
  100396. decoder->private_->frame.header.sample_rate = x*1000;
  100397. else if(sample_rate_hint == 13)
  100398. decoder->private_->frame.header.sample_rate = x;
  100399. else
  100400. decoder->private_->frame.header.sample_rate = x*10;
  100401. }
  100402. /* read the CRC-8 byte */
  100403. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100404. return false; /* read_callback_ sets the state for us */
  100405. crc8 = (FLAC__byte)x;
  100406. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100407. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100408. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100409. return true;
  100410. }
  100411. /* calculate the sample number from the frame number if needed */
  100412. decoder->private_->next_fixed_block_size = 0;
  100413. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100414. x = decoder->private_->frame.header.number.frame_number;
  100415. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100416. if(decoder->private_->fixed_block_size)
  100417. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100418. else if(decoder->private_->has_stream_info) {
  100419. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100420. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100421. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100422. }
  100423. else
  100424. is_unparseable = true;
  100425. }
  100426. else if(x == 0) {
  100427. decoder->private_->frame.header.number.sample_number = 0;
  100428. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100429. }
  100430. else {
  100431. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100432. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100433. }
  100434. }
  100435. if(is_unparseable) {
  100436. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100437. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100438. return true;
  100439. }
  100440. return true;
  100441. }
  100442. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100443. {
  100444. FLAC__uint32 x;
  100445. FLAC__bool wasted_bits;
  100446. unsigned i;
  100447. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100448. return false; /* read_callback_ sets the state for us */
  100449. wasted_bits = (x & 1);
  100450. x &= 0xfe;
  100451. if(wasted_bits) {
  100452. unsigned u;
  100453. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100454. return false; /* read_callback_ sets the state for us */
  100455. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100456. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100457. }
  100458. else
  100459. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100460. /*
  100461. * Lots of magic numbers here
  100462. */
  100463. if(x & 0x80) {
  100464. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100465. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100466. return true;
  100467. }
  100468. else if(x == 0) {
  100469. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100470. return false;
  100471. }
  100472. else if(x == 2) {
  100473. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100474. return false;
  100475. }
  100476. else if(x < 16) {
  100477. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100478. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100479. return true;
  100480. }
  100481. else if(x <= 24) {
  100482. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100483. return false;
  100484. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100485. return true;
  100486. }
  100487. else if(x < 64) {
  100488. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100489. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100490. return true;
  100491. }
  100492. else {
  100493. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100494. return false;
  100495. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100496. return true;
  100497. }
  100498. if(wasted_bits && do_full_decode) {
  100499. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100500. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100501. decoder->private_->output[channel][i] <<= x;
  100502. }
  100503. return true;
  100504. }
  100505. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100506. {
  100507. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100508. FLAC__int32 x;
  100509. unsigned i;
  100510. FLAC__int32 *output = decoder->private_->output[channel];
  100511. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100512. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100513. return false; /* read_callback_ sets the state for us */
  100514. subframe->value = x;
  100515. /* decode the subframe */
  100516. if(do_full_decode) {
  100517. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100518. output[i] = x;
  100519. }
  100520. return true;
  100521. }
  100522. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100523. {
  100524. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100525. FLAC__int32 i32;
  100526. FLAC__uint32 u32;
  100527. unsigned u;
  100528. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100529. subframe->residual = decoder->private_->residual[channel];
  100530. subframe->order = order;
  100531. /* read warm-up samples */
  100532. for(u = 0; u < order; u++) {
  100533. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100534. return false; /* read_callback_ sets the state for us */
  100535. subframe->warmup[u] = i32;
  100536. }
  100537. /* read entropy coding method info */
  100538. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100539. return false; /* read_callback_ sets the state for us */
  100540. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100541. switch(subframe->entropy_coding_method.type) {
  100542. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100543. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100544. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100545. return false; /* read_callback_ sets the state for us */
  100546. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100547. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100548. break;
  100549. default:
  100550. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100551. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100552. return true;
  100553. }
  100554. /* read residual */
  100555. switch(subframe->entropy_coding_method.type) {
  100556. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100557. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100558. 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))
  100559. return false;
  100560. break;
  100561. default:
  100562. FLAC__ASSERT(0);
  100563. }
  100564. /* decode the subframe */
  100565. if(do_full_decode) {
  100566. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100567. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100568. }
  100569. return true;
  100570. }
  100571. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100572. {
  100573. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100574. FLAC__int32 i32;
  100575. FLAC__uint32 u32;
  100576. unsigned u;
  100577. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100578. subframe->residual = decoder->private_->residual[channel];
  100579. subframe->order = order;
  100580. /* read warm-up samples */
  100581. for(u = 0; u < order; u++) {
  100582. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100583. return false; /* read_callback_ sets the state for us */
  100584. subframe->warmup[u] = i32;
  100585. }
  100586. /* read qlp coeff precision */
  100587. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100588. return false; /* read_callback_ sets the state for us */
  100589. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100590. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100591. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100592. return true;
  100593. }
  100594. subframe->qlp_coeff_precision = u32+1;
  100595. /* read qlp shift */
  100596. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100597. return false; /* read_callback_ sets the state for us */
  100598. subframe->quantization_level = i32;
  100599. /* read quantized lp coefficiencts */
  100600. for(u = 0; u < order; u++) {
  100601. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100602. return false; /* read_callback_ sets the state for us */
  100603. subframe->qlp_coeff[u] = i32;
  100604. }
  100605. /* read entropy coding method info */
  100606. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100607. return false; /* read_callback_ sets the state for us */
  100608. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100609. switch(subframe->entropy_coding_method.type) {
  100610. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100611. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100612. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100613. return false; /* read_callback_ sets the state for us */
  100614. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100615. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100616. break;
  100617. default:
  100618. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100619. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100620. return true;
  100621. }
  100622. /* read residual */
  100623. switch(subframe->entropy_coding_method.type) {
  100624. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100625. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100626. 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))
  100627. return false;
  100628. break;
  100629. default:
  100630. FLAC__ASSERT(0);
  100631. }
  100632. /* decode the subframe */
  100633. if(do_full_decode) {
  100634. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100635. /*@@@@@@ technically not pessimistic enough, should be more like
  100636. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100637. */
  100638. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100639. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100640. if(order <= 8)
  100641. 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);
  100642. else
  100643. 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);
  100644. }
  100645. else
  100646. 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);
  100647. else
  100648. 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);
  100649. }
  100650. return true;
  100651. }
  100652. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100653. {
  100654. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100655. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100656. unsigned i;
  100657. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100658. subframe->data = residual;
  100659. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100660. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100661. return false; /* read_callback_ sets the state for us */
  100662. residual[i] = x;
  100663. }
  100664. /* decode the subframe */
  100665. if(do_full_decode)
  100666. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100667. return true;
  100668. }
  100669. 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)
  100670. {
  100671. FLAC__uint32 rice_parameter;
  100672. int i;
  100673. unsigned partition, sample, u;
  100674. const unsigned partitions = 1u << partition_order;
  100675. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100676. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100677. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100678. /* sanity checks */
  100679. if(partition_order == 0) {
  100680. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100681. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100682. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100683. return true;
  100684. }
  100685. }
  100686. else {
  100687. if(partition_samples < predictor_order) {
  100688. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100689. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100690. return true;
  100691. }
  100692. }
  100693. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100694. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100695. return false;
  100696. }
  100697. sample = 0;
  100698. for(partition = 0; partition < partitions; partition++) {
  100699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100700. return false; /* read_callback_ sets the state for us */
  100701. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100702. if(rice_parameter < pesc) {
  100703. partitioned_rice_contents->raw_bits[partition] = 0;
  100704. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100705. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100706. return false; /* read_callback_ sets the state for us */
  100707. sample += u;
  100708. }
  100709. else {
  100710. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100711. return false; /* read_callback_ sets the state for us */
  100712. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100713. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100714. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100715. return false; /* read_callback_ sets the state for us */
  100716. residual[sample] = i;
  100717. }
  100718. }
  100719. }
  100720. return true;
  100721. }
  100722. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100723. {
  100724. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100725. FLAC__uint32 zero = 0;
  100726. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100727. return false; /* read_callback_ sets the state for us */
  100728. if(zero != 0) {
  100729. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100730. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100731. }
  100732. }
  100733. return true;
  100734. }
  100735. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100736. {
  100737. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100738. if(
  100739. #if FLAC__HAS_OGG
  100740. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100741. !decoder->private_->is_ogg &&
  100742. #endif
  100743. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100744. ) {
  100745. *bytes = 0;
  100746. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100747. return false;
  100748. }
  100749. else if(*bytes > 0) {
  100750. /* While seeking, it is possible for our seek to land in the
  100751. * middle of audio data that looks exactly like a frame header
  100752. * from a future version of an encoder. When that happens, our
  100753. * error callback will get an
  100754. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100755. * unparseable_frame_count. But there is a remote possibility
  100756. * that it is properly synced at such a "future-codec frame",
  100757. * so to make sure, we wait to see many "unparseable" errors in
  100758. * a row before bailing out.
  100759. */
  100760. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100761. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100762. return false;
  100763. }
  100764. else {
  100765. const FLAC__StreamDecoderReadStatus status =
  100766. #if FLAC__HAS_OGG
  100767. decoder->private_->is_ogg?
  100768. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100769. #endif
  100770. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100771. ;
  100772. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100773. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100774. return false;
  100775. }
  100776. else if(*bytes == 0) {
  100777. if(
  100778. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100779. (
  100780. #if FLAC__HAS_OGG
  100781. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100782. !decoder->private_->is_ogg &&
  100783. #endif
  100784. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100785. )
  100786. ) {
  100787. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100788. return false;
  100789. }
  100790. else
  100791. return true;
  100792. }
  100793. else
  100794. return true;
  100795. }
  100796. }
  100797. else {
  100798. /* abort to avoid a deadlock */
  100799. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100800. return false;
  100801. }
  100802. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100803. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100804. * and at the same time hit the end of the stream (for example, seeking
  100805. * to a point that is after the beginning of the last Ogg page). There
  100806. * is no way to report an Ogg sync loss through the callbacks (see note
  100807. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100808. * So to keep the decoder from stopping at this point we gate the call
  100809. * to the eof_callback and let the Ogg decoder aspect set the
  100810. * end-of-stream state when it is needed.
  100811. */
  100812. }
  100813. #if FLAC__HAS_OGG
  100814. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100815. {
  100816. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100817. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100818. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100819. /* we don't really have a way to handle lost sync via read
  100820. * callback so we'll let it pass and let the underlying
  100821. * FLAC decoder catch the error
  100822. */
  100823. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  100824. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100825. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  100826. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100827. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  100828. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  100829. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  100830. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  100831. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  100832. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100833. default:
  100834. FLAC__ASSERT(0);
  100835. /* double protection */
  100836. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100837. }
  100838. }
  100839. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100840. {
  100841. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  100842. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  100843. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  100844. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  100845. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  100846. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  100847. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  100848. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100849. default:
  100850. /* double protection: */
  100851. FLAC__ASSERT(0);
  100852. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100853. }
  100854. }
  100855. #endif
  100856. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  100857. {
  100858. if(decoder->private_->is_seeking) {
  100859. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  100860. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  100861. FLAC__uint64 target_sample = decoder->private_->target_sample;
  100862. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100863. #if FLAC__HAS_OGG
  100864. decoder->private_->got_a_frame = true;
  100865. #endif
  100866. decoder->private_->last_frame = *frame; /* save the frame */
  100867. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  100868. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  100869. /* kick out of seek mode */
  100870. decoder->private_->is_seeking = false;
  100871. /* shift out the samples before target_sample */
  100872. if(delta > 0) {
  100873. unsigned channel;
  100874. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  100875. for(channel = 0; channel < frame->header.channels; channel++)
  100876. newbuffer[channel] = buffer[channel] + delta;
  100877. decoder->private_->last_frame.header.blocksize -= delta;
  100878. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  100879. /* write the relevant samples */
  100880. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  100881. }
  100882. else {
  100883. /* write the relevant samples */
  100884. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100885. }
  100886. }
  100887. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100888. }
  100889. /*
  100890. * If we never got STREAMINFO, turn off MD5 checking to save
  100891. * cycles since we don't have a sum to compare to anyway
  100892. */
  100893. if(!decoder->private_->has_stream_info)
  100894. decoder->private_->do_md5_checking = false;
  100895. if(decoder->private_->do_md5_checking) {
  100896. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  100897. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100898. }
  100899. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100900. }
  100901. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  100902. {
  100903. if(!decoder->private_->is_seeking)
  100904. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  100905. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  100906. decoder->private_->unparseable_frame_count++;
  100907. }
  100908. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100909. {
  100910. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  100911. FLAC__int64 pos = -1;
  100912. int i;
  100913. unsigned approx_bytes_per_frame;
  100914. FLAC__bool first_seek = true;
  100915. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  100916. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  100917. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100918. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  100919. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  100920. /* take these from the current frame in case they've changed mid-stream */
  100921. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  100922. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  100923. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  100924. /* use values from stream info if we didn't decode a frame */
  100925. if(channels == 0)
  100926. channels = decoder->private_->stream_info.data.stream_info.channels;
  100927. if(bps == 0)
  100928. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100929. /* we are just guessing here */
  100930. if(max_framesize > 0)
  100931. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  100932. /*
  100933. * Check if it's a known fixed-blocksize stream. Note that though
  100934. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  100935. * never get a STREAMINFO block when decoding so the value of
  100936. * min_blocksize might be zero.
  100937. */
  100938. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  100939. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  100940. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  100941. }
  100942. else
  100943. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  100944. /*
  100945. * First, we set an upper and lower bound on where in the
  100946. * stream we will search. For now we assume the worst case
  100947. * scenario, which is our best guess at the beginning of
  100948. * the first frame and end of the stream.
  100949. */
  100950. lower_bound = first_frame_offset;
  100951. lower_bound_sample = 0;
  100952. upper_bound = stream_length;
  100953. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  100954. /*
  100955. * Now we refine the bounds if we have a seektable with
  100956. * suitable points. Note that according to the spec they
  100957. * must be ordered by ascending sample number.
  100958. *
  100959. * Note: to protect against invalid seek tables we will ignore points
  100960. * that have frame_samples==0 or sample_number>=total_samples
  100961. */
  100962. if(seek_table) {
  100963. FLAC__uint64 new_lower_bound = lower_bound;
  100964. FLAC__uint64 new_upper_bound = upper_bound;
  100965. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  100966. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  100967. /* find the closest seek point <= target_sample, if it exists */
  100968. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  100969. if(
  100970. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100971. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100972. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100973. seek_table->points[i].sample_number <= target_sample
  100974. )
  100975. break;
  100976. }
  100977. if(i >= 0) { /* i.e. we found a suitable seek point... */
  100978. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100979. new_lower_bound_sample = seek_table->points[i].sample_number;
  100980. }
  100981. /* find the closest seek point > target_sample, if it exists */
  100982. for(i = 0; i < (int)seek_table->num_points; i++) {
  100983. if(
  100984. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100985. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100986. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100987. seek_table->points[i].sample_number > target_sample
  100988. )
  100989. break;
  100990. }
  100991. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  100992. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100993. new_upper_bound_sample = seek_table->points[i].sample_number;
  100994. }
  100995. /* final protection against unsorted seek tables; keep original values if bogus */
  100996. if(new_upper_bound >= new_lower_bound) {
  100997. lower_bound = new_lower_bound;
  100998. upper_bound = new_upper_bound;
  100999. lower_bound_sample = new_lower_bound_sample;
  101000. upper_bound_sample = new_upper_bound_sample;
  101001. }
  101002. }
  101003. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101004. /* there are 2 insidious ways that the following equality occurs, which
  101005. * we need to fix:
  101006. * 1) total_samples is 0 (unknown) and target_sample is 0
  101007. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101008. * exactly equal to the last seek point in the seek table; this
  101009. * means there is no seek point above it, and upper_bound_samples
  101010. * remains equal to the estimate (of target_samples) we made above
  101011. * in either case it does not hurt to move upper_bound_sample up by 1
  101012. */
  101013. if(upper_bound_sample == lower_bound_sample)
  101014. upper_bound_sample++;
  101015. decoder->private_->target_sample = target_sample;
  101016. while(1) {
  101017. /* check if the bounds are still ok */
  101018. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101019. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101020. return false;
  101021. }
  101022. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101023. #if defined _MSC_VER || defined __MINGW32__
  101024. /* with VC++ you have to spoon feed it the casting */
  101025. 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;
  101026. #else
  101027. 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;
  101028. #endif
  101029. #else
  101030. /* a little less accurate: */
  101031. if(upper_bound - lower_bound < 0xffffffff)
  101032. 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;
  101033. else /* @@@ WATCHOUT, ~2TB limit */
  101034. 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;
  101035. #endif
  101036. if(pos >= (FLAC__int64)upper_bound)
  101037. pos = (FLAC__int64)upper_bound - 1;
  101038. if(pos < (FLAC__int64)lower_bound)
  101039. pos = (FLAC__int64)lower_bound;
  101040. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101041. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101042. return false;
  101043. }
  101044. if(!FLAC__stream_decoder_flush(decoder)) {
  101045. /* above call sets the state for us */
  101046. return false;
  101047. }
  101048. /* Now we need to get a frame. First we need to reset our
  101049. * unparseable_frame_count; if we get too many unparseable
  101050. * frames in a row, the read callback will return
  101051. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101052. * FLAC__stream_decoder_process_single() to return false.
  101053. */
  101054. decoder->private_->unparseable_frame_count = 0;
  101055. if(!FLAC__stream_decoder_process_single(decoder)) {
  101056. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101057. return false;
  101058. }
  101059. /* our write callback will change the state when it gets to the target frame */
  101060. /* 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 */
  101061. #if 0
  101062. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101063. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101064. break;
  101065. #endif
  101066. if(!decoder->private_->is_seeking)
  101067. break;
  101068. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101069. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101070. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101071. if (pos == (FLAC__int64)lower_bound) {
  101072. /* can't move back any more than the first frame, something is fatally wrong */
  101073. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101074. return false;
  101075. }
  101076. /* our last move backwards wasn't big enough, try again */
  101077. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101078. continue;
  101079. }
  101080. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101081. first_seek = false;
  101082. /* make sure we are not seeking in corrupted stream */
  101083. if (this_frame_sample < lower_bound_sample) {
  101084. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101085. return false;
  101086. }
  101087. /* we need to narrow the search */
  101088. if(target_sample < this_frame_sample) {
  101089. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101090. /*@@@@@@ what will decode position be if at end of stream? */
  101091. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101092. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101093. return false;
  101094. }
  101095. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101096. }
  101097. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101098. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101099. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101100. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101101. return false;
  101102. }
  101103. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101104. }
  101105. }
  101106. return true;
  101107. }
  101108. #if FLAC__HAS_OGG
  101109. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101110. {
  101111. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101112. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101113. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101114. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101115. FLAC__bool did_a_seek;
  101116. unsigned iteration = 0;
  101117. /* In the first iterations, we will calculate the target byte position
  101118. * by the distance from the target sample to left_sample and
  101119. * right_sample (let's call it "proportional search"). After that, we
  101120. * will switch to binary search.
  101121. */
  101122. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101123. /* We will switch to a linear search once our current sample is less
  101124. * than this number of samples ahead of the target sample
  101125. */
  101126. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101127. /* If the total number of samples is unknown, use a large value, and
  101128. * force binary search immediately.
  101129. */
  101130. if(right_sample == 0) {
  101131. right_sample = (FLAC__uint64)(-1);
  101132. BINARY_SEARCH_AFTER_ITERATION = 0;
  101133. }
  101134. decoder->private_->target_sample = target_sample;
  101135. for( ; ; iteration++) {
  101136. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101137. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101138. pos = (right_pos + left_pos) / 2;
  101139. }
  101140. else {
  101141. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101142. #if defined _MSC_VER || defined __MINGW32__
  101143. /* with MSVC you have to spoon feed it the casting */
  101144. 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));
  101145. #else
  101146. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101147. #endif
  101148. #else
  101149. /* a little less accurate: */
  101150. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101151. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101152. else /* @@@ WATCHOUT, ~2TB limit */
  101153. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101154. #endif
  101155. /* @@@ TODO: might want to limit pos to some distance
  101156. * before EOF, to make sure we land before the last frame,
  101157. * thereby getting a this_frame_sample and so having a better
  101158. * estimate.
  101159. */
  101160. }
  101161. /* physical seek */
  101162. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101163. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101164. return false;
  101165. }
  101166. if(!FLAC__stream_decoder_flush(decoder)) {
  101167. /* above call sets the state for us */
  101168. return false;
  101169. }
  101170. did_a_seek = true;
  101171. }
  101172. else
  101173. did_a_seek = false;
  101174. decoder->private_->got_a_frame = false;
  101175. if(!FLAC__stream_decoder_process_single(decoder)) {
  101176. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101177. return false;
  101178. }
  101179. if(!decoder->private_->got_a_frame) {
  101180. if(did_a_seek) {
  101181. /* this can happen if we seek to a point after the last frame; we drop
  101182. * to binary search right away in this case to avoid any wasted
  101183. * iterations of proportional search.
  101184. */
  101185. right_pos = pos;
  101186. BINARY_SEARCH_AFTER_ITERATION = 0;
  101187. }
  101188. else {
  101189. /* this can probably only happen if total_samples is unknown and the
  101190. * target_sample is past the end of the stream
  101191. */
  101192. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101193. return false;
  101194. }
  101195. }
  101196. /* our write callback will change the state when it gets to the target frame */
  101197. else if(!decoder->private_->is_seeking) {
  101198. break;
  101199. }
  101200. else {
  101201. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101202. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101203. if (did_a_seek) {
  101204. if (this_frame_sample <= target_sample) {
  101205. /* The 'equal' case should not happen, since
  101206. * FLAC__stream_decoder_process_single()
  101207. * should recognize that it has hit the
  101208. * target sample and we would exit through
  101209. * the 'break' above.
  101210. */
  101211. FLAC__ASSERT(this_frame_sample != target_sample);
  101212. left_sample = this_frame_sample;
  101213. /* sanity check to avoid infinite loop */
  101214. if (left_pos == pos) {
  101215. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101216. return false;
  101217. }
  101218. left_pos = pos;
  101219. }
  101220. else if(this_frame_sample > target_sample) {
  101221. right_sample = this_frame_sample;
  101222. /* sanity check to avoid infinite loop */
  101223. if (right_pos == pos) {
  101224. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101225. return false;
  101226. }
  101227. right_pos = pos;
  101228. }
  101229. }
  101230. }
  101231. }
  101232. return true;
  101233. }
  101234. #endif
  101235. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101236. {
  101237. (void)client_data;
  101238. if(*bytes > 0) {
  101239. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101240. if(ferror(decoder->private_->file))
  101241. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101242. else if(*bytes == 0)
  101243. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101244. else
  101245. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101246. }
  101247. else
  101248. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101249. }
  101250. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101251. {
  101252. (void)client_data;
  101253. if(decoder->private_->file == stdin)
  101254. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101255. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101256. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101257. else
  101258. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101259. }
  101260. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101261. {
  101262. off_t pos;
  101263. (void)client_data;
  101264. if(decoder->private_->file == stdin)
  101265. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101266. else if((pos = ftello(decoder->private_->file)) < 0)
  101267. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101268. else {
  101269. *absolute_byte_offset = (FLAC__uint64)pos;
  101270. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101271. }
  101272. }
  101273. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101274. {
  101275. struct stat filestats;
  101276. (void)client_data;
  101277. if(decoder->private_->file == stdin)
  101278. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101279. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101280. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101281. else {
  101282. *stream_length = (FLAC__uint64)filestats.st_size;
  101283. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101284. }
  101285. }
  101286. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101287. {
  101288. (void)client_data;
  101289. return feof(decoder->private_->file)? true : false;
  101290. }
  101291. #endif
  101292. /*** End of inlined file: stream_decoder.c ***/
  101293. /*** Start of inlined file: stream_encoder.c ***/
  101294. /*** Start of inlined file: juce_FlacHeader.h ***/
  101295. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101296. // tasks..
  101297. #define VERSION "1.2.1"
  101298. #define FLAC__NO_DLL 1
  101299. #if JUCE_MSVC
  101300. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101301. #endif
  101302. #if JUCE_MAC
  101303. #define FLAC__SYS_DARWIN 1
  101304. #endif
  101305. /*** End of inlined file: juce_FlacHeader.h ***/
  101306. #if JUCE_USE_FLAC
  101307. #if HAVE_CONFIG_H
  101308. # include <config.h>
  101309. #endif
  101310. #if defined _MSC_VER || defined __MINGW32__
  101311. #include <io.h> /* for _setmode() */
  101312. #include <fcntl.h> /* for _O_BINARY */
  101313. #endif
  101314. #if defined __CYGWIN__ || defined __EMX__
  101315. #include <io.h> /* for setmode(), O_BINARY */
  101316. #include <fcntl.h> /* for _O_BINARY */
  101317. #endif
  101318. #include <limits.h>
  101319. #include <stdio.h>
  101320. #include <stdlib.h> /* for malloc() */
  101321. #include <string.h> /* for memcpy() */
  101322. #include <sys/types.h> /* for off_t */
  101323. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101324. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101325. #define fseeko fseek
  101326. #define ftello ftell
  101327. #endif
  101328. #endif
  101329. /*** Start of inlined file: stream_encoder.h ***/
  101330. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101331. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101332. #if FLAC__HAS_OGG
  101333. #include "private/ogg_encoder_aspect.h"
  101334. #endif
  101335. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101336. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101337. typedef enum {
  101338. FLAC__APODIZATION_BARTLETT,
  101339. FLAC__APODIZATION_BARTLETT_HANN,
  101340. FLAC__APODIZATION_BLACKMAN,
  101341. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101342. FLAC__APODIZATION_CONNES,
  101343. FLAC__APODIZATION_FLATTOP,
  101344. FLAC__APODIZATION_GAUSS,
  101345. FLAC__APODIZATION_HAMMING,
  101346. FLAC__APODIZATION_HANN,
  101347. FLAC__APODIZATION_KAISER_BESSEL,
  101348. FLAC__APODIZATION_NUTTALL,
  101349. FLAC__APODIZATION_RECTANGLE,
  101350. FLAC__APODIZATION_TRIANGLE,
  101351. FLAC__APODIZATION_TUKEY,
  101352. FLAC__APODIZATION_WELCH
  101353. } FLAC__ApodizationFunction;
  101354. typedef struct {
  101355. FLAC__ApodizationFunction type;
  101356. union {
  101357. struct {
  101358. FLAC__real stddev;
  101359. } gauss;
  101360. struct {
  101361. FLAC__real p;
  101362. } tukey;
  101363. } parameters;
  101364. } FLAC__ApodizationSpecification;
  101365. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101366. typedef struct FLAC__StreamEncoderProtected {
  101367. FLAC__StreamEncoderState state;
  101368. FLAC__bool verify;
  101369. FLAC__bool streamable_subset;
  101370. FLAC__bool do_md5;
  101371. FLAC__bool do_mid_side_stereo;
  101372. FLAC__bool loose_mid_side_stereo;
  101373. unsigned channels;
  101374. unsigned bits_per_sample;
  101375. unsigned sample_rate;
  101376. unsigned blocksize;
  101377. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101378. unsigned num_apodizations;
  101379. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101380. #endif
  101381. unsigned max_lpc_order;
  101382. unsigned qlp_coeff_precision;
  101383. FLAC__bool do_qlp_coeff_prec_search;
  101384. FLAC__bool do_exhaustive_model_search;
  101385. FLAC__bool do_escape_coding;
  101386. unsigned min_residual_partition_order;
  101387. unsigned max_residual_partition_order;
  101388. unsigned rice_parameter_search_dist;
  101389. FLAC__uint64 total_samples_estimate;
  101390. FLAC__StreamMetadata **metadata;
  101391. unsigned num_metadata_blocks;
  101392. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101393. #if FLAC__HAS_OGG
  101394. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101395. #endif
  101396. } FLAC__StreamEncoderProtected;
  101397. #endif
  101398. /*** End of inlined file: stream_encoder.h ***/
  101399. #if FLAC__HAS_OGG
  101400. #include "include/private/ogg_helper.h"
  101401. #include "include/private/ogg_mapping.h"
  101402. #endif
  101403. /*** Start of inlined file: stream_encoder_framing.h ***/
  101404. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101405. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101406. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101407. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101408. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101409. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101410. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101411. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101412. #endif
  101413. /*** End of inlined file: stream_encoder_framing.h ***/
  101414. /*** Start of inlined file: window.h ***/
  101415. #ifndef FLAC__PRIVATE__WINDOW_H
  101416. #define FLAC__PRIVATE__WINDOW_H
  101417. #ifdef HAVE_CONFIG_H
  101418. #include <config.h>
  101419. #endif
  101420. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101421. /*
  101422. * FLAC__window_*()
  101423. * --------------------------------------------------------------------
  101424. * Calculates window coefficients according to different apodization
  101425. * functions.
  101426. *
  101427. * OUT window[0,L-1]
  101428. * IN L (number of points in window)
  101429. */
  101430. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101431. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101432. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101433. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101434. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101435. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101436. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101437. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101438. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101439. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101440. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101441. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101442. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101443. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101444. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101445. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101446. #endif
  101447. /*** End of inlined file: window.h ***/
  101448. #ifndef FLaC__INLINE
  101449. #define FLaC__INLINE
  101450. #endif
  101451. #ifdef min
  101452. #undef min
  101453. #endif
  101454. #define min(x,y) ((x)<(y)?(x):(y))
  101455. #ifdef max
  101456. #undef max
  101457. #endif
  101458. #define max(x,y) ((x)>(y)?(x):(y))
  101459. /* Exact Rice codeword length calculation is off by default. The simple
  101460. * (and fast) estimation (of how many bits a residual value will be
  101461. * encoded with) in this encoder is very good, almost always yielding
  101462. * compression within 0.1% of exact calculation.
  101463. */
  101464. #undef EXACT_RICE_BITS_CALCULATION
  101465. /* Rice parameter searching is off by default. The simple (and fast)
  101466. * parameter estimation in this encoder is very good, almost always
  101467. * yielding compression within 0.1% of the optimal parameters.
  101468. */
  101469. #undef ENABLE_RICE_PARAMETER_SEARCH
  101470. typedef struct {
  101471. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101472. unsigned size; /* of each data[] in samples */
  101473. unsigned tail;
  101474. } verify_input_fifo;
  101475. typedef struct {
  101476. const FLAC__byte *data;
  101477. unsigned capacity;
  101478. unsigned bytes;
  101479. } verify_output;
  101480. typedef enum {
  101481. ENCODER_IN_MAGIC = 0,
  101482. ENCODER_IN_METADATA = 1,
  101483. ENCODER_IN_AUDIO = 2
  101484. } EncoderStateHint;
  101485. static struct CompressionLevels {
  101486. FLAC__bool do_mid_side_stereo;
  101487. FLAC__bool loose_mid_side_stereo;
  101488. unsigned max_lpc_order;
  101489. unsigned qlp_coeff_precision;
  101490. FLAC__bool do_qlp_coeff_prec_search;
  101491. FLAC__bool do_escape_coding;
  101492. FLAC__bool do_exhaustive_model_search;
  101493. unsigned min_residual_partition_order;
  101494. unsigned max_residual_partition_order;
  101495. unsigned rice_parameter_search_dist;
  101496. } compression_levels_[] = {
  101497. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101498. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101499. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101500. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101501. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101502. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101503. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101504. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101505. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101506. };
  101507. /***********************************************************************
  101508. *
  101509. * Private class method prototypes
  101510. *
  101511. ***********************************************************************/
  101512. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101513. static void free_(FLAC__StreamEncoder *encoder);
  101514. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101515. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101516. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101517. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101518. #if FLAC__HAS_OGG
  101519. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101520. #endif
  101521. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101522. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101523. static FLAC__bool process_subframe_(
  101524. FLAC__StreamEncoder *encoder,
  101525. unsigned min_partition_order,
  101526. unsigned max_partition_order,
  101527. const FLAC__FrameHeader *frame_header,
  101528. unsigned subframe_bps,
  101529. const FLAC__int32 integer_signal[],
  101530. FLAC__Subframe *subframe[2],
  101531. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101532. FLAC__int32 *residual[2],
  101533. unsigned *best_subframe,
  101534. unsigned *best_bits
  101535. );
  101536. static FLAC__bool add_subframe_(
  101537. FLAC__StreamEncoder *encoder,
  101538. unsigned blocksize,
  101539. unsigned subframe_bps,
  101540. const FLAC__Subframe *subframe,
  101541. FLAC__BitWriter *frame
  101542. );
  101543. static unsigned evaluate_constant_subframe_(
  101544. FLAC__StreamEncoder *encoder,
  101545. const FLAC__int32 signal,
  101546. unsigned blocksize,
  101547. unsigned subframe_bps,
  101548. FLAC__Subframe *subframe
  101549. );
  101550. static unsigned evaluate_fixed_subframe_(
  101551. FLAC__StreamEncoder *encoder,
  101552. const FLAC__int32 signal[],
  101553. FLAC__int32 residual[],
  101554. FLAC__uint64 abs_residual_partition_sums[],
  101555. unsigned raw_bits_per_partition[],
  101556. unsigned blocksize,
  101557. unsigned subframe_bps,
  101558. unsigned order,
  101559. unsigned rice_parameter,
  101560. unsigned rice_parameter_limit,
  101561. unsigned min_partition_order,
  101562. unsigned max_partition_order,
  101563. FLAC__bool do_escape_coding,
  101564. unsigned rice_parameter_search_dist,
  101565. FLAC__Subframe *subframe,
  101566. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101567. );
  101568. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101569. static unsigned evaluate_lpc_subframe_(
  101570. FLAC__StreamEncoder *encoder,
  101571. const FLAC__int32 signal[],
  101572. FLAC__int32 residual[],
  101573. FLAC__uint64 abs_residual_partition_sums[],
  101574. unsigned raw_bits_per_partition[],
  101575. const FLAC__real lp_coeff[],
  101576. unsigned blocksize,
  101577. unsigned subframe_bps,
  101578. unsigned order,
  101579. unsigned qlp_coeff_precision,
  101580. unsigned rice_parameter,
  101581. unsigned rice_parameter_limit,
  101582. unsigned min_partition_order,
  101583. unsigned max_partition_order,
  101584. FLAC__bool do_escape_coding,
  101585. unsigned rice_parameter_search_dist,
  101586. FLAC__Subframe *subframe,
  101587. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101588. );
  101589. #endif
  101590. static unsigned evaluate_verbatim_subframe_(
  101591. FLAC__StreamEncoder *encoder,
  101592. const FLAC__int32 signal[],
  101593. unsigned blocksize,
  101594. unsigned subframe_bps,
  101595. FLAC__Subframe *subframe
  101596. );
  101597. static unsigned find_best_partition_order_(
  101598. struct FLAC__StreamEncoderPrivate *private_,
  101599. const FLAC__int32 residual[],
  101600. FLAC__uint64 abs_residual_partition_sums[],
  101601. unsigned raw_bits_per_partition[],
  101602. unsigned residual_samples,
  101603. unsigned predictor_order,
  101604. unsigned rice_parameter,
  101605. unsigned rice_parameter_limit,
  101606. unsigned min_partition_order,
  101607. unsigned max_partition_order,
  101608. unsigned bps,
  101609. FLAC__bool do_escape_coding,
  101610. unsigned rice_parameter_search_dist,
  101611. FLAC__EntropyCodingMethod *best_ecm
  101612. );
  101613. static void precompute_partition_info_sums_(
  101614. const FLAC__int32 residual[],
  101615. FLAC__uint64 abs_residual_partition_sums[],
  101616. unsigned residual_samples,
  101617. unsigned predictor_order,
  101618. unsigned min_partition_order,
  101619. unsigned max_partition_order,
  101620. unsigned bps
  101621. );
  101622. static void precompute_partition_info_escapes_(
  101623. const FLAC__int32 residual[],
  101624. unsigned raw_bits_per_partition[],
  101625. unsigned residual_samples,
  101626. unsigned predictor_order,
  101627. unsigned min_partition_order,
  101628. unsigned max_partition_order
  101629. );
  101630. static FLAC__bool set_partitioned_rice_(
  101631. #ifdef EXACT_RICE_BITS_CALCULATION
  101632. const FLAC__int32 residual[],
  101633. #endif
  101634. const FLAC__uint64 abs_residual_partition_sums[],
  101635. const unsigned raw_bits_per_partition[],
  101636. const unsigned residual_samples,
  101637. const unsigned predictor_order,
  101638. const unsigned suggested_rice_parameter,
  101639. const unsigned rice_parameter_limit,
  101640. const unsigned rice_parameter_search_dist,
  101641. const unsigned partition_order,
  101642. const FLAC__bool search_for_escapes,
  101643. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101644. unsigned *bits
  101645. );
  101646. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101647. /* verify-related routines: */
  101648. static void append_to_verify_fifo_(
  101649. verify_input_fifo *fifo,
  101650. const FLAC__int32 * const input[],
  101651. unsigned input_offset,
  101652. unsigned channels,
  101653. unsigned wide_samples
  101654. );
  101655. static void append_to_verify_fifo_interleaved_(
  101656. verify_input_fifo *fifo,
  101657. const FLAC__int32 input[],
  101658. unsigned input_offset,
  101659. unsigned channels,
  101660. unsigned wide_samples
  101661. );
  101662. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101663. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101664. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101665. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101666. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101667. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101668. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101669. 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);
  101670. static FILE *get_binary_stdout_(void);
  101671. /***********************************************************************
  101672. *
  101673. * Private class data
  101674. *
  101675. ***********************************************************************/
  101676. typedef struct FLAC__StreamEncoderPrivate {
  101677. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101678. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101679. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101680. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101681. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101682. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101683. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101684. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101685. #endif
  101686. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101687. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101688. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101689. FLAC__int32 *residual_workspace_mid_side[2][2];
  101690. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101691. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101692. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101693. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101694. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101695. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101696. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101697. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101698. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101699. unsigned best_subframe_mid_side[2];
  101700. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101701. unsigned best_subframe_bits_mid_side[2];
  101702. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101703. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101704. FLAC__BitWriter *frame; /* the current frame being worked on */
  101705. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101706. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101707. FLAC__ChannelAssignment last_channel_assignment;
  101708. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101709. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101710. unsigned current_sample_number;
  101711. unsigned current_frame_number;
  101712. FLAC__MD5Context md5context;
  101713. FLAC__CPUInfo cpuinfo;
  101714. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101715. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101716. #else
  101717. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101718. #endif
  101719. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101720. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101721. 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[]);
  101722. 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[]);
  101723. 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[]);
  101724. #endif
  101725. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101726. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101727. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101728. FLAC__bool disable_constant_subframes;
  101729. FLAC__bool disable_fixed_subframes;
  101730. FLAC__bool disable_verbatim_subframes;
  101731. #if FLAC__HAS_OGG
  101732. FLAC__bool is_ogg;
  101733. #endif
  101734. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101735. FLAC__StreamEncoderSeekCallback seek_callback;
  101736. FLAC__StreamEncoderTellCallback tell_callback;
  101737. FLAC__StreamEncoderWriteCallback write_callback;
  101738. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101739. FLAC__StreamEncoderProgressCallback progress_callback;
  101740. void *client_data;
  101741. unsigned first_seekpoint_to_check;
  101742. FILE *file; /* only used when encoding to a file */
  101743. FLAC__uint64 bytes_written;
  101744. FLAC__uint64 samples_written;
  101745. unsigned frames_written;
  101746. unsigned total_frames_estimate;
  101747. /* unaligned (original) pointers to allocated data */
  101748. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101749. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101750. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101751. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101752. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101753. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101754. FLAC__real *windowed_signal_unaligned;
  101755. #endif
  101756. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101757. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101758. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101759. unsigned *raw_bits_per_partition_unaligned;
  101760. /*
  101761. * These fields have been moved here from private function local
  101762. * declarations merely to save stack space during encoding.
  101763. */
  101764. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101765. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101766. #endif
  101767. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101768. /*
  101769. * The data for the verify section
  101770. */
  101771. struct {
  101772. FLAC__StreamDecoder *decoder;
  101773. EncoderStateHint state_hint;
  101774. FLAC__bool needs_magic_hack;
  101775. verify_input_fifo input_fifo;
  101776. verify_output output;
  101777. struct {
  101778. FLAC__uint64 absolute_sample;
  101779. unsigned frame_number;
  101780. unsigned channel;
  101781. unsigned sample;
  101782. FLAC__int32 expected;
  101783. FLAC__int32 got;
  101784. } error_stats;
  101785. } verify;
  101786. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101787. } FLAC__StreamEncoderPrivate;
  101788. /***********************************************************************
  101789. *
  101790. * Public static class data
  101791. *
  101792. ***********************************************************************/
  101793. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101794. "FLAC__STREAM_ENCODER_OK",
  101795. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101796. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101797. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101798. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101799. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101800. "FLAC__STREAM_ENCODER_IO_ERROR",
  101801. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101802. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101803. };
  101804. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101805. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101806. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101807. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101808. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101809. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101810. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101811. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101812. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101813. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101814. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101815. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101816. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101817. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101818. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101819. };
  101820. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  101821. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  101822. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  101823. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  101824. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  101825. };
  101826. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  101827. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  101828. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  101829. };
  101830. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  101831. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  101832. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  101833. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  101834. };
  101835. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  101836. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  101837. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  101838. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  101839. };
  101840. /* Number of samples that will be overread to watch for end of stream. By
  101841. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  101842. * always try to read blocksize+1 samples before encoding a block, so that
  101843. * even if the stream has a total sample count that is an integral multiple
  101844. * of the blocksize, we will still notice when we are encoding the last
  101845. * block. This is needed, for example, to correctly set the end-of-stream
  101846. * marker in Ogg FLAC.
  101847. *
  101848. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  101849. * not really any reason to change it.
  101850. */
  101851. static const unsigned OVERREAD_ = 1;
  101852. /***********************************************************************
  101853. *
  101854. * Class constructor/destructor
  101855. *
  101856. */
  101857. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  101858. {
  101859. FLAC__StreamEncoder *encoder;
  101860. unsigned i;
  101861. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  101862. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  101863. if(encoder == 0) {
  101864. return 0;
  101865. }
  101866. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  101867. if(encoder->protected_ == 0) {
  101868. free(encoder);
  101869. return 0;
  101870. }
  101871. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  101872. if(encoder->private_ == 0) {
  101873. free(encoder->protected_);
  101874. free(encoder);
  101875. return 0;
  101876. }
  101877. encoder->private_->frame = FLAC__bitwriter_new();
  101878. if(encoder->private_->frame == 0) {
  101879. free(encoder->private_);
  101880. free(encoder->protected_);
  101881. free(encoder);
  101882. return 0;
  101883. }
  101884. encoder->private_->file = 0;
  101885. set_defaults_enc(encoder);
  101886. encoder->private_->is_being_deleted = false;
  101887. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101888. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  101889. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  101890. }
  101891. for(i = 0; i < 2; i++) {
  101892. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  101893. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  101894. }
  101895. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101896. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  101897. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  101898. }
  101899. for(i = 0; i < 2; i++) {
  101900. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  101901. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  101902. }
  101903. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101904. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101905. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101906. }
  101907. for(i = 0; i < 2; i++) {
  101908. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101909. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101910. }
  101911. for(i = 0; i < 2; i++)
  101912. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  101913. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  101914. return encoder;
  101915. }
  101916. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  101917. {
  101918. unsigned i;
  101919. FLAC__ASSERT(0 != encoder);
  101920. FLAC__ASSERT(0 != encoder->protected_);
  101921. FLAC__ASSERT(0 != encoder->private_);
  101922. FLAC__ASSERT(0 != encoder->private_->frame);
  101923. encoder->private_->is_being_deleted = true;
  101924. (void)FLAC__stream_encoder_finish(encoder);
  101925. if(0 != encoder->private_->verify.decoder)
  101926. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  101927. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101928. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101929. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101930. }
  101931. for(i = 0; i < 2; i++) {
  101932. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101933. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101934. }
  101935. for(i = 0; i < 2; i++)
  101936. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  101937. FLAC__bitwriter_delete(encoder->private_->frame);
  101938. free(encoder->private_);
  101939. free(encoder->protected_);
  101940. free(encoder);
  101941. }
  101942. /***********************************************************************
  101943. *
  101944. * Public class methods
  101945. *
  101946. ***********************************************************************/
  101947. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  101948. FLAC__StreamEncoder *encoder,
  101949. FLAC__StreamEncoderReadCallback read_callback,
  101950. FLAC__StreamEncoderWriteCallback write_callback,
  101951. FLAC__StreamEncoderSeekCallback seek_callback,
  101952. FLAC__StreamEncoderTellCallback tell_callback,
  101953. FLAC__StreamEncoderMetadataCallback metadata_callback,
  101954. void *client_data,
  101955. FLAC__bool is_ogg
  101956. )
  101957. {
  101958. unsigned i;
  101959. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  101960. FLAC__ASSERT(0 != encoder);
  101961. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  101962. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  101963. #if !FLAC__HAS_OGG
  101964. if(is_ogg)
  101965. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  101966. #endif
  101967. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  101968. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  101969. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  101970. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  101971. if(encoder->protected_->channels != 2) {
  101972. encoder->protected_->do_mid_side_stereo = false;
  101973. encoder->protected_->loose_mid_side_stereo = false;
  101974. }
  101975. else if(!encoder->protected_->do_mid_side_stereo)
  101976. encoder->protected_->loose_mid_side_stereo = false;
  101977. if(encoder->protected_->bits_per_sample >= 32)
  101978. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  101979. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  101980. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  101981. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  101982. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  101983. if(encoder->protected_->blocksize == 0) {
  101984. if(encoder->protected_->max_lpc_order == 0)
  101985. encoder->protected_->blocksize = 1152;
  101986. else
  101987. encoder->protected_->blocksize = 4096;
  101988. }
  101989. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  101990. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  101991. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  101992. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  101993. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  101994. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  101995. if(encoder->protected_->qlp_coeff_precision == 0) {
  101996. if(encoder->protected_->bits_per_sample < 16) {
  101997. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  101998. /* @@@ until then we'll make a guess */
  101999. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102000. }
  102001. else if(encoder->protected_->bits_per_sample == 16) {
  102002. if(encoder->protected_->blocksize <= 192)
  102003. encoder->protected_->qlp_coeff_precision = 7;
  102004. else if(encoder->protected_->blocksize <= 384)
  102005. encoder->protected_->qlp_coeff_precision = 8;
  102006. else if(encoder->protected_->blocksize <= 576)
  102007. encoder->protected_->qlp_coeff_precision = 9;
  102008. else if(encoder->protected_->blocksize <= 1152)
  102009. encoder->protected_->qlp_coeff_precision = 10;
  102010. else if(encoder->protected_->blocksize <= 2304)
  102011. encoder->protected_->qlp_coeff_precision = 11;
  102012. else if(encoder->protected_->blocksize <= 4608)
  102013. encoder->protected_->qlp_coeff_precision = 12;
  102014. else
  102015. encoder->protected_->qlp_coeff_precision = 13;
  102016. }
  102017. else {
  102018. if(encoder->protected_->blocksize <= 384)
  102019. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102020. else if(encoder->protected_->blocksize <= 1152)
  102021. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102022. else
  102023. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102024. }
  102025. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102026. }
  102027. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102028. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102029. if(encoder->protected_->streamable_subset) {
  102030. if(
  102031. encoder->protected_->blocksize != 192 &&
  102032. encoder->protected_->blocksize != 576 &&
  102033. encoder->protected_->blocksize != 1152 &&
  102034. encoder->protected_->blocksize != 2304 &&
  102035. encoder->protected_->blocksize != 4608 &&
  102036. encoder->protected_->blocksize != 256 &&
  102037. encoder->protected_->blocksize != 512 &&
  102038. encoder->protected_->blocksize != 1024 &&
  102039. encoder->protected_->blocksize != 2048 &&
  102040. encoder->protected_->blocksize != 4096 &&
  102041. encoder->protected_->blocksize != 8192 &&
  102042. encoder->protected_->blocksize != 16384
  102043. )
  102044. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102045. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102046. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102047. if(
  102048. encoder->protected_->bits_per_sample != 8 &&
  102049. encoder->protected_->bits_per_sample != 12 &&
  102050. encoder->protected_->bits_per_sample != 16 &&
  102051. encoder->protected_->bits_per_sample != 20 &&
  102052. encoder->protected_->bits_per_sample != 24
  102053. )
  102054. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102055. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102056. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102057. if(
  102058. encoder->protected_->sample_rate <= 48000 &&
  102059. (
  102060. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102061. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102062. )
  102063. ) {
  102064. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102065. }
  102066. }
  102067. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102068. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102069. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102070. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102071. #if FLAC__HAS_OGG
  102072. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102073. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102074. unsigned i;
  102075. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102076. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102077. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102078. for( ; i > 0; i--)
  102079. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102080. encoder->protected_->metadata[0] = vc;
  102081. break;
  102082. }
  102083. }
  102084. }
  102085. #endif
  102086. /* keep track of any SEEKTABLE block */
  102087. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102088. unsigned i;
  102089. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102090. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102091. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102092. break; /* take only the first one */
  102093. }
  102094. }
  102095. }
  102096. /* validate metadata */
  102097. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102098. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102099. metadata_has_seektable = false;
  102100. metadata_has_vorbis_comment = false;
  102101. metadata_picture_has_type1 = false;
  102102. metadata_picture_has_type2 = false;
  102103. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102104. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102105. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102106. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102107. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102108. if(metadata_has_seektable) /* only one is allowed */
  102109. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102110. metadata_has_seektable = true;
  102111. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102112. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102113. }
  102114. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102115. if(metadata_has_vorbis_comment) /* only one is allowed */
  102116. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102117. metadata_has_vorbis_comment = true;
  102118. }
  102119. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102120. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102121. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102122. }
  102123. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102124. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102125. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102126. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102127. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102128. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102129. metadata_picture_has_type1 = true;
  102130. /* standard icon must be 32x32 pixel PNG */
  102131. if(
  102132. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102133. (
  102134. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102135. m->data.picture.width != 32 ||
  102136. m->data.picture.height != 32
  102137. )
  102138. )
  102139. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102140. }
  102141. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102142. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102143. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102144. metadata_picture_has_type2 = true;
  102145. }
  102146. }
  102147. }
  102148. encoder->private_->input_capacity = 0;
  102149. for(i = 0; i < encoder->protected_->channels; i++) {
  102150. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102151. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102152. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102153. #endif
  102154. }
  102155. for(i = 0; i < 2; i++) {
  102156. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102157. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102158. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102159. #endif
  102160. }
  102161. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102162. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102163. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102164. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102165. #endif
  102166. for(i = 0; i < encoder->protected_->channels; i++) {
  102167. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102168. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102169. encoder->private_->best_subframe[i] = 0;
  102170. }
  102171. for(i = 0; i < 2; i++) {
  102172. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102173. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102174. encoder->private_->best_subframe_mid_side[i] = 0;
  102175. }
  102176. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102177. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102178. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102179. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102180. #else
  102181. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102182. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102183. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102184. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102185. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102186. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102187. 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);
  102188. #endif
  102189. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102190. encoder->private_->loose_mid_side_stereo_frames = 1;
  102191. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102192. encoder->private_->current_sample_number = 0;
  102193. encoder->private_->current_frame_number = 0;
  102194. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102195. 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? */
  102196. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102197. /*
  102198. * get the CPU info and set the function pointers
  102199. */
  102200. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102201. /* first default to the non-asm routines */
  102202. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102203. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102204. #endif
  102205. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102206. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102207. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102208. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102209. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102210. #endif
  102211. /* now override with asm where appropriate */
  102212. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102213. # ifndef FLAC__NO_ASM
  102214. if(encoder->private_->cpuinfo.use_asm) {
  102215. # ifdef FLAC__CPU_IA32
  102216. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102217. # ifdef FLAC__HAS_NASM
  102218. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102219. if(encoder->protected_->max_lpc_order < 4)
  102220. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102221. else if(encoder->protected_->max_lpc_order < 8)
  102222. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102223. else if(encoder->protected_->max_lpc_order < 12)
  102224. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102225. else
  102226. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102227. }
  102228. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102229. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102230. else
  102231. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102232. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102233. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102234. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102235. }
  102236. else {
  102237. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102238. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102239. }
  102240. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102241. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102242. # endif /* FLAC__HAS_NASM */
  102243. # endif /* FLAC__CPU_IA32 */
  102244. }
  102245. # endif /* !FLAC__NO_ASM */
  102246. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102247. /* finally override based on wide-ness if necessary */
  102248. if(encoder->private_->use_wide_by_block) {
  102249. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102250. }
  102251. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102252. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102253. #if FLAC__HAS_OGG
  102254. encoder->private_->is_ogg = is_ogg;
  102255. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102256. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102257. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102258. }
  102259. #endif
  102260. encoder->private_->read_callback = read_callback;
  102261. encoder->private_->write_callback = write_callback;
  102262. encoder->private_->seek_callback = seek_callback;
  102263. encoder->private_->tell_callback = tell_callback;
  102264. encoder->private_->metadata_callback = metadata_callback;
  102265. encoder->private_->client_data = client_data;
  102266. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102267. /* the above function sets the state for us in case of an error */
  102268. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102269. }
  102270. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102271. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102272. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102273. }
  102274. /*
  102275. * Set up the verify stuff if necessary
  102276. */
  102277. if(encoder->protected_->verify) {
  102278. /*
  102279. * First, set up the fifo which will hold the
  102280. * original signal to compare against
  102281. */
  102282. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102283. for(i = 0; i < encoder->protected_->channels; i++) {
  102284. 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))) {
  102285. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102286. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102287. }
  102288. }
  102289. encoder->private_->verify.input_fifo.tail = 0;
  102290. /*
  102291. * Now set up a stream decoder for verification
  102292. */
  102293. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102294. if(0 == encoder->private_->verify.decoder) {
  102295. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102296. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102297. }
  102298. 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) {
  102299. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102300. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102301. }
  102302. }
  102303. encoder->private_->verify.error_stats.absolute_sample = 0;
  102304. encoder->private_->verify.error_stats.frame_number = 0;
  102305. encoder->private_->verify.error_stats.channel = 0;
  102306. encoder->private_->verify.error_stats.sample = 0;
  102307. encoder->private_->verify.error_stats.expected = 0;
  102308. encoder->private_->verify.error_stats.got = 0;
  102309. /*
  102310. * These must be done before we write any metadata, because that
  102311. * calls the write_callback, which uses these values.
  102312. */
  102313. encoder->private_->first_seekpoint_to_check = 0;
  102314. encoder->private_->samples_written = 0;
  102315. encoder->protected_->streaminfo_offset = 0;
  102316. encoder->protected_->seektable_offset = 0;
  102317. encoder->protected_->audio_offset = 0;
  102318. /*
  102319. * write the stream header
  102320. */
  102321. if(encoder->protected_->verify)
  102322. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102323. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102324. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102325. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102326. }
  102327. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102328. /* the above function sets the state for us in case of an error */
  102329. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102330. }
  102331. /*
  102332. * write the STREAMINFO metadata block
  102333. */
  102334. if(encoder->protected_->verify)
  102335. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102336. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102337. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102338. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102339. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102340. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102341. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102342. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102343. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102344. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102345. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102346. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102347. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102348. if(encoder->protected_->do_md5)
  102349. FLAC__MD5Init(&encoder->private_->md5context);
  102350. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102351. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102352. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102353. }
  102354. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102355. /* the above function sets the state for us in case of an error */
  102356. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102357. }
  102358. /*
  102359. * Now that the STREAMINFO block is written, we can init this to an
  102360. * absurdly-high value...
  102361. */
  102362. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102363. /* ... and clear this to 0 */
  102364. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102365. /*
  102366. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102367. * if not, we will write an empty one (FLAC__add_metadata_block()
  102368. * automatically supplies the vendor string).
  102369. *
  102370. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102371. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102372. * true it will have already insured that the metadata list is properly
  102373. * ordered.)
  102374. */
  102375. if(!metadata_has_vorbis_comment) {
  102376. FLAC__StreamMetadata vorbis_comment;
  102377. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102378. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102379. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102380. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102381. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102382. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102383. vorbis_comment.data.vorbis_comment.comments = 0;
  102384. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102385. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102386. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102387. }
  102388. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102389. /* the above function sets the state for us in case of an error */
  102390. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102391. }
  102392. }
  102393. /*
  102394. * write the user's metadata blocks
  102395. */
  102396. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102397. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102398. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102399. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102400. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102401. }
  102402. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102403. /* the above function sets the state for us in case of an error */
  102404. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102405. }
  102406. }
  102407. /* now that all the metadata is written, we save the stream offset */
  102408. 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 */
  102409. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102410. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102411. }
  102412. if(encoder->protected_->verify)
  102413. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102414. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102415. }
  102416. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102417. FLAC__StreamEncoder *encoder,
  102418. FLAC__StreamEncoderWriteCallback write_callback,
  102419. FLAC__StreamEncoderSeekCallback seek_callback,
  102420. FLAC__StreamEncoderTellCallback tell_callback,
  102421. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102422. void *client_data
  102423. )
  102424. {
  102425. return init_stream_internal_enc(
  102426. encoder,
  102427. /*read_callback=*/0,
  102428. write_callback,
  102429. seek_callback,
  102430. tell_callback,
  102431. metadata_callback,
  102432. client_data,
  102433. /*is_ogg=*/false
  102434. );
  102435. }
  102436. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102437. FLAC__StreamEncoder *encoder,
  102438. FLAC__StreamEncoderReadCallback read_callback,
  102439. FLAC__StreamEncoderWriteCallback write_callback,
  102440. FLAC__StreamEncoderSeekCallback seek_callback,
  102441. FLAC__StreamEncoderTellCallback tell_callback,
  102442. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102443. void *client_data
  102444. )
  102445. {
  102446. return init_stream_internal_enc(
  102447. encoder,
  102448. read_callback,
  102449. write_callback,
  102450. seek_callback,
  102451. tell_callback,
  102452. metadata_callback,
  102453. client_data,
  102454. /*is_ogg=*/true
  102455. );
  102456. }
  102457. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102458. FLAC__StreamEncoder *encoder,
  102459. FILE *file,
  102460. FLAC__StreamEncoderProgressCallback progress_callback,
  102461. void *client_data,
  102462. FLAC__bool is_ogg
  102463. )
  102464. {
  102465. FLAC__StreamEncoderInitStatus init_status;
  102466. FLAC__ASSERT(0 != encoder);
  102467. FLAC__ASSERT(0 != file);
  102468. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102469. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102470. /* double protection */
  102471. if(file == 0) {
  102472. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102473. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102474. }
  102475. /*
  102476. * To make sure that our file does not go unclosed after an error, we
  102477. * must assign the FILE pointer before any further error can occur in
  102478. * this routine.
  102479. */
  102480. if(file == stdout)
  102481. file = get_binary_stdout_(); /* just to be safe */
  102482. encoder->private_->file = file;
  102483. encoder->private_->progress_callback = progress_callback;
  102484. encoder->private_->bytes_written = 0;
  102485. encoder->private_->samples_written = 0;
  102486. encoder->private_->frames_written = 0;
  102487. init_status = init_stream_internal_enc(
  102488. encoder,
  102489. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102490. file_write_callback_,
  102491. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102492. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102493. /*metadata_callback=*/0,
  102494. client_data,
  102495. is_ogg
  102496. );
  102497. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102498. /* the above function sets the state for us in case of an error */
  102499. return init_status;
  102500. }
  102501. {
  102502. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102503. FLAC__ASSERT(blocksize != 0);
  102504. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102505. }
  102506. return init_status;
  102507. }
  102508. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102509. FLAC__StreamEncoder *encoder,
  102510. FILE *file,
  102511. FLAC__StreamEncoderProgressCallback progress_callback,
  102512. void *client_data
  102513. )
  102514. {
  102515. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102516. }
  102517. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102518. FLAC__StreamEncoder *encoder,
  102519. FILE *file,
  102520. FLAC__StreamEncoderProgressCallback progress_callback,
  102521. void *client_data
  102522. )
  102523. {
  102524. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102525. }
  102526. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102527. FLAC__StreamEncoder *encoder,
  102528. const char *filename,
  102529. FLAC__StreamEncoderProgressCallback progress_callback,
  102530. void *client_data,
  102531. FLAC__bool is_ogg
  102532. )
  102533. {
  102534. FILE *file;
  102535. FLAC__ASSERT(0 != encoder);
  102536. /*
  102537. * To make sure that our file does not go unclosed after an error, we
  102538. * have to do the same entrance checks here that are later performed
  102539. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102540. */
  102541. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102542. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102543. file = filename? fopen(filename, "w+b") : stdout;
  102544. if(file == 0) {
  102545. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102546. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102547. }
  102548. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102549. }
  102550. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102551. FLAC__StreamEncoder *encoder,
  102552. const char *filename,
  102553. FLAC__StreamEncoderProgressCallback progress_callback,
  102554. void *client_data
  102555. )
  102556. {
  102557. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102558. }
  102559. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102560. FLAC__StreamEncoder *encoder,
  102561. const char *filename,
  102562. FLAC__StreamEncoderProgressCallback progress_callback,
  102563. void *client_data
  102564. )
  102565. {
  102566. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102567. }
  102568. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102569. {
  102570. FLAC__bool error = false;
  102571. FLAC__ASSERT(0 != encoder);
  102572. FLAC__ASSERT(0 != encoder->private_);
  102573. FLAC__ASSERT(0 != encoder->protected_);
  102574. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102575. return true;
  102576. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102577. if(encoder->private_->current_sample_number != 0) {
  102578. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102579. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102580. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102581. error = true;
  102582. }
  102583. }
  102584. if(encoder->protected_->do_md5)
  102585. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102586. if(!encoder->private_->is_being_deleted) {
  102587. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102588. if(encoder->private_->seek_callback) {
  102589. #if FLAC__HAS_OGG
  102590. if(encoder->private_->is_ogg)
  102591. update_ogg_metadata_(encoder);
  102592. else
  102593. #endif
  102594. update_metadata_(encoder);
  102595. /* check if an error occurred while updating metadata */
  102596. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102597. error = true;
  102598. }
  102599. if(encoder->private_->metadata_callback)
  102600. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102601. }
  102602. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102603. if(!error)
  102604. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102605. error = true;
  102606. }
  102607. }
  102608. if(0 != encoder->private_->file) {
  102609. if(encoder->private_->file != stdout)
  102610. fclose(encoder->private_->file);
  102611. encoder->private_->file = 0;
  102612. }
  102613. #if FLAC__HAS_OGG
  102614. if(encoder->private_->is_ogg)
  102615. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102616. #endif
  102617. free_(encoder);
  102618. set_defaults_enc(encoder);
  102619. if(!error)
  102620. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102621. return !error;
  102622. }
  102623. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102624. {
  102625. FLAC__ASSERT(0 != encoder);
  102626. FLAC__ASSERT(0 != encoder->private_);
  102627. FLAC__ASSERT(0 != encoder->protected_);
  102628. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102629. return false;
  102630. #if FLAC__HAS_OGG
  102631. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102632. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102633. return true;
  102634. #else
  102635. (void)value;
  102636. return false;
  102637. #endif
  102638. }
  102639. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102640. {
  102641. FLAC__ASSERT(0 != encoder);
  102642. FLAC__ASSERT(0 != encoder->private_);
  102643. FLAC__ASSERT(0 != encoder->protected_);
  102644. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102645. return false;
  102646. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102647. encoder->protected_->verify = value;
  102648. #endif
  102649. return true;
  102650. }
  102651. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102652. {
  102653. FLAC__ASSERT(0 != encoder);
  102654. FLAC__ASSERT(0 != encoder->private_);
  102655. FLAC__ASSERT(0 != encoder->protected_);
  102656. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102657. return false;
  102658. encoder->protected_->streamable_subset = value;
  102659. return true;
  102660. }
  102661. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102662. {
  102663. FLAC__ASSERT(0 != encoder);
  102664. FLAC__ASSERT(0 != encoder->private_);
  102665. FLAC__ASSERT(0 != encoder->protected_);
  102666. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102667. return false;
  102668. encoder->protected_->do_md5 = value;
  102669. return true;
  102670. }
  102671. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102672. {
  102673. FLAC__ASSERT(0 != encoder);
  102674. FLAC__ASSERT(0 != encoder->private_);
  102675. FLAC__ASSERT(0 != encoder->protected_);
  102676. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102677. return false;
  102678. encoder->protected_->channels = value;
  102679. return true;
  102680. }
  102681. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102682. {
  102683. FLAC__ASSERT(0 != encoder);
  102684. FLAC__ASSERT(0 != encoder->private_);
  102685. FLAC__ASSERT(0 != encoder->protected_);
  102686. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102687. return false;
  102688. encoder->protected_->bits_per_sample = value;
  102689. return true;
  102690. }
  102691. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102692. {
  102693. FLAC__ASSERT(0 != encoder);
  102694. FLAC__ASSERT(0 != encoder->private_);
  102695. FLAC__ASSERT(0 != encoder->protected_);
  102696. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102697. return false;
  102698. encoder->protected_->sample_rate = value;
  102699. return true;
  102700. }
  102701. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102702. {
  102703. FLAC__bool ok = true;
  102704. FLAC__ASSERT(0 != encoder);
  102705. FLAC__ASSERT(0 != encoder->private_);
  102706. FLAC__ASSERT(0 != encoder->protected_);
  102707. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102708. return false;
  102709. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102710. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102711. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102712. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102713. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102714. #if 0
  102715. /* was: */
  102716. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102717. /* but it's too hard to specify the string in a locale-specific way */
  102718. #else
  102719. encoder->protected_->num_apodizations = 1;
  102720. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102721. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102722. #endif
  102723. #endif
  102724. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102725. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102726. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102727. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102728. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102729. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102730. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102731. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102732. return ok;
  102733. }
  102734. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102735. {
  102736. FLAC__ASSERT(0 != encoder);
  102737. FLAC__ASSERT(0 != encoder->private_);
  102738. FLAC__ASSERT(0 != encoder->protected_);
  102739. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102740. return false;
  102741. encoder->protected_->blocksize = value;
  102742. return true;
  102743. }
  102744. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102745. {
  102746. FLAC__ASSERT(0 != encoder);
  102747. FLAC__ASSERT(0 != encoder->private_);
  102748. FLAC__ASSERT(0 != encoder->protected_);
  102749. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102750. return false;
  102751. encoder->protected_->do_mid_side_stereo = value;
  102752. return true;
  102753. }
  102754. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102755. {
  102756. FLAC__ASSERT(0 != encoder);
  102757. FLAC__ASSERT(0 != encoder->private_);
  102758. FLAC__ASSERT(0 != encoder->protected_);
  102759. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102760. return false;
  102761. encoder->protected_->loose_mid_side_stereo = value;
  102762. return true;
  102763. }
  102764. /*@@@@add to tests*/
  102765. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102766. {
  102767. FLAC__ASSERT(0 != encoder);
  102768. FLAC__ASSERT(0 != encoder->private_);
  102769. FLAC__ASSERT(0 != encoder->protected_);
  102770. FLAC__ASSERT(0 != specification);
  102771. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102772. return false;
  102773. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102774. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102775. #else
  102776. encoder->protected_->num_apodizations = 0;
  102777. while(1) {
  102778. const char *s = strchr(specification, ';');
  102779. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102780. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102781. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102782. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102783. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102784. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102785. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102786. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102787. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102788. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102789. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102790. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102791. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102792. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102793. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102794. if (stddev > 0.0 && stddev <= 0.5) {
  102795. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102796. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102797. }
  102798. }
  102799. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102800. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102801. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102802. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102803. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102804. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102805. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102806. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102807. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102808. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102809. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102810. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102811. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102812. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102813. if (p >= 0.0 && p <= 1.0) {
  102814. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102815. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102816. }
  102817. }
  102818. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102819. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  102820. if (encoder->protected_->num_apodizations == 32)
  102821. break;
  102822. if (s)
  102823. specification = s+1;
  102824. else
  102825. break;
  102826. }
  102827. if(encoder->protected_->num_apodizations == 0) {
  102828. encoder->protected_->num_apodizations = 1;
  102829. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102830. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102831. }
  102832. #endif
  102833. return true;
  102834. }
  102835. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  102836. {
  102837. FLAC__ASSERT(0 != encoder);
  102838. FLAC__ASSERT(0 != encoder->private_);
  102839. FLAC__ASSERT(0 != encoder->protected_);
  102840. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102841. return false;
  102842. encoder->protected_->max_lpc_order = value;
  102843. return true;
  102844. }
  102845. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  102846. {
  102847. FLAC__ASSERT(0 != encoder);
  102848. FLAC__ASSERT(0 != encoder->private_);
  102849. FLAC__ASSERT(0 != encoder->protected_);
  102850. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102851. return false;
  102852. encoder->protected_->qlp_coeff_precision = value;
  102853. return true;
  102854. }
  102855. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102856. {
  102857. FLAC__ASSERT(0 != encoder);
  102858. FLAC__ASSERT(0 != encoder->private_);
  102859. FLAC__ASSERT(0 != encoder->protected_);
  102860. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102861. return false;
  102862. encoder->protected_->do_qlp_coeff_prec_search = value;
  102863. return true;
  102864. }
  102865. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102866. {
  102867. FLAC__ASSERT(0 != encoder);
  102868. FLAC__ASSERT(0 != encoder->private_);
  102869. FLAC__ASSERT(0 != encoder->protected_);
  102870. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102871. return false;
  102872. #if 0
  102873. /*@@@ deprecated: */
  102874. encoder->protected_->do_escape_coding = value;
  102875. #else
  102876. (void)value;
  102877. #endif
  102878. return true;
  102879. }
  102880. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102881. {
  102882. FLAC__ASSERT(0 != encoder);
  102883. FLAC__ASSERT(0 != encoder->private_);
  102884. FLAC__ASSERT(0 != encoder->protected_);
  102885. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102886. return false;
  102887. encoder->protected_->do_exhaustive_model_search = value;
  102888. return true;
  102889. }
  102890. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102891. {
  102892. FLAC__ASSERT(0 != encoder);
  102893. FLAC__ASSERT(0 != encoder->private_);
  102894. FLAC__ASSERT(0 != encoder->protected_);
  102895. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102896. return false;
  102897. encoder->protected_->min_residual_partition_order = value;
  102898. return true;
  102899. }
  102900. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102901. {
  102902. FLAC__ASSERT(0 != encoder);
  102903. FLAC__ASSERT(0 != encoder->private_);
  102904. FLAC__ASSERT(0 != encoder->protected_);
  102905. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102906. return false;
  102907. encoder->protected_->max_residual_partition_order = value;
  102908. return true;
  102909. }
  102910. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  102911. {
  102912. FLAC__ASSERT(0 != encoder);
  102913. FLAC__ASSERT(0 != encoder->private_);
  102914. FLAC__ASSERT(0 != encoder->protected_);
  102915. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102916. return false;
  102917. #if 0
  102918. /*@@@ deprecated: */
  102919. encoder->protected_->rice_parameter_search_dist = value;
  102920. #else
  102921. (void)value;
  102922. #endif
  102923. return true;
  102924. }
  102925. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  102926. {
  102927. FLAC__ASSERT(0 != encoder);
  102928. FLAC__ASSERT(0 != encoder->private_);
  102929. FLAC__ASSERT(0 != encoder->protected_);
  102930. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102931. return false;
  102932. encoder->protected_->total_samples_estimate = value;
  102933. return true;
  102934. }
  102935. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  102936. {
  102937. FLAC__ASSERT(0 != encoder);
  102938. FLAC__ASSERT(0 != encoder->private_);
  102939. FLAC__ASSERT(0 != encoder->protected_);
  102940. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102941. return false;
  102942. if(0 == metadata)
  102943. num_blocks = 0;
  102944. if(0 == num_blocks)
  102945. metadata = 0;
  102946. /* realloc() does not do exactly what we want so... */
  102947. if(encoder->protected_->metadata) {
  102948. free(encoder->protected_->metadata);
  102949. encoder->protected_->metadata = 0;
  102950. encoder->protected_->num_metadata_blocks = 0;
  102951. }
  102952. if(num_blocks) {
  102953. FLAC__StreamMetadata **m;
  102954. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  102955. return false;
  102956. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  102957. encoder->protected_->metadata = m;
  102958. encoder->protected_->num_metadata_blocks = num_blocks;
  102959. }
  102960. #if FLAC__HAS_OGG
  102961. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  102962. return false;
  102963. #endif
  102964. return true;
  102965. }
  102966. /*
  102967. * These three functions are not static, but not publically exposed in
  102968. * include/FLAC/ either. They are used by the test suite.
  102969. */
  102970. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102971. {
  102972. FLAC__ASSERT(0 != encoder);
  102973. FLAC__ASSERT(0 != encoder->private_);
  102974. FLAC__ASSERT(0 != encoder->protected_);
  102975. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102976. return false;
  102977. encoder->private_->disable_constant_subframes = value;
  102978. return true;
  102979. }
  102980. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102981. {
  102982. FLAC__ASSERT(0 != encoder);
  102983. FLAC__ASSERT(0 != encoder->private_);
  102984. FLAC__ASSERT(0 != encoder->protected_);
  102985. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102986. return false;
  102987. encoder->private_->disable_fixed_subframes = value;
  102988. return true;
  102989. }
  102990. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102991. {
  102992. FLAC__ASSERT(0 != encoder);
  102993. FLAC__ASSERT(0 != encoder->private_);
  102994. FLAC__ASSERT(0 != encoder->protected_);
  102995. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102996. return false;
  102997. encoder->private_->disable_verbatim_subframes = value;
  102998. return true;
  102999. }
  103000. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103001. {
  103002. FLAC__ASSERT(0 != encoder);
  103003. FLAC__ASSERT(0 != encoder->private_);
  103004. FLAC__ASSERT(0 != encoder->protected_);
  103005. return encoder->protected_->state;
  103006. }
  103007. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103008. {
  103009. FLAC__ASSERT(0 != encoder);
  103010. FLAC__ASSERT(0 != encoder->private_);
  103011. FLAC__ASSERT(0 != encoder->protected_);
  103012. if(encoder->protected_->verify)
  103013. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103014. else
  103015. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103016. }
  103017. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103018. {
  103019. FLAC__ASSERT(0 != encoder);
  103020. FLAC__ASSERT(0 != encoder->private_);
  103021. FLAC__ASSERT(0 != encoder->protected_);
  103022. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103023. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103024. else
  103025. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103026. }
  103027. 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)
  103028. {
  103029. FLAC__ASSERT(0 != encoder);
  103030. FLAC__ASSERT(0 != encoder->private_);
  103031. FLAC__ASSERT(0 != encoder->protected_);
  103032. if(0 != absolute_sample)
  103033. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103034. if(0 != frame_number)
  103035. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103036. if(0 != channel)
  103037. *channel = encoder->private_->verify.error_stats.channel;
  103038. if(0 != sample)
  103039. *sample = encoder->private_->verify.error_stats.sample;
  103040. if(0 != expected)
  103041. *expected = encoder->private_->verify.error_stats.expected;
  103042. if(0 != got)
  103043. *got = encoder->private_->verify.error_stats.got;
  103044. }
  103045. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103046. {
  103047. FLAC__ASSERT(0 != encoder);
  103048. FLAC__ASSERT(0 != encoder->private_);
  103049. FLAC__ASSERT(0 != encoder->protected_);
  103050. return encoder->protected_->verify;
  103051. }
  103052. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103053. {
  103054. FLAC__ASSERT(0 != encoder);
  103055. FLAC__ASSERT(0 != encoder->private_);
  103056. FLAC__ASSERT(0 != encoder->protected_);
  103057. return encoder->protected_->streamable_subset;
  103058. }
  103059. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103060. {
  103061. FLAC__ASSERT(0 != encoder);
  103062. FLAC__ASSERT(0 != encoder->private_);
  103063. FLAC__ASSERT(0 != encoder->protected_);
  103064. return encoder->protected_->do_md5;
  103065. }
  103066. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103067. {
  103068. FLAC__ASSERT(0 != encoder);
  103069. FLAC__ASSERT(0 != encoder->private_);
  103070. FLAC__ASSERT(0 != encoder->protected_);
  103071. return encoder->protected_->channels;
  103072. }
  103073. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103074. {
  103075. FLAC__ASSERT(0 != encoder);
  103076. FLAC__ASSERT(0 != encoder->private_);
  103077. FLAC__ASSERT(0 != encoder->protected_);
  103078. return encoder->protected_->bits_per_sample;
  103079. }
  103080. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103081. {
  103082. FLAC__ASSERT(0 != encoder);
  103083. FLAC__ASSERT(0 != encoder->private_);
  103084. FLAC__ASSERT(0 != encoder->protected_);
  103085. return encoder->protected_->sample_rate;
  103086. }
  103087. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103088. {
  103089. FLAC__ASSERT(0 != encoder);
  103090. FLAC__ASSERT(0 != encoder->private_);
  103091. FLAC__ASSERT(0 != encoder->protected_);
  103092. return encoder->protected_->blocksize;
  103093. }
  103094. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103095. {
  103096. FLAC__ASSERT(0 != encoder);
  103097. FLAC__ASSERT(0 != encoder->private_);
  103098. FLAC__ASSERT(0 != encoder->protected_);
  103099. return encoder->protected_->do_mid_side_stereo;
  103100. }
  103101. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103102. {
  103103. FLAC__ASSERT(0 != encoder);
  103104. FLAC__ASSERT(0 != encoder->private_);
  103105. FLAC__ASSERT(0 != encoder->protected_);
  103106. return encoder->protected_->loose_mid_side_stereo;
  103107. }
  103108. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103109. {
  103110. FLAC__ASSERT(0 != encoder);
  103111. FLAC__ASSERT(0 != encoder->private_);
  103112. FLAC__ASSERT(0 != encoder->protected_);
  103113. return encoder->protected_->max_lpc_order;
  103114. }
  103115. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103116. {
  103117. FLAC__ASSERT(0 != encoder);
  103118. FLAC__ASSERT(0 != encoder->private_);
  103119. FLAC__ASSERT(0 != encoder->protected_);
  103120. return encoder->protected_->qlp_coeff_precision;
  103121. }
  103122. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103123. {
  103124. FLAC__ASSERT(0 != encoder);
  103125. FLAC__ASSERT(0 != encoder->private_);
  103126. FLAC__ASSERT(0 != encoder->protected_);
  103127. return encoder->protected_->do_qlp_coeff_prec_search;
  103128. }
  103129. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103130. {
  103131. FLAC__ASSERT(0 != encoder);
  103132. FLAC__ASSERT(0 != encoder->private_);
  103133. FLAC__ASSERT(0 != encoder->protected_);
  103134. return encoder->protected_->do_escape_coding;
  103135. }
  103136. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103137. {
  103138. FLAC__ASSERT(0 != encoder);
  103139. FLAC__ASSERT(0 != encoder->private_);
  103140. FLAC__ASSERT(0 != encoder->protected_);
  103141. return encoder->protected_->do_exhaustive_model_search;
  103142. }
  103143. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103144. {
  103145. FLAC__ASSERT(0 != encoder);
  103146. FLAC__ASSERT(0 != encoder->private_);
  103147. FLAC__ASSERT(0 != encoder->protected_);
  103148. return encoder->protected_->min_residual_partition_order;
  103149. }
  103150. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103151. {
  103152. FLAC__ASSERT(0 != encoder);
  103153. FLAC__ASSERT(0 != encoder->private_);
  103154. FLAC__ASSERT(0 != encoder->protected_);
  103155. return encoder->protected_->max_residual_partition_order;
  103156. }
  103157. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103158. {
  103159. FLAC__ASSERT(0 != encoder);
  103160. FLAC__ASSERT(0 != encoder->private_);
  103161. FLAC__ASSERT(0 != encoder->protected_);
  103162. return encoder->protected_->rice_parameter_search_dist;
  103163. }
  103164. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103165. {
  103166. FLAC__ASSERT(0 != encoder);
  103167. FLAC__ASSERT(0 != encoder->private_);
  103168. FLAC__ASSERT(0 != encoder->protected_);
  103169. return encoder->protected_->total_samples_estimate;
  103170. }
  103171. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103172. {
  103173. unsigned i, j = 0, channel;
  103174. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103175. FLAC__ASSERT(0 != encoder);
  103176. FLAC__ASSERT(0 != encoder->private_);
  103177. FLAC__ASSERT(0 != encoder->protected_);
  103178. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103179. do {
  103180. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103181. if(encoder->protected_->verify)
  103182. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103183. for(channel = 0; channel < channels; channel++)
  103184. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103185. if(encoder->protected_->do_mid_side_stereo) {
  103186. FLAC__ASSERT(channels == 2);
  103187. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103188. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103189. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103190. 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' ! */
  103191. }
  103192. }
  103193. else
  103194. j += n;
  103195. encoder->private_->current_sample_number += n;
  103196. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103197. if(encoder->private_->current_sample_number > blocksize) {
  103198. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103199. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103200. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103201. return false;
  103202. /* move unprocessed overread samples to beginnings of arrays */
  103203. for(channel = 0; channel < channels; channel++)
  103204. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103205. if(encoder->protected_->do_mid_side_stereo) {
  103206. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103207. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103208. }
  103209. encoder->private_->current_sample_number = 1;
  103210. }
  103211. } while(j < samples);
  103212. return true;
  103213. }
  103214. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103215. {
  103216. unsigned i, j, k, channel;
  103217. FLAC__int32 x, mid, side;
  103218. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103219. FLAC__ASSERT(0 != encoder);
  103220. FLAC__ASSERT(0 != encoder->private_);
  103221. FLAC__ASSERT(0 != encoder->protected_);
  103222. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103223. j = k = 0;
  103224. /*
  103225. * we have several flavors of the same basic loop, optimized for
  103226. * different conditions:
  103227. */
  103228. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103229. /*
  103230. * stereo coding: unroll channel loop
  103231. */
  103232. do {
  103233. if(encoder->protected_->verify)
  103234. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103235. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103236. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103237. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103238. x = buffer[k++];
  103239. encoder->private_->integer_signal[1][i] = x;
  103240. mid += x;
  103241. side -= x;
  103242. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103243. encoder->private_->integer_signal_mid_side[1][i] = side;
  103244. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103245. }
  103246. encoder->private_->current_sample_number = i;
  103247. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103248. if(i > blocksize) {
  103249. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103250. return false;
  103251. /* move unprocessed overread samples to beginnings of arrays */
  103252. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103253. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103254. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103255. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103256. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103257. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103258. encoder->private_->current_sample_number = 1;
  103259. }
  103260. } while(j < samples);
  103261. }
  103262. else {
  103263. /*
  103264. * independent channel coding: buffer each channel in inner loop
  103265. */
  103266. do {
  103267. if(encoder->protected_->verify)
  103268. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103269. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103270. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103271. for(channel = 0; channel < channels; channel++)
  103272. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103273. }
  103274. encoder->private_->current_sample_number = i;
  103275. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103276. if(i > blocksize) {
  103277. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103278. return false;
  103279. /* move unprocessed overread samples to beginnings of arrays */
  103280. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103281. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103282. for(channel = 0; channel < channels; channel++)
  103283. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103284. encoder->private_->current_sample_number = 1;
  103285. }
  103286. } while(j < samples);
  103287. }
  103288. return true;
  103289. }
  103290. /***********************************************************************
  103291. *
  103292. * Private class methods
  103293. *
  103294. ***********************************************************************/
  103295. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103296. {
  103297. FLAC__ASSERT(0 != encoder);
  103298. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103299. encoder->protected_->verify = true;
  103300. #else
  103301. encoder->protected_->verify = false;
  103302. #endif
  103303. encoder->protected_->streamable_subset = true;
  103304. encoder->protected_->do_md5 = true;
  103305. encoder->protected_->do_mid_side_stereo = false;
  103306. encoder->protected_->loose_mid_side_stereo = false;
  103307. encoder->protected_->channels = 2;
  103308. encoder->protected_->bits_per_sample = 16;
  103309. encoder->protected_->sample_rate = 44100;
  103310. encoder->protected_->blocksize = 0;
  103311. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103312. encoder->protected_->num_apodizations = 1;
  103313. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103314. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103315. #endif
  103316. encoder->protected_->max_lpc_order = 0;
  103317. encoder->protected_->qlp_coeff_precision = 0;
  103318. encoder->protected_->do_qlp_coeff_prec_search = false;
  103319. encoder->protected_->do_exhaustive_model_search = false;
  103320. encoder->protected_->do_escape_coding = false;
  103321. encoder->protected_->min_residual_partition_order = 0;
  103322. encoder->protected_->max_residual_partition_order = 0;
  103323. encoder->protected_->rice_parameter_search_dist = 0;
  103324. encoder->protected_->total_samples_estimate = 0;
  103325. encoder->protected_->metadata = 0;
  103326. encoder->protected_->num_metadata_blocks = 0;
  103327. encoder->private_->seek_table = 0;
  103328. encoder->private_->disable_constant_subframes = false;
  103329. encoder->private_->disable_fixed_subframes = false;
  103330. encoder->private_->disable_verbatim_subframes = false;
  103331. #if FLAC__HAS_OGG
  103332. encoder->private_->is_ogg = false;
  103333. #endif
  103334. encoder->private_->read_callback = 0;
  103335. encoder->private_->write_callback = 0;
  103336. encoder->private_->seek_callback = 0;
  103337. encoder->private_->tell_callback = 0;
  103338. encoder->private_->metadata_callback = 0;
  103339. encoder->private_->progress_callback = 0;
  103340. encoder->private_->client_data = 0;
  103341. #if FLAC__HAS_OGG
  103342. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103343. #endif
  103344. }
  103345. void free_(FLAC__StreamEncoder *encoder)
  103346. {
  103347. unsigned i, channel;
  103348. FLAC__ASSERT(0 != encoder);
  103349. if(encoder->protected_->metadata) {
  103350. free(encoder->protected_->metadata);
  103351. encoder->protected_->metadata = 0;
  103352. encoder->protected_->num_metadata_blocks = 0;
  103353. }
  103354. for(i = 0; i < encoder->protected_->channels; i++) {
  103355. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103356. free(encoder->private_->integer_signal_unaligned[i]);
  103357. encoder->private_->integer_signal_unaligned[i] = 0;
  103358. }
  103359. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103360. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103361. free(encoder->private_->real_signal_unaligned[i]);
  103362. encoder->private_->real_signal_unaligned[i] = 0;
  103363. }
  103364. #endif
  103365. }
  103366. for(i = 0; i < 2; i++) {
  103367. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103368. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103369. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103370. }
  103371. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103372. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103373. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103374. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103375. }
  103376. #endif
  103377. }
  103378. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103379. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103380. if(0 != encoder->private_->window_unaligned[i]) {
  103381. free(encoder->private_->window_unaligned[i]);
  103382. encoder->private_->window_unaligned[i] = 0;
  103383. }
  103384. }
  103385. if(0 != encoder->private_->windowed_signal_unaligned) {
  103386. free(encoder->private_->windowed_signal_unaligned);
  103387. encoder->private_->windowed_signal_unaligned = 0;
  103388. }
  103389. #endif
  103390. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103391. for(i = 0; i < 2; i++) {
  103392. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103393. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103394. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103395. }
  103396. }
  103397. }
  103398. for(channel = 0; channel < 2; channel++) {
  103399. for(i = 0; i < 2; i++) {
  103400. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103401. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103402. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103403. }
  103404. }
  103405. }
  103406. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103407. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103408. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103409. }
  103410. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103411. free(encoder->private_->raw_bits_per_partition_unaligned);
  103412. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103413. }
  103414. if(encoder->protected_->verify) {
  103415. for(i = 0; i < encoder->protected_->channels; i++) {
  103416. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103417. free(encoder->private_->verify.input_fifo.data[i]);
  103418. encoder->private_->verify.input_fifo.data[i] = 0;
  103419. }
  103420. }
  103421. }
  103422. FLAC__bitwriter_free(encoder->private_->frame);
  103423. }
  103424. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103425. {
  103426. FLAC__bool ok;
  103427. unsigned i, channel;
  103428. FLAC__ASSERT(new_blocksize > 0);
  103429. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103430. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103431. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103432. if(new_blocksize <= encoder->private_->input_capacity)
  103433. return true;
  103434. ok = true;
  103435. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103436. * requires that the input arrays (in our case the integer signals)
  103437. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103438. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103439. */
  103440. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103441. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103442. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103443. encoder->private_->integer_signal[i] += 4;
  103444. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103445. #if 0 /* @@@ currently unused */
  103446. if(encoder->protected_->max_lpc_order > 0)
  103447. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103448. #endif
  103449. #endif
  103450. }
  103451. for(i = 0; ok && i < 2; i++) {
  103452. 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]);
  103453. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103454. encoder->private_->integer_signal_mid_side[i] += 4;
  103455. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103456. #if 0 /* @@@ currently unused */
  103457. if(encoder->protected_->max_lpc_order > 0)
  103458. 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]);
  103459. #endif
  103460. #endif
  103461. }
  103462. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103463. if(ok && encoder->protected_->max_lpc_order > 0) {
  103464. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103465. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103466. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103467. }
  103468. #endif
  103469. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103470. for(i = 0; ok && i < 2; i++) {
  103471. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103472. }
  103473. }
  103474. for(channel = 0; ok && channel < 2; channel++) {
  103475. for(i = 0; ok && i < 2; i++) {
  103476. 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]);
  103477. }
  103478. }
  103479. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103480. /*@@@ 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) */
  103481. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103482. if(encoder->protected_->do_escape_coding)
  103483. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103484. /* now adjust the windows if the blocksize has changed */
  103485. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103486. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103487. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103488. switch(encoder->protected_->apodizations[i].type) {
  103489. case FLAC__APODIZATION_BARTLETT:
  103490. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103491. break;
  103492. case FLAC__APODIZATION_BARTLETT_HANN:
  103493. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103494. break;
  103495. case FLAC__APODIZATION_BLACKMAN:
  103496. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103497. break;
  103498. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103499. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103500. break;
  103501. case FLAC__APODIZATION_CONNES:
  103502. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103503. break;
  103504. case FLAC__APODIZATION_FLATTOP:
  103505. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103506. break;
  103507. case FLAC__APODIZATION_GAUSS:
  103508. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103509. break;
  103510. case FLAC__APODIZATION_HAMMING:
  103511. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103512. break;
  103513. case FLAC__APODIZATION_HANN:
  103514. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103515. break;
  103516. case FLAC__APODIZATION_KAISER_BESSEL:
  103517. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103518. break;
  103519. case FLAC__APODIZATION_NUTTALL:
  103520. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103521. break;
  103522. case FLAC__APODIZATION_RECTANGLE:
  103523. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103524. break;
  103525. case FLAC__APODIZATION_TRIANGLE:
  103526. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103527. break;
  103528. case FLAC__APODIZATION_TUKEY:
  103529. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103530. break;
  103531. case FLAC__APODIZATION_WELCH:
  103532. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103533. break;
  103534. default:
  103535. FLAC__ASSERT(0);
  103536. /* double protection */
  103537. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103538. break;
  103539. }
  103540. }
  103541. }
  103542. #endif
  103543. if(ok)
  103544. encoder->private_->input_capacity = new_blocksize;
  103545. else
  103546. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103547. return ok;
  103548. }
  103549. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103550. {
  103551. const FLAC__byte *buffer;
  103552. size_t bytes;
  103553. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103554. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103555. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103556. return false;
  103557. }
  103558. if(encoder->protected_->verify) {
  103559. encoder->private_->verify.output.data = buffer;
  103560. encoder->private_->verify.output.bytes = bytes;
  103561. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103562. encoder->private_->verify.needs_magic_hack = true;
  103563. }
  103564. else {
  103565. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103566. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103567. FLAC__bitwriter_clear(encoder->private_->frame);
  103568. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103569. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103570. return false;
  103571. }
  103572. }
  103573. }
  103574. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103575. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103576. FLAC__bitwriter_clear(encoder->private_->frame);
  103577. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103578. return false;
  103579. }
  103580. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103581. FLAC__bitwriter_clear(encoder->private_->frame);
  103582. if(samples > 0) {
  103583. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103584. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103585. }
  103586. return true;
  103587. }
  103588. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103589. {
  103590. FLAC__StreamEncoderWriteStatus status;
  103591. FLAC__uint64 output_position = 0;
  103592. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103593. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103594. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103595. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103596. }
  103597. /*
  103598. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103599. */
  103600. if(samples == 0) {
  103601. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103602. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103603. encoder->protected_->streaminfo_offset = output_position;
  103604. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103605. encoder->protected_->seektable_offset = output_position;
  103606. }
  103607. /*
  103608. * Mark the current seek point if hit (if audio_offset == 0 that
  103609. * means we're still writing metadata and haven't hit the first
  103610. * frame yet)
  103611. */
  103612. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103613. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103614. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103615. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103616. FLAC__uint64 test_sample;
  103617. unsigned i;
  103618. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103619. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103620. if(test_sample > frame_last_sample) {
  103621. break;
  103622. }
  103623. else if(test_sample >= frame_first_sample) {
  103624. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103625. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103626. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103627. encoder->private_->first_seekpoint_to_check++;
  103628. /* DO NOT: "break;" and here's why:
  103629. * The seektable template may contain more than one target
  103630. * sample for any given frame; we will keep looping, generating
  103631. * duplicate seekpoints for them, and we'll clean it up later,
  103632. * just before writing the seektable back to the metadata.
  103633. */
  103634. }
  103635. else {
  103636. encoder->private_->first_seekpoint_to_check++;
  103637. }
  103638. }
  103639. }
  103640. #if FLAC__HAS_OGG
  103641. if(encoder->private_->is_ogg) {
  103642. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103643. &encoder->protected_->ogg_encoder_aspect,
  103644. buffer,
  103645. bytes,
  103646. samples,
  103647. encoder->private_->current_frame_number,
  103648. is_last_block,
  103649. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103650. encoder,
  103651. encoder->private_->client_data
  103652. );
  103653. }
  103654. else
  103655. #endif
  103656. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103657. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103658. encoder->private_->bytes_written += bytes;
  103659. encoder->private_->samples_written += samples;
  103660. /* we keep a high watermark on the number of frames written because
  103661. * when the encoder goes back to write metadata, 'current_frame'
  103662. * will drop back to 0.
  103663. */
  103664. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103665. }
  103666. else
  103667. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103668. return status;
  103669. }
  103670. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103671. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103672. {
  103673. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103674. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103675. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103676. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103677. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103678. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103679. FLAC__StreamEncoderSeekStatus seek_status;
  103680. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103681. /* All this is based on intimate knowledge of the stream header
  103682. * layout, but a change to the header format that would break this
  103683. * would also break all streams encoded in the previous format.
  103684. */
  103685. /*
  103686. * Write MD5 signature
  103687. */
  103688. {
  103689. const unsigned md5_offset =
  103690. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103691. (
  103692. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103693. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103694. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103695. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103696. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103697. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103698. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103699. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103700. ) / 8;
  103701. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103702. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103703. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103704. return;
  103705. }
  103706. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103707. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103708. return;
  103709. }
  103710. }
  103711. /*
  103712. * Write total samples
  103713. */
  103714. {
  103715. const unsigned total_samples_byte_offset =
  103716. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103717. (
  103718. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103719. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103720. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103721. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103722. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103723. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103724. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103725. - 4
  103726. ) / 8;
  103727. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103728. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103729. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103730. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103731. b[4] = (FLAC__byte)(samples & 0xFF);
  103732. 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) {
  103733. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103734. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103735. return;
  103736. }
  103737. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103738. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103739. return;
  103740. }
  103741. }
  103742. /*
  103743. * Write min/max framesize
  103744. */
  103745. {
  103746. const unsigned min_framesize_offset =
  103747. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103748. (
  103749. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103750. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103751. ) / 8;
  103752. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103753. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103754. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103755. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103756. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103757. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103758. 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) {
  103759. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103760. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103761. return;
  103762. }
  103763. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103764. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103765. return;
  103766. }
  103767. }
  103768. /*
  103769. * Write seektable
  103770. */
  103771. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103772. unsigned i;
  103773. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103774. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103775. 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) {
  103776. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103777. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103778. return;
  103779. }
  103780. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103781. FLAC__uint64 xx;
  103782. unsigned x;
  103783. xx = encoder->private_->seek_table->points[i].sample_number;
  103784. b[7] = (FLAC__byte)xx; xx >>= 8;
  103785. b[6] = (FLAC__byte)xx; xx >>= 8;
  103786. b[5] = (FLAC__byte)xx; xx >>= 8;
  103787. b[4] = (FLAC__byte)xx; xx >>= 8;
  103788. b[3] = (FLAC__byte)xx; xx >>= 8;
  103789. b[2] = (FLAC__byte)xx; xx >>= 8;
  103790. b[1] = (FLAC__byte)xx; xx >>= 8;
  103791. b[0] = (FLAC__byte)xx; xx >>= 8;
  103792. xx = encoder->private_->seek_table->points[i].stream_offset;
  103793. b[15] = (FLAC__byte)xx; xx >>= 8;
  103794. b[14] = (FLAC__byte)xx; xx >>= 8;
  103795. b[13] = (FLAC__byte)xx; xx >>= 8;
  103796. b[12] = (FLAC__byte)xx; xx >>= 8;
  103797. b[11] = (FLAC__byte)xx; xx >>= 8;
  103798. b[10] = (FLAC__byte)xx; xx >>= 8;
  103799. b[9] = (FLAC__byte)xx; xx >>= 8;
  103800. b[8] = (FLAC__byte)xx; xx >>= 8;
  103801. x = encoder->private_->seek_table->points[i].frame_samples;
  103802. b[17] = (FLAC__byte)x; x >>= 8;
  103803. b[16] = (FLAC__byte)x; x >>= 8;
  103804. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103805. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103806. return;
  103807. }
  103808. }
  103809. }
  103810. }
  103811. #if FLAC__HAS_OGG
  103812. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103813. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103814. {
  103815. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103816. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103817. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103818. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103819. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  103820. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  103821. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  103822. FLAC__STREAM_SYNC_LENGTH
  103823. ;
  103824. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103825. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103826. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103827. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103828. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103829. ogg_page page;
  103830. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103831. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  103832. /* Pre-check that client supports seeking, since we don't want the
  103833. * ogg_helper code to ever have to deal with this condition.
  103834. */
  103835. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  103836. return;
  103837. /* All this is based on intimate knowledge of the stream header
  103838. * layout, but a change to the header format that would break this
  103839. * would also break all streams encoded in the previous format.
  103840. */
  103841. /**
  103842. ** Write STREAMINFO stats
  103843. **/
  103844. simple_ogg_page__init(&page);
  103845. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103846. simple_ogg_page__clear(&page);
  103847. return; /* state already set */
  103848. }
  103849. /*
  103850. * Write MD5 signature
  103851. */
  103852. {
  103853. const unsigned md5_offset =
  103854. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103855. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103856. (
  103857. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103858. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103859. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103860. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103861. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103862. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103863. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103864. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103865. ) / 8;
  103866. if(md5_offset + 16 > (unsigned)page.body_len) {
  103867. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103868. simple_ogg_page__clear(&page);
  103869. return;
  103870. }
  103871. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  103872. }
  103873. /*
  103874. * Write total samples
  103875. */
  103876. {
  103877. const unsigned total_samples_byte_offset =
  103878. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103879. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103880. (
  103881. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103882. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103883. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103884. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103885. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103886. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103887. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103888. - 4
  103889. ) / 8;
  103890. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  103891. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103892. simple_ogg_page__clear(&page);
  103893. return;
  103894. }
  103895. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  103896. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  103897. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103898. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103899. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103900. b[4] = (FLAC__byte)(samples & 0xFF);
  103901. memcpy(page.body + total_samples_byte_offset, b, 5);
  103902. }
  103903. /*
  103904. * Write min/max framesize
  103905. */
  103906. {
  103907. const unsigned min_framesize_offset =
  103908. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103909. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103910. (
  103911. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103912. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103913. ) / 8;
  103914. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  103915. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103916. simple_ogg_page__clear(&page);
  103917. return;
  103918. }
  103919. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103920. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103921. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103922. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103923. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103924. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103925. memcpy(page.body + min_framesize_offset, b, 6);
  103926. }
  103927. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103928. simple_ogg_page__clear(&page);
  103929. return; /* state already set */
  103930. }
  103931. simple_ogg_page__clear(&page);
  103932. /*
  103933. * Write seektable
  103934. */
  103935. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103936. unsigned i;
  103937. FLAC__byte *p;
  103938. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103939. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103940. simple_ogg_page__init(&page);
  103941. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103942. simple_ogg_page__clear(&page);
  103943. return; /* state already set */
  103944. }
  103945. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  103946. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103947. simple_ogg_page__clear(&page);
  103948. return;
  103949. }
  103950. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  103951. FLAC__uint64 xx;
  103952. unsigned x;
  103953. xx = encoder->private_->seek_table->points[i].sample_number;
  103954. b[7] = (FLAC__byte)xx; xx >>= 8;
  103955. b[6] = (FLAC__byte)xx; xx >>= 8;
  103956. b[5] = (FLAC__byte)xx; xx >>= 8;
  103957. b[4] = (FLAC__byte)xx; xx >>= 8;
  103958. b[3] = (FLAC__byte)xx; xx >>= 8;
  103959. b[2] = (FLAC__byte)xx; xx >>= 8;
  103960. b[1] = (FLAC__byte)xx; xx >>= 8;
  103961. b[0] = (FLAC__byte)xx; xx >>= 8;
  103962. xx = encoder->private_->seek_table->points[i].stream_offset;
  103963. b[15] = (FLAC__byte)xx; xx >>= 8;
  103964. b[14] = (FLAC__byte)xx; xx >>= 8;
  103965. b[13] = (FLAC__byte)xx; xx >>= 8;
  103966. b[12] = (FLAC__byte)xx; xx >>= 8;
  103967. b[11] = (FLAC__byte)xx; xx >>= 8;
  103968. b[10] = (FLAC__byte)xx; xx >>= 8;
  103969. b[9] = (FLAC__byte)xx; xx >>= 8;
  103970. b[8] = (FLAC__byte)xx; xx >>= 8;
  103971. x = encoder->private_->seek_table->points[i].frame_samples;
  103972. b[17] = (FLAC__byte)x; x >>= 8;
  103973. b[16] = (FLAC__byte)x; x >>= 8;
  103974. memcpy(p, b, 18);
  103975. }
  103976. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103977. simple_ogg_page__clear(&page);
  103978. return; /* state already set */
  103979. }
  103980. simple_ogg_page__clear(&page);
  103981. }
  103982. }
  103983. #endif
  103984. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  103985. {
  103986. FLAC__uint16 crc;
  103987. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103988. /*
  103989. * Accumulate raw signal to the MD5 signature
  103990. */
  103991. 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)) {
  103992. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103993. return false;
  103994. }
  103995. /*
  103996. * Process the frame header and subframes into the frame bitbuffer
  103997. */
  103998. if(!process_subframes_(encoder, is_fractional_block)) {
  103999. /* the above function sets the state for us in case of an error */
  104000. return false;
  104001. }
  104002. /*
  104003. * Zero-pad the frame to a byte_boundary
  104004. */
  104005. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104006. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104007. return false;
  104008. }
  104009. /*
  104010. * CRC-16 the whole thing
  104011. */
  104012. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104013. if(
  104014. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104015. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104016. ) {
  104017. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104018. return false;
  104019. }
  104020. /*
  104021. * Write it
  104022. */
  104023. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104024. /* the above function sets the state for us in case of an error */
  104025. return false;
  104026. }
  104027. /*
  104028. * Get ready for the next frame
  104029. */
  104030. encoder->private_->current_sample_number = 0;
  104031. encoder->private_->current_frame_number++;
  104032. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104033. return true;
  104034. }
  104035. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104036. {
  104037. FLAC__FrameHeader frame_header;
  104038. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104039. FLAC__bool do_independent, do_mid_side;
  104040. /*
  104041. * Calculate the min,max Rice partition orders
  104042. */
  104043. if(is_fractional_block) {
  104044. max_partition_order = 0;
  104045. }
  104046. else {
  104047. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104048. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104049. }
  104050. min_partition_order = min(min_partition_order, max_partition_order);
  104051. /*
  104052. * Setup the frame
  104053. */
  104054. frame_header.blocksize = encoder->protected_->blocksize;
  104055. frame_header.sample_rate = encoder->protected_->sample_rate;
  104056. frame_header.channels = encoder->protected_->channels;
  104057. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104058. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104059. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104060. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104061. /*
  104062. * Figure out what channel assignments to try
  104063. */
  104064. if(encoder->protected_->do_mid_side_stereo) {
  104065. if(encoder->protected_->loose_mid_side_stereo) {
  104066. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104067. do_independent = true;
  104068. do_mid_side = true;
  104069. }
  104070. else {
  104071. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104072. do_mid_side = !do_independent;
  104073. }
  104074. }
  104075. else {
  104076. do_independent = true;
  104077. do_mid_side = true;
  104078. }
  104079. }
  104080. else {
  104081. do_independent = true;
  104082. do_mid_side = false;
  104083. }
  104084. FLAC__ASSERT(do_independent || do_mid_side);
  104085. /*
  104086. * Check for wasted bits; set effective bps for each subframe
  104087. */
  104088. if(do_independent) {
  104089. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104090. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104091. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104092. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104093. }
  104094. }
  104095. if(do_mid_side) {
  104096. FLAC__ASSERT(encoder->protected_->channels == 2);
  104097. for(channel = 0; channel < 2; channel++) {
  104098. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104099. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104100. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104101. }
  104102. }
  104103. /*
  104104. * First do a normal encoding pass of each independent channel
  104105. */
  104106. if(do_independent) {
  104107. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104108. if(!
  104109. process_subframe_(
  104110. encoder,
  104111. min_partition_order,
  104112. max_partition_order,
  104113. &frame_header,
  104114. encoder->private_->subframe_bps[channel],
  104115. encoder->private_->integer_signal[channel],
  104116. encoder->private_->subframe_workspace_ptr[channel],
  104117. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104118. encoder->private_->residual_workspace[channel],
  104119. encoder->private_->best_subframe+channel,
  104120. encoder->private_->best_subframe_bits+channel
  104121. )
  104122. )
  104123. return false;
  104124. }
  104125. }
  104126. /*
  104127. * Now do mid and side channels if requested
  104128. */
  104129. if(do_mid_side) {
  104130. FLAC__ASSERT(encoder->protected_->channels == 2);
  104131. for(channel = 0; channel < 2; channel++) {
  104132. if(!
  104133. process_subframe_(
  104134. encoder,
  104135. min_partition_order,
  104136. max_partition_order,
  104137. &frame_header,
  104138. encoder->private_->subframe_bps_mid_side[channel],
  104139. encoder->private_->integer_signal_mid_side[channel],
  104140. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104141. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104142. encoder->private_->residual_workspace_mid_side[channel],
  104143. encoder->private_->best_subframe_mid_side+channel,
  104144. encoder->private_->best_subframe_bits_mid_side+channel
  104145. )
  104146. )
  104147. return false;
  104148. }
  104149. }
  104150. /*
  104151. * Compose the frame bitbuffer
  104152. */
  104153. if(do_mid_side) {
  104154. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104155. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104156. FLAC__ChannelAssignment channel_assignment;
  104157. FLAC__ASSERT(encoder->protected_->channels == 2);
  104158. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104159. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104160. }
  104161. else {
  104162. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104163. unsigned min_bits;
  104164. int ca;
  104165. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104166. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104167. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104168. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104169. FLAC__ASSERT(do_independent && do_mid_side);
  104170. /* We have to figure out which channel assignent results in the smallest frame */
  104171. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104172. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104173. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104174. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104175. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104176. min_bits = bits[channel_assignment];
  104177. for(ca = 1; ca <= 3; ca++) {
  104178. if(bits[ca] < min_bits) {
  104179. min_bits = bits[ca];
  104180. channel_assignment = (FLAC__ChannelAssignment)ca;
  104181. }
  104182. }
  104183. }
  104184. frame_header.channel_assignment = channel_assignment;
  104185. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104186. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104187. return false;
  104188. }
  104189. switch(channel_assignment) {
  104190. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104191. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104192. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104193. break;
  104194. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104195. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104196. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104197. break;
  104198. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104199. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104200. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104201. break;
  104202. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104203. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104204. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104205. break;
  104206. default:
  104207. FLAC__ASSERT(0);
  104208. }
  104209. switch(channel_assignment) {
  104210. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104211. left_bps = encoder->private_->subframe_bps [0];
  104212. right_bps = encoder->private_->subframe_bps [1];
  104213. break;
  104214. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104215. left_bps = encoder->private_->subframe_bps [0];
  104216. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104217. break;
  104218. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104219. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104220. right_bps = encoder->private_->subframe_bps [1];
  104221. break;
  104222. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104223. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104224. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104225. break;
  104226. default:
  104227. FLAC__ASSERT(0);
  104228. }
  104229. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104230. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104231. return false;
  104232. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104233. return false;
  104234. }
  104235. else {
  104236. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104237. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104238. return false;
  104239. }
  104240. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104241. 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)) {
  104242. /* the above function sets the state for us in case of an error */
  104243. return false;
  104244. }
  104245. }
  104246. }
  104247. if(encoder->protected_->loose_mid_side_stereo) {
  104248. encoder->private_->loose_mid_side_stereo_frame_count++;
  104249. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104250. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104251. }
  104252. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104253. return true;
  104254. }
  104255. FLAC__bool process_subframe_(
  104256. FLAC__StreamEncoder *encoder,
  104257. unsigned min_partition_order,
  104258. unsigned max_partition_order,
  104259. const FLAC__FrameHeader *frame_header,
  104260. unsigned subframe_bps,
  104261. const FLAC__int32 integer_signal[],
  104262. FLAC__Subframe *subframe[2],
  104263. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104264. FLAC__int32 *residual[2],
  104265. unsigned *best_subframe,
  104266. unsigned *best_bits
  104267. )
  104268. {
  104269. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104270. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104271. #else
  104272. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104273. #endif
  104274. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104275. FLAC__double lpc_residual_bits_per_sample;
  104276. 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 */
  104277. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104278. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104279. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104280. #endif
  104281. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104282. unsigned rice_parameter;
  104283. unsigned _candidate_bits, _best_bits;
  104284. unsigned _best_subframe;
  104285. /* only use RICE2 partitions if stream bps > 16 */
  104286. 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;
  104287. FLAC__ASSERT(frame_header->blocksize > 0);
  104288. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104289. _best_subframe = 0;
  104290. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104291. _best_bits = UINT_MAX;
  104292. else
  104293. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104294. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104295. unsigned signal_is_constant = false;
  104296. 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);
  104297. /* check for constant subframe */
  104298. if(
  104299. !encoder->private_->disable_constant_subframes &&
  104300. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104301. fixed_residual_bits_per_sample[1] == 0.0
  104302. #else
  104303. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104304. #endif
  104305. ) {
  104306. /* the above means it's possible all samples are the same value; now double-check it: */
  104307. unsigned i;
  104308. signal_is_constant = true;
  104309. for(i = 1; i < frame_header->blocksize; i++) {
  104310. if(integer_signal[0] != integer_signal[i]) {
  104311. signal_is_constant = false;
  104312. break;
  104313. }
  104314. }
  104315. }
  104316. if(signal_is_constant) {
  104317. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104318. if(_candidate_bits < _best_bits) {
  104319. _best_subframe = !_best_subframe;
  104320. _best_bits = _candidate_bits;
  104321. }
  104322. }
  104323. else {
  104324. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104325. /* encode fixed */
  104326. if(encoder->protected_->do_exhaustive_model_search) {
  104327. min_fixed_order = 0;
  104328. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104329. }
  104330. else {
  104331. min_fixed_order = max_fixed_order = guess_fixed_order;
  104332. }
  104333. if(max_fixed_order >= frame_header->blocksize)
  104334. max_fixed_order = frame_header->blocksize - 1;
  104335. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104336. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104337. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104338. continue; /* don't even try */
  104339. 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 */
  104340. #else
  104341. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104342. continue; /* don't even try */
  104343. 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 */
  104344. #endif
  104345. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104346. if(rice_parameter >= rice_parameter_limit) {
  104347. #ifdef DEBUG_VERBOSE
  104348. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104349. #endif
  104350. rice_parameter = rice_parameter_limit - 1;
  104351. }
  104352. _candidate_bits =
  104353. evaluate_fixed_subframe_(
  104354. encoder,
  104355. integer_signal,
  104356. residual[!_best_subframe],
  104357. encoder->private_->abs_residual_partition_sums,
  104358. encoder->private_->raw_bits_per_partition,
  104359. frame_header->blocksize,
  104360. subframe_bps,
  104361. fixed_order,
  104362. rice_parameter,
  104363. rice_parameter_limit,
  104364. min_partition_order,
  104365. max_partition_order,
  104366. encoder->protected_->do_escape_coding,
  104367. encoder->protected_->rice_parameter_search_dist,
  104368. subframe[!_best_subframe],
  104369. partitioned_rice_contents[!_best_subframe]
  104370. );
  104371. if(_candidate_bits < _best_bits) {
  104372. _best_subframe = !_best_subframe;
  104373. _best_bits = _candidate_bits;
  104374. }
  104375. }
  104376. }
  104377. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104378. /* encode lpc */
  104379. if(encoder->protected_->max_lpc_order > 0) {
  104380. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104381. max_lpc_order = frame_header->blocksize-1;
  104382. else
  104383. max_lpc_order = encoder->protected_->max_lpc_order;
  104384. if(max_lpc_order > 0) {
  104385. unsigned a;
  104386. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104387. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104388. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104389. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104390. if(autoc[0] != 0.0) {
  104391. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104392. if(encoder->protected_->do_exhaustive_model_search) {
  104393. min_lpc_order = 1;
  104394. }
  104395. else {
  104396. const unsigned guess_lpc_order =
  104397. FLAC__lpc_compute_best_order(
  104398. lpc_error,
  104399. max_lpc_order,
  104400. frame_header->blocksize,
  104401. subframe_bps + (
  104402. encoder->protected_->do_qlp_coeff_prec_search?
  104403. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104404. encoder->protected_->qlp_coeff_precision
  104405. )
  104406. );
  104407. min_lpc_order = max_lpc_order = guess_lpc_order;
  104408. }
  104409. if(max_lpc_order >= frame_header->blocksize)
  104410. max_lpc_order = frame_header->blocksize - 1;
  104411. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104412. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104413. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104414. continue; /* don't even try */
  104415. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104416. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104417. if(rice_parameter >= rice_parameter_limit) {
  104418. #ifdef DEBUG_VERBOSE
  104419. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104420. #endif
  104421. rice_parameter = rice_parameter_limit - 1;
  104422. }
  104423. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104424. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104425. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104426. if(subframe_bps <= 17) {
  104427. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104428. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104429. }
  104430. else
  104431. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104432. }
  104433. else {
  104434. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104435. }
  104436. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104437. _candidate_bits =
  104438. evaluate_lpc_subframe_(
  104439. encoder,
  104440. integer_signal,
  104441. residual[!_best_subframe],
  104442. encoder->private_->abs_residual_partition_sums,
  104443. encoder->private_->raw_bits_per_partition,
  104444. encoder->private_->lp_coeff[lpc_order-1],
  104445. frame_header->blocksize,
  104446. subframe_bps,
  104447. lpc_order,
  104448. qlp_coeff_precision,
  104449. rice_parameter,
  104450. rice_parameter_limit,
  104451. min_partition_order,
  104452. max_partition_order,
  104453. encoder->protected_->do_escape_coding,
  104454. encoder->protected_->rice_parameter_search_dist,
  104455. subframe[!_best_subframe],
  104456. partitioned_rice_contents[!_best_subframe]
  104457. );
  104458. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104459. if(_candidate_bits < _best_bits) {
  104460. _best_subframe = !_best_subframe;
  104461. _best_bits = _candidate_bits;
  104462. }
  104463. }
  104464. }
  104465. }
  104466. }
  104467. }
  104468. }
  104469. }
  104470. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104471. }
  104472. }
  104473. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104474. if(_best_bits == UINT_MAX) {
  104475. FLAC__ASSERT(_best_subframe == 0);
  104476. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104477. }
  104478. *best_subframe = _best_subframe;
  104479. *best_bits = _best_bits;
  104480. return true;
  104481. }
  104482. FLAC__bool add_subframe_(
  104483. FLAC__StreamEncoder *encoder,
  104484. unsigned blocksize,
  104485. unsigned subframe_bps,
  104486. const FLAC__Subframe *subframe,
  104487. FLAC__BitWriter *frame
  104488. )
  104489. {
  104490. switch(subframe->type) {
  104491. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104492. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104493. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104494. return false;
  104495. }
  104496. break;
  104497. case FLAC__SUBFRAME_TYPE_FIXED:
  104498. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104499. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104500. return false;
  104501. }
  104502. break;
  104503. case FLAC__SUBFRAME_TYPE_LPC:
  104504. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104505. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104506. return false;
  104507. }
  104508. break;
  104509. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104510. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104511. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104512. return false;
  104513. }
  104514. break;
  104515. default:
  104516. FLAC__ASSERT(0);
  104517. }
  104518. return true;
  104519. }
  104520. #define SPOTCHECK_ESTIMATE 0
  104521. #if SPOTCHECK_ESTIMATE
  104522. static void spotcheck_subframe_estimate_(
  104523. FLAC__StreamEncoder *encoder,
  104524. unsigned blocksize,
  104525. unsigned subframe_bps,
  104526. const FLAC__Subframe *subframe,
  104527. unsigned estimate
  104528. )
  104529. {
  104530. FLAC__bool ret;
  104531. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104532. if(frame == 0) {
  104533. fprintf(stderr, "EST: can't allocate frame\n");
  104534. return;
  104535. }
  104536. if(!FLAC__bitwriter_init(frame)) {
  104537. fprintf(stderr, "EST: can't init frame\n");
  104538. return;
  104539. }
  104540. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104541. FLAC__ASSERT(ret);
  104542. {
  104543. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104544. if(estimate != actual)
  104545. 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);
  104546. }
  104547. FLAC__bitwriter_delete(frame);
  104548. }
  104549. #endif
  104550. unsigned evaluate_constant_subframe_(
  104551. FLAC__StreamEncoder *encoder,
  104552. const FLAC__int32 signal,
  104553. unsigned blocksize,
  104554. unsigned subframe_bps,
  104555. FLAC__Subframe *subframe
  104556. )
  104557. {
  104558. unsigned estimate;
  104559. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104560. subframe->data.constant.value = signal;
  104561. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104562. #if SPOTCHECK_ESTIMATE
  104563. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104564. #else
  104565. (void)encoder, (void)blocksize;
  104566. #endif
  104567. return estimate;
  104568. }
  104569. unsigned evaluate_fixed_subframe_(
  104570. FLAC__StreamEncoder *encoder,
  104571. const FLAC__int32 signal[],
  104572. FLAC__int32 residual[],
  104573. FLAC__uint64 abs_residual_partition_sums[],
  104574. unsigned raw_bits_per_partition[],
  104575. unsigned blocksize,
  104576. unsigned subframe_bps,
  104577. unsigned order,
  104578. unsigned rice_parameter,
  104579. unsigned rice_parameter_limit,
  104580. unsigned min_partition_order,
  104581. unsigned max_partition_order,
  104582. FLAC__bool do_escape_coding,
  104583. unsigned rice_parameter_search_dist,
  104584. FLAC__Subframe *subframe,
  104585. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104586. )
  104587. {
  104588. unsigned i, residual_bits, estimate;
  104589. const unsigned residual_samples = blocksize - order;
  104590. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104591. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104592. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104593. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104594. subframe->data.fixed.residual = residual;
  104595. residual_bits =
  104596. find_best_partition_order_(
  104597. encoder->private_,
  104598. residual,
  104599. abs_residual_partition_sums,
  104600. raw_bits_per_partition,
  104601. residual_samples,
  104602. order,
  104603. rice_parameter,
  104604. rice_parameter_limit,
  104605. min_partition_order,
  104606. max_partition_order,
  104607. subframe_bps,
  104608. do_escape_coding,
  104609. rice_parameter_search_dist,
  104610. &subframe->data.fixed.entropy_coding_method
  104611. );
  104612. subframe->data.fixed.order = order;
  104613. for(i = 0; i < order; i++)
  104614. subframe->data.fixed.warmup[i] = signal[i];
  104615. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104616. #if SPOTCHECK_ESTIMATE
  104617. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104618. #endif
  104619. return estimate;
  104620. }
  104621. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104622. unsigned evaluate_lpc_subframe_(
  104623. FLAC__StreamEncoder *encoder,
  104624. const FLAC__int32 signal[],
  104625. FLAC__int32 residual[],
  104626. FLAC__uint64 abs_residual_partition_sums[],
  104627. unsigned raw_bits_per_partition[],
  104628. const FLAC__real lp_coeff[],
  104629. unsigned blocksize,
  104630. unsigned subframe_bps,
  104631. unsigned order,
  104632. unsigned qlp_coeff_precision,
  104633. unsigned rice_parameter,
  104634. unsigned rice_parameter_limit,
  104635. unsigned min_partition_order,
  104636. unsigned max_partition_order,
  104637. FLAC__bool do_escape_coding,
  104638. unsigned rice_parameter_search_dist,
  104639. FLAC__Subframe *subframe,
  104640. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104641. )
  104642. {
  104643. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104644. unsigned i, residual_bits, estimate;
  104645. int quantization, ret;
  104646. const unsigned residual_samples = blocksize - order;
  104647. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104648. if(subframe_bps <= 16) {
  104649. FLAC__ASSERT(order > 0);
  104650. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104651. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104652. }
  104653. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104654. if(ret != 0)
  104655. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104656. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104657. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104658. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104659. else
  104660. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104661. else
  104662. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104663. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104664. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104665. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104666. subframe->data.lpc.residual = residual;
  104667. residual_bits =
  104668. find_best_partition_order_(
  104669. encoder->private_,
  104670. residual,
  104671. abs_residual_partition_sums,
  104672. raw_bits_per_partition,
  104673. residual_samples,
  104674. order,
  104675. rice_parameter,
  104676. rice_parameter_limit,
  104677. min_partition_order,
  104678. max_partition_order,
  104679. subframe_bps,
  104680. do_escape_coding,
  104681. rice_parameter_search_dist,
  104682. &subframe->data.lpc.entropy_coding_method
  104683. );
  104684. subframe->data.lpc.order = order;
  104685. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104686. subframe->data.lpc.quantization_level = quantization;
  104687. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104688. for(i = 0; i < order; i++)
  104689. subframe->data.lpc.warmup[i] = signal[i];
  104690. 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;
  104691. #if SPOTCHECK_ESTIMATE
  104692. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104693. #endif
  104694. return estimate;
  104695. }
  104696. #endif
  104697. unsigned evaluate_verbatim_subframe_(
  104698. FLAC__StreamEncoder *encoder,
  104699. const FLAC__int32 signal[],
  104700. unsigned blocksize,
  104701. unsigned subframe_bps,
  104702. FLAC__Subframe *subframe
  104703. )
  104704. {
  104705. unsigned estimate;
  104706. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104707. subframe->data.verbatim.data = signal;
  104708. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104709. #if SPOTCHECK_ESTIMATE
  104710. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104711. #else
  104712. (void)encoder;
  104713. #endif
  104714. return estimate;
  104715. }
  104716. unsigned find_best_partition_order_(
  104717. FLAC__StreamEncoderPrivate *private_,
  104718. const FLAC__int32 residual[],
  104719. FLAC__uint64 abs_residual_partition_sums[],
  104720. unsigned raw_bits_per_partition[],
  104721. unsigned residual_samples,
  104722. unsigned predictor_order,
  104723. unsigned rice_parameter,
  104724. unsigned rice_parameter_limit,
  104725. unsigned min_partition_order,
  104726. unsigned max_partition_order,
  104727. unsigned bps,
  104728. FLAC__bool do_escape_coding,
  104729. unsigned rice_parameter_search_dist,
  104730. FLAC__EntropyCodingMethod *best_ecm
  104731. )
  104732. {
  104733. unsigned residual_bits, best_residual_bits = 0;
  104734. unsigned best_parameters_index = 0;
  104735. unsigned best_partition_order = 0;
  104736. const unsigned blocksize = residual_samples + predictor_order;
  104737. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104738. min_partition_order = min(min_partition_order, max_partition_order);
  104739. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104740. if(do_escape_coding)
  104741. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104742. {
  104743. int partition_order;
  104744. unsigned sum;
  104745. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104746. if(!
  104747. set_partitioned_rice_(
  104748. #ifdef EXACT_RICE_BITS_CALCULATION
  104749. residual,
  104750. #endif
  104751. abs_residual_partition_sums+sum,
  104752. raw_bits_per_partition+sum,
  104753. residual_samples,
  104754. predictor_order,
  104755. rice_parameter,
  104756. rice_parameter_limit,
  104757. rice_parameter_search_dist,
  104758. (unsigned)partition_order,
  104759. do_escape_coding,
  104760. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104761. &residual_bits
  104762. )
  104763. )
  104764. {
  104765. FLAC__ASSERT(best_residual_bits != 0);
  104766. break;
  104767. }
  104768. sum += 1u << partition_order;
  104769. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104770. best_residual_bits = residual_bits;
  104771. best_parameters_index = !best_parameters_index;
  104772. best_partition_order = partition_order;
  104773. }
  104774. }
  104775. }
  104776. best_ecm->data.partitioned_rice.order = best_partition_order;
  104777. {
  104778. /*
  104779. * We are allowed to de-const the pointer based on our special
  104780. * knowledge; it is const to the outside world.
  104781. */
  104782. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104783. unsigned partition;
  104784. /* save best parameters and raw_bits */
  104785. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104786. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104787. if(do_escape_coding)
  104788. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104789. /*
  104790. * Now need to check if the type should be changed to
  104791. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104792. * size of the rice parameters.
  104793. */
  104794. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104795. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104796. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104797. break;
  104798. }
  104799. }
  104800. }
  104801. return best_residual_bits;
  104802. }
  104803. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104804. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104805. const FLAC__int32 residual[],
  104806. FLAC__uint64 abs_residual_partition_sums[],
  104807. unsigned blocksize,
  104808. unsigned predictor_order,
  104809. unsigned min_partition_order,
  104810. unsigned max_partition_order
  104811. );
  104812. #endif
  104813. void precompute_partition_info_sums_(
  104814. const FLAC__int32 residual[],
  104815. FLAC__uint64 abs_residual_partition_sums[],
  104816. unsigned residual_samples,
  104817. unsigned predictor_order,
  104818. unsigned min_partition_order,
  104819. unsigned max_partition_order,
  104820. unsigned bps
  104821. )
  104822. {
  104823. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  104824. unsigned partitions = 1u << max_partition_order;
  104825. FLAC__ASSERT(default_partition_samples > predictor_order);
  104826. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104827. /* slightly pessimistic but still catches all common cases */
  104828. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104829. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104830. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  104831. return;
  104832. }
  104833. #endif
  104834. /* first do max_partition_order */
  104835. {
  104836. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  104837. /* slightly pessimistic but still catches all common cases */
  104838. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104839. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104840. FLAC__uint32 abs_residual_partition_sum;
  104841. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104842. end += default_partition_samples;
  104843. abs_residual_partition_sum = 0;
  104844. for( ; residual_sample < end; residual_sample++)
  104845. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104846. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104847. }
  104848. }
  104849. else { /* have to pessimistically use 64 bits for accumulator */
  104850. FLAC__uint64 abs_residual_partition_sum;
  104851. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104852. end += default_partition_samples;
  104853. abs_residual_partition_sum = 0;
  104854. for( ; residual_sample < end; residual_sample++)
  104855. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104856. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104857. }
  104858. }
  104859. }
  104860. /* now merge partitions for lower orders */
  104861. {
  104862. unsigned from_partition = 0, to_partition = partitions;
  104863. int partition_order;
  104864. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  104865. unsigned i;
  104866. partitions >>= 1;
  104867. for(i = 0; i < partitions; i++) {
  104868. abs_residual_partition_sums[to_partition++] =
  104869. abs_residual_partition_sums[from_partition ] +
  104870. abs_residual_partition_sums[from_partition+1];
  104871. from_partition += 2;
  104872. }
  104873. }
  104874. }
  104875. }
  104876. void precompute_partition_info_escapes_(
  104877. const FLAC__int32 residual[],
  104878. unsigned raw_bits_per_partition[],
  104879. unsigned residual_samples,
  104880. unsigned predictor_order,
  104881. unsigned min_partition_order,
  104882. unsigned max_partition_order
  104883. )
  104884. {
  104885. int partition_order;
  104886. unsigned from_partition, to_partition = 0;
  104887. const unsigned blocksize = residual_samples + predictor_order;
  104888. /* first do max_partition_order */
  104889. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  104890. FLAC__int32 r;
  104891. FLAC__uint32 rmax;
  104892. unsigned partition, partition_sample, partition_samples, residual_sample;
  104893. const unsigned partitions = 1u << partition_order;
  104894. const unsigned default_partition_samples = blocksize >> partition_order;
  104895. FLAC__ASSERT(default_partition_samples > predictor_order);
  104896. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104897. partition_samples = default_partition_samples;
  104898. if(partition == 0)
  104899. partition_samples -= predictor_order;
  104900. rmax = 0;
  104901. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  104902. r = residual[residual_sample++];
  104903. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  104904. if(r < 0)
  104905. rmax |= ~r;
  104906. else
  104907. rmax |= r;
  104908. }
  104909. /* now we know all residual values are in the range [-rmax-1,rmax] */
  104910. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  104911. }
  104912. to_partition = partitions;
  104913. break; /*@@@ yuck, should remove the 'for' loop instead */
  104914. }
  104915. /* now merge partitions for lower orders */
  104916. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  104917. unsigned m;
  104918. unsigned i;
  104919. const unsigned partitions = 1u << partition_order;
  104920. for(i = 0; i < partitions; i++) {
  104921. m = raw_bits_per_partition[from_partition];
  104922. from_partition++;
  104923. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  104924. from_partition++;
  104925. to_partition++;
  104926. }
  104927. }
  104928. }
  104929. #ifdef EXACT_RICE_BITS_CALCULATION
  104930. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104931. const unsigned rice_parameter,
  104932. const unsigned partition_samples,
  104933. const FLAC__int32 *residual
  104934. )
  104935. {
  104936. unsigned i, partition_bits =
  104937. 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 */
  104938. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  104939. ;
  104940. for(i = 0; i < partition_samples; i++)
  104941. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  104942. return partition_bits;
  104943. }
  104944. #else
  104945. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104946. const unsigned rice_parameter,
  104947. const unsigned partition_samples,
  104948. const FLAC__uint64 abs_residual_partition_sum
  104949. )
  104950. {
  104951. return
  104952. 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 */
  104953. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  104954. (
  104955. rice_parameter?
  104956. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  104957. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  104958. )
  104959. - (partition_samples >> 1)
  104960. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  104961. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  104962. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  104963. * So the subtraction term tries to guess how many extra bits were contributed.
  104964. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  104965. */
  104966. ;
  104967. }
  104968. #endif
  104969. FLAC__bool set_partitioned_rice_(
  104970. #ifdef EXACT_RICE_BITS_CALCULATION
  104971. const FLAC__int32 residual[],
  104972. #endif
  104973. const FLAC__uint64 abs_residual_partition_sums[],
  104974. const unsigned raw_bits_per_partition[],
  104975. const unsigned residual_samples,
  104976. const unsigned predictor_order,
  104977. const unsigned suggested_rice_parameter,
  104978. const unsigned rice_parameter_limit,
  104979. const unsigned rice_parameter_search_dist,
  104980. const unsigned partition_order,
  104981. const FLAC__bool search_for_escapes,
  104982. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  104983. unsigned *bits
  104984. )
  104985. {
  104986. unsigned rice_parameter, partition_bits;
  104987. unsigned best_partition_bits, best_rice_parameter = 0;
  104988. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  104989. unsigned *parameters, *raw_bits;
  104990. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104991. unsigned min_rice_parameter, max_rice_parameter;
  104992. #else
  104993. (void)rice_parameter_search_dist;
  104994. #endif
  104995. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104996. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104997. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  104998. parameters = partitioned_rice_contents->parameters;
  104999. raw_bits = partitioned_rice_contents->raw_bits;
  105000. if(partition_order == 0) {
  105001. best_partition_bits = (unsigned)(-1);
  105002. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105003. if(rice_parameter_search_dist) {
  105004. if(suggested_rice_parameter < rice_parameter_search_dist)
  105005. min_rice_parameter = 0;
  105006. else
  105007. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105008. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105009. if(max_rice_parameter >= rice_parameter_limit) {
  105010. #ifdef DEBUG_VERBOSE
  105011. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105012. #endif
  105013. max_rice_parameter = rice_parameter_limit - 1;
  105014. }
  105015. }
  105016. else
  105017. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105018. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105019. #else
  105020. rice_parameter = suggested_rice_parameter;
  105021. #endif
  105022. #ifdef EXACT_RICE_BITS_CALCULATION
  105023. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105024. #else
  105025. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105026. #endif
  105027. if(partition_bits < best_partition_bits) {
  105028. best_rice_parameter = rice_parameter;
  105029. best_partition_bits = partition_bits;
  105030. }
  105031. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105032. }
  105033. #endif
  105034. if(search_for_escapes) {
  105035. 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;
  105036. if(partition_bits <= best_partition_bits) {
  105037. raw_bits[0] = raw_bits_per_partition[0];
  105038. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105039. best_partition_bits = partition_bits;
  105040. }
  105041. else
  105042. raw_bits[0] = 0;
  105043. }
  105044. parameters[0] = best_rice_parameter;
  105045. bits_ += best_partition_bits;
  105046. }
  105047. else {
  105048. unsigned partition, residual_sample;
  105049. unsigned partition_samples;
  105050. FLAC__uint64 mean, k;
  105051. const unsigned partitions = 1u << partition_order;
  105052. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105053. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105054. if(partition == 0) {
  105055. if(partition_samples <= predictor_order)
  105056. return false;
  105057. else
  105058. partition_samples -= predictor_order;
  105059. }
  105060. mean = abs_residual_partition_sums[partition];
  105061. /* we are basically calculating the size in bits of the
  105062. * average residual magnitude in the partition:
  105063. * rice_parameter = floor(log2(mean/partition_samples))
  105064. * 'mean' is not a good name for the variable, it is
  105065. * actually the sum of magnitudes of all residual values
  105066. * in the partition, so the actual mean is
  105067. * mean/partition_samples
  105068. */
  105069. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105070. ;
  105071. if(rice_parameter >= rice_parameter_limit) {
  105072. #ifdef DEBUG_VERBOSE
  105073. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105074. #endif
  105075. rice_parameter = rice_parameter_limit - 1;
  105076. }
  105077. best_partition_bits = (unsigned)(-1);
  105078. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105079. if(rice_parameter_search_dist) {
  105080. if(rice_parameter < rice_parameter_search_dist)
  105081. min_rice_parameter = 0;
  105082. else
  105083. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105084. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105085. if(max_rice_parameter >= rice_parameter_limit) {
  105086. #ifdef DEBUG_VERBOSE
  105087. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105088. #endif
  105089. max_rice_parameter = rice_parameter_limit - 1;
  105090. }
  105091. }
  105092. else
  105093. min_rice_parameter = max_rice_parameter = rice_parameter;
  105094. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105095. #endif
  105096. #ifdef EXACT_RICE_BITS_CALCULATION
  105097. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105098. #else
  105099. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105100. #endif
  105101. if(partition_bits < best_partition_bits) {
  105102. best_rice_parameter = rice_parameter;
  105103. best_partition_bits = partition_bits;
  105104. }
  105105. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105106. }
  105107. #endif
  105108. if(search_for_escapes) {
  105109. 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;
  105110. if(partition_bits <= best_partition_bits) {
  105111. raw_bits[partition] = raw_bits_per_partition[partition];
  105112. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105113. best_partition_bits = partition_bits;
  105114. }
  105115. else
  105116. raw_bits[partition] = 0;
  105117. }
  105118. parameters[partition] = best_rice_parameter;
  105119. bits_ += best_partition_bits;
  105120. residual_sample += partition_samples;
  105121. }
  105122. }
  105123. *bits = bits_;
  105124. return true;
  105125. }
  105126. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105127. {
  105128. unsigned i, shift;
  105129. FLAC__int32 x = 0;
  105130. for(i = 0; i < samples && !(x&1); i++)
  105131. x |= signal[i];
  105132. if(x == 0) {
  105133. shift = 0;
  105134. }
  105135. else {
  105136. for(shift = 0; !(x&1); shift++)
  105137. x >>= 1;
  105138. }
  105139. if(shift > 0) {
  105140. for(i = 0; i < samples; i++)
  105141. signal[i] >>= shift;
  105142. }
  105143. return shift;
  105144. }
  105145. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105146. {
  105147. unsigned channel;
  105148. for(channel = 0; channel < channels; channel++)
  105149. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105150. fifo->tail += wide_samples;
  105151. FLAC__ASSERT(fifo->tail <= fifo->size);
  105152. }
  105153. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105154. {
  105155. unsigned channel;
  105156. unsigned sample, wide_sample;
  105157. unsigned tail = fifo->tail;
  105158. sample = input_offset * channels;
  105159. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105160. for(channel = 0; channel < channels; channel++)
  105161. fifo->data[channel][tail] = input[sample++];
  105162. tail++;
  105163. }
  105164. fifo->tail = tail;
  105165. FLAC__ASSERT(fifo->tail <= fifo->size);
  105166. }
  105167. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105168. {
  105169. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105170. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105171. (void)decoder;
  105172. if(encoder->private_->verify.needs_magic_hack) {
  105173. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105174. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105175. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105176. encoder->private_->verify.needs_magic_hack = false;
  105177. }
  105178. else {
  105179. if(encoded_bytes == 0) {
  105180. /*
  105181. * If we get here, a FIFO underflow has occurred,
  105182. * which means there is a bug somewhere.
  105183. */
  105184. FLAC__ASSERT(0);
  105185. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105186. }
  105187. else if(encoded_bytes < *bytes)
  105188. *bytes = encoded_bytes;
  105189. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105190. encoder->private_->verify.output.data += *bytes;
  105191. encoder->private_->verify.output.bytes -= *bytes;
  105192. }
  105193. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105194. }
  105195. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105196. {
  105197. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105198. unsigned channel;
  105199. const unsigned channels = frame->header.channels;
  105200. const unsigned blocksize = frame->header.blocksize;
  105201. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105202. (void)decoder;
  105203. for(channel = 0; channel < channels; channel++) {
  105204. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105205. unsigned i, sample = 0;
  105206. FLAC__int32 expect = 0, got = 0;
  105207. for(i = 0; i < blocksize; i++) {
  105208. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105209. sample = i;
  105210. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105211. got = (FLAC__int32)buffer[channel][i];
  105212. break;
  105213. }
  105214. }
  105215. FLAC__ASSERT(i < blocksize);
  105216. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105217. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105218. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105219. encoder->private_->verify.error_stats.channel = channel;
  105220. encoder->private_->verify.error_stats.sample = sample;
  105221. encoder->private_->verify.error_stats.expected = expect;
  105222. encoder->private_->verify.error_stats.got = got;
  105223. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105224. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105225. }
  105226. }
  105227. /* dequeue the frame from the fifo */
  105228. encoder->private_->verify.input_fifo.tail -= blocksize;
  105229. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105230. for(channel = 0; channel < channels; channel++)
  105231. 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]));
  105232. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105233. }
  105234. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105235. {
  105236. (void)decoder, (void)metadata, (void)client_data;
  105237. }
  105238. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105239. {
  105240. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105241. (void)decoder, (void)status;
  105242. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105243. }
  105244. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105245. {
  105246. (void)client_data;
  105247. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105248. if (*bytes == 0) {
  105249. if (feof(encoder->private_->file))
  105250. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105251. else if (ferror(encoder->private_->file))
  105252. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105253. }
  105254. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105255. }
  105256. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105257. {
  105258. (void)client_data;
  105259. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105260. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105261. else
  105262. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105263. }
  105264. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105265. {
  105266. off_t offset;
  105267. (void)client_data;
  105268. offset = ftello(encoder->private_->file);
  105269. if(offset < 0) {
  105270. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105271. }
  105272. else {
  105273. *absolute_byte_offset = (FLAC__uint64)offset;
  105274. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105275. }
  105276. }
  105277. #ifdef FLAC__VALGRIND_TESTING
  105278. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105279. {
  105280. size_t ret = fwrite(ptr, size, nmemb, stream);
  105281. if(!ferror(stream))
  105282. fflush(stream);
  105283. return ret;
  105284. }
  105285. #else
  105286. #define local__fwrite fwrite
  105287. #endif
  105288. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105289. {
  105290. (void)client_data, (void)current_frame;
  105291. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105292. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105293. #if FLAC__HAS_OGG
  105294. /* We would like to be able to use 'samples > 0' in the
  105295. * clause here but currently because of the nature of our
  105296. * Ogg writing implementation, 'samples' is always 0 (see
  105297. * ogg_encoder_aspect.c). The downside is extra progress
  105298. * callbacks.
  105299. */
  105300. encoder->private_->is_ogg? true :
  105301. #endif
  105302. samples > 0
  105303. );
  105304. if(call_it) {
  105305. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105306. * because at this point in the callback chain, the stats
  105307. * have not been updated. Only after we return and control
  105308. * gets back to write_frame_() are the stats updated
  105309. */
  105310. 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);
  105311. }
  105312. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105313. }
  105314. else
  105315. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105316. }
  105317. /*
  105318. * This will forcibly set stdout to binary mode (for OSes that require it)
  105319. */
  105320. FILE *get_binary_stdout_(void)
  105321. {
  105322. /* if something breaks here it is probably due to the presence or
  105323. * absence of an underscore before the identifiers 'setmode',
  105324. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105325. */
  105326. #if defined _MSC_VER || defined __MINGW32__
  105327. _setmode(_fileno(stdout), _O_BINARY);
  105328. #elif defined __CYGWIN__
  105329. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105330. setmode(_fileno(stdout), _O_BINARY);
  105331. #elif defined __EMX__
  105332. setmode(fileno(stdout), O_BINARY);
  105333. #endif
  105334. return stdout;
  105335. }
  105336. #endif
  105337. /*** End of inlined file: stream_encoder.c ***/
  105338. /*** Start of inlined file: stream_encoder_framing.c ***/
  105339. /*** Start of inlined file: juce_FlacHeader.h ***/
  105340. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105341. // tasks..
  105342. #define VERSION "1.2.1"
  105343. #define FLAC__NO_DLL 1
  105344. #if JUCE_MSVC
  105345. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105346. #endif
  105347. #if JUCE_MAC
  105348. #define FLAC__SYS_DARWIN 1
  105349. #endif
  105350. /*** End of inlined file: juce_FlacHeader.h ***/
  105351. #if JUCE_USE_FLAC
  105352. #if HAVE_CONFIG_H
  105353. # include <config.h>
  105354. #endif
  105355. #include <stdio.h>
  105356. #include <string.h> /* for strlen() */
  105357. #ifdef max
  105358. #undef max
  105359. #endif
  105360. #define max(x,y) ((x)>(y)?(x):(y))
  105361. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105362. 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);
  105363. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105364. {
  105365. unsigned i, j;
  105366. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105367. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105368. return false;
  105369. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105370. return false;
  105371. /*
  105372. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105373. */
  105374. i = metadata->length;
  105375. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105376. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105377. i -= metadata->data.vorbis_comment.vendor_string.length;
  105378. i += vendor_string_length;
  105379. }
  105380. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105381. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105382. return false;
  105383. switch(metadata->type) {
  105384. case FLAC__METADATA_TYPE_STREAMINFO:
  105385. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105386. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105387. return false;
  105388. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105389. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105390. return false;
  105391. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105392. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105393. return false;
  105394. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105395. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105396. return false;
  105397. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105398. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105399. return false;
  105400. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105401. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105402. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105403. return false;
  105404. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105405. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105406. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105407. return false;
  105408. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105409. return false;
  105410. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105411. return false;
  105412. break;
  105413. case FLAC__METADATA_TYPE_PADDING:
  105414. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105415. return false;
  105416. break;
  105417. case FLAC__METADATA_TYPE_APPLICATION:
  105418. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105419. return false;
  105420. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105421. return false;
  105422. break;
  105423. case FLAC__METADATA_TYPE_SEEKTABLE:
  105424. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105425. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105426. return false;
  105427. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105428. return false;
  105429. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105430. return false;
  105431. }
  105432. break;
  105433. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105434. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105435. return false;
  105436. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105437. return false;
  105438. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105439. return false;
  105440. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105441. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105442. return false;
  105443. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105444. return false;
  105445. }
  105446. break;
  105447. case FLAC__METADATA_TYPE_CUESHEET:
  105448. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105449. 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))
  105450. return false;
  105451. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105452. return false;
  105453. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105454. return false;
  105455. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105456. return false;
  105457. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105458. return false;
  105459. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105460. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105461. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105462. return false;
  105463. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105464. return false;
  105465. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105466. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105467. return false;
  105468. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105469. return false;
  105470. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105471. return false;
  105472. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105473. return false;
  105474. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105475. return false;
  105476. for(j = 0; j < track->num_indices; j++) {
  105477. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105478. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105479. return false;
  105480. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105481. return false;
  105482. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105483. return false;
  105484. }
  105485. }
  105486. break;
  105487. case FLAC__METADATA_TYPE_PICTURE:
  105488. {
  105489. size_t len;
  105490. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105491. return false;
  105492. len = strlen(metadata->data.picture.mime_type);
  105493. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105494. return false;
  105495. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105496. return false;
  105497. len = strlen((const char *)metadata->data.picture.description);
  105498. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105499. return false;
  105500. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105501. return false;
  105502. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105503. return false;
  105504. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105505. return false;
  105506. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105507. return false;
  105508. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105509. return false;
  105510. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105511. return false;
  105512. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105513. return false;
  105514. }
  105515. break;
  105516. default:
  105517. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105518. return false;
  105519. break;
  105520. }
  105521. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105522. return true;
  105523. }
  105524. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105525. {
  105526. unsigned u, blocksize_hint, sample_rate_hint;
  105527. FLAC__byte crc;
  105528. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105529. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105530. return false;
  105531. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105532. return false;
  105533. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105534. return false;
  105535. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105536. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105537. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105538. blocksize_hint = 0;
  105539. switch(header->blocksize) {
  105540. case 192: u = 1; break;
  105541. case 576: u = 2; break;
  105542. case 1152: u = 3; break;
  105543. case 2304: u = 4; break;
  105544. case 4608: u = 5; break;
  105545. case 256: u = 8; break;
  105546. case 512: u = 9; break;
  105547. case 1024: u = 10; break;
  105548. case 2048: u = 11; break;
  105549. case 4096: u = 12; break;
  105550. case 8192: u = 13; break;
  105551. case 16384: u = 14; break;
  105552. case 32768: u = 15; break;
  105553. default:
  105554. if(header->blocksize <= 0x100)
  105555. blocksize_hint = u = 6;
  105556. else
  105557. blocksize_hint = u = 7;
  105558. break;
  105559. }
  105560. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105561. return false;
  105562. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105563. sample_rate_hint = 0;
  105564. switch(header->sample_rate) {
  105565. case 88200: u = 1; break;
  105566. case 176400: u = 2; break;
  105567. case 192000: u = 3; break;
  105568. case 8000: u = 4; break;
  105569. case 16000: u = 5; break;
  105570. case 22050: u = 6; break;
  105571. case 24000: u = 7; break;
  105572. case 32000: u = 8; break;
  105573. case 44100: u = 9; break;
  105574. case 48000: u = 10; break;
  105575. case 96000: u = 11; break;
  105576. default:
  105577. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105578. sample_rate_hint = u = 12;
  105579. else if(header->sample_rate % 10 == 0)
  105580. sample_rate_hint = u = 14;
  105581. else if(header->sample_rate <= 0xffff)
  105582. sample_rate_hint = u = 13;
  105583. else
  105584. u = 0;
  105585. break;
  105586. }
  105587. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105588. return false;
  105589. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105590. switch(header->channel_assignment) {
  105591. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105592. u = header->channels - 1;
  105593. break;
  105594. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105595. FLAC__ASSERT(header->channels == 2);
  105596. u = 8;
  105597. break;
  105598. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105599. FLAC__ASSERT(header->channels == 2);
  105600. u = 9;
  105601. break;
  105602. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105603. FLAC__ASSERT(header->channels == 2);
  105604. u = 10;
  105605. break;
  105606. default:
  105607. FLAC__ASSERT(0);
  105608. }
  105609. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105610. return false;
  105611. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105612. switch(header->bits_per_sample) {
  105613. case 8 : u = 1; break;
  105614. case 12: u = 2; break;
  105615. case 16: u = 4; break;
  105616. case 20: u = 5; break;
  105617. case 24: u = 6; break;
  105618. default: u = 0; break;
  105619. }
  105620. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105621. return false;
  105622. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105623. return false;
  105624. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105625. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105626. return false;
  105627. }
  105628. else {
  105629. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105630. return false;
  105631. }
  105632. if(blocksize_hint)
  105633. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105634. return false;
  105635. switch(sample_rate_hint) {
  105636. case 12:
  105637. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105638. return false;
  105639. break;
  105640. case 13:
  105641. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105642. return false;
  105643. break;
  105644. case 14:
  105645. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105646. return false;
  105647. break;
  105648. }
  105649. /* write the CRC */
  105650. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105651. return false;
  105652. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105653. return false;
  105654. return true;
  105655. }
  105656. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105657. {
  105658. FLAC__bool ok;
  105659. ok =
  105660. 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) &&
  105661. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105662. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105663. ;
  105664. return ok;
  105665. }
  105666. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105667. {
  105668. unsigned i;
  105669. 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))
  105670. return false;
  105671. if(wasted_bits)
  105672. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105673. return false;
  105674. for(i = 0; i < subframe->order; i++)
  105675. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105676. return false;
  105677. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105678. return false;
  105679. switch(subframe->entropy_coding_method.type) {
  105680. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105681. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105682. if(!add_residual_partitioned_rice_(
  105683. bw,
  105684. subframe->residual,
  105685. residual_samples,
  105686. subframe->order,
  105687. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105688. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105689. subframe->entropy_coding_method.data.partitioned_rice.order,
  105690. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105691. ))
  105692. return false;
  105693. break;
  105694. default:
  105695. FLAC__ASSERT(0);
  105696. }
  105697. return true;
  105698. }
  105699. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105700. {
  105701. unsigned i;
  105702. 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))
  105703. return false;
  105704. if(wasted_bits)
  105705. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105706. return false;
  105707. for(i = 0; i < subframe->order; i++)
  105708. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105709. return false;
  105710. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105711. return false;
  105712. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105713. return false;
  105714. for(i = 0; i < subframe->order; i++)
  105715. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105716. return false;
  105717. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105718. return false;
  105719. switch(subframe->entropy_coding_method.type) {
  105720. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105721. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105722. if(!add_residual_partitioned_rice_(
  105723. bw,
  105724. subframe->residual,
  105725. residual_samples,
  105726. subframe->order,
  105727. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105728. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105729. subframe->entropy_coding_method.data.partitioned_rice.order,
  105730. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105731. ))
  105732. return false;
  105733. break;
  105734. default:
  105735. FLAC__ASSERT(0);
  105736. }
  105737. return true;
  105738. }
  105739. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105740. {
  105741. unsigned i;
  105742. const FLAC__int32 *signal = subframe->data;
  105743. 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))
  105744. return false;
  105745. if(wasted_bits)
  105746. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105747. return false;
  105748. for(i = 0; i < samples; i++)
  105749. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105750. return false;
  105751. return true;
  105752. }
  105753. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105754. {
  105755. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105756. return false;
  105757. switch(method->type) {
  105758. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105759. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105760. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105761. return false;
  105762. break;
  105763. default:
  105764. FLAC__ASSERT(0);
  105765. }
  105766. return true;
  105767. }
  105768. 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)
  105769. {
  105770. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105771. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105772. if(partition_order == 0) {
  105773. unsigned i;
  105774. if(raw_bits[0] == 0) {
  105775. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105776. return false;
  105777. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105778. return false;
  105779. }
  105780. else {
  105781. FLAC__ASSERT(rice_parameters[0] == 0);
  105782. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105783. return false;
  105784. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105785. return false;
  105786. for(i = 0; i < residual_samples; i++) {
  105787. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105788. return false;
  105789. }
  105790. }
  105791. return true;
  105792. }
  105793. else {
  105794. unsigned i, j, k = 0, k_last = 0;
  105795. unsigned partition_samples;
  105796. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105797. for(i = 0; i < (1u<<partition_order); i++) {
  105798. partition_samples = default_partition_samples;
  105799. if(i == 0)
  105800. partition_samples -= predictor_order;
  105801. k += partition_samples;
  105802. if(raw_bits[i] == 0) {
  105803. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105804. return false;
  105805. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105806. return false;
  105807. }
  105808. else {
  105809. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105810. return false;
  105811. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105812. return false;
  105813. for(j = k_last; j < k; j++) {
  105814. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105815. return false;
  105816. }
  105817. }
  105818. k_last = k;
  105819. }
  105820. return true;
  105821. }
  105822. }
  105823. #endif
  105824. /*** End of inlined file: stream_encoder_framing.c ***/
  105825. /*** Start of inlined file: window_flac.c ***/
  105826. /*** Start of inlined file: juce_FlacHeader.h ***/
  105827. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105828. // tasks..
  105829. #define VERSION "1.2.1"
  105830. #define FLAC__NO_DLL 1
  105831. #if JUCE_MSVC
  105832. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105833. #endif
  105834. #if JUCE_MAC
  105835. #define FLAC__SYS_DARWIN 1
  105836. #endif
  105837. /*** End of inlined file: juce_FlacHeader.h ***/
  105838. #if JUCE_USE_FLAC
  105839. #if HAVE_CONFIG_H
  105840. # include <config.h>
  105841. #endif
  105842. #include <math.h>
  105843. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105844. #ifndef M_PI
  105845. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  105846. #define M_PI 3.14159265358979323846
  105847. #endif
  105848. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  105849. {
  105850. const FLAC__int32 N = L - 1;
  105851. FLAC__int32 n;
  105852. if (L & 1) {
  105853. for (n = 0; n <= N/2; n++)
  105854. window[n] = 2.0f * n / (float)N;
  105855. for (; n <= N; n++)
  105856. window[n] = 2.0f - 2.0f * n / (float)N;
  105857. }
  105858. else {
  105859. for (n = 0; n <= L/2-1; n++)
  105860. window[n] = 2.0f * n / (float)N;
  105861. for (; n <= N; n++)
  105862. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  105863. }
  105864. }
  105865. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  105866. {
  105867. const FLAC__int32 N = L - 1;
  105868. FLAC__int32 n;
  105869. for (n = 0; n < L; n++)
  105870. 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)));
  105871. }
  105872. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  105873. {
  105874. const FLAC__int32 N = L - 1;
  105875. FLAC__int32 n;
  105876. for (n = 0; n < L; n++)
  105877. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  105878. }
  105879. /* 4-term -92dB side-lobe */
  105880. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  105881. {
  105882. const FLAC__int32 N = L - 1;
  105883. FLAC__int32 n;
  105884. for (n = 0; n <= N; n++)
  105885. 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));
  105886. }
  105887. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  105888. {
  105889. const FLAC__int32 N = L - 1;
  105890. const double N2 = (double)N / 2.;
  105891. FLAC__int32 n;
  105892. for (n = 0; n <= N; n++) {
  105893. double k = ((double)n - N2) / N2;
  105894. k = 1.0f - k * k;
  105895. window[n] = (FLAC__real)(k * k);
  105896. }
  105897. }
  105898. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  105899. {
  105900. const FLAC__int32 N = L - 1;
  105901. FLAC__int32 n;
  105902. for (n = 0; n < L; n++)
  105903. 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));
  105904. }
  105905. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  105906. {
  105907. const FLAC__int32 N = L - 1;
  105908. const double N2 = (double)N / 2.;
  105909. FLAC__int32 n;
  105910. for (n = 0; n <= N; n++) {
  105911. const double k = ((double)n - N2) / (stddev * N2);
  105912. window[n] = (FLAC__real)exp(-0.5f * k * k);
  105913. }
  105914. }
  105915. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  105916. {
  105917. const FLAC__int32 N = L - 1;
  105918. FLAC__int32 n;
  105919. for (n = 0; n < L; n++)
  105920. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  105921. }
  105922. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  105923. {
  105924. const FLAC__int32 N = L - 1;
  105925. FLAC__int32 n;
  105926. for (n = 0; n < L; n++)
  105927. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  105928. }
  105929. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  105930. {
  105931. const FLAC__int32 N = L - 1;
  105932. FLAC__int32 n;
  105933. for (n = 0; n < L; n++)
  105934. 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));
  105935. }
  105936. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  105937. {
  105938. const FLAC__int32 N = L - 1;
  105939. FLAC__int32 n;
  105940. for (n = 0; n < L; n++)
  105941. 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));
  105942. }
  105943. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  105944. {
  105945. FLAC__int32 n;
  105946. for (n = 0; n < L; n++)
  105947. window[n] = 1.0f;
  105948. }
  105949. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  105950. {
  105951. FLAC__int32 n;
  105952. if (L & 1) {
  105953. for (n = 1; n <= L+1/2; n++)
  105954. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  105955. for (; n <= L; n++)
  105956. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  105957. }
  105958. else {
  105959. for (n = 1; n <= L/2; n++)
  105960. window[n-1] = 2.0f * n / (float)L;
  105961. for (; n <= L; n++)
  105962. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  105963. }
  105964. }
  105965. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  105966. {
  105967. if (p <= 0.0)
  105968. FLAC__window_rectangle(window, L);
  105969. else if (p >= 1.0)
  105970. FLAC__window_hann(window, L);
  105971. else {
  105972. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  105973. FLAC__int32 n;
  105974. /* start with rectangle... */
  105975. FLAC__window_rectangle(window, L);
  105976. /* ...replace ends with hann */
  105977. if (Np > 0) {
  105978. for (n = 0; n <= Np; n++) {
  105979. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  105980. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  105981. }
  105982. }
  105983. }
  105984. }
  105985. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  105986. {
  105987. const FLAC__int32 N = L - 1;
  105988. const double N2 = (double)N / 2.;
  105989. FLAC__int32 n;
  105990. for (n = 0; n <= N; n++) {
  105991. const double k = ((double)n - N2) / N2;
  105992. window[n] = (FLAC__real)(1.0f - k * k);
  105993. }
  105994. }
  105995. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105996. #endif
  105997. /*** End of inlined file: window_flac.c ***/
  105998. #else
  105999. #include <FLAC/all.h>
  106000. #endif
  106001. }
  106002. #undef max
  106003. #undef min
  106004. BEGIN_JUCE_NAMESPACE
  106005. static const char* const flacFormatName = "FLAC file";
  106006. static const char* const flacExtensions[] = { ".flac", 0 };
  106007. class FlacReader : public AudioFormatReader
  106008. {
  106009. public:
  106010. FlacReader (InputStream* const in)
  106011. : AudioFormatReader (in, TRANS (flacFormatName)),
  106012. reservoir (2, 0),
  106013. reservoirStart (0),
  106014. samplesInReservoir (0),
  106015. scanningForLength (false)
  106016. {
  106017. using namespace FlacNamespace;
  106018. lengthInSamples = 0;
  106019. decoder = FLAC__stream_decoder_new();
  106020. ok = FLAC__stream_decoder_init_stream (decoder,
  106021. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106022. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106023. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106024. if (ok)
  106025. {
  106026. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106027. if (lengthInSamples == 0 && sampleRate > 0)
  106028. {
  106029. // the length hasn't been stored in the metadata, so we'll need to
  106030. // work it out the length the hard way, by scanning the whole file..
  106031. scanningForLength = true;
  106032. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106033. scanningForLength = false;
  106034. const int64 tempLength = lengthInSamples;
  106035. FLAC__stream_decoder_reset (decoder);
  106036. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106037. lengthInSamples = tempLength;
  106038. }
  106039. }
  106040. }
  106041. ~FlacReader()
  106042. {
  106043. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106044. }
  106045. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106046. {
  106047. sampleRate = info.sample_rate;
  106048. bitsPerSample = info.bits_per_sample;
  106049. lengthInSamples = (unsigned int) info.total_samples;
  106050. numChannels = info.channels;
  106051. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106052. }
  106053. // returns the number of samples read
  106054. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106055. int64 startSampleInFile, int numSamples)
  106056. {
  106057. using namespace FlacNamespace;
  106058. if (! ok)
  106059. return false;
  106060. while (numSamples > 0)
  106061. {
  106062. if (startSampleInFile >= reservoirStart
  106063. && startSampleInFile < reservoirStart + samplesInReservoir)
  106064. {
  106065. const int num = (int) jmin ((int64) numSamples,
  106066. reservoirStart + samplesInReservoir - startSampleInFile);
  106067. jassert (num > 0);
  106068. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106069. if (destSamples[i] != 0)
  106070. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106071. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106072. sizeof (int) * num);
  106073. startOffsetInDestBuffer += num;
  106074. startSampleInFile += num;
  106075. numSamples -= num;
  106076. }
  106077. else
  106078. {
  106079. if (startSampleInFile >= (int) lengthInSamples)
  106080. {
  106081. samplesInReservoir = 0;
  106082. }
  106083. else if (startSampleInFile < reservoirStart
  106084. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106085. {
  106086. // had some problems with flac crashing if the read pos is aligned more
  106087. // accurately than this. Probably fixed in newer versions of the library, though.
  106088. reservoirStart = (int) (startSampleInFile & ~511);
  106089. samplesInReservoir = 0;
  106090. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106091. }
  106092. else
  106093. {
  106094. reservoirStart += samplesInReservoir;
  106095. samplesInReservoir = 0;
  106096. FLAC__stream_decoder_process_single (decoder);
  106097. }
  106098. if (samplesInReservoir == 0)
  106099. break;
  106100. }
  106101. }
  106102. if (numSamples > 0)
  106103. {
  106104. for (int i = numDestChannels; --i >= 0;)
  106105. if (destSamples[i] != 0)
  106106. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106107. sizeof (int) * numSamples);
  106108. }
  106109. return true;
  106110. }
  106111. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106112. {
  106113. if (scanningForLength)
  106114. {
  106115. lengthInSamples += numSamples;
  106116. }
  106117. else
  106118. {
  106119. if (numSamples > reservoir.getNumSamples())
  106120. reservoir.setSize (numChannels, numSamples, false, false, true);
  106121. const int bitsToShift = 32 - bitsPerSample;
  106122. for (int i = 0; i < (int) numChannels; ++i)
  106123. {
  106124. const FlacNamespace::FLAC__int32* src = buffer[i];
  106125. int n = i;
  106126. while (src == 0 && n > 0)
  106127. src = buffer [--n];
  106128. if (src != 0)
  106129. {
  106130. int* dest = (int*) reservoir.getSampleData(i);
  106131. for (int j = 0; j < numSamples; ++j)
  106132. dest[j] = src[j] << bitsToShift;
  106133. }
  106134. }
  106135. samplesInReservoir = numSamples;
  106136. }
  106137. }
  106138. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106139. {
  106140. using namespace FlacNamespace;
  106141. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106142. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106143. }
  106144. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106145. {
  106146. using namespace FlacNamespace;
  106147. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106148. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106149. }
  106150. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106151. {
  106152. using namespace FlacNamespace;
  106153. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106154. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106155. }
  106156. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106157. {
  106158. using namespace FlacNamespace;
  106159. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106160. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106161. }
  106162. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106163. {
  106164. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106165. }
  106166. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106167. const FlacNamespace::FLAC__Frame* frame,
  106168. const FlacNamespace::FLAC__int32* const buffer[],
  106169. void* client_data)
  106170. {
  106171. using namespace FlacNamespace;
  106172. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106173. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106174. }
  106175. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106176. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106177. void* client_data)
  106178. {
  106179. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106180. }
  106181. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106182. {
  106183. }
  106184. juce_UseDebuggingNewOperator
  106185. private:
  106186. FlacNamespace::FLAC__StreamDecoder* decoder;
  106187. AudioSampleBuffer reservoir;
  106188. int reservoirStart, samplesInReservoir;
  106189. bool ok, scanningForLength;
  106190. FlacReader (const FlacReader&);
  106191. FlacReader& operator= (const FlacReader&);
  106192. };
  106193. class FlacWriter : public AudioFormatWriter
  106194. {
  106195. public:
  106196. FlacWriter (OutputStream* const out,
  106197. const double sampleRate_,
  106198. const int numChannels_,
  106199. const int bitsPerSample_)
  106200. : AudioFormatWriter (out, TRANS (flacFormatName),
  106201. sampleRate_,
  106202. numChannels_,
  106203. bitsPerSample_)
  106204. {
  106205. using namespace FlacNamespace;
  106206. encoder = FLAC__stream_encoder_new();
  106207. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106208. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106209. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106210. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106211. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106212. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106213. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106214. ok = FLAC__stream_encoder_init_stream (encoder,
  106215. encodeWriteCallback, encodeSeekCallback,
  106216. encodeTellCallback, encodeMetadataCallback,
  106217. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106218. }
  106219. ~FlacWriter()
  106220. {
  106221. if (ok)
  106222. {
  106223. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106224. output->flush();
  106225. }
  106226. else
  106227. {
  106228. output = 0; // to stop the base class deleting this, as it needs to be returned
  106229. // to the caller of createWriter()
  106230. }
  106231. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106232. }
  106233. bool write (const int** samplesToWrite, int numSamples)
  106234. {
  106235. using namespace FlacNamespace;
  106236. if (! ok)
  106237. return false;
  106238. int* buf[3];
  106239. const int bitsToShift = 32 - bitsPerSample;
  106240. if (bitsToShift > 0)
  106241. {
  106242. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106243. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106244. buf[0] = (int*) temp.getData();
  106245. buf[1] = buf[0] + numSamples;
  106246. buf[2] = 0;
  106247. for (int i = numChannelsToWrite; --i >= 0;)
  106248. {
  106249. if (samplesToWrite[i] != 0)
  106250. {
  106251. for (int j = 0; j < numSamples; ++j)
  106252. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106253. }
  106254. }
  106255. samplesToWrite = (const int**) buf;
  106256. }
  106257. return FLAC__stream_encoder_process (encoder,
  106258. (const FLAC__int32**) samplesToWrite,
  106259. numSamples) != 0;
  106260. }
  106261. bool writeData (const void* const data, const int size) const
  106262. {
  106263. return output->write (data, size);
  106264. }
  106265. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106266. {
  106267. using namespace FlacNamespace;
  106268. b += bytes;
  106269. for (int i = 0; i < bytes; ++i)
  106270. {
  106271. *(--b) = (FLAC__byte) (val & 0xff);
  106272. val >>= 8;
  106273. }
  106274. }
  106275. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106276. {
  106277. using namespace FlacNamespace;
  106278. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106279. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106280. const unsigned int channelsMinus1 = info.channels - 1;
  106281. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106282. packUint32 (info.min_blocksize, buffer, 2);
  106283. packUint32 (info.max_blocksize, buffer + 2, 2);
  106284. packUint32 (info.min_framesize, buffer + 4, 3);
  106285. packUint32 (info.max_framesize, buffer + 7, 3);
  106286. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106287. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106288. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106289. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106290. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106291. memcpy (buffer + 18, info.md5sum, 16);
  106292. const bool seekOk = output->setPosition (4);
  106293. (void) seekOk;
  106294. // if this fails, you've given it an output stream that can't seek! It needs
  106295. // to be able to seek back to write the header
  106296. jassert (seekOk);
  106297. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106298. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106299. }
  106300. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106301. const FlacNamespace::FLAC__byte buffer[],
  106302. size_t bytes,
  106303. unsigned int /*samples*/,
  106304. unsigned int /*current_frame*/,
  106305. void* client_data)
  106306. {
  106307. using namespace FlacNamespace;
  106308. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106309. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106310. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106311. }
  106312. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106313. {
  106314. using namespace FlacNamespace;
  106315. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106316. }
  106317. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106318. {
  106319. using namespace FlacNamespace;
  106320. if (client_data == 0)
  106321. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106322. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106323. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106324. }
  106325. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106326. {
  106327. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106328. }
  106329. juce_UseDebuggingNewOperator
  106330. bool ok;
  106331. private:
  106332. FlacNamespace::FLAC__StreamEncoder* encoder;
  106333. MemoryBlock temp;
  106334. FlacWriter (const FlacWriter&);
  106335. FlacWriter& operator= (const FlacWriter&);
  106336. };
  106337. FlacAudioFormat::FlacAudioFormat()
  106338. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106339. {
  106340. }
  106341. FlacAudioFormat::~FlacAudioFormat()
  106342. {
  106343. }
  106344. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106345. {
  106346. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106347. return Array <int> (rates);
  106348. }
  106349. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106350. {
  106351. const int depths[] = { 16, 24, 0 };
  106352. return Array <int> (depths);
  106353. }
  106354. bool FlacAudioFormat::canDoStereo()
  106355. {
  106356. return true;
  106357. }
  106358. bool FlacAudioFormat::canDoMono()
  106359. {
  106360. return true;
  106361. }
  106362. bool FlacAudioFormat::isCompressed()
  106363. {
  106364. return true;
  106365. }
  106366. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106367. const bool deleteStreamIfOpeningFails)
  106368. {
  106369. ScopedPointer<FlacReader> r (new FlacReader (in));
  106370. if (r->sampleRate != 0)
  106371. return r.release();
  106372. if (! deleteStreamIfOpeningFails)
  106373. r->input = 0;
  106374. return 0;
  106375. }
  106376. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106377. double sampleRate,
  106378. unsigned int numberOfChannels,
  106379. int bitsPerSample,
  106380. const StringPairArray& /*metadataValues*/,
  106381. int /*qualityOptionIndex*/)
  106382. {
  106383. if (getPossibleBitDepths().contains (bitsPerSample))
  106384. {
  106385. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106386. if (w->ok)
  106387. return w.release();
  106388. }
  106389. return 0;
  106390. }
  106391. END_JUCE_NAMESPACE
  106392. #endif
  106393. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106394. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106395. #if JUCE_USE_OGGVORBIS
  106396. #if JUCE_MAC
  106397. #define __MACOSX__ 1
  106398. #endif
  106399. namespace OggVorbisNamespace
  106400. {
  106401. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106402. /*** Start of inlined file: vorbisenc.h ***/
  106403. #ifndef _OV_ENC_H_
  106404. #define _OV_ENC_H_
  106405. #ifdef __cplusplus
  106406. extern "C"
  106407. {
  106408. #endif /* __cplusplus */
  106409. /*** Start of inlined file: codec.h ***/
  106410. #ifndef _vorbis_codec_h_
  106411. #define _vorbis_codec_h_
  106412. #ifdef __cplusplus
  106413. extern "C"
  106414. {
  106415. #endif /* __cplusplus */
  106416. /*** Start of inlined file: ogg.h ***/
  106417. #ifndef _OGG_H
  106418. #define _OGG_H
  106419. #ifdef __cplusplus
  106420. extern "C" {
  106421. #endif
  106422. /*** Start of inlined file: os_types.h ***/
  106423. #ifndef _OS_TYPES_H
  106424. #define _OS_TYPES_H
  106425. /* make it easy on the folks that want to compile the libs with a
  106426. different malloc than stdlib */
  106427. #define _ogg_malloc malloc
  106428. #define _ogg_calloc calloc
  106429. #define _ogg_realloc realloc
  106430. #define _ogg_free free
  106431. #if defined(_WIN32)
  106432. # if defined(__CYGWIN__)
  106433. # include <_G_config.h>
  106434. typedef _G_int64_t ogg_int64_t;
  106435. typedef _G_int32_t ogg_int32_t;
  106436. typedef _G_uint32_t ogg_uint32_t;
  106437. typedef _G_int16_t ogg_int16_t;
  106438. typedef _G_uint16_t ogg_uint16_t;
  106439. # elif defined(__MINGW32__)
  106440. typedef short ogg_int16_t;
  106441. typedef unsigned short ogg_uint16_t;
  106442. typedef int ogg_int32_t;
  106443. typedef unsigned int ogg_uint32_t;
  106444. typedef long long ogg_int64_t;
  106445. typedef unsigned long long ogg_uint64_t;
  106446. # elif defined(__MWERKS__)
  106447. typedef long long ogg_int64_t;
  106448. typedef int ogg_int32_t;
  106449. typedef unsigned int ogg_uint32_t;
  106450. typedef short ogg_int16_t;
  106451. typedef unsigned short ogg_uint16_t;
  106452. # else
  106453. /* MSVC/Borland */
  106454. typedef __int64 ogg_int64_t;
  106455. typedef __int32 ogg_int32_t;
  106456. typedef unsigned __int32 ogg_uint32_t;
  106457. typedef __int16 ogg_int16_t;
  106458. typedef unsigned __int16 ogg_uint16_t;
  106459. # endif
  106460. #elif defined(__MACOS__)
  106461. # include <sys/types.h>
  106462. typedef SInt16 ogg_int16_t;
  106463. typedef UInt16 ogg_uint16_t;
  106464. typedef SInt32 ogg_int32_t;
  106465. typedef UInt32 ogg_uint32_t;
  106466. typedef SInt64 ogg_int64_t;
  106467. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106468. # include <sys/types.h>
  106469. typedef int16_t ogg_int16_t;
  106470. typedef u_int16_t ogg_uint16_t;
  106471. typedef int32_t ogg_int32_t;
  106472. typedef u_int32_t ogg_uint32_t;
  106473. typedef int64_t ogg_int64_t;
  106474. #elif defined(__BEOS__)
  106475. /* Be */
  106476. # include <inttypes.h>
  106477. typedef int16_t ogg_int16_t;
  106478. typedef u_int16_t ogg_uint16_t;
  106479. typedef int32_t ogg_int32_t;
  106480. typedef u_int32_t ogg_uint32_t;
  106481. typedef int64_t ogg_int64_t;
  106482. #elif defined (__EMX__)
  106483. /* OS/2 GCC */
  106484. typedef short ogg_int16_t;
  106485. typedef unsigned short ogg_uint16_t;
  106486. typedef int ogg_int32_t;
  106487. typedef unsigned int ogg_uint32_t;
  106488. typedef long long ogg_int64_t;
  106489. #elif defined (DJGPP)
  106490. /* DJGPP */
  106491. typedef short ogg_int16_t;
  106492. typedef int ogg_int32_t;
  106493. typedef unsigned int ogg_uint32_t;
  106494. typedef long long ogg_int64_t;
  106495. #elif defined(R5900)
  106496. /* PS2 EE */
  106497. typedef long ogg_int64_t;
  106498. typedef int ogg_int32_t;
  106499. typedef unsigned ogg_uint32_t;
  106500. typedef short ogg_int16_t;
  106501. #elif defined(__SYMBIAN32__)
  106502. /* Symbian GCC */
  106503. typedef signed short ogg_int16_t;
  106504. typedef unsigned short ogg_uint16_t;
  106505. typedef signed int ogg_int32_t;
  106506. typedef unsigned int ogg_uint32_t;
  106507. typedef long long int ogg_int64_t;
  106508. #else
  106509. # include <sys/types.h>
  106510. /*** Start of inlined file: config_types.h ***/
  106511. #ifndef __CONFIG_TYPES_H__
  106512. #define __CONFIG_TYPES_H__
  106513. typedef int16_t ogg_int16_t;
  106514. typedef unsigned short ogg_uint16_t;
  106515. typedef int32_t ogg_int32_t;
  106516. typedef unsigned int ogg_uint32_t;
  106517. typedef int64_t ogg_int64_t;
  106518. #endif
  106519. /*** End of inlined file: config_types.h ***/
  106520. #endif
  106521. #endif /* _OS_TYPES_H */
  106522. /*** End of inlined file: os_types.h ***/
  106523. typedef struct {
  106524. long endbyte;
  106525. int endbit;
  106526. unsigned char *buffer;
  106527. unsigned char *ptr;
  106528. long storage;
  106529. } oggpack_buffer;
  106530. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106531. typedef struct {
  106532. unsigned char *header;
  106533. long header_len;
  106534. unsigned char *body;
  106535. long body_len;
  106536. } ogg_page;
  106537. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106538. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106539. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106540. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106541. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106542. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106543. }
  106544. /* ogg_stream_state contains the current encode/decode state of a logical
  106545. Ogg bitstream **********************************************************/
  106546. typedef struct {
  106547. unsigned char *body_data; /* bytes from packet bodies */
  106548. long body_storage; /* storage elements allocated */
  106549. long body_fill; /* elements stored; fill mark */
  106550. long body_returned; /* elements of fill returned */
  106551. int *lacing_vals; /* The values that will go to the segment table */
  106552. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106553. this way, but it is simple coupled to the
  106554. lacing fifo */
  106555. long lacing_storage;
  106556. long lacing_fill;
  106557. long lacing_packet;
  106558. long lacing_returned;
  106559. unsigned char header[282]; /* working space for header encode */
  106560. int header_fill;
  106561. int e_o_s; /* set when we have buffered the last packet in the
  106562. logical bitstream */
  106563. int b_o_s; /* set after we've written the initial page
  106564. of a logical bitstream */
  106565. long serialno;
  106566. long pageno;
  106567. ogg_int64_t packetno; /* sequence number for decode; the framing
  106568. knows where there's a hole in the data,
  106569. but we need coupling so that the codec
  106570. (which is in a seperate abstraction
  106571. layer) also knows about the gap */
  106572. ogg_int64_t granulepos;
  106573. } ogg_stream_state;
  106574. /* ogg_packet is used to encapsulate the data and metadata belonging
  106575. to a single raw Ogg/Vorbis packet *************************************/
  106576. typedef struct {
  106577. unsigned char *packet;
  106578. long bytes;
  106579. long b_o_s;
  106580. long e_o_s;
  106581. ogg_int64_t granulepos;
  106582. ogg_int64_t packetno; /* sequence number for decode; the framing
  106583. knows where there's a hole in the data,
  106584. but we need coupling so that the codec
  106585. (which is in a seperate abstraction
  106586. layer) also knows about the gap */
  106587. } ogg_packet;
  106588. typedef struct {
  106589. unsigned char *data;
  106590. int storage;
  106591. int fill;
  106592. int returned;
  106593. int unsynced;
  106594. int headerbytes;
  106595. int bodybytes;
  106596. } ogg_sync_state;
  106597. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106598. extern void oggpack_writeinit(oggpack_buffer *b);
  106599. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106600. extern void oggpack_writealign(oggpack_buffer *b);
  106601. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106602. extern void oggpack_reset(oggpack_buffer *b);
  106603. extern void oggpack_writeclear(oggpack_buffer *b);
  106604. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106605. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106606. extern long oggpack_look(oggpack_buffer *b,int bits);
  106607. extern long oggpack_look1(oggpack_buffer *b);
  106608. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106609. extern void oggpack_adv1(oggpack_buffer *b);
  106610. extern long oggpack_read(oggpack_buffer *b,int bits);
  106611. extern long oggpack_read1(oggpack_buffer *b);
  106612. extern long oggpack_bytes(oggpack_buffer *b);
  106613. extern long oggpack_bits(oggpack_buffer *b);
  106614. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106615. extern void oggpackB_writeinit(oggpack_buffer *b);
  106616. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106617. extern void oggpackB_writealign(oggpack_buffer *b);
  106618. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106619. extern void oggpackB_reset(oggpack_buffer *b);
  106620. extern void oggpackB_writeclear(oggpack_buffer *b);
  106621. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106622. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106623. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106624. extern long oggpackB_look1(oggpack_buffer *b);
  106625. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106626. extern void oggpackB_adv1(oggpack_buffer *b);
  106627. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106628. extern long oggpackB_read1(oggpack_buffer *b);
  106629. extern long oggpackB_bytes(oggpack_buffer *b);
  106630. extern long oggpackB_bits(oggpack_buffer *b);
  106631. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106632. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106633. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106634. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106635. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106636. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106637. extern int ogg_sync_init(ogg_sync_state *oy);
  106638. extern int ogg_sync_clear(ogg_sync_state *oy);
  106639. extern int ogg_sync_reset(ogg_sync_state *oy);
  106640. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106641. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106642. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106643. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106644. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106645. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106646. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106647. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106648. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106649. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106650. extern int ogg_stream_clear(ogg_stream_state *os);
  106651. extern int ogg_stream_reset(ogg_stream_state *os);
  106652. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106653. extern int ogg_stream_destroy(ogg_stream_state *os);
  106654. extern int ogg_stream_eos(ogg_stream_state *os);
  106655. extern void ogg_page_checksum_set(ogg_page *og);
  106656. extern int ogg_page_version(ogg_page *og);
  106657. extern int ogg_page_continued(ogg_page *og);
  106658. extern int ogg_page_bos(ogg_page *og);
  106659. extern int ogg_page_eos(ogg_page *og);
  106660. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106661. extern int ogg_page_serialno(ogg_page *og);
  106662. extern long ogg_page_pageno(ogg_page *og);
  106663. extern int ogg_page_packets(ogg_page *og);
  106664. extern void ogg_packet_clear(ogg_packet *op);
  106665. #ifdef __cplusplus
  106666. }
  106667. #endif
  106668. #endif /* _OGG_H */
  106669. /*** End of inlined file: ogg.h ***/
  106670. typedef struct vorbis_info{
  106671. int version;
  106672. int channels;
  106673. long rate;
  106674. /* The below bitrate declarations are *hints*.
  106675. Combinations of the three values carry the following implications:
  106676. all three set to the same value:
  106677. implies a fixed rate bitstream
  106678. only nominal set:
  106679. implies a VBR stream that averages the nominal bitrate. No hard
  106680. upper/lower limit
  106681. upper and or lower set:
  106682. implies a VBR bitstream that obeys the bitrate limits. nominal
  106683. may also be set to give a nominal rate.
  106684. none set:
  106685. the coder does not care to speculate.
  106686. */
  106687. long bitrate_upper;
  106688. long bitrate_nominal;
  106689. long bitrate_lower;
  106690. long bitrate_window;
  106691. void *codec_setup;
  106692. } vorbis_info;
  106693. /* vorbis_dsp_state buffers the current vorbis audio
  106694. analysis/synthesis state. The DSP state belongs to a specific
  106695. logical bitstream ****************************************************/
  106696. typedef struct vorbis_dsp_state{
  106697. int analysisp;
  106698. vorbis_info *vi;
  106699. float **pcm;
  106700. float **pcmret;
  106701. int pcm_storage;
  106702. int pcm_current;
  106703. int pcm_returned;
  106704. int preextrapolate;
  106705. int eofflag;
  106706. long lW;
  106707. long W;
  106708. long nW;
  106709. long centerW;
  106710. ogg_int64_t granulepos;
  106711. ogg_int64_t sequence;
  106712. ogg_int64_t glue_bits;
  106713. ogg_int64_t time_bits;
  106714. ogg_int64_t floor_bits;
  106715. ogg_int64_t res_bits;
  106716. void *backend_state;
  106717. } vorbis_dsp_state;
  106718. typedef struct vorbis_block{
  106719. /* necessary stream state for linking to the framing abstraction */
  106720. float **pcm; /* this is a pointer into local storage */
  106721. oggpack_buffer opb;
  106722. long lW;
  106723. long W;
  106724. long nW;
  106725. int pcmend;
  106726. int mode;
  106727. int eofflag;
  106728. ogg_int64_t granulepos;
  106729. ogg_int64_t sequence;
  106730. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106731. /* local storage to avoid remallocing; it's up to the mapping to
  106732. structure it */
  106733. void *localstore;
  106734. long localtop;
  106735. long localalloc;
  106736. long totaluse;
  106737. struct alloc_chain *reap;
  106738. /* bitmetrics for the frame */
  106739. long glue_bits;
  106740. long time_bits;
  106741. long floor_bits;
  106742. long res_bits;
  106743. void *internal;
  106744. } vorbis_block;
  106745. /* vorbis_block is a single block of data to be processed as part of
  106746. the analysis/synthesis stream; it belongs to a specific logical
  106747. bitstream, but is independant from other vorbis_blocks belonging to
  106748. that logical bitstream. *************************************************/
  106749. struct alloc_chain{
  106750. void *ptr;
  106751. struct alloc_chain *next;
  106752. };
  106753. /* vorbis_info contains all the setup information specific to the
  106754. specific compression/decompression mode in progress (eg,
  106755. psychoacoustic settings, channel setup, options, codebook
  106756. etc). vorbis_info and substructures are in backends.h.
  106757. *********************************************************************/
  106758. /* the comments are not part of vorbis_info so that vorbis_info can be
  106759. static storage */
  106760. typedef struct vorbis_comment{
  106761. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106762. whatever vendor is set to in encode */
  106763. char **user_comments;
  106764. int *comment_lengths;
  106765. int comments;
  106766. char *vendor;
  106767. } vorbis_comment;
  106768. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106769. and produce a packet (see docs/analysis.txt). The packet is then
  106770. coded into a framed OggSquish bitstream by the second layer (see
  106771. docs/framing.txt). Decode is the reverse process; we sync/frame
  106772. the bitstream and extract individual packets, then decode the
  106773. packet back into PCM audio.
  106774. The extra framing/packetizing is used in streaming formats, such as
  106775. files. Over the net (such as with UDP), the framing and
  106776. packetization aren't necessary as they're provided by the transport
  106777. and the streaming layer is not used */
  106778. /* Vorbis PRIMITIVES: general ***************************************/
  106779. extern void vorbis_info_init(vorbis_info *vi);
  106780. extern void vorbis_info_clear(vorbis_info *vi);
  106781. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106782. extern void vorbis_comment_init(vorbis_comment *vc);
  106783. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106784. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106785. const char *tag, char *contents);
  106786. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106787. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106788. extern void vorbis_comment_clear(vorbis_comment *vc);
  106789. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106790. extern int vorbis_block_clear(vorbis_block *vb);
  106791. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106792. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106793. ogg_int64_t granulepos);
  106794. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106795. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106796. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106797. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106798. vorbis_comment *vc,
  106799. ogg_packet *op,
  106800. ogg_packet *op_comm,
  106801. ogg_packet *op_code);
  106802. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106803. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106804. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106805. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106806. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106807. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106808. ogg_packet *op);
  106809. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106810. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106811. ogg_packet *op);
  106812. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106813. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106814. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106815. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106816. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106817. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106818. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106819. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  106820. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  106821. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  106822. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  106823. /* Vorbis ERRORS and return codes ***********************************/
  106824. #define OV_FALSE -1
  106825. #define OV_EOF -2
  106826. #define OV_HOLE -3
  106827. #define OV_EREAD -128
  106828. #define OV_EFAULT -129
  106829. #define OV_EIMPL -130
  106830. #define OV_EINVAL -131
  106831. #define OV_ENOTVORBIS -132
  106832. #define OV_EBADHEADER -133
  106833. #define OV_EVERSION -134
  106834. #define OV_ENOTAUDIO -135
  106835. #define OV_EBADPACKET -136
  106836. #define OV_EBADLINK -137
  106837. #define OV_ENOSEEK -138
  106838. #ifdef __cplusplus
  106839. }
  106840. #endif /* __cplusplus */
  106841. #endif
  106842. /*** End of inlined file: codec.h ***/
  106843. extern int vorbis_encode_init(vorbis_info *vi,
  106844. long channels,
  106845. long rate,
  106846. long max_bitrate,
  106847. long nominal_bitrate,
  106848. long min_bitrate);
  106849. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  106850. long channels,
  106851. long rate,
  106852. long max_bitrate,
  106853. long nominal_bitrate,
  106854. long min_bitrate);
  106855. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  106856. long channels,
  106857. long rate,
  106858. float quality /* quality level from 0. (lo) to 1. (hi) */
  106859. );
  106860. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  106861. long channels,
  106862. long rate,
  106863. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  106864. );
  106865. extern int vorbis_encode_setup_init(vorbis_info *vi);
  106866. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  106867. /* deprecated rate management supported only for compatability */
  106868. #define OV_ECTL_RATEMANAGE_GET 0x10
  106869. #define OV_ECTL_RATEMANAGE_SET 0x11
  106870. #define OV_ECTL_RATEMANAGE_AVG 0x12
  106871. #define OV_ECTL_RATEMANAGE_HARD 0x13
  106872. struct ovectl_ratemanage_arg {
  106873. int management_active;
  106874. long bitrate_hard_min;
  106875. long bitrate_hard_max;
  106876. double bitrate_hard_window;
  106877. long bitrate_av_lo;
  106878. long bitrate_av_hi;
  106879. double bitrate_av_window;
  106880. double bitrate_av_window_center;
  106881. };
  106882. /* new rate setup */
  106883. #define OV_ECTL_RATEMANAGE2_GET 0x14
  106884. #define OV_ECTL_RATEMANAGE2_SET 0x15
  106885. struct ovectl_ratemanage2_arg {
  106886. int management_active;
  106887. long bitrate_limit_min_kbps;
  106888. long bitrate_limit_max_kbps;
  106889. long bitrate_limit_reservoir_bits;
  106890. double bitrate_limit_reservoir_bias;
  106891. long bitrate_average_kbps;
  106892. double bitrate_average_damping;
  106893. };
  106894. #define OV_ECTL_LOWPASS_GET 0x20
  106895. #define OV_ECTL_LOWPASS_SET 0x21
  106896. #define OV_ECTL_IBLOCK_GET 0x30
  106897. #define OV_ECTL_IBLOCK_SET 0x31
  106898. #ifdef __cplusplus
  106899. }
  106900. #endif /* __cplusplus */
  106901. #endif
  106902. /*** End of inlined file: vorbisenc.h ***/
  106903. /*** Start of inlined file: vorbisfile.h ***/
  106904. #ifndef _OV_FILE_H_
  106905. #define _OV_FILE_H_
  106906. #ifdef __cplusplus
  106907. extern "C"
  106908. {
  106909. #endif /* __cplusplus */
  106910. #include <stdio.h>
  106911. /* The function prototypes for the callbacks are basically the same as for
  106912. * the stdio functions fread, fseek, fclose, ftell.
  106913. * The one difference is that the FILE * arguments have been replaced with
  106914. * a void * - this is to be used as a pointer to whatever internal data these
  106915. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  106916. *
  106917. * If you use other functions, check the docs for these functions and return
  106918. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  106919. * unseekable
  106920. */
  106921. typedef struct {
  106922. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  106923. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  106924. int (*close_func) (void *datasource);
  106925. long (*tell_func) (void *datasource);
  106926. } ov_callbacks;
  106927. #define NOTOPEN 0
  106928. #define PARTOPEN 1
  106929. #define OPENED 2
  106930. #define STREAMSET 3
  106931. #define INITSET 4
  106932. typedef struct OggVorbis_File {
  106933. void *datasource; /* Pointer to a FILE *, etc. */
  106934. int seekable;
  106935. ogg_int64_t offset;
  106936. ogg_int64_t end;
  106937. ogg_sync_state oy;
  106938. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  106939. stream appears */
  106940. int links;
  106941. ogg_int64_t *offsets;
  106942. ogg_int64_t *dataoffsets;
  106943. long *serialnos;
  106944. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  106945. compatability; x2 size, stores both
  106946. beginning and end values */
  106947. vorbis_info *vi;
  106948. vorbis_comment *vc;
  106949. /* Decoding working state local storage */
  106950. ogg_int64_t pcm_offset;
  106951. int ready_state;
  106952. long current_serialno;
  106953. int current_link;
  106954. double bittrack;
  106955. double samptrack;
  106956. ogg_stream_state os; /* take physical pages, weld into a logical
  106957. stream of packets */
  106958. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  106959. vorbis_block vb; /* local working space for packet->PCM decode */
  106960. ov_callbacks callbacks;
  106961. } OggVorbis_File;
  106962. extern int ov_clear(OggVorbis_File *vf);
  106963. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106964. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  106965. char *initial, long ibytes, ov_callbacks callbacks);
  106966. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106967. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  106968. char *initial, long ibytes, ov_callbacks callbacks);
  106969. extern int ov_test_open(OggVorbis_File *vf);
  106970. extern long ov_bitrate(OggVorbis_File *vf,int i);
  106971. extern long ov_bitrate_instant(OggVorbis_File *vf);
  106972. extern long ov_streams(OggVorbis_File *vf);
  106973. extern long ov_seekable(OggVorbis_File *vf);
  106974. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  106975. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  106976. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  106977. extern double ov_time_total(OggVorbis_File *vf,int i);
  106978. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106979. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106980. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  106981. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  106982. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  106983. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106984. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106985. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106986. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  106987. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  106988. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  106989. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  106990. extern double ov_time_tell(OggVorbis_File *vf);
  106991. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  106992. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  106993. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  106994. int *bitstream);
  106995. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  106996. int bigendianp,int word,int sgned,int *bitstream);
  106997. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  106998. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  106999. extern int ov_halfrate_p(OggVorbis_File *vf);
  107000. #ifdef __cplusplus
  107001. }
  107002. #endif /* __cplusplus */
  107003. #endif
  107004. /*** End of inlined file: vorbisfile.h ***/
  107005. /*** Start of inlined file: bitwise.c ***/
  107006. /* We're 'LSb' endian; if we write a word but read individual bits,
  107007. then we'll read the lsb first */
  107008. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107009. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107010. // tasks..
  107011. #if JUCE_MSVC
  107012. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107013. #endif
  107014. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107015. #if JUCE_USE_OGGVORBIS
  107016. #include <string.h>
  107017. #include <stdlib.h>
  107018. #define BUFFER_INCREMENT 256
  107019. static const unsigned long mask[]=
  107020. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107021. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107022. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107023. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107024. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107025. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107026. 0x3fffffff,0x7fffffff,0xffffffff };
  107027. static const unsigned int mask8B[]=
  107028. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107029. void oggpack_writeinit(oggpack_buffer *b){
  107030. memset(b,0,sizeof(*b));
  107031. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107032. b->buffer[0]='\0';
  107033. b->storage=BUFFER_INCREMENT;
  107034. }
  107035. void oggpackB_writeinit(oggpack_buffer *b){
  107036. oggpack_writeinit(b);
  107037. }
  107038. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107039. long bytes=bits>>3;
  107040. bits-=bytes*8;
  107041. b->ptr=b->buffer+bytes;
  107042. b->endbit=bits;
  107043. b->endbyte=bytes;
  107044. *b->ptr&=mask[bits];
  107045. }
  107046. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107047. long bytes=bits>>3;
  107048. bits-=bytes*8;
  107049. b->ptr=b->buffer+bytes;
  107050. b->endbit=bits;
  107051. b->endbyte=bytes;
  107052. *b->ptr&=mask8B[bits];
  107053. }
  107054. /* Takes only up to 32 bits. */
  107055. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107056. if(b->endbyte+4>=b->storage){
  107057. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107058. b->storage+=BUFFER_INCREMENT;
  107059. b->ptr=b->buffer+b->endbyte;
  107060. }
  107061. value&=mask[bits];
  107062. bits+=b->endbit;
  107063. b->ptr[0]|=value<<b->endbit;
  107064. if(bits>=8){
  107065. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107066. if(bits>=16){
  107067. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107068. if(bits>=24){
  107069. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107070. if(bits>=32){
  107071. if(b->endbit)
  107072. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107073. else
  107074. b->ptr[4]=0;
  107075. }
  107076. }
  107077. }
  107078. }
  107079. b->endbyte+=bits/8;
  107080. b->ptr+=bits/8;
  107081. b->endbit=bits&7;
  107082. }
  107083. /* Takes only up to 32 bits. */
  107084. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107085. if(b->endbyte+4>=b->storage){
  107086. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107087. b->storage+=BUFFER_INCREMENT;
  107088. b->ptr=b->buffer+b->endbyte;
  107089. }
  107090. value=(value&mask[bits])<<(32-bits);
  107091. bits+=b->endbit;
  107092. b->ptr[0]|=value>>(24+b->endbit);
  107093. if(bits>=8){
  107094. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107095. if(bits>=16){
  107096. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107097. if(bits>=24){
  107098. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107099. if(bits>=32){
  107100. if(b->endbit)
  107101. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107102. else
  107103. b->ptr[4]=0;
  107104. }
  107105. }
  107106. }
  107107. }
  107108. b->endbyte+=bits/8;
  107109. b->ptr+=bits/8;
  107110. b->endbit=bits&7;
  107111. }
  107112. void oggpack_writealign(oggpack_buffer *b){
  107113. int bits=8-b->endbit;
  107114. if(bits<8)
  107115. oggpack_write(b,0,bits);
  107116. }
  107117. void oggpackB_writealign(oggpack_buffer *b){
  107118. int bits=8-b->endbit;
  107119. if(bits<8)
  107120. oggpackB_write(b,0,bits);
  107121. }
  107122. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107123. void *source,
  107124. long bits,
  107125. void (*w)(oggpack_buffer *,
  107126. unsigned long,
  107127. int),
  107128. int msb){
  107129. unsigned char *ptr=(unsigned char *)source;
  107130. long bytes=bits/8;
  107131. bits-=bytes*8;
  107132. if(b->endbit){
  107133. int i;
  107134. /* unaligned copy. Do it the hard way. */
  107135. for(i=0;i<bytes;i++)
  107136. w(b,(unsigned long)(ptr[i]),8);
  107137. }else{
  107138. /* aligned block copy */
  107139. if(b->endbyte+bytes+1>=b->storage){
  107140. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107141. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107142. b->ptr=b->buffer+b->endbyte;
  107143. }
  107144. memmove(b->ptr,source,bytes);
  107145. b->ptr+=bytes;
  107146. b->endbyte+=bytes;
  107147. *b->ptr=0;
  107148. }
  107149. if(bits){
  107150. if(msb)
  107151. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107152. else
  107153. w(b,(unsigned long)(ptr[bytes]),bits);
  107154. }
  107155. }
  107156. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107157. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107158. }
  107159. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107160. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107161. }
  107162. void oggpack_reset(oggpack_buffer *b){
  107163. b->ptr=b->buffer;
  107164. b->buffer[0]=0;
  107165. b->endbit=b->endbyte=0;
  107166. }
  107167. void oggpackB_reset(oggpack_buffer *b){
  107168. oggpack_reset(b);
  107169. }
  107170. void oggpack_writeclear(oggpack_buffer *b){
  107171. _ogg_free(b->buffer);
  107172. memset(b,0,sizeof(*b));
  107173. }
  107174. void oggpackB_writeclear(oggpack_buffer *b){
  107175. oggpack_writeclear(b);
  107176. }
  107177. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107178. memset(b,0,sizeof(*b));
  107179. b->buffer=b->ptr=buf;
  107180. b->storage=bytes;
  107181. }
  107182. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107183. oggpack_readinit(b,buf,bytes);
  107184. }
  107185. /* Read in bits without advancing the bitptr; bits <= 32 */
  107186. long oggpack_look(oggpack_buffer *b,int bits){
  107187. unsigned long ret;
  107188. unsigned long m=mask[bits];
  107189. bits+=b->endbit;
  107190. if(b->endbyte+4>=b->storage){
  107191. /* not the main path */
  107192. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107193. }
  107194. ret=b->ptr[0]>>b->endbit;
  107195. if(bits>8){
  107196. ret|=b->ptr[1]<<(8-b->endbit);
  107197. if(bits>16){
  107198. ret|=b->ptr[2]<<(16-b->endbit);
  107199. if(bits>24){
  107200. ret|=b->ptr[3]<<(24-b->endbit);
  107201. if(bits>32 && b->endbit)
  107202. ret|=b->ptr[4]<<(32-b->endbit);
  107203. }
  107204. }
  107205. }
  107206. return(m&ret);
  107207. }
  107208. /* Read in bits without advancing the bitptr; bits <= 32 */
  107209. long oggpackB_look(oggpack_buffer *b,int bits){
  107210. unsigned long ret;
  107211. int m=32-bits;
  107212. bits+=b->endbit;
  107213. if(b->endbyte+4>=b->storage){
  107214. /* not the main path */
  107215. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107216. }
  107217. ret=b->ptr[0]<<(24+b->endbit);
  107218. if(bits>8){
  107219. ret|=b->ptr[1]<<(16+b->endbit);
  107220. if(bits>16){
  107221. ret|=b->ptr[2]<<(8+b->endbit);
  107222. if(bits>24){
  107223. ret|=b->ptr[3]<<(b->endbit);
  107224. if(bits>32 && b->endbit)
  107225. ret|=b->ptr[4]>>(8-b->endbit);
  107226. }
  107227. }
  107228. }
  107229. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107230. }
  107231. long oggpack_look1(oggpack_buffer *b){
  107232. if(b->endbyte>=b->storage)return(-1);
  107233. return((b->ptr[0]>>b->endbit)&1);
  107234. }
  107235. long oggpackB_look1(oggpack_buffer *b){
  107236. if(b->endbyte>=b->storage)return(-1);
  107237. return((b->ptr[0]>>(7-b->endbit))&1);
  107238. }
  107239. void oggpack_adv(oggpack_buffer *b,int bits){
  107240. bits+=b->endbit;
  107241. b->ptr+=bits/8;
  107242. b->endbyte+=bits/8;
  107243. b->endbit=bits&7;
  107244. }
  107245. void oggpackB_adv(oggpack_buffer *b,int bits){
  107246. oggpack_adv(b,bits);
  107247. }
  107248. void oggpack_adv1(oggpack_buffer *b){
  107249. if(++(b->endbit)>7){
  107250. b->endbit=0;
  107251. b->ptr++;
  107252. b->endbyte++;
  107253. }
  107254. }
  107255. void oggpackB_adv1(oggpack_buffer *b){
  107256. oggpack_adv1(b);
  107257. }
  107258. /* bits <= 32 */
  107259. long oggpack_read(oggpack_buffer *b,int bits){
  107260. long ret;
  107261. unsigned long m=mask[bits];
  107262. bits+=b->endbit;
  107263. if(b->endbyte+4>=b->storage){
  107264. /* not the main path */
  107265. ret=-1L;
  107266. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107267. }
  107268. ret=b->ptr[0]>>b->endbit;
  107269. if(bits>8){
  107270. ret|=b->ptr[1]<<(8-b->endbit);
  107271. if(bits>16){
  107272. ret|=b->ptr[2]<<(16-b->endbit);
  107273. if(bits>24){
  107274. ret|=b->ptr[3]<<(24-b->endbit);
  107275. if(bits>32 && b->endbit){
  107276. ret|=b->ptr[4]<<(32-b->endbit);
  107277. }
  107278. }
  107279. }
  107280. }
  107281. ret&=m;
  107282. overflow:
  107283. b->ptr+=bits/8;
  107284. b->endbyte+=bits/8;
  107285. b->endbit=bits&7;
  107286. return(ret);
  107287. }
  107288. /* bits <= 32 */
  107289. long oggpackB_read(oggpack_buffer *b,int bits){
  107290. long ret;
  107291. long m=32-bits;
  107292. bits+=b->endbit;
  107293. if(b->endbyte+4>=b->storage){
  107294. /* not the main path */
  107295. ret=-1L;
  107296. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107297. }
  107298. ret=b->ptr[0]<<(24+b->endbit);
  107299. if(bits>8){
  107300. ret|=b->ptr[1]<<(16+b->endbit);
  107301. if(bits>16){
  107302. ret|=b->ptr[2]<<(8+b->endbit);
  107303. if(bits>24){
  107304. ret|=b->ptr[3]<<(b->endbit);
  107305. if(bits>32 && b->endbit)
  107306. ret|=b->ptr[4]>>(8-b->endbit);
  107307. }
  107308. }
  107309. }
  107310. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107311. overflow:
  107312. b->ptr+=bits/8;
  107313. b->endbyte+=bits/8;
  107314. b->endbit=bits&7;
  107315. return(ret);
  107316. }
  107317. long oggpack_read1(oggpack_buffer *b){
  107318. long ret;
  107319. if(b->endbyte>=b->storage){
  107320. /* not the main path */
  107321. ret=-1L;
  107322. goto overflow;
  107323. }
  107324. ret=(b->ptr[0]>>b->endbit)&1;
  107325. overflow:
  107326. b->endbit++;
  107327. if(b->endbit>7){
  107328. b->endbit=0;
  107329. b->ptr++;
  107330. b->endbyte++;
  107331. }
  107332. return(ret);
  107333. }
  107334. long oggpackB_read1(oggpack_buffer *b){
  107335. long ret;
  107336. if(b->endbyte>=b->storage){
  107337. /* not the main path */
  107338. ret=-1L;
  107339. goto overflow;
  107340. }
  107341. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107342. overflow:
  107343. b->endbit++;
  107344. if(b->endbit>7){
  107345. b->endbit=0;
  107346. b->ptr++;
  107347. b->endbyte++;
  107348. }
  107349. return(ret);
  107350. }
  107351. long oggpack_bytes(oggpack_buffer *b){
  107352. return(b->endbyte+(b->endbit+7)/8);
  107353. }
  107354. long oggpack_bits(oggpack_buffer *b){
  107355. return(b->endbyte*8+b->endbit);
  107356. }
  107357. long oggpackB_bytes(oggpack_buffer *b){
  107358. return oggpack_bytes(b);
  107359. }
  107360. long oggpackB_bits(oggpack_buffer *b){
  107361. return oggpack_bits(b);
  107362. }
  107363. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107364. return(b->buffer);
  107365. }
  107366. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107367. return oggpack_get_buffer(b);
  107368. }
  107369. /* Self test of the bitwise routines; everything else is based on
  107370. them, so they damned well better be solid. */
  107371. #ifdef _V_SELFTEST
  107372. #include <stdio.h>
  107373. static int ilog(unsigned int v){
  107374. int ret=0;
  107375. while(v){
  107376. ret++;
  107377. v>>=1;
  107378. }
  107379. return(ret);
  107380. }
  107381. oggpack_buffer o;
  107382. oggpack_buffer r;
  107383. void report(char *in){
  107384. fprintf(stderr,"%s",in);
  107385. exit(1);
  107386. }
  107387. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107388. long bytes,i;
  107389. unsigned char *buffer;
  107390. oggpack_reset(&o);
  107391. for(i=0;i<vals;i++)
  107392. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107393. buffer=oggpack_get_buffer(&o);
  107394. bytes=oggpack_bytes(&o);
  107395. if(bytes!=compsize)report("wrong number of bytes!\n");
  107396. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107397. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107398. report("wrote incorrect value!\n");
  107399. }
  107400. oggpack_readinit(&r,buffer,bytes);
  107401. for(i=0;i<vals;i++){
  107402. int tbit=bits?bits:ilog(b[i]);
  107403. if(oggpack_look(&r,tbit)==-1)
  107404. report("out of data!\n");
  107405. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107406. report("looked at incorrect value!\n");
  107407. if(tbit==1)
  107408. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107409. report("looked at single bit incorrect value!\n");
  107410. if(tbit==1){
  107411. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107412. report("read incorrect single bit value!\n");
  107413. }else{
  107414. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107415. report("read incorrect value!\n");
  107416. }
  107417. }
  107418. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107419. }
  107420. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107421. long bytes,i;
  107422. unsigned char *buffer;
  107423. oggpackB_reset(&o);
  107424. for(i=0;i<vals;i++)
  107425. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107426. buffer=oggpackB_get_buffer(&o);
  107427. bytes=oggpackB_bytes(&o);
  107428. if(bytes!=compsize)report("wrong number of bytes!\n");
  107429. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107430. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107431. report("wrote incorrect value!\n");
  107432. }
  107433. oggpackB_readinit(&r,buffer,bytes);
  107434. for(i=0;i<vals;i++){
  107435. int tbit=bits?bits:ilog(b[i]);
  107436. if(oggpackB_look(&r,tbit)==-1)
  107437. report("out of data!\n");
  107438. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107439. report("looked at incorrect value!\n");
  107440. if(tbit==1)
  107441. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107442. report("looked at single bit incorrect value!\n");
  107443. if(tbit==1){
  107444. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107445. report("read incorrect single bit value!\n");
  107446. }else{
  107447. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107448. report("read incorrect value!\n");
  107449. }
  107450. }
  107451. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107452. }
  107453. int main(void){
  107454. unsigned char *buffer;
  107455. long bytes,i;
  107456. static unsigned long testbuffer1[]=
  107457. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107458. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107459. int test1size=43;
  107460. static unsigned long testbuffer2[]=
  107461. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107462. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107463. 85525151,0,12321,1,349528352};
  107464. int test2size=21;
  107465. static unsigned long testbuffer3[]=
  107466. {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,
  107467. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107468. int test3size=56;
  107469. static unsigned long large[]=
  107470. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107471. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107472. 85525151,0,12321,1,2146528352};
  107473. int onesize=33;
  107474. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107475. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107476. 223,4};
  107477. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107478. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107479. 245,251,128};
  107480. int twosize=6;
  107481. static int two[6]={61,255,255,251,231,29};
  107482. static int twoB[6]={247,63,255,253,249,120};
  107483. int threesize=54;
  107484. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107485. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107486. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107487. 100,52,4,14,18,86,77,1};
  107488. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107489. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107490. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107491. 200,20,254,4,58,106,176,144,0};
  107492. int foursize=38;
  107493. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107494. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107495. 28,2,133,0,1};
  107496. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107497. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107498. 129,10,4,32};
  107499. int fivesize=45;
  107500. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107501. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107502. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107503. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107504. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107505. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107506. int sixsize=7;
  107507. static int six[7]={17,177,170,242,169,19,148};
  107508. static int sixB[7]={136,141,85,79,149,200,41};
  107509. /* Test read/write together */
  107510. /* Later we test against pregenerated bitstreams */
  107511. oggpack_writeinit(&o);
  107512. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107513. cliptest(testbuffer1,test1size,0,one,onesize);
  107514. fprintf(stderr,"ok.");
  107515. fprintf(stderr,"\nNull bit call (LSb): ");
  107516. cliptest(testbuffer3,test3size,0,two,twosize);
  107517. fprintf(stderr,"ok.");
  107518. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107519. cliptest(testbuffer2,test2size,0,three,threesize);
  107520. fprintf(stderr,"ok.");
  107521. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107522. oggpack_reset(&o);
  107523. for(i=0;i<test2size;i++)
  107524. oggpack_write(&o,large[i],32);
  107525. buffer=oggpack_get_buffer(&o);
  107526. bytes=oggpack_bytes(&o);
  107527. oggpack_readinit(&r,buffer,bytes);
  107528. for(i=0;i<test2size;i++){
  107529. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107530. if(oggpack_look(&r,32)!=large[i]){
  107531. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107532. oggpack_look(&r,32),large[i]);
  107533. report("read incorrect value!\n");
  107534. }
  107535. oggpack_adv(&r,32);
  107536. }
  107537. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107538. fprintf(stderr,"ok.");
  107539. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107540. cliptest(testbuffer1,test1size,7,four,foursize);
  107541. fprintf(stderr,"ok.");
  107542. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107543. cliptest(testbuffer2,test2size,17,five,fivesize);
  107544. fprintf(stderr,"ok.");
  107545. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107546. cliptest(testbuffer3,test3size,1,six,sixsize);
  107547. fprintf(stderr,"ok.");
  107548. fprintf(stderr,"\nTesting read past end (LSb): ");
  107549. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107550. for(i=0;i<64;i++){
  107551. if(oggpack_read(&r,1)!=0){
  107552. fprintf(stderr,"failed; got -1 prematurely.\n");
  107553. exit(1);
  107554. }
  107555. }
  107556. if(oggpack_look(&r,1)!=-1 ||
  107557. oggpack_read(&r,1)!=-1){
  107558. fprintf(stderr,"failed; read past end without -1.\n");
  107559. exit(1);
  107560. }
  107561. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107562. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107563. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107564. exit(1);
  107565. }
  107566. if(oggpack_look(&r,18)!=0 ||
  107567. oggpack_look(&r,18)!=0){
  107568. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107569. exit(1);
  107570. }
  107571. if(oggpack_look(&r,19)!=-1 ||
  107572. oggpack_look(&r,19)!=-1){
  107573. fprintf(stderr,"failed; read past end without -1.\n");
  107574. exit(1);
  107575. }
  107576. if(oggpack_look(&r,32)!=-1 ||
  107577. oggpack_look(&r,32)!=-1){
  107578. fprintf(stderr,"failed; read past end without -1.\n");
  107579. exit(1);
  107580. }
  107581. oggpack_writeclear(&o);
  107582. fprintf(stderr,"ok.\n");
  107583. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107584. /* Test read/write together */
  107585. /* Later we test against pregenerated bitstreams */
  107586. oggpackB_writeinit(&o);
  107587. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107588. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107589. fprintf(stderr,"ok.");
  107590. fprintf(stderr,"\nNull bit call (MSb): ");
  107591. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107592. fprintf(stderr,"ok.");
  107593. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107594. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107595. fprintf(stderr,"ok.");
  107596. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107597. oggpackB_reset(&o);
  107598. for(i=0;i<test2size;i++)
  107599. oggpackB_write(&o,large[i],32);
  107600. buffer=oggpackB_get_buffer(&o);
  107601. bytes=oggpackB_bytes(&o);
  107602. oggpackB_readinit(&r,buffer,bytes);
  107603. for(i=0;i<test2size;i++){
  107604. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107605. if(oggpackB_look(&r,32)!=large[i]){
  107606. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107607. oggpackB_look(&r,32),large[i]);
  107608. report("read incorrect value!\n");
  107609. }
  107610. oggpackB_adv(&r,32);
  107611. }
  107612. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107613. fprintf(stderr,"ok.");
  107614. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107615. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107616. fprintf(stderr,"ok.");
  107617. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107618. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107619. fprintf(stderr,"ok.");
  107620. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107621. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107622. fprintf(stderr,"ok.");
  107623. fprintf(stderr,"\nTesting read past end (MSb): ");
  107624. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107625. for(i=0;i<64;i++){
  107626. if(oggpackB_read(&r,1)!=0){
  107627. fprintf(stderr,"failed; got -1 prematurely.\n");
  107628. exit(1);
  107629. }
  107630. }
  107631. if(oggpackB_look(&r,1)!=-1 ||
  107632. oggpackB_read(&r,1)!=-1){
  107633. fprintf(stderr,"failed; read past end without -1.\n");
  107634. exit(1);
  107635. }
  107636. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107637. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107638. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107639. exit(1);
  107640. }
  107641. if(oggpackB_look(&r,18)!=0 ||
  107642. oggpackB_look(&r,18)!=0){
  107643. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107644. exit(1);
  107645. }
  107646. if(oggpackB_look(&r,19)!=-1 ||
  107647. oggpackB_look(&r,19)!=-1){
  107648. fprintf(stderr,"failed; read past end without -1.\n");
  107649. exit(1);
  107650. }
  107651. if(oggpackB_look(&r,32)!=-1 ||
  107652. oggpackB_look(&r,32)!=-1){
  107653. fprintf(stderr,"failed; read past end without -1.\n");
  107654. exit(1);
  107655. }
  107656. oggpackB_writeclear(&o);
  107657. fprintf(stderr,"ok.\n\n");
  107658. return(0);
  107659. }
  107660. #endif /* _V_SELFTEST */
  107661. #undef BUFFER_INCREMENT
  107662. #endif
  107663. /*** End of inlined file: bitwise.c ***/
  107664. /*** Start of inlined file: framing.c ***/
  107665. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107666. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107667. // tasks..
  107668. #if JUCE_MSVC
  107669. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107670. #endif
  107671. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107672. #if JUCE_USE_OGGVORBIS
  107673. #include <stdlib.h>
  107674. #include <string.h>
  107675. /* A complete description of Ogg framing exists in docs/framing.html */
  107676. int ogg_page_version(ogg_page *og){
  107677. return((int)(og->header[4]));
  107678. }
  107679. int ogg_page_continued(ogg_page *og){
  107680. return((int)(og->header[5]&0x01));
  107681. }
  107682. int ogg_page_bos(ogg_page *og){
  107683. return((int)(og->header[5]&0x02));
  107684. }
  107685. int ogg_page_eos(ogg_page *og){
  107686. return((int)(og->header[5]&0x04));
  107687. }
  107688. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107689. unsigned char *page=og->header;
  107690. ogg_int64_t granulepos=page[13]&(0xff);
  107691. granulepos= (granulepos<<8)|(page[12]&0xff);
  107692. granulepos= (granulepos<<8)|(page[11]&0xff);
  107693. granulepos= (granulepos<<8)|(page[10]&0xff);
  107694. granulepos= (granulepos<<8)|(page[9]&0xff);
  107695. granulepos= (granulepos<<8)|(page[8]&0xff);
  107696. granulepos= (granulepos<<8)|(page[7]&0xff);
  107697. granulepos= (granulepos<<8)|(page[6]&0xff);
  107698. return(granulepos);
  107699. }
  107700. int ogg_page_serialno(ogg_page *og){
  107701. return(og->header[14] |
  107702. (og->header[15]<<8) |
  107703. (og->header[16]<<16) |
  107704. (og->header[17]<<24));
  107705. }
  107706. long ogg_page_pageno(ogg_page *og){
  107707. return(og->header[18] |
  107708. (og->header[19]<<8) |
  107709. (og->header[20]<<16) |
  107710. (og->header[21]<<24));
  107711. }
  107712. /* returns the number of packets that are completed on this page (if
  107713. the leading packet is begun on a previous page, but ends on this
  107714. page, it's counted */
  107715. /* NOTE:
  107716. If a page consists of a packet begun on a previous page, and a new
  107717. packet begun (but not completed) on this page, the return will be:
  107718. ogg_page_packets(page) ==1,
  107719. ogg_page_continued(page) !=0
  107720. If a page happens to be a single packet that was begun on a
  107721. previous page, and spans to the next page (in the case of a three or
  107722. more page packet), the return will be:
  107723. ogg_page_packets(page) ==0,
  107724. ogg_page_continued(page) !=0
  107725. */
  107726. int ogg_page_packets(ogg_page *og){
  107727. int i,n=og->header[26],count=0;
  107728. for(i=0;i<n;i++)
  107729. if(og->header[27+i]<255)count++;
  107730. return(count);
  107731. }
  107732. #if 0
  107733. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107734. use the static init below) */
  107735. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107736. int i;
  107737. unsigned long r;
  107738. r = index << 24;
  107739. for (i=0; i<8; i++)
  107740. if (r & 0x80000000UL)
  107741. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107742. polynomial, although we use an
  107743. unreflected alg and an init/final
  107744. of 0, not 0xffffffff */
  107745. else
  107746. r<<=1;
  107747. return (r & 0xffffffffUL);
  107748. }
  107749. #endif
  107750. static const ogg_uint32_t crc_lookup[256]={
  107751. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107752. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107753. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107754. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107755. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107756. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107757. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107758. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107759. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107760. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107761. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107762. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107763. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107764. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107765. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107766. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107767. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107768. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107769. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107770. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107771. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107772. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107773. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107774. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107775. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107776. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107777. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107778. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107779. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107780. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107781. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107782. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107783. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107784. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107785. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107786. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107787. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107788. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107789. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107790. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107791. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107792. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107793. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107794. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107795. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107796. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107797. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107798. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107799. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107800. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107801. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107802. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107803. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107804. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107805. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107806. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107807. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107808. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107809. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107810. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107811. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107812. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107813. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107814. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107815. /* init the encode/decode logical stream state */
  107816. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107817. if(os){
  107818. memset(os,0,sizeof(*os));
  107819. os->body_storage=16*1024;
  107820. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  107821. os->lacing_storage=1024;
  107822. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  107823. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  107824. os->serialno=serialno;
  107825. return(0);
  107826. }
  107827. return(-1);
  107828. }
  107829. /* _clear does not free os, only the non-flat storage within */
  107830. int ogg_stream_clear(ogg_stream_state *os){
  107831. if(os){
  107832. if(os->body_data)_ogg_free(os->body_data);
  107833. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  107834. if(os->granule_vals)_ogg_free(os->granule_vals);
  107835. memset(os,0,sizeof(*os));
  107836. }
  107837. return(0);
  107838. }
  107839. int ogg_stream_destroy(ogg_stream_state *os){
  107840. if(os){
  107841. ogg_stream_clear(os);
  107842. _ogg_free(os);
  107843. }
  107844. return(0);
  107845. }
  107846. /* Helpers for ogg_stream_encode; this keeps the structure and
  107847. what's happening fairly clear */
  107848. static void _os_body_expand(ogg_stream_state *os,int needed){
  107849. if(os->body_storage<=os->body_fill+needed){
  107850. os->body_storage+=(needed+1024);
  107851. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  107852. }
  107853. }
  107854. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  107855. if(os->lacing_storage<=os->lacing_fill+needed){
  107856. os->lacing_storage+=(needed+32);
  107857. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  107858. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  107859. }
  107860. }
  107861. /* checksum the page */
  107862. /* Direct table CRC; note that this will be faster in the future if we
  107863. perform the checksum silmultaneously with other copies */
  107864. void ogg_page_checksum_set(ogg_page *og){
  107865. if(og){
  107866. ogg_uint32_t crc_reg=0;
  107867. int i;
  107868. /* safety; needed for API behavior, but not framing code */
  107869. og->header[22]=0;
  107870. og->header[23]=0;
  107871. og->header[24]=0;
  107872. og->header[25]=0;
  107873. for(i=0;i<og->header_len;i++)
  107874. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  107875. for(i=0;i<og->body_len;i++)
  107876. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  107877. og->header[22]=(unsigned char)(crc_reg&0xff);
  107878. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  107879. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  107880. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  107881. }
  107882. }
  107883. /* submit data to the internal buffer of the framing engine */
  107884. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  107885. int lacing_vals=op->bytes/255+1,i;
  107886. if(os->body_returned){
  107887. /* advance packet data according to the body_returned pointer. We
  107888. had to keep it around to return a pointer into the buffer last
  107889. call */
  107890. os->body_fill-=os->body_returned;
  107891. if(os->body_fill)
  107892. memmove(os->body_data,os->body_data+os->body_returned,
  107893. os->body_fill);
  107894. os->body_returned=0;
  107895. }
  107896. /* make sure we have the buffer storage */
  107897. _os_body_expand(os,op->bytes);
  107898. _os_lacing_expand(os,lacing_vals);
  107899. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  107900. the liability of overly clean abstraction for the time being. It
  107901. will actually be fairly easy to eliminate the extra copy in the
  107902. future */
  107903. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  107904. os->body_fill+=op->bytes;
  107905. /* Store lacing vals for this packet */
  107906. for(i=0;i<lacing_vals-1;i++){
  107907. os->lacing_vals[os->lacing_fill+i]=255;
  107908. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  107909. }
  107910. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  107911. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  107912. /* flag the first segment as the beginning of the packet */
  107913. os->lacing_vals[os->lacing_fill]|= 0x100;
  107914. os->lacing_fill+=lacing_vals;
  107915. /* for the sake of completeness */
  107916. os->packetno++;
  107917. if(op->e_o_s)os->e_o_s=1;
  107918. return(0);
  107919. }
  107920. /* This will flush remaining packets into a page (returning nonzero),
  107921. even if there is not enough data to trigger a flush normally
  107922. (undersized page). If there are no packets or partial packets to
  107923. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  107924. try to flush a normal sized page like ogg_stream_pageout; a call to
  107925. ogg_stream_flush does not guarantee that all packets have flushed.
  107926. Only a return value of 0 from ogg_stream_flush indicates all packet
  107927. data is flushed into pages.
  107928. since ogg_stream_flush will flush the last page in a stream even if
  107929. it's undersized, you almost certainly want to use ogg_stream_pageout
  107930. (and *not* ogg_stream_flush) unless you specifically need to flush
  107931. an page regardless of size in the middle of a stream. */
  107932. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  107933. int i;
  107934. int vals=0;
  107935. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  107936. int bytes=0;
  107937. long acc=0;
  107938. ogg_int64_t granule_pos=-1;
  107939. if(maxvals==0)return(0);
  107940. /* construct a page */
  107941. /* decide how many segments to include */
  107942. /* If this is the initial header case, the first page must only include
  107943. the initial header packet */
  107944. if(os->b_o_s==0){ /* 'initial header page' case */
  107945. granule_pos=0;
  107946. for(vals=0;vals<maxvals;vals++){
  107947. if((os->lacing_vals[vals]&0x0ff)<255){
  107948. vals++;
  107949. break;
  107950. }
  107951. }
  107952. }else{
  107953. for(vals=0;vals<maxvals;vals++){
  107954. if(acc>4096)break;
  107955. acc+=os->lacing_vals[vals]&0x0ff;
  107956. if((os->lacing_vals[vals]&0xff)<255)
  107957. granule_pos=os->granule_vals[vals];
  107958. }
  107959. }
  107960. /* construct the header in temp storage */
  107961. memcpy(os->header,"OggS",4);
  107962. /* stream structure version */
  107963. os->header[4]=0x00;
  107964. /* continued packet flag? */
  107965. os->header[5]=0x00;
  107966. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  107967. /* first page flag? */
  107968. if(os->b_o_s==0)os->header[5]|=0x02;
  107969. /* last page flag? */
  107970. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  107971. os->b_o_s=1;
  107972. /* 64 bits of PCM position */
  107973. for(i=6;i<14;i++){
  107974. os->header[i]=(unsigned char)(granule_pos&0xff);
  107975. granule_pos>>=8;
  107976. }
  107977. /* 32 bits of stream serial number */
  107978. {
  107979. long serialno=os->serialno;
  107980. for(i=14;i<18;i++){
  107981. os->header[i]=(unsigned char)(serialno&0xff);
  107982. serialno>>=8;
  107983. }
  107984. }
  107985. /* 32 bits of page counter (we have both counter and page header
  107986. because this val can roll over) */
  107987. if(os->pageno==-1)os->pageno=0; /* because someone called
  107988. stream_reset; this would be a
  107989. strange thing to do in an
  107990. encode stream, but it has
  107991. plausible uses */
  107992. {
  107993. long pageno=os->pageno++;
  107994. for(i=18;i<22;i++){
  107995. os->header[i]=(unsigned char)(pageno&0xff);
  107996. pageno>>=8;
  107997. }
  107998. }
  107999. /* zero for computation; filled in later */
  108000. os->header[22]=0;
  108001. os->header[23]=0;
  108002. os->header[24]=0;
  108003. os->header[25]=0;
  108004. /* segment table */
  108005. os->header[26]=(unsigned char)(vals&0xff);
  108006. for(i=0;i<vals;i++)
  108007. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108008. /* set pointers in the ogg_page struct */
  108009. og->header=os->header;
  108010. og->header_len=os->header_fill=vals+27;
  108011. og->body=os->body_data+os->body_returned;
  108012. og->body_len=bytes;
  108013. /* advance the lacing data and set the body_returned pointer */
  108014. os->lacing_fill-=vals;
  108015. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108016. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108017. os->body_returned+=bytes;
  108018. /* calculate the checksum */
  108019. ogg_page_checksum_set(og);
  108020. /* done */
  108021. return(1);
  108022. }
  108023. /* This constructs pages from buffered packet segments. The pointers
  108024. returned are to static buffers; do not free. The returned buffers are
  108025. good only until the next call (using the same ogg_stream_state) */
  108026. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108027. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108028. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108029. os->lacing_fill>=255 || /* 'segment table full' case */
  108030. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108031. return(ogg_stream_flush(os,og));
  108032. }
  108033. /* not enough data to construct a page and not end of stream */
  108034. return(0);
  108035. }
  108036. int ogg_stream_eos(ogg_stream_state *os){
  108037. return os->e_o_s;
  108038. }
  108039. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108040. /* This has two layers to place more of the multi-serialno and paging
  108041. control in the application's hands. First, we expose a data buffer
  108042. using ogg_sync_buffer(). The app either copies into the
  108043. buffer, or passes it directly to read(), etc. We then call
  108044. ogg_sync_wrote() to tell how many bytes we just added.
  108045. Pages are returned (pointers into the buffer in ogg_sync_state)
  108046. by ogg_sync_pageout(). The page is then submitted to
  108047. ogg_stream_pagein() along with the appropriate
  108048. ogg_stream_state* (ie, matching serialno). We then get raw
  108049. packets out calling ogg_stream_packetout() with a
  108050. ogg_stream_state. */
  108051. /* initialize the struct to a known state */
  108052. int ogg_sync_init(ogg_sync_state *oy){
  108053. if(oy){
  108054. memset(oy,0,sizeof(*oy));
  108055. }
  108056. return(0);
  108057. }
  108058. /* clear non-flat storage within */
  108059. int ogg_sync_clear(ogg_sync_state *oy){
  108060. if(oy){
  108061. if(oy->data)_ogg_free(oy->data);
  108062. ogg_sync_init(oy);
  108063. }
  108064. return(0);
  108065. }
  108066. int ogg_sync_destroy(ogg_sync_state *oy){
  108067. if(oy){
  108068. ogg_sync_clear(oy);
  108069. _ogg_free(oy);
  108070. }
  108071. return(0);
  108072. }
  108073. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108074. /* first, clear out any space that has been previously returned */
  108075. if(oy->returned){
  108076. oy->fill-=oy->returned;
  108077. if(oy->fill>0)
  108078. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108079. oy->returned=0;
  108080. }
  108081. if(size>oy->storage-oy->fill){
  108082. /* We need to extend the internal buffer */
  108083. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108084. if(oy->data)
  108085. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108086. else
  108087. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108088. oy->storage=newsize;
  108089. }
  108090. /* expose a segment at least as large as requested at the fill mark */
  108091. return((char *)oy->data+oy->fill);
  108092. }
  108093. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108094. if(oy->fill+bytes>oy->storage)return(-1);
  108095. oy->fill+=bytes;
  108096. return(0);
  108097. }
  108098. /* sync the stream. This is meant to be useful for finding page
  108099. boundaries.
  108100. return values for this:
  108101. -n) skipped n bytes
  108102. 0) page not ready; more data (no bytes skipped)
  108103. n) page synced at current location; page length n bytes
  108104. */
  108105. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108106. unsigned char *page=oy->data+oy->returned;
  108107. unsigned char *next;
  108108. long bytes=oy->fill-oy->returned;
  108109. if(oy->headerbytes==0){
  108110. int headerbytes,i;
  108111. if(bytes<27)return(0); /* not enough for a header */
  108112. /* verify capture pattern */
  108113. if(memcmp(page,"OggS",4))goto sync_fail;
  108114. headerbytes=page[26]+27;
  108115. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108116. /* count up body length in the segment table */
  108117. for(i=0;i<page[26];i++)
  108118. oy->bodybytes+=page[27+i];
  108119. oy->headerbytes=headerbytes;
  108120. }
  108121. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108122. /* The whole test page is buffered. Verify the checksum */
  108123. {
  108124. /* Grab the checksum bytes, set the header field to zero */
  108125. char chksum[4];
  108126. ogg_page log;
  108127. memcpy(chksum,page+22,4);
  108128. memset(page+22,0,4);
  108129. /* set up a temp page struct and recompute the checksum */
  108130. log.header=page;
  108131. log.header_len=oy->headerbytes;
  108132. log.body=page+oy->headerbytes;
  108133. log.body_len=oy->bodybytes;
  108134. ogg_page_checksum_set(&log);
  108135. /* Compare */
  108136. if(memcmp(chksum,page+22,4)){
  108137. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108138. at all) */
  108139. /* replace the computed checksum with the one actually read in */
  108140. memcpy(page+22,chksum,4);
  108141. /* Bad checksum. Lose sync */
  108142. goto sync_fail;
  108143. }
  108144. }
  108145. /* yes, have a whole page all ready to go */
  108146. {
  108147. unsigned char *page=oy->data+oy->returned;
  108148. long bytes;
  108149. if(og){
  108150. og->header=page;
  108151. og->header_len=oy->headerbytes;
  108152. og->body=page+oy->headerbytes;
  108153. og->body_len=oy->bodybytes;
  108154. }
  108155. oy->unsynced=0;
  108156. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108157. oy->headerbytes=0;
  108158. oy->bodybytes=0;
  108159. return(bytes);
  108160. }
  108161. sync_fail:
  108162. oy->headerbytes=0;
  108163. oy->bodybytes=0;
  108164. /* search for possible capture */
  108165. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108166. if(!next)
  108167. next=oy->data+oy->fill;
  108168. oy->returned=next-oy->data;
  108169. return(-(next-page));
  108170. }
  108171. /* sync the stream and get a page. Keep trying until we find a page.
  108172. Supress 'sync errors' after reporting the first.
  108173. return values:
  108174. -1) recapture (hole in data)
  108175. 0) need more data
  108176. 1) page returned
  108177. Returns pointers into buffered data; invalidated by next call to
  108178. _stream, _clear, _init, or _buffer */
  108179. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108180. /* all we need to do is verify a page at the head of the stream
  108181. buffer. If it doesn't verify, we look for the next potential
  108182. frame */
  108183. for(;;){
  108184. long ret=ogg_sync_pageseek(oy,og);
  108185. if(ret>0){
  108186. /* have a page */
  108187. return(1);
  108188. }
  108189. if(ret==0){
  108190. /* need more data */
  108191. return(0);
  108192. }
  108193. /* head did not start a synced page... skipped some bytes */
  108194. if(!oy->unsynced){
  108195. oy->unsynced=1;
  108196. return(-1);
  108197. }
  108198. /* loop. keep looking */
  108199. }
  108200. }
  108201. /* add the incoming page to the stream state; we decompose the page
  108202. into packet segments here as well. */
  108203. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108204. unsigned char *header=og->header;
  108205. unsigned char *body=og->body;
  108206. long bodysize=og->body_len;
  108207. int segptr=0;
  108208. int version=ogg_page_version(og);
  108209. int continued=ogg_page_continued(og);
  108210. int bos=ogg_page_bos(og);
  108211. int eos=ogg_page_eos(og);
  108212. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108213. int serialno=ogg_page_serialno(og);
  108214. long pageno=ogg_page_pageno(og);
  108215. int segments=header[26];
  108216. /* clean up 'returned data' */
  108217. {
  108218. long lr=os->lacing_returned;
  108219. long br=os->body_returned;
  108220. /* body data */
  108221. if(br){
  108222. os->body_fill-=br;
  108223. if(os->body_fill)
  108224. memmove(os->body_data,os->body_data+br,os->body_fill);
  108225. os->body_returned=0;
  108226. }
  108227. if(lr){
  108228. /* segment table */
  108229. if(os->lacing_fill-lr){
  108230. memmove(os->lacing_vals,os->lacing_vals+lr,
  108231. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108232. memmove(os->granule_vals,os->granule_vals+lr,
  108233. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108234. }
  108235. os->lacing_fill-=lr;
  108236. os->lacing_packet-=lr;
  108237. os->lacing_returned=0;
  108238. }
  108239. }
  108240. /* check the serial number */
  108241. if(serialno!=os->serialno)return(-1);
  108242. if(version>0)return(-1);
  108243. _os_lacing_expand(os,segments+1);
  108244. /* are we in sequence? */
  108245. if(pageno!=os->pageno){
  108246. int i;
  108247. /* unroll previous partial packet (if any) */
  108248. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108249. os->body_fill-=os->lacing_vals[i]&0xff;
  108250. os->lacing_fill=os->lacing_packet;
  108251. /* make a note of dropped data in segment table */
  108252. if(os->pageno!=-1){
  108253. os->lacing_vals[os->lacing_fill++]=0x400;
  108254. os->lacing_packet++;
  108255. }
  108256. }
  108257. /* are we a 'continued packet' page? If so, we may need to skip
  108258. some segments */
  108259. if(continued){
  108260. if(os->lacing_fill<1 ||
  108261. os->lacing_vals[os->lacing_fill-1]==0x400){
  108262. bos=0;
  108263. for(;segptr<segments;segptr++){
  108264. int val=header[27+segptr];
  108265. body+=val;
  108266. bodysize-=val;
  108267. if(val<255){
  108268. segptr++;
  108269. break;
  108270. }
  108271. }
  108272. }
  108273. }
  108274. if(bodysize){
  108275. _os_body_expand(os,bodysize);
  108276. memcpy(os->body_data+os->body_fill,body,bodysize);
  108277. os->body_fill+=bodysize;
  108278. }
  108279. {
  108280. int saved=-1;
  108281. while(segptr<segments){
  108282. int val=header[27+segptr];
  108283. os->lacing_vals[os->lacing_fill]=val;
  108284. os->granule_vals[os->lacing_fill]=-1;
  108285. if(bos){
  108286. os->lacing_vals[os->lacing_fill]|=0x100;
  108287. bos=0;
  108288. }
  108289. if(val<255)saved=os->lacing_fill;
  108290. os->lacing_fill++;
  108291. segptr++;
  108292. if(val<255)os->lacing_packet=os->lacing_fill;
  108293. }
  108294. /* set the granulepos on the last granuleval of the last full packet */
  108295. if(saved!=-1){
  108296. os->granule_vals[saved]=granulepos;
  108297. }
  108298. }
  108299. if(eos){
  108300. os->e_o_s=1;
  108301. if(os->lacing_fill>0)
  108302. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108303. }
  108304. os->pageno=pageno+1;
  108305. return(0);
  108306. }
  108307. /* clear things to an initial state. Good to call, eg, before seeking */
  108308. int ogg_sync_reset(ogg_sync_state *oy){
  108309. oy->fill=0;
  108310. oy->returned=0;
  108311. oy->unsynced=0;
  108312. oy->headerbytes=0;
  108313. oy->bodybytes=0;
  108314. return(0);
  108315. }
  108316. int ogg_stream_reset(ogg_stream_state *os){
  108317. os->body_fill=0;
  108318. os->body_returned=0;
  108319. os->lacing_fill=0;
  108320. os->lacing_packet=0;
  108321. os->lacing_returned=0;
  108322. os->header_fill=0;
  108323. os->e_o_s=0;
  108324. os->b_o_s=0;
  108325. os->pageno=-1;
  108326. os->packetno=0;
  108327. os->granulepos=0;
  108328. return(0);
  108329. }
  108330. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108331. ogg_stream_reset(os);
  108332. os->serialno=serialno;
  108333. return(0);
  108334. }
  108335. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108336. /* The last part of decode. We have the stream broken into packet
  108337. segments. Now we need to group them into packets (or return the
  108338. out of sync markers) */
  108339. int ptr=os->lacing_returned;
  108340. if(os->lacing_packet<=ptr)return(0);
  108341. if(os->lacing_vals[ptr]&0x400){
  108342. /* we need to tell the codec there's a gap; it might need to
  108343. handle previous packet dependencies. */
  108344. os->lacing_returned++;
  108345. os->packetno++;
  108346. return(-1);
  108347. }
  108348. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108349. to ask if there's a whole packet
  108350. waiting */
  108351. /* Gather the whole packet. We'll have no holes or a partial packet */
  108352. {
  108353. int size=os->lacing_vals[ptr]&0xff;
  108354. int bytes=size;
  108355. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108356. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108357. while(size==255){
  108358. int val=os->lacing_vals[++ptr];
  108359. size=val&0xff;
  108360. if(val&0x200)eos=0x200;
  108361. bytes+=size;
  108362. }
  108363. if(op){
  108364. op->e_o_s=eos;
  108365. op->b_o_s=bos;
  108366. op->packet=os->body_data+os->body_returned;
  108367. op->packetno=os->packetno;
  108368. op->granulepos=os->granule_vals[ptr];
  108369. op->bytes=bytes;
  108370. }
  108371. if(adv){
  108372. os->body_returned+=bytes;
  108373. os->lacing_returned=ptr+1;
  108374. os->packetno++;
  108375. }
  108376. }
  108377. return(1);
  108378. }
  108379. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108380. return _packetout(os,op,1);
  108381. }
  108382. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108383. return _packetout(os,op,0);
  108384. }
  108385. void ogg_packet_clear(ogg_packet *op) {
  108386. _ogg_free(op->packet);
  108387. memset(op, 0, sizeof(*op));
  108388. }
  108389. #ifdef _V_SELFTEST
  108390. #include <stdio.h>
  108391. ogg_stream_state os_en, os_de;
  108392. ogg_sync_state oy;
  108393. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108394. long j;
  108395. static int sequence=0;
  108396. static int lastno=0;
  108397. if(op->bytes!=len){
  108398. fprintf(stderr,"incorrect packet length!\n");
  108399. exit(1);
  108400. }
  108401. if(op->granulepos!=pos){
  108402. fprintf(stderr,"incorrect packet position!\n");
  108403. exit(1);
  108404. }
  108405. /* packet number just follows sequence/gap; adjust the input number
  108406. for that */
  108407. if(no==0){
  108408. sequence=0;
  108409. }else{
  108410. sequence++;
  108411. if(no>lastno+1)
  108412. sequence++;
  108413. }
  108414. lastno=no;
  108415. if(op->packetno!=sequence){
  108416. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108417. (long)(op->packetno),sequence);
  108418. exit(1);
  108419. }
  108420. /* Test data */
  108421. for(j=0;j<op->bytes;j++)
  108422. if(op->packet[j]!=((j+no)&0xff)){
  108423. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108424. j,op->packet[j],(j+no)&0xff);
  108425. exit(1);
  108426. }
  108427. }
  108428. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108429. long j;
  108430. /* Test data */
  108431. for(j=0;j<og->body_len;j++)
  108432. if(og->body[j]!=data[j]){
  108433. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108434. j,data[j],og->body[j]);
  108435. exit(1);
  108436. }
  108437. /* Test header */
  108438. for(j=0;j<og->header_len;j++){
  108439. if(og->header[j]!=header[j]){
  108440. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108441. for(j=0;j<header[26]+27;j++)
  108442. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108443. fprintf(stderr,"\n");
  108444. exit(1);
  108445. }
  108446. }
  108447. if(og->header_len!=header[26]+27){
  108448. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108449. og->header_len,header[26]+27);
  108450. exit(1);
  108451. }
  108452. }
  108453. void print_header(ogg_page *og){
  108454. int j;
  108455. fprintf(stderr,"\nHEADER:\n");
  108456. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108457. og->header[0],og->header[1],og->header[2],og->header[3],
  108458. (int)og->header[4],(int)og->header[5]);
  108459. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108460. (og->header[9]<<24)|(og->header[8]<<16)|
  108461. (og->header[7]<<8)|og->header[6],
  108462. (og->header[17]<<24)|(og->header[16]<<16)|
  108463. (og->header[15]<<8)|og->header[14],
  108464. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108465. (og->header[19]<<8)|og->header[18]);
  108466. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108467. (int)og->header[22],(int)og->header[23],
  108468. (int)og->header[24],(int)og->header[25],
  108469. (int)og->header[26]);
  108470. for(j=27;j<og->header_len;j++)
  108471. fprintf(stderr,"%d ",(int)og->header[j]);
  108472. fprintf(stderr,")\n\n");
  108473. }
  108474. void copy_page(ogg_page *og){
  108475. unsigned char *temp=_ogg_malloc(og->header_len);
  108476. memcpy(temp,og->header,og->header_len);
  108477. og->header=temp;
  108478. temp=_ogg_malloc(og->body_len);
  108479. memcpy(temp,og->body,og->body_len);
  108480. og->body=temp;
  108481. }
  108482. void free_page(ogg_page *og){
  108483. _ogg_free (og->header);
  108484. _ogg_free (og->body);
  108485. }
  108486. void error(void){
  108487. fprintf(stderr,"error!\n");
  108488. exit(1);
  108489. }
  108490. /* 17 only */
  108491. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108492. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108493. 0x01,0x02,0x03,0x04,0,0,0,0,
  108494. 0x15,0xed,0xec,0x91,
  108495. 1,
  108496. 17};
  108497. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108498. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108499. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108500. 0x01,0x02,0x03,0x04,0,0,0,0,
  108501. 0x59,0x10,0x6c,0x2c,
  108502. 1,
  108503. 17};
  108504. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108505. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108506. 0x01,0x02,0x03,0x04,1,0,0,0,
  108507. 0x89,0x33,0x85,0xce,
  108508. 13,
  108509. 254,255,0,255,1,255,245,255,255,0,
  108510. 255,255,90};
  108511. /* nil packets; beginning,middle,end */
  108512. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108513. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108514. 0x01,0x02,0x03,0x04,0,0,0,0,
  108515. 0xff,0x7b,0x23,0x17,
  108516. 1,
  108517. 0};
  108518. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108519. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108520. 0x01,0x02,0x03,0x04,1,0,0,0,
  108521. 0x5c,0x3f,0x66,0xcb,
  108522. 17,
  108523. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108524. 255,255,90,0};
  108525. /* large initial packet */
  108526. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108527. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108528. 0x01,0x02,0x03,0x04,0,0,0,0,
  108529. 0x01,0x27,0x31,0xaa,
  108530. 18,
  108531. 255,255,255,255,255,255,255,255,
  108532. 255,255,255,255,255,255,255,255,255,10};
  108533. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108534. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108535. 0x01,0x02,0x03,0x04,1,0,0,0,
  108536. 0x7f,0x4e,0x8a,0xd2,
  108537. 4,
  108538. 255,4,255,0};
  108539. /* continuing packet test */
  108540. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108541. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108542. 0x01,0x02,0x03,0x04,0,0,0,0,
  108543. 0xff,0x7b,0x23,0x17,
  108544. 1,
  108545. 0};
  108546. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108547. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108548. 0x01,0x02,0x03,0x04,1,0,0,0,
  108549. 0x54,0x05,0x51,0xc8,
  108550. 17,
  108551. 255,255,255,255,255,255,255,255,
  108552. 255,255,255,255,255,255,255,255,255};
  108553. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108554. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108555. 0x01,0x02,0x03,0x04,2,0,0,0,
  108556. 0xc8,0xc3,0xcb,0xed,
  108557. 5,
  108558. 10,255,4,255,0};
  108559. /* page with the 255 segment limit */
  108560. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108561. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108562. 0x01,0x02,0x03,0x04,0,0,0,0,
  108563. 0xff,0x7b,0x23,0x17,
  108564. 1,
  108565. 0};
  108566. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108567. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108568. 0x01,0x02,0x03,0x04,1,0,0,0,
  108569. 0xed,0x2a,0x2e,0xa7,
  108570. 255,
  108571. 10,10,10,10,10,10,10,10,
  108572. 10,10,10,10,10,10,10,10,
  108573. 10,10,10,10,10,10,10,10,
  108574. 10,10,10,10,10,10,10,10,
  108575. 10,10,10,10,10,10,10,10,
  108576. 10,10,10,10,10,10,10,10,
  108577. 10,10,10,10,10,10,10,10,
  108578. 10,10,10,10,10,10,10,10,
  108579. 10,10,10,10,10,10,10,10,
  108580. 10,10,10,10,10,10,10,10,
  108581. 10,10,10,10,10,10,10,10,
  108582. 10,10,10,10,10,10,10,10,
  108583. 10,10,10,10,10,10,10,10,
  108584. 10,10,10,10,10,10,10,10,
  108585. 10,10,10,10,10,10,10,10,
  108586. 10,10,10,10,10,10,10,10,
  108587. 10,10,10,10,10,10,10,10,
  108588. 10,10,10,10,10,10,10,10,
  108589. 10,10,10,10,10,10,10,10,
  108590. 10,10,10,10,10,10,10,10,
  108591. 10,10,10,10,10,10,10,10,
  108592. 10,10,10,10,10,10,10,10,
  108593. 10,10,10,10,10,10,10,10,
  108594. 10,10,10,10,10,10,10,10,
  108595. 10,10,10,10,10,10,10,10,
  108596. 10,10,10,10,10,10,10,10,
  108597. 10,10,10,10,10,10,10,10,
  108598. 10,10,10,10,10,10,10,10,
  108599. 10,10,10,10,10,10,10,10,
  108600. 10,10,10,10,10,10,10,10,
  108601. 10,10,10,10,10,10,10,10,
  108602. 10,10,10,10,10,10,10};
  108603. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108604. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108605. 0x01,0x02,0x03,0x04,2,0,0,0,
  108606. 0x6c,0x3b,0x82,0x3d,
  108607. 1,
  108608. 50};
  108609. /* packet that overspans over an entire page */
  108610. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108611. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108612. 0x01,0x02,0x03,0x04,0,0,0,0,
  108613. 0xff,0x7b,0x23,0x17,
  108614. 1,
  108615. 0};
  108616. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108617. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108618. 0x01,0x02,0x03,0x04,1,0,0,0,
  108619. 0x3c,0xd9,0x4d,0x3f,
  108620. 17,
  108621. 100,255,255,255,255,255,255,255,255,
  108622. 255,255,255,255,255,255,255,255};
  108623. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108624. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108625. 0x01,0x02,0x03,0x04,2,0,0,0,
  108626. 0x01,0xd2,0xe5,0xe5,
  108627. 17,
  108628. 255,255,255,255,255,255,255,255,
  108629. 255,255,255,255,255,255,255,255,255};
  108630. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108631. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108632. 0x01,0x02,0x03,0x04,3,0,0,0,
  108633. 0xef,0xdd,0x88,0xde,
  108634. 7,
  108635. 255,255,75,255,4,255,0};
  108636. /* packet that overspans over an entire page */
  108637. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108638. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108639. 0x01,0x02,0x03,0x04,0,0,0,0,
  108640. 0xff,0x7b,0x23,0x17,
  108641. 1,
  108642. 0};
  108643. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108644. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108645. 0x01,0x02,0x03,0x04,1,0,0,0,
  108646. 0x3c,0xd9,0x4d,0x3f,
  108647. 17,
  108648. 100,255,255,255,255,255,255,255,255,
  108649. 255,255,255,255,255,255,255,255};
  108650. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108651. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108652. 0x01,0x02,0x03,0x04,2,0,0,0,
  108653. 0xd4,0xe0,0x60,0xe5,
  108654. 1,0};
  108655. void test_pack(const int *pl, const int **headers, int byteskip,
  108656. int pageskip, int packetskip){
  108657. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108658. long inptr=0;
  108659. long outptr=0;
  108660. long deptr=0;
  108661. long depacket=0;
  108662. long granule_pos=7,pageno=0;
  108663. int i,j,packets,pageout=pageskip;
  108664. int eosflag=0;
  108665. int bosflag=0;
  108666. int byteskipcount=0;
  108667. ogg_stream_reset(&os_en);
  108668. ogg_stream_reset(&os_de);
  108669. ogg_sync_reset(&oy);
  108670. for(packets=0;packets<packetskip;packets++)
  108671. depacket+=pl[packets];
  108672. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108673. for(i=0;i<packets;i++){
  108674. /* construct a test packet */
  108675. ogg_packet op;
  108676. int len=pl[i];
  108677. op.packet=data+inptr;
  108678. op.bytes=len;
  108679. op.e_o_s=(pl[i+1]<0?1:0);
  108680. op.granulepos=granule_pos;
  108681. granule_pos+=1024;
  108682. for(j=0;j<len;j++)data[inptr++]=i+j;
  108683. /* submit the test packet */
  108684. ogg_stream_packetin(&os_en,&op);
  108685. /* retrieve any finished pages */
  108686. {
  108687. ogg_page og;
  108688. while(ogg_stream_pageout(&os_en,&og)){
  108689. /* We have a page. Check it carefully */
  108690. fprintf(stderr,"%ld, ",pageno);
  108691. if(headers[pageno]==NULL){
  108692. fprintf(stderr,"coded too many pages!\n");
  108693. exit(1);
  108694. }
  108695. check_page(data+outptr,headers[pageno],&og);
  108696. outptr+=og.body_len;
  108697. pageno++;
  108698. if(pageskip){
  108699. bosflag=1;
  108700. pageskip--;
  108701. deptr+=og.body_len;
  108702. }
  108703. /* have a complete page; submit it to sync/decode */
  108704. {
  108705. ogg_page og_de;
  108706. ogg_packet op_de,op_de2;
  108707. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108708. char *next=buf;
  108709. byteskipcount+=og.header_len;
  108710. if(byteskipcount>byteskip){
  108711. memcpy(next,og.header,byteskipcount-byteskip);
  108712. next+=byteskipcount-byteskip;
  108713. byteskipcount=byteskip;
  108714. }
  108715. byteskipcount+=og.body_len;
  108716. if(byteskipcount>byteskip){
  108717. memcpy(next,og.body,byteskipcount-byteskip);
  108718. next+=byteskipcount-byteskip;
  108719. byteskipcount=byteskip;
  108720. }
  108721. ogg_sync_wrote(&oy,next-buf);
  108722. while(1){
  108723. int ret=ogg_sync_pageout(&oy,&og_de);
  108724. if(ret==0)break;
  108725. if(ret<0)continue;
  108726. /* got a page. Happy happy. Verify that it's good. */
  108727. fprintf(stderr,"(%ld), ",pageout);
  108728. check_page(data+deptr,headers[pageout],&og_de);
  108729. deptr+=og_de.body_len;
  108730. pageout++;
  108731. /* submit it to deconstitution */
  108732. ogg_stream_pagein(&os_de,&og_de);
  108733. /* packets out? */
  108734. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108735. ogg_stream_packetpeek(&os_de,NULL);
  108736. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108737. /* verify peek and out match */
  108738. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108739. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108740. depacket);
  108741. exit(1);
  108742. }
  108743. /* verify the packet! */
  108744. /* check data */
  108745. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108746. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108747. depacket);
  108748. exit(1);
  108749. }
  108750. /* check bos flag */
  108751. if(bosflag==0 && op_de.b_o_s==0){
  108752. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108753. exit(1);
  108754. }
  108755. if(bosflag && op_de.b_o_s){
  108756. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108757. exit(1);
  108758. }
  108759. bosflag=1;
  108760. depacket+=op_de.bytes;
  108761. /* check eos flag */
  108762. if(eosflag){
  108763. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108764. exit(1);
  108765. }
  108766. if(op_de.e_o_s)eosflag=1;
  108767. /* check granulepos flag */
  108768. if(op_de.granulepos!=-1){
  108769. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108770. }
  108771. }
  108772. }
  108773. }
  108774. }
  108775. }
  108776. }
  108777. _ogg_free(data);
  108778. if(headers[pageno]!=NULL){
  108779. fprintf(stderr,"did not write last page!\n");
  108780. exit(1);
  108781. }
  108782. if(headers[pageout]!=NULL){
  108783. fprintf(stderr,"did not decode last page!\n");
  108784. exit(1);
  108785. }
  108786. if(inptr!=outptr){
  108787. fprintf(stderr,"encoded page data incomplete!\n");
  108788. exit(1);
  108789. }
  108790. if(inptr!=deptr){
  108791. fprintf(stderr,"decoded page data incomplete!\n");
  108792. exit(1);
  108793. }
  108794. if(inptr!=depacket){
  108795. fprintf(stderr,"decoded packet data incomplete!\n");
  108796. exit(1);
  108797. }
  108798. if(!eosflag){
  108799. fprintf(stderr,"Never got a packet with EOS set!\n");
  108800. exit(1);
  108801. }
  108802. fprintf(stderr,"ok.\n");
  108803. }
  108804. int main(void){
  108805. ogg_stream_init(&os_en,0x04030201);
  108806. ogg_stream_init(&os_de,0x04030201);
  108807. ogg_sync_init(&oy);
  108808. /* Exercise each code path in the framing code. Also verify that
  108809. the checksums are working. */
  108810. {
  108811. /* 17 only */
  108812. const int packets[]={17, -1};
  108813. const int *headret[]={head1_0,NULL};
  108814. fprintf(stderr,"testing single page encoding... ");
  108815. test_pack(packets,headret,0,0,0);
  108816. }
  108817. {
  108818. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108819. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  108820. const int *headret[]={head1_1,head2_1,NULL};
  108821. fprintf(stderr,"testing basic page encoding... ");
  108822. test_pack(packets,headret,0,0,0);
  108823. }
  108824. {
  108825. /* nil packets; beginning,middle,end */
  108826. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  108827. const int *headret[]={head1_2,head2_2,NULL};
  108828. fprintf(stderr,"testing basic nil packets... ");
  108829. test_pack(packets,headret,0,0,0);
  108830. }
  108831. {
  108832. /* large initial packet */
  108833. const int packets[]={4345,259,255,-1};
  108834. const int *headret[]={head1_3,head2_3,NULL};
  108835. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  108836. test_pack(packets,headret,0,0,0);
  108837. }
  108838. {
  108839. /* continuing packet test */
  108840. const int packets[]={0,4345,259,255,-1};
  108841. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  108842. fprintf(stderr,"testing single packet page span... ");
  108843. test_pack(packets,headret,0,0,0);
  108844. }
  108845. /* page with the 255 segment limit */
  108846. {
  108847. const int packets[]={0,10,10,10,10,10,10,10,10,
  108848. 10,10,10,10,10,10,10,10,
  108849. 10,10,10,10,10,10,10,10,
  108850. 10,10,10,10,10,10,10,10,
  108851. 10,10,10,10,10,10,10,10,
  108852. 10,10,10,10,10,10,10,10,
  108853. 10,10,10,10,10,10,10,10,
  108854. 10,10,10,10,10,10,10,10,
  108855. 10,10,10,10,10,10,10,10,
  108856. 10,10,10,10,10,10,10,10,
  108857. 10,10,10,10,10,10,10,10,
  108858. 10,10,10,10,10,10,10,10,
  108859. 10,10,10,10,10,10,10,10,
  108860. 10,10,10,10,10,10,10,10,
  108861. 10,10,10,10,10,10,10,10,
  108862. 10,10,10,10,10,10,10,10,
  108863. 10,10,10,10,10,10,10,10,
  108864. 10,10,10,10,10,10,10,10,
  108865. 10,10,10,10,10,10,10,10,
  108866. 10,10,10,10,10,10,10,10,
  108867. 10,10,10,10,10,10,10,10,
  108868. 10,10,10,10,10,10,10,10,
  108869. 10,10,10,10,10,10,10,10,
  108870. 10,10,10,10,10,10,10,10,
  108871. 10,10,10,10,10,10,10,10,
  108872. 10,10,10,10,10,10,10,10,
  108873. 10,10,10,10,10,10,10,10,
  108874. 10,10,10,10,10,10,10,10,
  108875. 10,10,10,10,10,10,10,10,
  108876. 10,10,10,10,10,10,10,10,
  108877. 10,10,10,10,10,10,10,10,
  108878. 10,10,10,10,10,10,10,50,-1};
  108879. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  108880. fprintf(stderr,"testing max packet segments... ");
  108881. test_pack(packets,headret,0,0,0);
  108882. }
  108883. {
  108884. /* packet that overspans over an entire page */
  108885. const int packets[]={0,100,9000,259,255,-1};
  108886. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108887. fprintf(stderr,"testing very large packets... ");
  108888. test_pack(packets,headret,0,0,0);
  108889. }
  108890. {
  108891. /* test for the libogg 1.1.1 resync in large continuation bug
  108892. found by Josh Coalson) */
  108893. const int packets[]={0,100,9000,259,255,-1};
  108894. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108895. fprintf(stderr,"testing continuation resync in very large packets... ");
  108896. test_pack(packets,headret,100,2,3);
  108897. }
  108898. {
  108899. /* term only page. why not? */
  108900. const int packets[]={0,100,4080,-1};
  108901. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  108902. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  108903. test_pack(packets,headret,0,0,0);
  108904. }
  108905. {
  108906. /* build a bunch of pages for testing */
  108907. unsigned char *data=_ogg_malloc(1024*1024);
  108908. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  108909. int inptr=0,i,j;
  108910. ogg_page og[5];
  108911. ogg_stream_reset(&os_en);
  108912. for(i=0;pl[i]!=-1;i++){
  108913. ogg_packet op;
  108914. int len=pl[i];
  108915. op.packet=data+inptr;
  108916. op.bytes=len;
  108917. op.e_o_s=(pl[i+1]<0?1:0);
  108918. op.granulepos=(i+1)*1000;
  108919. for(j=0;j<len;j++)data[inptr++]=i+j;
  108920. ogg_stream_packetin(&os_en,&op);
  108921. }
  108922. _ogg_free(data);
  108923. /* retrieve finished pages */
  108924. for(i=0;i<5;i++){
  108925. if(ogg_stream_pageout(&os_en,&og[i])==0){
  108926. fprintf(stderr,"Too few pages output building sync tests!\n");
  108927. exit(1);
  108928. }
  108929. copy_page(&og[i]);
  108930. }
  108931. /* Test lost pages on pagein/packetout: no rollback */
  108932. {
  108933. ogg_page temp;
  108934. ogg_packet test;
  108935. fprintf(stderr,"Testing loss of pages... ");
  108936. ogg_sync_reset(&oy);
  108937. ogg_stream_reset(&os_de);
  108938. for(i=0;i<5;i++){
  108939. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108940. og[i].header_len);
  108941. ogg_sync_wrote(&oy,og[i].header_len);
  108942. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108943. ogg_sync_wrote(&oy,og[i].body_len);
  108944. }
  108945. ogg_sync_pageout(&oy,&temp);
  108946. ogg_stream_pagein(&os_de,&temp);
  108947. ogg_sync_pageout(&oy,&temp);
  108948. ogg_stream_pagein(&os_de,&temp);
  108949. ogg_sync_pageout(&oy,&temp);
  108950. /* skip */
  108951. ogg_sync_pageout(&oy,&temp);
  108952. ogg_stream_pagein(&os_de,&temp);
  108953. /* do we get the expected results/packets? */
  108954. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108955. checkpacket(&test,0,0,0);
  108956. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108957. checkpacket(&test,100,1,-1);
  108958. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108959. checkpacket(&test,4079,2,3000);
  108960. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108961. fprintf(stderr,"Error: loss of page did not return error\n");
  108962. exit(1);
  108963. }
  108964. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108965. checkpacket(&test,76,5,-1);
  108966. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108967. checkpacket(&test,34,6,-1);
  108968. fprintf(stderr,"ok.\n");
  108969. }
  108970. /* Test lost pages on pagein/packetout: rollback with continuation */
  108971. {
  108972. ogg_page temp;
  108973. ogg_packet test;
  108974. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  108975. ogg_sync_reset(&oy);
  108976. ogg_stream_reset(&os_de);
  108977. for(i=0;i<5;i++){
  108978. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108979. og[i].header_len);
  108980. ogg_sync_wrote(&oy,og[i].header_len);
  108981. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108982. ogg_sync_wrote(&oy,og[i].body_len);
  108983. }
  108984. ogg_sync_pageout(&oy,&temp);
  108985. ogg_stream_pagein(&os_de,&temp);
  108986. ogg_sync_pageout(&oy,&temp);
  108987. ogg_stream_pagein(&os_de,&temp);
  108988. ogg_sync_pageout(&oy,&temp);
  108989. ogg_stream_pagein(&os_de,&temp);
  108990. ogg_sync_pageout(&oy,&temp);
  108991. /* skip */
  108992. ogg_sync_pageout(&oy,&temp);
  108993. ogg_stream_pagein(&os_de,&temp);
  108994. /* do we get the expected results/packets? */
  108995. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108996. checkpacket(&test,0,0,0);
  108997. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108998. checkpacket(&test,100,1,-1);
  108999. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109000. checkpacket(&test,4079,2,3000);
  109001. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109002. checkpacket(&test,2956,3,4000);
  109003. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109004. fprintf(stderr,"Error: loss of page did not return error\n");
  109005. exit(1);
  109006. }
  109007. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109008. checkpacket(&test,300,13,14000);
  109009. fprintf(stderr,"ok.\n");
  109010. }
  109011. /* the rest only test sync */
  109012. {
  109013. ogg_page og_de;
  109014. /* Test fractional page inputs: incomplete capture */
  109015. fprintf(stderr,"Testing sync on partial inputs... ");
  109016. ogg_sync_reset(&oy);
  109017. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109018. 3);
  109019. ogg_sync_wrote(&oy,3);
  109020. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109021. /* Test fractional page inputs: incomplete fixed header */
  109022. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109023. 20);
  109024. ogg_sync_wrote(&oy,20);
  109025. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109026. /* Test fractional page inputs: incomplete header */
  109027. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109028. 5);
  109029. ogg_sync_wrote(&oy,5);
  109030. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109031. /* Test fractional page inputs: incomplete body */
  109032. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109033. og[1].header_len-28);
  109034. ogg_sync_wrote(&oy,og[1].header_len-28);
  109035. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109036. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109037. ogg_sync_wrote(&oy,1000);
  109038. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109039. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109040. og[1].body_len-1000);
  109041. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109042. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109043. fprintf(stderr,"ok.\n");
  109044. }
  109045. /* Test fractional page inputs: page + incomplete capture */
  109046. {
  109047. ogg_page og_de;
  109048. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109049. ogg_sync_reset(&oy);
  109050. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109051. og[1].header_len);
  109052. ogg_sync_wrote(&oy,og[1].header_len);
  109053. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109054. og[1].body_len);
  109055. ogg_sync_wrote(&oy,og[1].body_len);
  109056. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109057. 20);
  109058. ogg_sync_wrote(&oy,20);
  109059. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109060. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109061. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109062. og[1].header_len-20);
  109063. ogg_sync_wrote(&oy,og[1].header_len-20);
  109064. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109065. og[1].body_len);
  109066. ogg_sync_wrote(&oy,og[1].body_len);
  109067. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109068. fprintf(stderr,"ok.\n");
  109069. }
  109070. /* Test recapture: garbage + page */
  109071. {
  109072. ogg_page og_de;
  109073. fprintf(stderr,"Testing search for capture... ");
  109074. ogg_sync_reset(&oy);
  109075. /* 'garbage' */
  109076. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109077. og[1].body_len);
  109078. ogg_sync_wrote(&oy,og[1].body_len);
  109079. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109080. og[1].header_len);
  109081. ogg_sync_wrote(&oy,og[1].header_len);
  109082. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109083. og[1].body_len);
  109084. ogg_sync_wrote(&oy,og[1].body_len);
  109085. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109086. 20);
  109087. ogg_sync_wrote(&oy,20);
  109088. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109089. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109090. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109091. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109092. og[2].header_len-20);
  109093. ogg_sync_wrote(&oy,og[2].header_len-20);
  109094. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109095. og[2].body_len);
  109096. ogg_sync_wrote(&oy,og[2].body_len);
  109097. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109098. fprintf(stderr,"ok.\n");
  109099. }
  109100. /* Test recapture: page + garbage + page */
  109101. {
  109102. ogg_page og_de;
  109103. fprintf(stderr,"Testing recapture... ");
  109104. ogg_sync_reset(&oy);
  109105. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109106. og[1].header_len);
  109107. ogg_sync_wrote(&oy,og[1].header_len);
  109108. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109109. og[1].body_len);
  109110. ogg_sync_wrote(&oy,og[1].body_len);
  109111. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109112. og[2].header_len);
  109113. ogg_sync_wrote(&oy,og[2].header_len);
  109114. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109115. og[2].header_len);
  109116. ogg_sync_wrote(&oy,og[2].header_len);
  109117. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109118. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109119. og[2].body_len-5);
  109120. ogg_sync_wrote(&oy,og[2].body_len-5);
  109121. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109122. og[3].header_len);
  109123. ogg_sync_wrote(&oy,og[3].header_len);
  109124. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109125. og[3].body_len);
  109126. ogg_sync_wrote(&oy,og[3].body_len);
  109127. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109128. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109129. fprintf(stderr,"ok.\n");
  109130. }
  109131. /* Free page data that was previously copied */
  109132. {
  109133. for(i=0;i<5;i++){
  109134. free_page(&og[i]);
  109135. }
  109136. }
  109137. }
  109138. return(0);
  109139. }
  109140. #endif
  109141. #endif
  109142. /*** End of inlined file: framing.c ***/
  109143. /*** Start of inlined file: analysis.c ***/
  109144. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109145. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109146. // tasks..
  109147. #if JUCE_MSVC
  109148. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109149. #endif
  109150. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109151. #if JUCE_USE_OGGVORBIS
  109152. #include <stdio.h>
  109153. #include <string.h>
  109154. #include <math.h>
  109155. /*** Start of inlined file: codec_internal.h ***/
  109156. #ifndef _V_CODECI_H_
  109157. #define _V_CODECI_H_
  109158. /*** Start of inlined file: envelope.h ***/
  109159. #ifndef _V_ENVELOPE_
  109160. #define _V_ENVELOPE_
  109161. /*** Start of inlined file: mdct.h ***/
  109162. #ifndef _OGG_mdct_H_
  109163. #define _OGG_mdct_H_
  109164. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109165. #ifdef MDCT_INTEGERIZED
  109166. #define DATA_TYPE int
  109167. #define REG_TYPE register int
  109168. #define TRIGBITS 14
  109169. #define cPI3_8 6270
  109170. #define cPI2_8 11585
  109171. #define cPI1_8 15137
  109172. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109173. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109174. #define HALVE(x) ((x)>>1)
  109175. #else
  109176. #define DATA_TYPE float
  109177. #define REG_TYPE float
  109178. #define cPI3_8 .38268343236508977175F
  109179. #define cPI2_8 .70710678118654752441F
  109180. #define cPI1_8 .92387953251128675613F
  109181. #define FLOAT_CONV(x) (x)
  109182. #define MULT_NORM(x) (x)
  109183. #define HALVE(x) ((x)*.5f)
  109184. #endif
  109185. typedef struct {
  109186. int n;
  109187. int log2n;
  109188. DATA_TYPE *trig;
  109189. int *bitrev;
  109190. DATA_TYPE scale;
  109191. } mdct_lookup;
  109192. extern void mdct_init(mdct_lookup *lookup,int n);
  109193. extern void mdct_clear(mdct_lookup *l);
  109194. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109195. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109196. #endif
  109197. /*** End of inlined file: mdct.h ***/
  109198. #define VE_PRE 16
  109199. #define VE_WIN 4
  109200. #define VE_POST 2
  109201. #define VE_AMP (VE_PRE+VE_POST-1)
  109202. #define VE_BANDS 7
  109203. #define VE_NEARDC 15
  109204. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109205. #define VE_MAXSTRETCH 12 /* one-third full block */
  109206. typedef struct {
  109207. float ampbuf[VE_AMP];
  109208. int ampptr;
  109209. float nearDC[VE_NEARDC];
  109210. float nearDC_acc;
  109211. float nearDC_partialacc;
  109212. int nearptr;
  109213. } envelope_filter_state;
  109214. typedef struct {
  109215. int begin;
  109216. int end;
  109217. float *window;
  109218. float total;
  109219. } envelope_band;
  109220. typedef struct {
  109221. int ch;
  109222. int winlength;
  109223. int searchstep;
  109224. float minenergy;
  109225. mdct_lookup mdct;
  109226. float *mdct_win;
  109227. envelope_band band[VE_BANDS];
  109228. envelope_filter_state *filter;
  109229. int stretch;
  109230. int *mark;
  109231. long storage;
  109232. long current;
  109233. long curmark;
  109234. long cursor;
  109235. } envelope_lookup;
  109236. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109237. extern void _ve_envelope_clear(envelope_lookup *e);
  109238. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109239. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109240. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109241. #endif
  109242. /*** End of inlined file: envelope.h ***/
  109243. /*** Start of inlined file: codebook.h ***/
  109244. #ifndef _V_CODEBOOK_H_
  109245. #define _V_CODEBOOK_H_
  109246. /* This structure encapsulates huffman and VQ style encoding books; it
  109247. doesn't do anything specific to either.
  109248. valuelist/quantlist are nonNULL (and q_* significant) only if
  109249. there's entry->value mapping to be done.
  109250. If encode-side mapping must be done (and thus the entry needs to be
  109251. hunted), the auxiliary encode pointer will point to a decision
  109252. tree. This is true of both VQ and huffman, but is mostly useful
  109253. with VQ.
  109254. */
  109255. typedef struct static_codebook{
  109256. long dim; /* codebook dimensions (elements per vector) */
  109257. long entries; /* codebook entries */
  109258. long *lengthlist; /* codeword lengths in bits */
  109259. /* mapping ***************************************************************/
  109260. int maptype; /* 0=none
  109261. 1=implicitly populated values from map column
  109262. 2=listed arbitrary values */
  109263. /* The below does a linear, single monotonic sequence mapping. */
  109264. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109265. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109266. int q_quant; /* bits: 0 < quant <= 16 */
  109267. int q_sequencep; /* bitflag */
  109268. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109269. map == 2: list of dim*entries quantized entry vals
  109270. */
  109271. /* encode helpers ********************************************************/
  109272. struct encode_aux_nearestmatch *nearest_tree;
  109273. struct encode_aux_threshmatch *thresh_tree;
  109274. struct encode_aux_pigeonhole *pigeon_tree;
  109275. int allocedp;
  109276. } static_codebook;
  109277. /* this structures an arbitrary trained book to quickly find the
  109278. nearest cell match */
  109279. typedef struct encode_aux_nearestmatch{
  109280. /* pre-calculated partitioning tree */
  109281. long *ptr0;
  109282. long *ptr1;
  109283. long *p; /* decision points (each is an entry) */
  109284. long *q; /* decision points (each is an entry) */
  109285. long aux; /* number of tree entries */
  109286. long alloc;
  109287. } encode_aux_nearestmatch;
  109288. /* assumes a maptype of 1; encode side only, so that's OK */
  109289. typedef struct encode_aux_threshmatch{
  109290. float *quantthresh;
  109291. long *quantmap;
  109292. int quantvals;
  109293. int threshvals;
  109294. } encode_aux_threshmatch;
  109295. typedef struct encode_aux_pigeonhole{
  109296. float min;
  109297. float del;
  109298. int mapentries;
  109299. int quantvals;
  109300. long *pigeonmap;
  109301. long fittotal;
  109302. long *fitlist;
  109303. long *fitmap;
  109304. long *fitlength;
  109305. } encode_aux_pigeonhole;
  109306. typedef struct codebook{
  109307. long dim; /* codebook dimensions (elements per vector) */
  109308. long entries; /* codebook entries */
  109309. long used_entries; /* populated codebook entries */
  109310. const static_codebook *c;
  109311. /* for encode, the below are entry-ordered, fully populated */
  109312. /* for decode, the below are ordered by bitreversed codeword and only
  109313. used entries are populated */
  109314. float *valuelist; /* list of dim*entries actual entry values */
  109315. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109316. int *dec_index; /* only used if sparseness collapsed */
  109317. char *dec_codelengths;
  109318. ogg_uint32_t *dec_firsttable;
  109319. int dec_firsttablen;
  109320. int dec_maxlength;
  109321. } codebook;
  109322. extern void vorbis_staticbook_clear(static_codebook *b);
  109323. extern void vorbis_staticbook_destroy(static_codebook *b);
  109324. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109325. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109326. extern void vorbis_book_clear(codebook *b);
  109327. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109328. extern float *_book_logdist(const static_codebook *b,float *vals);
  109329. extern float _float32_unpack(long val);
  109330. extern long _float32_pack(float val);
  109331. extern int _best(codebook *book, float *a, int step);
  109332. extern int _ilog(unsigned int v);
  109333. extern long _book_maptype1_quantvals(const static_codebook *b);
  109334. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109335. extern long vorbis_book_codeword(codebook *book,int entry);
  109336. extern long vorbis_book_codelen(codebook *book,int entry);
  109337. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109338. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109339. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109340. extern int vorbis_book_errorv(codebook *book, float *a);
  109341. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109342. oggpack_buffer *b);
  109343. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109344. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109345. oggpack_buffer *b,int n);
  109346. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109347. oggpack_buffer *b,int n);
  109348. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109349. oggpack_buffer *b,int n);
  109350. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109351. long off,int ch,
  109352. oggpack_buffer *b,int n);
  109353. #endif
  109354. /*** End of inlined file: codebook.h ***/
  109355. #define BLOCKTYPE_IMPULSE 0
  109356. #define BLOCKTYPE_PADDING 1
  109357. #define BLOCKTYPE_TRANSITION 0
  109358. #define BLOCKTYPE_LONG 1
  109359. #define PACKETBLOBS 15
  109360. typedef struct vorbis_block_internal{
  109361. float **pcmdelay; /* this is a pointer into local storage */
  109362. float ampmax;
  109363. int blocktype;
  109364. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109365. blob [PACKETBLOBS/2] points to
  109366. the oggpack_buffer in the
  109367. main vorbis_block */
  109368. } vorbis_block_internal;
  109369. typedef void vorbis_look_floor;
  109370. typedef void vorbis_look_residue;
  109371. typedef void vorbis_look_transform;
  109372. /* mode ************************************************************/
  109373. typedef struct {
  109374. int blockflag;
  109375. int windowtype;
  109376. int transformtype;
  109377. int mapping;
  109378. } vorbis_info_mode;
  109379. typedef void vorbis_info_floor;
  109380. typedef void vorbis_info_residue;
  109381. typedef void vorbis_info_mapping;
  109382. /*** Start of inlined file: psy.h ***/
  109383. #ifndef _V_PSY_H_
  109384. #define _V_PSY_H_
  109385. /*** Start of inlined file: smallft.h ***/
  109386. #ifndef _V_SMFT_H_
  109387. #define _V_SMFT_H_
  109388. typedef struct {
  109389. int n;
  109390. float *trigcache;
  109391. int *splitcache;
  109392. } drft_lookup;
  109393. extern void drft_forward(drft_lookup *l,float *data);
  109394. extern void drft_backward(drft_lookup *l,float *data);
  109395. extern void drft_init(drft_lookup *l,int n);
  109396. extern void drft_clear(drft_lookup *l);
  109397. #endif
  109398. /*** End of inlined file: smallft.h ***/
  109399. /*** Start of inlined file: backends.h ***/
  109400. /* this is exposed up here because we need it for static modes.
  109401. Lookups for each backend aren't exposed because there's no reason
  109402. to do so */
  109403. #ifndef _vorbis_backend_h_
  109404. #define _vorbis_backend_h_
  109405. /* this would all be simpler/shorter with templates, but.... */
  109406. /* Floor backend generic *****************************************/
  109407. typedef struct{
  109408. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109409. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109410. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109411. void (*free_info) (vorbis_info_floor *);
  109412. void (*free_look) (vorbis_look_floor *);
  109413. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109414. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109415. void *buffer,float *);
  109416. } vorbis_func_floor;
  109417. typedef struct{
  109418. int order;
  109419. long rate;
  109420. long barkmap;
  109421. int ampbits;
  109422. int ampdB;
  109423. int numbooks; /* <= 16 */
  109424. int books[16];
  109425. float lessthan; /* encode-only config setting hacks for libvorbis */
  109426. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109427. } vorbis_info_floor0;
  109428. #define VIF_POSIT 63
  109429. #define VIF_CLASS 16
  109430. #define VIF_PARTS 31
  109431. typedef struct{
  109432. int partitions; /* 0 to 31 */
  109433. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109434. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109435. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109436. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109437. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109438. int mult; /* 1 2 3 or 4 */
  109439. int postlist[VIF_POSIT+2]; /* first two implicit */
  109440. /* encode side analysis parameters */
  109441. float maxover;
  109442. float maxunder;
  109443. float maxerr;
  109444. float twofitweight;
  109445. float twofitatten;
  109446. int n;
  109447. } vorbis_info_floor1;
  109448. /* Residue backend generic *****************************************/
  109449. typedef struct{
  109450. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109451. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109452. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109453. vorbis_info_residue *);
  109454. void (*free_info) (vorbis_info_residue *);
  109455. void (*free_look) (vorbis_look_residue *);
  109456. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109457. float **,int *,int);
  109458. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109459. vorbis_look_residue *,
  109460. float **,float **,int *,int,long **);
  109461. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109462. float **,int *,int);
  109463. } vorbis_func_residue;
  109464. typedef struct vorbis_info_residue0{
  109465. /* block-partitioned VQ coded straight residue */
  109466. long begin;
  109467. long end;
  109468. /* first stage (lossless partitioning) */
  109469. int grouping; /* group n vectors per partition */
  109470. int partitions; /* possible codebooks for a partition */
  109471. int groupbook; /* huffbook for partitioning */
  109472. int secondstages[64]; /* expanded out to pointers in lookup */
  109473. int booklist[256]; /* list of second stage books */
  109474. float classmetric1[64];
  109475. float classmetric2[64];
  109476. } vorbis_info_residue0;
  109477. /* Mapping backend generic *****************************************/
  109478. typedef struct{
  109479. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109480. oggpack_buffer *);
  109481. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109482. void (*free_info) (vorbis_info_mapping *);
  109483. int (*forward) (struct vorbis_block *vb);
  109484. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109485. } vorbis_func_mapping;
  109486. typedef struct vorbis_info_mapping0{
  109487. int submaps; /* <= 16 */
  109488. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109489. int floorsubmap[16]; /* [mux] submap to floors */
  109490. int residuesubmap[16]; /* [mux] submap to residue */
  109491. int coupling_steps;
  109492. int coupling_mag[256];
  109493. int coupling_ang[256];
  109494. } vorbis_info_mapping0;
  109495. #endif
  109496. /*** End of inlined file: backends.h ***/
  109497. #ifndef EHMER_MAX
  109498. #define EHMER_MAX 56
  109499. #endif
  109500. /* psychoacoustic setup ********************************************/
  109501. #define P_BANDS 17 /* 62Hz to 16kHz */
  109502. #define P_LEVELS 8 /* 30dB to 100dB */
  109503. #define P_LEVEL_0 30. /* 30 dB */
  109504. #define P_NOISECURVES 3
  109505. #define NOISE_COMPAND_LEVELS 40
  109506. typedef struct vorbis_info_psy{
  109507. int blockflag;
  109508. float ath_adjatt;
  109509. float ath_maxatt;
  109510. float tone_masteratt[P_NOISECURVES];
  109511. float tone_centerboost;
  109512. float tone_decay;
  109513. float tone_abs_limit;
  109514. float toneatt[P_BANDS];
  109515. int noisemaskp;
  109516. float noisemaxsupp;
  109517. float noisewindowlo;
  109518. float noisewindowhi;
  109519. int noisewindowlomin;
  109520. int noisewindowhimin;
  109521. int noisewindowfixed;
  109522. float noiseoff[P_NOISECURVES][P_BANDS];
  109523. float noisecompand[NOISE_COMPAND_LEVELS];
  109524. float max_curve_dB;
  109525. int normal_channel_p;
  109526. int normal_point_p;
  109527. int normal_start;
  109528. int normal_partition;
  109529. double normal_thresh;
  109530. } vorbis_info_psy;
  109531. typedef struct{
  109532. int eighth_octave_lines;
  109533. /* for block long/short tuning; encode only */
  109534. float preecho_thresh[VE_BANDS];
  109535. float postecho_thresh[VE_BANDS];
  109536. float stretch_penalty;
  109537. float preecho_minenergy;
  109538. float ampmax_att_per_sec;
  109539. /* channel coupling config */
  109540. int coupling_pkHz[PACKETBLOBS];
  109541. int coupling_pointlimit[2][PACKETBLOBS];
  109542. int coupling_prepointamp[PACKETBLOBS];
  109543. int coupling_postpointamp[PACKETBLOBS];
  109544. int sliding_lowpass[2][PACKETBLOBS];
  109545. } vorbis_info_psy_global;
  109546. typedef struct {
  109547. float ampmax;
  109548. int channels;
  109549. vorbis_info_psy_global *gi;
  109550. int coupling_pointlimit[2][P_NOISECURVES];
  109551. } vorbis_look_psy_global;
  109552. typedef struct {
  109553. int n;
  109554. struct vorbis_info_psy *vi;
  109555. float ***tonecurves;
  109556. float **noiseoffset;
  109557. float *ath;
  109558. long *octave; /* in n.ocshift format */
  109559. long *bark;
  109560. long firstoc;
  109561. long shiftoc;
  109562. int eighth_octave_lines; /* power of two, please */
  109563. int total_octave_lines;
  109564. long rate; /* cache it */
  109565. float m_val; /* Masking compensation value */
  109566. } vorbis_look_psy;
  109567. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109568. vorbis_info_psy_global *gi,int n,long rate);
  109569. extern void _vp_psy_clear(vorbis_look_psy *p);
  109570. extern void *_vi_psy_dup(void *source);
  109571. extern void _vi_psy_free(vorbis_info_psy *i);
  109572. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109573. extern void _vp_remove_floor(vorbis_look_psy *p,
  109574. float *mdct,
  109575. int *icodedflr,
  109576. float *residue,
  109577. int sliding_lowpass);
  109578. extern void _vp_noisemask(vorbis_look_psy *p,
  109579. float *logmdct,
  109580. float *logmask);
  109581. extern void _vp_tonemask(vorbis_look_psy *p,
  109582. float *logfft,
  109583. float *logmask,
  109584. float global_specmax,
  109585. float local_specmax);
  109586. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109587. float *noise,
  109588. float *tone,
  109589. int offset_select,
  109590. float *logmask,
  109591. float *mdct,
  109592. float *logmdct);
  109593. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109594. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109595. vorbis_info_psy_global *g,
  109596. vorbis_look_psy *p,
  109597. vorbis_info_mapping0 *vi,
  109598. float **mdct);
  109599. extern void _vp_couple(int blobno,
  109600. vorbis_info_psy_global *g,
  109601. vorbis_look_psy *p,
  109602. vorbis_info_mapping0 *vi,
  109603. float **res,
  109604. float **mag_memo,
  109605. int **mag_sort,
  109606. int **ifloor,
  109607. int *nonzero,
  109608. int sliding_lowpass);
  109609. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109610. float *in,float *out,int *sortedindex);
  109611. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109612. float *magnitudes,int *sortedindex);
  109613. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109614. vorbis_look_psy *p,
  109615. vorbis_info_mapping0 *vi,
  109616. float **mags);
  109617. extern void hf_reduction(vorbis_info_psy_global *g,
  109618. vorbis_look_psy *p,
  109619. vorbis_info_mapping0 *vi,
  109620. float **mdct);
  109621. #endif
  109622. /*** End of inlined file: psy.h ***/
  109623. /*** Start of inlined file: bitrate.h ***/
  109624. #ifndef _V_BITRATE_H_
  109625. #define _V_BITRATE_H_
  109626. /*** Start of inlined file: os.h ***/
  109627. #ifndef _OS_H
  109628. #define _OS_H
  109629. /********************************************************************
  109630. * *
  109631. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109632. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109633. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109634. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109635. * *
  109636. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109637. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109638. * *
  109639. ********************************************************************
  109640. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109641. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109642. ********************************************************************/
  109643. #ifdef HAVE_CONFIG_H
  109644. #include "config.h"
  109645. #endif
  109646. #include <math.h>
  109647. /*** Start of inlined file: misc.h ***/
  109648. #ifndef _V_RANDOM_H_
  109649. #define _V_RANDOM_H_
  109650. extern int analysis_noisy;
  109651. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109652. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109653. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109654. ogg_int64_t off);
  109655. #ifdef DEBUG_MALLOC
  109656. #define _VDBG_GRAPHFILE "malloc.m"
  109657. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109658. extern void _VDBG_free(void *ptr,char *file,long line);
  109659. #ifndef MISC_C
  109660. #undef _ogg_malloc
  109661. #undef _ogg_calloc
  109662. #undef _ogg_realloc
  109663. #undef _ogg_free
  109664. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109665. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109666. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109667. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109668. #endif
  109669. #endif
  109670. #endif
  109671. /*** End of inlined file: misc.h ***/
  109672. #ifndef _V_IFDEFJAIL_H_
  109673. # define _V_IFDEFJAIL_H_
  109674. # ifdef __GNUC__
  109675. # define STIN static __inline__
  109676. # elif _WIN32
  109677. # define STIN static __inline
  109678. # else
  109679. # define STIN static
  109680. # endif
  109681. #ifdef DJGPP
  109682. # define rint(x) (floor((x)+0.5f))
  109683. #endif
  109684. #ifndef M_PI
  109685. # define M_PI (3.1415926536f)
  109686. #endif
  109687. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109688. # include <malloc.h>
  109689. # define rint(x) (floor((x)+0.5f))
  109690. # define NO_FLOAT_MATH_LIB
  109691. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109692. #endif
  109693. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109694. void *_alloca(size_t size);
  109695. # define alloca _alloca
  109696. #endif
  109697. #ifndef FAST_HYPOT
  109698. # define FAST_HYPOT hypot
  109699. #endif
  109700. #endif
  109701. #ifdef HAVE_ALLOCA_H
  109702. # include <alloca.h>
  109703. #endif
  109704. #ifdef USE_MEMORY_H
  109705. # include <memory.h>
  109706. #endif
  109707. #ifndef min
  109708. # define min(x,y) ((x)>(y)?(y):(x))
  109709. #endif
  109710. #ifndef max
  109711. # define max(x,y) ((x)<(y)?(y):(x))
  109712. #endif
  109713. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109714. # define VORBIS_FPU_CONTROL
  109715. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109716. Because of encapsulation constraints (GCC can't see inside the asm
  109717. block and so we end up doing stupid things like a store/load that
  109718. is collectively a noop), we do it this way */
  109719. /* we must set up the fpu before this works!! */
  109720. typedef ogg_int16_t vorbis_fpu_control;
  109721. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109722. ogg_int16_t ret;
  109723. ogg_int16_t temp;
  109724. __asm__ __volatile__("fnstcw %0\n\t"
  109725. "movw %0,%%dx\n\t"
  109726. "orw $62463,%%dx\n\t"
  109727. "movw %%dx,%1\n\t"
  109728. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109729. *fpu=ret;
  109730. }
  109731. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109732. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109733. }
  109734. /* assumes the FPU is in round mode! */
  109735. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109736. we get extra fst/fld to
  109737. truncate precision */
  109738. int i;
  109739. __asm__("fistl %0": "=m"(i) : "t"(f));
  109740. return(i);
  109741. }
  109742. #endif
  109743. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109744. # define VORBIS_FPU_CONTROL
  109745. typedef ogg_int16_t vorbis_fpu_control;
  109746. static __inline int vorbis_ftoi(double f){
  109747. int i;
  109748. __asm{
  109749. fld f
  109750. fistp i
  109751. }
  109752. return i;
  109753. }
  109754. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109755. }
  109756. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109757. }
  109758. #endif
  109759. #ifndef VORBIS_FPU_CONTROL
  109760. typedef int vorbis_fpu_control;
  109761. static int vorbis_ftoi(double f){
  109762. return (int)(f+.5);
  109763. }
  109764. /* We don't have special code for this compiler/arch, so do it the slow way */
  109765. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109766. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109767. #endif
  109768. #endif /* _OS_H */
  109769. /*** End of inlined file: os.h ***/
  109770. /* encode side bitrate tracking */
  109771. typedef struct bitrate_manager_state {
  109772. int managed;
  109773. long avg_reservoir;
  109774. long minmax_reservoir;
  109775. long avg_bitsper;
  109776. long min_bitsper;
  109777. long max_bitsper;
  109778. long short_per_long;
  109779. double avgfloat;
  109780. vorbis_block *vb;
  109781. int choice;
  109782. } bitrate_manager_state;
  109783. typedef struct bitrate_manager_info{
  109784. long avg_rate;
  109785. long min_rate;
  109786. long max_rate;
  109787. long reservoir_bits;
  109788. double reservoir_bias;
  109789. double slew_damp;
  109790. } bitrate_manager_info;
  109791. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109792. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109793. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109794. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109795. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109796. #endif
  109797. /*** End of inlined file: bitrate.h ***/
  109798. static int ilog(unsigned int v){
  109799. int ret=0;
  109800. while(v){
  109801. ret++;
  109802. v>>=1;
  109803. }
  109804. return(ret);
  109805. }
  109806. static int ilog2(unsigned int v){
  109807. int ret=0;
  109808. if(v)--v;
  109809. while(v){
  109810. ret++;
  109811. v>>=1;
  109812. }
  109813. return(ret);
  109814. }
  109815. typedef struct private_state {
  109816. /* local lookup storage */
  109817. envelope_lookup *ve; /* envelope lookup */
  109818. int window[2];
  109819. vorbis_look_transform **transform[2]; /* block, type */
  109820. drft_lookup fft_look[2];
  109821. int modebits;
  109822. vorbis_look_floor **flr;
  109823. vorbis_look_residue **residue;
  109824. vorbis_look_psy *psy;
  109825. vorbis_look_psy_global *psy_g_look;
  109826. /* local storage, only used on the encoding side. This way the
  109827. application does not need to worry about freeing some packets'
  109828. memory and not others'; packet storage is always tracked.
  109829. Cleared next call to a _dsp_ function */
  109830. unsigned char *header;
  109831. unsigned char *header1;
  109832. unsigned char *header2;
  109833. bitrate_manager_state bms;
  109834. ogg_int64_t sample_count;
  109835. } private_state;
  109836. /* codec_setup_info contains all the setup information specific to the
  109837. specific compression/decompression mode in progress (eg,
  109838. psychoacoustic settings, channel setup, options, codebook
  109839. etc).
  109840. *********************************************************************/
  109841. /*** Start of inlined file: highlevel.h ***/
  109842. typedef struct highlevel_byblocktype {
  109843. double tone_mask_setting;
  109844. double tone_peaklimit_setting;
  109845. double noise_bias_setting;
  109846. double noise_compand_setting;
  109847. } highlevel_byblocktype;
  109848. typedef struct highlevel_encode_setup {
  109849. void *setup;
  109850. int set_in_stone;
  109851. double base_setting;
  109852. double long_setting;
  109853. double short_setting;
  109854. double impulse_noisetune;
  109855. int managed;
  109856. long bitrate_min;
  109857. long bitrate_av;
  109858. double bitrate_av_damp;
  109859. long bitrate_max;
  109860. long bitrate_reservoir;
  109861. double bitrate_reservoir_bias;
  109862. int impulse_block_p;
  109863. int noise_normalize_p;
  109864. double stereo_point_setting;
  109865. double lowpass_kHz;
  109866. double ath_floating_dB;
  109867. double ath_absolute_dB;
  109868. double amplitude_track_dBpersec;
  109869. double trigger_setting;
  109870. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  109871. } highlevel_encode_setup;
  109872. /*** End of inlined file: highlevel.h ***/
  109873. typedef struct codec_setup_info {
  109874. /* Vorbis supports only short and long blocks, but allows the
  109875. encoder to choose the sizes */
  109876. long blocksizes[2];
  109877. /* modes are the primary means of supporting on-the-fly different
  109878. blocksizes, different channel mappings (LR or M/A),
  109879. different residue backends, etc. Each mode consists of a
  109880. blocksize flag and a mapping (along with the mapping setup */
  109881. int modes;
  109882. int maps;
  109883. int floors;
  109884. int residues;
  109885. int books;
  109886. int psys; /* encode only */
  109887. vorbis_info_mode *mode_param[64];
  109888. int map_type[64];
  109889. vorbis_info_mapping *map_param[64];
  109890. int floor_type[64];
  109891. vorbis_info_floor *floor_param[64];
  109892. int residue_type[64];
  109893. vorbis_info_residue *residue_param[64];
  109894. static_codebook *book_param[256];
  109895. codebook *fullbooks;
  109896. vorbis_info_psy *psy_param[4]; /* encode only */
  109897. vorbis_info_psy_global psy_g_param;
  109898. bitrate_manager_info bi;
  109899. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  109900. highly redundant structure, but
  109901. improves clarity of program flow. */
  109902. int halfrate_flag; /* painless downsample for decode */
  109903. } codec_setup_info;
  109904. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  109905. extern void _vp_global_free(vorbis_look_psy_global *look);
  109906. #endif
  109907. /*** End of inlined file: codec_internal.h ***/
  109908. /*** Start of inlined file: registry.h ***/
  109909. #ifndef _V_REG_H_
  109910. #define _V_REG_H_
  109911. #define VI_TRANSFORMB 1
  109912. #define VI_WINDOWB 1
  109913. #define VI_TIMEB 1
  109914. #define VI_FLOORB 2
  109915. #define VI_RESB 3
  109916. #define VI_MAPB 1
  109917. extern vorbis_func_floor *_floor_P[];
  109918. extern vorbis_func_residue *_residue_P[];
  109919. extern vorbis_func_mapping *_mapping_P[];
  109920. #endif
  109921. /*** End of inlined file: registry.h ***/
  109922. /*** Start of inlined file: scales.h ***/
  109923. #ifndef _V_SCALES_H_
  109924. #define _V_SCALES_H_
  109925. #include <math.h>
  109926. /* 20log10(x) */
  109927. #define VORBIS_IEEE_FLOAT32 1
  109928. #ifdef VORBIS_IEEE_FLOAT32
  109929. static float unitnorm(float x){
  109930. union {
  109931. ogg_uint32_t i;
  109932. float f;
  109933. } ix;
  109934. ix.f = x;
  109935. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  109936. return ix.f;
  109937. }
  109938. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  109939. static float todB(const float *x){
  109940. union {
  109941. ogg_uint32_t i;
  109942. float f;
  109943. } ix;
  109944. ix.f = *x;
  109945. ix.i = ix.i&0x7fffffff;
  109946. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  109947. }
  109948. #define todB_nn(x) todB(x)
  109949. #else
  109950. static float unitnorm(float x){
  109951. if(x<0)return(-1.f);
  109952. return(1.f);
  109953. }
  109954. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  109955. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  109956. #endif
  109957. #define fromdB(x) (exp((x)*.11512925f))
  109958. /* The bark scale equations are approximations, since the original
  109959. table was somewhat hand rolled. The below are chosen to have the
  109960. best possible fit to the rolled tables, thus their somewhat odd
  109961. appearance (these are more accurate and over a longer range than
  109962. the oft-quoted bark equations found in the texts I have). The
  109963. approximations are valid from 0 - 30kHz (nyquist) or so.
  109964. all f in Hz, z in Bark */
  109965. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  109966. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  109967. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  109968. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  109969. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  109970. 0.0 */
  109971. #define toOC(n) (log(n)*1.442695f-5.965784f)
  109972. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  109973. #endif
  109974. /*** End of inlined file: scales.h ***/
  109975. int analysis_noisy=1;
  109976. /* decides between modes, dispatches to the appropriate mapping. */
  109977. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  109978. int ret,i;
  109979. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109980. vb->glue_bits=0;
  109981. vb->time_bits=0;
  109982. vb->floor_bits=0;
  109983. vb->res_bits=0;
  109984. /* first things first. Make sure encode is ready */
  109985. for(i=0;i<PACKETBLOBS;i++)
  109986. oggpack_reset(vbi->packetblob[i]);
  109987. /* we only have one mapping type (0), and we let the mapping code
  109988. itself figure out what soft mode to use. This allows easier
  109989. bitrate management */
  109990. if((ret=_mapping_P[0]->forward(vb)))
  109991. return(ret);
  109992. if(op){
  109993. if(vorbis_bitrate_managed(vb))
  109994. /* The app is using a bitmanaged mode... but not using the
  109995. bitrate management interface. */
  109996. return(OV_EINVAL);
  109997. op->packet=oggpack_get_buffer(&vb->opb);
  109998. op->bytes=oggpack_bytes(&vb->opb);
  109999. op->b_o_s=0;
  110000. op->e_o_s=vb->eofflag;
  110001. op->granulepos=vb->granulepos;
  110002. op->packetno=vb->sequence; /* for sake of completeness */
  110003. }
  110004. return(0);
  110005. }
  110006. /* there was no great place to put this.... */
  110007. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110008. int j;
  110009. FILE *of;
  110010. char buffer[80];
  110011. /* if(i==5870){*/
  110012. sprintf(buffer,"%s_%d.m",base,i);
  110013. of=fopen(buffer,"w");
  110014. if(!of)perror("failed to open data dump file");
  110015. for(j=0;j<n;j++){
  110016. if(bark){
  110017. float b=toBARK((4000.f*j/n)+.25);
  110018. fprintf(of,"%f ",b);
  110019. }else
  110020. if(off!=0)
  110021. fprintf(of,"%f ",(double)(j+off)/8000.);
  110022. else
  110023. fprintf(of,"%f ",(double)j);
  110024. if(dB){
  110025. float val;
  110026. if(v[j]==0.)
  110027. val=-140.;
  110028. else
  110029. val=todB(v+j);
  110030. fprintf(of,"%f\n",val);
  110031. }else{
  110032. fprintf(of,"%f\n",v[j]);
  110033. }
  110034. }
  110035. fclose(of);
  110036. /* } */
  110037. }
  110038. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110039. ogg_int64_t off){
  110040. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110041. }
  110042. #endif
  110043. /*** End of inlined file: analysis.c ***/
  110044. /*** Start of inlined file: bitrate.c ***/
  110045. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110046. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110047. // tasks..
  110048. #if JUCE_MSVC
  110049. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110050. #endif
  110051. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110052. #if JUCE_USE_OGGVORBIS
  110053. #include <stdlib.h>
  110054. #include <string.h>
  110055. #include <math.h>
  110056. /* compute bitrate tracking setup */
  110057. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110058. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110059. bitrate_manager_info *bi=&ci->bi;
  110060. memset(bm,0,sizeof(*bm));
  110061. if(bi && (bi->reservoir_bits>0)){
  110062. long ratesamples=vi->rate;
  110063. int halfsamples=ci->blocksizes[0]>>1;
  110064. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110065. bm->managed=1;
  110066. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110067. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110068. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110069. bm->avgfloat=PACKETBLOBS/2;
  110070. /* not a necessary fix, but one that leads to a more balanced
  110071. typical initialization */
  110072. {
  110073. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110074. bm->minmax_reservoir=desired_fill;
  110075. bm->avg_reservoir=desired_fill;
  110076. }
  110077. }
  110078. }
  110079. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110080. memset(bm,0,sizeof(*bm));
  110081. return;
  110082. }
  110083. int vorbis_bitrate_managed(vorbis_block *vb){
  110084. vorbis_dsp_state *vd=vb->vd;
  110085. private_state *b=(private_state*)vd->backend_state;
  110086. bitrate_manager_state *bm=&b->bms;
  110087. if(bm && bm->managed)return(1);
  110088. return(0);
  110089. }
  110090. /* finish taking in the block we just processed */
  110091. int vorbis_bitrate_addblock(vorbis_block *vb){
  110092. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110093. vorbis_dsp_state *vd=vb->vd;
  110094. private_state *b=(private_state*)vd->backend_state;
  110095. bitrate_manager_state *bm=&b->bms;
  110096. vorbis_info *vi=vd->vi;
  110097. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110098. bitrate_manager_info *bi=&ci->bi;
  110099. int choice=rint(bm->avgfloat);
  110100. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110101. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110102. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110103. int samples=ci->blocksizes[vb->W]>>1;
  110104. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110105. if(!bm->managed){
  110106. /* not a bitrate managed stream, but for API simplicity, we'll
  110107. buffer the packet to keep the code path clean */
  110108. if(bm->vb)return(-1); /* one has been submitted without
  110109. being claimed */
  110110. bm->vb=vb;
  110111. return(0);
  110112. }
  110113. bm->vb=vb;
  110114. /* look ahead for avg floater */
  110115. if(bm->avg_bitsper>0){
  110116. double slew=0.;
  110117. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110118. double slewlimit= 15./bi->slew_damp;
  110119. /* choosing a new floater:
  110120. if we're over target, we slew down
  110121. if we're under target, we slew up
  110122. choose slew as follows: look through packetblobs of this frame
  110123. and set slew as the first in the appropriate direction that
  110124. gives us the slew we want. This may mean no slew if delta is
  110125. already favorable.
  110126. Then limit slew to slew max */
  110127. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110128. while(choice>0 && this_bits>avg_target_bits &&
  110129. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110130. choice--;
  110131. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110132. }
  110133. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110134. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110135. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110136. choice++;
  110137. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110138. }
  110139. }
  110140. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110141. if(slew<-slewlimit)slew=-slewlimit;
  110142. if(slew>slewlimit)slew=slewlimit;
  110143. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110144. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110145. }
  110146. /* enforce min(if used) on the current floater (if used) */
  110147. if(bm->min_bitsper>0){
  110148. /* do we need to force the bitrate up? */
  110149. if(this_bits<min_target_bits){
  110150. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110151. choice++;
  110152. if(choice>=PACKETBLOBS)break;
  110153. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110154. }
  110155. }
  110156. }
  110157. /* enforce max (if used) on the current floater (if used) */
  110158. if(bm->max_bitsper>0){
  110159. /* do we need to force the bitrate down? */
  110160. if(this_bits>max_target_bits){
  110161. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110162. choice--;
  110163. if(choice<0)break;
  110164. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110165. }
  110166. }
  110167. }
  110168. /* Choice of packetblobs now made based on floater, and min/max
  110169. requirements. Now boundary check extreme choices */
  110170. if(choice<0){
  110171. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110172. frame will need to be truncated */
  110173. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110174. bm->choice=choice=0;
  110175. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110176. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110177. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110178. }
  110179. }else{
  110180. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110181. if(choice>=PACKETBLOBS)
  110182. choice=PACKETBLOBS-1;
  110183. bm->choice=choice;
  110184. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110185. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110186. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110187. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110188. }
  110189. /* now we have the final packet and the final packet size. Update statistics */
  110190. /* min and max reservoir */
  110191. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110192. if(max_target_bits>0 && this_bits>max_target_bits){
  110193. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110194. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110195. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110196. }else{
  110197. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110198. if(bm->minmax_reservoir>desired_fill){
  110199. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110200. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110201. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110202. }else{
  110203. bm->minmax_reservoir=desired_fill;
  110204. }
  110205. }else{
  110206. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110207. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110208. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110209. }else{
  110210. bm->minmax_reservoir=desired_fill;
  110211. }
  110212. }
  110213. }
  110214. }
  110215. /* avg reservoir */
  110216. if(bm->avg_bitsper>0){
  110217. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110218. bm->avg_reservoir+=this_bits-avg_target_bits;
  110219. }
  110220. return(0);
  110221. }
  110222. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110223. private_state *b=(private_state*)vd->backend_state;
  110224. bitrate_manager_state *bm=&b->bms;
  110225. vorbis_block *vb=bm->vb;
  110226. int choice=PACKETBLOBS/2;
  110227. if(!vb)return 0;
  110228. if(op){
  110229. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110230. if(vorbis_bitrate_managed(vb))
  110231. choice=bm->choice;
  110232. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110233. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110234. op->b_o_s=0;
  110235. op->e_o_s=vb->eofflag;
  110236. op->granulepos=vb->granulepos;
  110237. op->packetno=vb->sequence; /* for sake of completeness */
  110238. }
  110239. bm->vb=0;
  110240. return(1);
  110241. }
  110242. #endif
  110243. /*** End of inlined file: bitrate.c ***/
  110244. /*** Start of inlined file: block.c ***/
  110245. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110246. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110247. // tasks..
  110248. #if JUCE_MSVC
  110249. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110250. #endif
  110251. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110252. #if JUCE_USE_OGGVORBIS
  110253. #include <stdio.h>
  110254. #include <stdlib.h>
  110255. #include <string.h>
  110256. /*** Start of inlined file: window.h ***/
  110257. #ifndef _V_WINDOW_
  110258. #define _V_WINDOW_
  110259. extern float *_vorbis_window_get(int n);
  110260. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110261. int lW,int W,int nW);
  110262. #endif
  110263. /*** End of inlined file: window.h ***/
  110264. /*** Start of inlined file: lpc.h ***/
  110265. #ifndef _V_LPC_H_
  110266. #define _V_LPC_H_
  110267. /* simple linear scale LPC code */
  110268. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110269. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110270. float *data,long n);
  110271. #endif
  110272. /*** End of inlined file: lpc.h ***/
  110273. /* pcm accumulator examples (not exhaustive):
  110274. <-------------- lW ---------------->
  110275. <--------------- W ---------------->
  110276. : .....|..... _______________ |
  110277. : .''' | '''_--- | |\ |
  110278. :.....''' |_____--- '''......| | \_______|
  110279. :.................|__________________|_______|__|______|
  110280. |<------ Sl ------>| > Sr < |endW
  110281. |beginSl |endSl | |endSr
  110282. |beginW |endlW |beginSr
  110283. |< lW >|
  110284. <--------------- W ---------------->
  110285. | | .. ______________ |
  110286. | | ' `/ | ---_ |
  110287. |___.'___/`. | ---_____|
  110288. |_______|__|_______|_________________|
  110289. | >|Sl|< |<------ Sr ----->|endW
  110290. | | |endSl |beginSr |endSr
  110291. |beginW | |endlW
  110292. mult[0] |beginSl mult[n]
  110293. <-------------- lW ----------------->
  110294. |<--W-->|
  110295. : .............. ___ | |
  110296. : .''' |`/ \ | |
  110297. :.....''' |/`....\|...|
  110298. :.........................|___|___|___|
  110299. |Sl |Sr |endW
  110300. | | |endSr
  110301. | |beginSr
  110302. | |endSl
  110303. |beginSl
  110304. |beginW
  110305. */
  110306. /* block abstraction setup *********************************************/
  110307. #ifndef WORD_ALIGN
  110308. #define WORD_ALIGN 8
  110309. #endif
  110310. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110311. int i;
  110312. memset(vb,0,sizeof(*vb));
  110313. vb->vd=v;
  110314. vb->localalloc=0;
  110315. vb->localstore=NULL;
  110316. if(v->analysisp){
  110317. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110318. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110319. vbi->ampmax=-9999;
  110320. for(i=0;i<PACKETBLOBS;i++){
  110321. if(i==PACKETBLOBS/2){
  110322. vbi->packetblob[i]=&vb->opb;
  110323. }else{
  110324. vbi->packetblob[i]=
  110325. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110326. }
  110327. oggpack_writeinit(vbi->packetblob[i]);
  110328. }
  110329. }
  110330. return(0);
  110331. }
  110332. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110333. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110334. if(bytes+vb->localtop>vb->localalloc){
  110335. /* can't just _ogg_realloc... there are outstanding pointers */
  110336. if(vb->localstore){
  110337. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110338. vb->totaluse+=vb->localtop;
  110339. link->next=vb->reap;
  110340. link->ptr=vb->localstore;
  110341. vb->reap=link;
  110342. }
  110343. /* highly conservative */
  110344. vb->localalloc=bytes;
  110345. vb->localstore=_ogg_malloc(vb->localalloc);
  110346. vb->localtop=0;
  110347. }
  110348. {
  110349. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110350. vb->localtop+=bytes;
  110351. return ret;
  110352. }
  110353. }
  110354. /* reap the chain, pull the ripcord */
  110355. void _vorbis_block_ripcord(vorbis_block *vb){
  110356. /* reap the chain */
  110357. struct alloc_chain *reap=vb->reap;
  110358. while(reap){
  110359. struct alloc_chain *next=reap->next;
  110360. _ogg_free(reap->ptr);
  110361. memset(reap,0,sizeof(*reap));
  110362. _ogg_free(reap);
  110363. reap=next;
  110364. }
  110365. /* consolidate storage */
  110366. if(vb->totaluse){
  110367. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110368. vb->localalloc+=vb->totaluse;
  110369. vb->totaluse=0;
  110370. }
  110371. /* pull the ripcord */
  110372. vb->localtop=0;
  110373. vb->reap=NULL;
  110374. }
  110375. int vorbis_block_clear(vorbis_block *vb){
  110376. int i;
  110377. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110378. _vorbis_block_ripcord(vb);
  110379. if(vb->localstore)_ogg_free(vb->localstore);
  110380. if(vbi){
  110381. for(i=0;i<PACKETBLOBS;i++){
  110382. oggpack_writeclear(vbi->packetblob[i]);
  110383. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110384. }
  110385. _ogg_free(vbi);
  110386. }
  110387. memset(vb,0,sizeof(*vb));
  110388. return(0);
  110389. }
  110390. /* Analysis side code, but directly related to blocking. Thus it's
  110391. here and not in analysis.c (which is for analysis transforms only).
  110392. The init is here because some of it is shared */
  110393. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110394. int i;
  110395. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110396. private_state *b=NULL;
  110397. int hs;
  110398. if(ci==NULL) return 1;
  110399. hs=ci->halfrate_flag;
  110400. memset(v,0,sizeof(*v));
  110401. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110402. v->vi=vi;
  110403. b->modebits=ilog2(ci->modes);
  110404. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110405. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110406. /* MDCT is tranform 0 */
  110407. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110408. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110409. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110410. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110411. /* Vorbis I uses only window type 0 */
  110412. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110413. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110414. if(encp){ /* encode/decode differ here */
  110415. /* analysis always needs an fft */
  110416. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110417. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110418. /* finish the codebooks */
  110419. if(!ci->fullbooks){
  110420. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110421. for(i=0;i<ci->books;i++)
  110422. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110423. }
  110424. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110425. for(i=0;i<ci->psys;i++){
  110426. _vp_psy_init(b->psy+i,
  110427. ci->psy_param[i],
  110428. &ci->psy_g_param,
  110429. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110430. vi->rate);
  110431. }
  110432. v->analysisp=1;
  110433. }else{
  110434. /* finish the codebooks */
  110435. if(!ci->fullbooks){
  110436. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110437. for(i=0;i<ci->books;i++){
  110438. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110439. /* decode codebooks are now standalone after init */
  110440. vorbis_staticbook_destroy(ci->book_param[i]);
  110441. ci->book_param[i]=NULL;
  110442. }
  110443. }
  110444. }
  110445. /* initialize the storage vectors. blocksize[1] is small for encode,
  110446. but the correct size for decode */
  110447. v->pcm_storage=ci->blocksizes[1];
  110448. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110449. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110450. {
  110451. int i;
  110452. for(i=0;i<vi->channels;i++)
  110453. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110454. }
  110455. /* all 1 (large block) or 0 (small block) */
  110456. /* explicitly set for the sake of clarity */
  110457. v->lW=0; /* previous window size */
  110458. v->W=0; /* current window size */
  110459. /* all vector indexes */
  110460. v->centerW=ci->blocksizes[1]/2;
  110461. v->pcm_current=v->centerW;
  110462. /* initialize all the backend lookups */
  110463. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110464. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110465. for(i=0;i<ci->floors;i++)
  110466. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110467. look(v,ci->floor_param[i]);
  110468. for(i=0;i<ci->residues;i++)
  110469. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110470. look(v,ci->residue_param[i]);
  110471. return 0;
  110472. }
  110473. /* arbitrary settings and spec-mandated numbers get filled in here */
  110474. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110475. private_state *b=NULL;
  110476. if(_vds_shared_init(v,vi,1))return 1;
  110477. b=(private_state*)v->backend_state;
  110478. b->psy_g_look=_vp_global_look(vi);
  110479. /* Initialize the envelope state storage */
  110480. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110481. _ve_envelope_init(b->ve,vi);
  110482. vorbis_bitrate_init(vi,&b->bms);
  110483. /* compressed audio packets start after the headers
  110484. with sequence number 3 */
  110485. v->sequence=3;
  110486. return(0);
  110487. }
  110488. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110489. int i;
  110490. if(v){
  110491. vorbis_info *vi=v->vi;
  110492. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110493. private_state *b=(private_state*)v->backend_state;
  110494. if(b){
  110495. if(b->ve){
  110496. _ve_envelope_clear(b->ve);
  110497. _ogg_free(b->ve);
  110498. }
  110499. if(b->transform[0]){
  110500. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110501. _ogg_free(b->transform[0][0]);
  110502. _ogg_free(b->transform[0]);
  110503. }
  110504. if(b->transform[1]){
  110505. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110506. _ogg_free(b->transform[1][0]);
  110507. _ogg_free(b->transform[1]);
  110508. }
  110509. if(b->flr){
  110510. for(i=0;i<ci->floors;i++)
  110511. _floor_P[ci->floor_type[i]]->
  110512. free_look(b->flr[i]);
  110513. _ogg_free(b->flr);
  110514. }
  110515. if(b->residue){
  110516. for(i=0;i<ci->residues;i++)
  110517. _residue_P[ci->residue_type[i]]->
  110518. free_look(b->residue[i]);
  110519. _ogg_free(b->residue);
  110520. }
  110521. if(b->psy){
  110522. for(i=0;i<ci->psys;i++)
  110523. _vp_psy_clear(b->psy+i);
  110524. _ogg_free(b->psy);
  110525. }
  110526. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110527. vorbis_bitrate_clear(&b->bms);
  110528. drft_clear(&b->fft_look[0]);
  110529. drft_clear(&b->fft_look[1]);
  110530. }
  110531. if(v->pcm){
  110532. for(i=0;i<vi->channels;i++)
  110533. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110534. _ogg_free(v->pcm);
  110535. if(v->pcmret)_ogg_free(v->pcmret);
  110536. }
  110537. if(b){
  110538. /* free header, header1, header2 */
  110539. if(b->header)_ogg_free(b->header);
  110540. if(b->header1)_ogg_free(b->header1);
  110541. if(b->header2)_ogg_free(b->header2);
  110542. _ogg_free(b);
  110543. }
  110544. memset(v,0,sizeof(*v));
  110545. }
  110546. }
  110547. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110548. int i;
  110549. vorbis_info *vi=v->vi;
  110550. private_state *b=(private_state*)v->backend_state;
  110551. /* free header, header1, header2 */
  110552. if(b->header)_ogg_free(b->header);b->header=NULL;
  110553. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110554. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110555. /* Do we have enough storage space for the requested buffer? If not,
  110556. expand the PCM (and envelope) storage */
  110557. if(v->pcm_current+vals>=v->pcm_storage){
  110558. v->pcm_storage=v->pcm_current+vals*2;
  110559. for(i=0;i<vi->channels;i++){
  110560. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110561. }
  110562. }
  110563. for(i=0;i<vi->channels;i++)
  110564. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110565. return(v->pcmret);
  110566. }
  110567. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110568. int i;
  110569. int order=32;
  110570. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110571. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110572. long j;
  110573. v->preextrapolate=1;
  110574. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110575. for(i=0;i<v->vi->channels;i++){
  110576. /* need to run the extrapolation in reverse! */
  110577. for(j=0;j<v->pcm_current;j++)
  110578. work[j]=v->pcm[i][v->pcm_current-j-1];
  110579. /* prime as above */
  110580. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110581. /* run the predictor filter */
  110582. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110583. order,
  110584. work+v->pcm_current-v->centerW,
  110585. v->centerW);
  110586. for(j=0;j<v->pcm_current;j++)
  110587. v->pcm[i][v->pcm_current-j-1]=work[j];
  110588. }
  110589. }
  110590. }
  110591. /* call with val<=0 to set eof */
  110592. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110593. vorbis_info *vi=v->vi;
  110594. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110595. if(vals<=0){
  110596. int order=32;
  110597. int i;
  110598. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110599. /* if it wasn't done earlier (very short sample) */
  110600. if(!v->preextrapolate)
  110601. _preextrapolate_helper(v);
  110602. /* We're encoding the end of the stream. Just make sure we have
  110603. [at least] a few full blocks of zeroes at the end. */
  110604. /* actually, we don't want zeroes; that could drop a large
  110605. amplitude off a cliff, creating spread spectrum noise that will
  110606. suck to encode. Extrapolate for the sake of cleanliness. */
  110607. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110608. v->eofflag=v->pcm_current;
  110609. v->pcm_current+=ci->blocksizes[1]*3;
  110610. for(i=0;i<vi->channels;i++){
  110611. if(v->eofflag>order*2){
  110612. /* extrapolate with LPC to fill in */
  110613. long n;
  110614. /* make a predictor filter */
  110615. n=v->eofflag;
  110616. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110617. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110618. /* run the predictor filter */
  110619. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110620. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110621. }else{
  110622. /* not enough data to extrapolate (unlikely to happen due to
  110623. guarding the overlap, but bulletproof in case that
  110624. assumtion goes away). zeroes will do. */
  110625. memset(v->pcm[i]+v->eofflag,0,
  110626. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110627. }
  110628. }
  110629. }else{
  110630. if(v->pcm_current+vals>v->pcm_storage)
  110631. return(OV_EINVAL);
  110632. v->pcm_current+=vals;
  110633. /* we may want to reverse extrapolate the beginning of a stream
  110634. too... in case we're beginning on a cliff! */
  110635. /* clumsy, but simple. It only runs once, so simple is good. */
  110636. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110637. _preextrapolate_helper(v);
  110638. }
  110639. return(0);
  110640. }
  110641. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110642. the next block on which to continue analysis */
  110643. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110644. int i;
  110645. vorbis_info *vi=v->vi;
  110646. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110647. private_state *b=(private_state*)v->backend_state;
  110648. vorbis_look_psy_global *g=b->psy_g_look;
  110649. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110650. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110651. /* check to see if we're started... */
  110652. if(!v->preextrapolate)return(0);
  110653. /* check to see if we're done... */
  110654. if(v->eofflag==-1)return(0);
  110655. /* By our invariant, we have lW, W and centerW set. Search for
  110656. the next boundary so we can determine nW (the next window size)
  110657. which lets us compute the shape of the current block's window */
  110658. /* we do an envelope search even on a single blocksize; we may still
  110659. be throwing more bits at impulses, and envelope search handles
  110660. marking impulses too. */
  110661. {
  110662. long bp=_ve_envelope_search(v);
  110663. if(bp==-1){
  110664. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110665. full long block */
  110666. v->nW=0;
  110667. }else{
  110668. if(ci->blocksizes[0]==ci->blocksizes[1])
  110669. v->nW=0;
  110670. else
  110671. v->nW=bp;
  110672. }
  110673. }
  110674. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110675. {
  110676. /* center of next block + next block maximum right side. */
  110677. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110678. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110679. although this check is
  110680. less strict that the
  110681. _ve_envelope_search,
  110682. the search is not run
  110683. if we only use one
  110684. block size */
  110685. }
  110686. /* fill in the block. Note that for a short window, lW and nW are *short*
  110687. regardless of actual settings in the stream */
  110688. _vorbis_block_ripcord(vb);
  110689. vb->lW=v->lW;
  110690. vb->W=v->W;
  110691. vb->nW=v->nW;
  110692. if(v->W){
  110693. if(!v->lW || !v->nW){
  110694. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110695. /*fprintf(stderr,"-");*/
  110696. }else{
  110697. vbi->blocktype=BLOCKTYPE_LONG;
  110698. /*fprintf(stderr,"_");*/
  110699. }
  110700. }else{
  110701. if(_ve_envelope_mark(v)){
  110702. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110703. /*fprintf(stderr,"|");*/
  110704. }else{
  110705. vbi->blocktype=BLOCKTYPE_PADDING;
  110706. /*fprintf(stderr,".");*/
  110707. }
  110708. }
  110709. vb->vd=v;
  110710. vb->sequence=v->sequence++;
  110711. vb->granulepos=v->granulepos;
  110712. vb->pcmend=ci->blocksizes[v->W];
  110713. /* copy the vectors; this uses the local storage in vb */
  110714. /* this tracks 'strongest peak' for later psychoacoustics */
  110715. /* moved to the global psy state; clean this mess up */
  110716. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110717. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110718. vbi->ampmax=g->ampmax;
  110719. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110720. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110721. for(i=0;i<vi->channels;i++){
  110722. vbi->pcmdelay[i]=
  110723. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110724. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110725. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110726. /* before we added the delay
  110727. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110728. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110729. */
  110730. }
  110731. /* handle eof detection: eof==0 means that we've not yet received EOF
  110732. eof>0 marks the last 'real' sample in pcm[]
  110733. eof<0 'no more to do'; doesn't get here */
  110734. if(v->eofflag){
  110735. if(v->centerW>=v->eofflag){
  110736. v->eofflag=-1;
  110737. vb->eofflag=1;
  110738. return(1);
  110739. }
  110740. }
  110741. /* advance storage vectors and clean up */
  110742. {
  110743. int new_centerNext=ci->blocksizes[1]/2;
  110744. int movementW=centerNext-new_centerNext;
  110745. if(movementW>0){
  110746. _ve_envelope_shift(b->ve,movementW);
  110747. v->pcm_current-=movementW;
  110748. for(i=0;i<vi->channels;i++)
  110749. memmove(v->pcm[i],v->pcm[i]+movementW,
  110750. v->pcm_current*sizeof(*v->pcm[i]));
  110751. v->lW=v->W;
  110752. v->W=v->nW;
  110753. v->centerW=new_centerNext;
  110754. if(v->eofflag){
  110755. v->eofflag-=movementW;
  110756. if(v->eofflag<=0)v->eofflag=-1;
  110757. /* do not add padding to end of stream! */
  110758. if(v->centerW>=v->eofflag){
  110759. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110760. }else{
  110761. v->granulepos+=movementW;
  110762. }
  110763. }else{
  110764. v->granulepos+=movementW;
  110765. }
  110766. }
  110767. }
  110768. /* done */
  110769. return(1);
  110770. }
  110771. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110772. vorbis_info *vi=v->vi;
  110773. codec_setup_info *ci;
  110774. int hs;
  110775. if(!v->backend_state)return -1;
  110776. if(!vi)return -1;
  110777. ci=(codec_setup_info*) vi->codec_setup;
  110778. if(!ci)return -1;
  110779. hs=ci->halfrate_flag;
  110780. v->centerW=ci->blocksizes[1]>>(hs+1);
  110781. v->pcm_current=v->centerW>>hs;
  110782. v->pcm_returned=-1;
  110783. v->granulepos=-1;
  110784. v->sequence=-1;
  110785. v->eofflag=0;
  110786. ((private_state *)(v->backend_state))->sample_count=-1;
  110787. return(0);
  110788. }
  110789. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110790. if(_vds_shared_init(v,vi,0)) return 1;
  110791. vorbis_synthesis_restart(v);
  110792. return 0;
  110793. }
  110794. /* Unlike in analysis, the window is only partially applied for each
  110795. block. The time domain envelope is not yet handled at the point of
  110796. calling (as it relies on the previous block). */
  110797. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110798. vorbis_info *vi=v->vi;
  110799. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110800. private_state *b=(private_state*)v->backend_state;
  110801. int hs=ci->halfrate_flag;
  110802. int i,j;
  110803. if(!vb)return(OV_EINVAL);
  110804. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110805. v->lW=v->W;
  110806. v->W=vb->W;
  110807. v->nW=-1;
  110808. if((v->sequence==-1)||
  110809. (v->sequence+1 != vb->sequence)){
  110810. v->granulepos=-1; /* out of sequence; lose count */
  110811. b->sample_count=-1;
  110812. }
  110813. v->sequence=vb->sequence;
  110814. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110815. was called on block */
  110816. int n=ci->blocksizes[v->W]>>(hs+1);
  110817. int n0=ci->blocksizes[0]>>(hs+1);
  110818. int n1=ci->blocksizes[1]>>(hs+1);
  110819. int thisCenter;
  110820. int prevCenter;
  110821. v->glue_bits+=vb->glue_bits;
  110822. v->time_bits+=vb->time_bits;
  110823. v->floor_bits+=vb->floor_bits;
  110824. v->res_bits+=vb->res_bits;
  110825. if(v->centerW){
  110826. thisCenter=n1;
  110827. prevCenter=0;
  110828. }else{
  110829. thisCenter=0;
  110830. prevCenter=n1;
  110831. }
  110832. /* v->pcm is now used like a two-stage double buffer. We don't want
  110833. to have to constantly shift *or* adjust memory usage. Don't
  110834. accept a new block until the old is shifted out */
  110835. for(j=0;j<vi->channels;j++){
  110836. /* the overlap/add section */
  110837. if(v->lW){
  110838. if(v->W){
  110839. /* large/large */
  110840. float *w=_vorbis_window_get(b->window[1]-hs);
  110841. float *pcm=v->pcm[j]+prevCenter;
  110842. float *p=vb->pcm[j];
  110843. for(i=0;i<n1;i++)
  110844. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  110845. }else{
  110846. /* large/small */
  110847. float *w=_vorbis_window_get(b->window[0]-hs);
  110848. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  110849. float *p=vb->pcm[j];
  110850. for(i=0;i<n0;i++)
  110851. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110852. }
  110853. }else{
  110854. if(v->W){
  110855. /* small/large */
  110856. float *w=_vorbis_window_get(b->window[0]-hs);
  110857. float *pcm=v->pcm[j]+prevCenter;
  110858. float *p=vb->pcm[j]+n1/2-n0/2;
  110859. for(i=0;i<n0;i++)
  110860. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110861. for(;i<n1/2+n0/2;i++)
  110862. pcm[i]=p[i];
  110863. }else{
  110864. /* small/small */
  110865. float *w=_vorbis_window_get(b->window[0]-hs);
  110866. float *pcm=v->pcm[j]+prevCenter;
  110867. float *p=vb->pcm[j];
  110868. for(i=0;i<n0;i++)
  110869. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110870. }
  110871. }
  110872. /* the copy section */
  110873. {
  110874. float *pcm=v->pcm[j]+thisCenter;
  110875. float *p=vb->pcm[j]+n;
  110876. for(i=0;i<n;i++)
  110877. pcm[i]=p[i];
  110878. }
  110879. }
  110880. if(v->centerW)
  110881. v->centerW=0;
  110882. else
  110883. v->centerW=n1;
  110884. /* deal with initial packet state; we do this using the explicit
  110885. pcm_returned==-1 flag otherwise we're sensitive to first block
  110886. being short or long */
  110887. if(v->pcm_returned==-1){
  110888. v->pcm_returned=thisCenter;
  110889. v->pcm_current=thisCenter;
  110890. }else{
  110891. v->pcm_returned=prevCenter;
  110892. v->pcm_current=prevCenter+
  110893. ((ci->blocksizes[v->lW]/4+
  110894. ci->blocksizes[v->W]/4)>>hs);
  110895. }
  110896. }
  110897. /* track the frame number... This is for convenience, but also
  110898. making sure our last packet doesn't end with added padding. If
  110899. the last packet is partial, the number of samples we'll have to
  110900. return will be past the vb->granulepos.
  110901. This is not foolproof! It will be confused if we begin
  110902. decoding at the last page after a seek or hole. In that case,
  110903. we don't have a starting point to judge where the last frame
  110904. is. For this reason, vorbisfile will always try to make sure
  110905. it reads the last two marked pages in proper sequence */
  110906. if(b->sample_count==-1){
  110907. b->sample_count=0;
  110908. }else{
  110909. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110910. }
  110911. if(v->granulepos==-1){
  110912. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  110913. v->granulepos=vb->granulepos;
  110914. /* is this a short page? */
  110915. if(b->sample_count>v->granulepos){
  110916. /* corner case; if this is both the first and last audio page,
  110917. then spec says the end is cut, not beginning */
  110918. if(vb->eofflag){
  110919. /* trim the end */
  110920. /* no preceeding granulepos; assume we started at zero (we'd
  110921. have to in a short single-page stream) */
  110922. /* granulepos could be -1 due to a seek, but that would result
  110923. in a long count, not short count */
  110924. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  110925. }else{
  110926. /* trim the beginning */
  110927. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  110928. if(v->pcm_returned>v->pcm_current)
  110929. v->pcm_returned=v->pcm_current;
  110930. }
  110931. }
  110932. }
  110933. }else{
  110934. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110935. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  110936. if(v->granulepos>vb->granulepos){
  110937. long extra=v->granulepos-vb->granulepos;
  110938. if(extra)
  110939. if(vb->eofflag){
  110940. /* partial last frame. Strip the extra samples off */
  110941. v->pcm_current-=extra>>hs;
  110942. } /* else {Shouldn't happen *unless* the bitstream is out of
  110943. spec. Either way, believe the bitstream } */
  110944. } /* else {Shouldn't happen *unless* the bitstream is out of
  110945. spec. Either way, believe the bitstream } */
  110946. v->granulepos=vb->granulepos;
  110947. }
  110948. }
  110949. /* Update, cleanup */
  110950. if(vb->eofflag)v->eofflag=1;
  110951. return(0);
  110952. }
  110953. /* pcm==NULL indicates we just want the pending samples, no more */
  110954. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  110955. vorbis_info *vi=v->vi;
  110956. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  110957. if(pcm){
  110958. int i;
  110959. for(i=0;i<vi->channels;i++)
  110960. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110961. *pcm=v->pcmret;
  110962. }
  110963. return(v->pcm_current-v->pcm_returned);
  110964. }
  110965. return(0);
  110966. }
  110967. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  110968. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  110969. v->pcm_returned+=n;
  110970. return(0);
  110971. }
  110972. /* intended for use with a specific vorbisfile feature; we want access
  110973. to the [usually synthetic/postextrapolated] buffer and lapping at
  110974. the end of a decode cycle, specifically, a half-short-block worth.
  110975. This funtion works like pcmout above, except it will also expose
  110976. this implicit buffer data not normally decoded. */
  110977. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  110978. vorbis_info *vi=v->vi;
  110979. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110980. int hs=ci->halfrate_flag;
  110981. int n=ci->blocksizes[v->W]>>(hs+1);
  110982. int n0=ci->blocksizes[0]>>(hs+1);
  110983. int n1=ci->blocksizes[1]>>(hs+1);
  110984. int i,j;
  110985. if(v->pcm_returned<0)return 0;
  110986. /* our returned data ends at pcm_returned; because the synthesis pcm
  110987. buffer is a two-fragment ring, that means our data block may be
  110988. fragmented by buffering, wrapping or a short block not filling
  110989. out a buffer. To simplify things, we unfragment if it's at all
  110990. possibly needed. Otherwise, we'd need to call lapout more than
  110991. once as well as hold additional dsp state. Opt for
  110992. simplicity. */
  110993. /* centerW was advanced by blockin; it would be the center of the
  110994. *next* block */
  110995. if(v->centerW==n1){
  110996. /* the data buffer wraps; swap the halves */
  110997. /* slow, sure, small */
  110998. for(j=0;j<vi->channels;j++){
  110999. float *p=v->pcm[j];
  111000. for(i=0;i<n1;i++){
  111001. float temp=p[i];
  111002. p[i]=p[i+n1];
  111003. p[i+n1]=temp;
  111004. }
  111005. }
  111006. v->pcm_current-=n1;
  111007. v->pcm_returned-=n1;
  111008. v->centerW=0;
  111009. }
  111010. /* solidify buffer into contiguous space */
  111011. if((v->lW^v->W)==1){
  111012. /* long/short or short/long */
  111013. for(j=0;j<vi->channels;j++){
  111014. float *s=v->pcm[j];
  111015. float *d=v->pcm[j]+(n1-n0)/2;
  111016. for(i=(n1+n0)/2-1;i>=0;--i)
  111017. d[i]=s[i];
  111018. }
  111019. v->pcm_returned+=(n1-n0)/2;
  111020. v->pcm_current+=(n1-n0)/2;
  111021. }else{
  111022. if(v->lW==0){
  111023. /* short/short */
  111024. for(j=0;j<vi->channels;j++){
  111025. float *s=v->pcm[j];
  111026. float *d=v->pcm[j]+n1-n0;
  111027. for(i=n0-1;i>=0;--i)
  111028. d[i]=s[i];
  111029. }
  111030. v->pcm_returned+=n1-n0;
  111031. v->pcm_current+=n1-n0;
  111032. }
  111033. }
  111034. if(pcm){
  111035. int i;
  111036. for(i=0;i<vi->channels;i++)
  111037. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111038. *pcm=v->pcmret;
  111039. }
  111040. return(n1+n-v->pcm_returned);
  111041. }
  111042. float *vorbis_window(vorbis_dsp_state *v,int W){
  111043. vorbis_info *vi=v->vi;
  111044. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111045. int hs=ci->halfrate_flag;
  111046. private_state *b=(private_state*)v->backend_state;
  111047. if(b->window[W]-1<0)return NULL;
  111048. return _vorbis_window_get(b->window[W]-hs);
  111049. }
  111050. #endif
  111051. /*** End of inlined file: block.c ***/
  111052. /*** Start of inlined file: codebook.c ***/
  111053. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111054. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111055. // tasks..
  111056. #if JUCE_MSVC
  111057. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111058. #endif
  111059. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111060. #if JUCE_USE_OGGVORBIS
  111061. #include <stdlib.h>
  111062. #include <string.h>
  111063. #include <math.h>
  111064. /* packs the given codebook into the bitstream **************************/
  111065. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111066. long i,j;
  111067. int ordered=0;
  111068. /* first the basic parameters */
  111069. oggpack_write(opb,0x564342,24);
  111070. oggpack_write(opb,c->dim,16);
  111071. oggpack_write(opb,c->entries,24);
  111072. /* pack the codewords. There are two packings; length ordered and
  111073. length random. Decide between the two now. */
  111074. for(i=1;i<c->entries;i++)
  111075. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111076. if(i==c->entries)ordered=1;
  111077. if(ordered){
  111078. /* length ordered. We only need to say how many codewords of
  111079. each length. The actual codewords are generated
  111080. deterministically */
  111081. long count=0;
  111082. oggpack_write(opb,1,1); /* ordered */
  111083. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111084. for(i=1;i<c->entries;i++){
  111085. long thisx=c->lengthlist[i];
  111086. long last=c->lengthlist[i-1];
  111087. if(thisx>last){
  111088. for(j=last;j<thisx;j++){
  111089. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111090. count=i;
  111091. }
  111092. }
  111093. }
  111094. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111095. }else{
  111096. /* length random. Again, we don't code the codeword itself, just
  111097. the length. This time, though, we have to encode each length */
  111098. oggpack_write(opb,0,1); /* unordered */
  111099. /* algortihmic mapping has use for 'unused entries', which we tag
  111100. here. The algorithmic mapping happens as usual, but the unused
  111101. entry has no codeword. */
  111102. for(i=0;i<c->entries;i++)
  111103. if(c->lengthlist[i]==0)break;
  111104. if(i==c->entries){
  111105. oggpack_write(opb,0,1); /* no unused entries */
  111106. for(i=0;i<c->entries;i++)
  111107. oggpack_write(opb,c->lengthlist[i]-1,5);
  111108. }else{
  111109. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111110. for(i=0;i<c->entries;i++){
  111111. if(c->lengthlist[i]==0){
  111112. oggpack_write(opb,0,1);
  111113. }else{
  111114. oggpack_write(opb,1,1);
  111115. oggpack_write(opb,c->lengthlist[i]-1,5);
  111116. }
  111117. }
  111118. }
  111119. }
  111120. /* is the entry number the desired return value, or do we have a
  111121. mapping? If we have a mapping, what type? */
  111122. oggpack_write(opb,c->maptype,4);
  111123. switch(c->maptype){
  111124. case 0:
  111125. /* no mapping */
  111126. break;
  111127. case 1:case 2:
  111128. /* implicitly populated value mapping */
  111129. /* explicitly populated value mapping */
  111130. if(!c->quantlist){
  111131. /* no quantlist? error */
  111132. return(-1);
  111133. }
  111134. /* values that define the dequantization */
  111135. oggpack_write(opb,c->q_min,32);
  111136. oggpack_write(opb,c->q_delta,32);
  111137. oggpack_write(opb,c->q_quant-1,4);
  111138. oggpack_write(opb,c->q_sequencep,1);
  111139. {
  111140. int quantvals;
  111141. switch(c->maptype){
  111142. case 1:
  111143. /* a single column of (c->entries/c->dim) quantized values for
  111144. building a full value list algorithmically (square lattice) */
  111145. quantvals=_book_maptype1_quantvals(c);
  111146. break;
  111147. case 2:
  111148. /* every value (c->entries*c->dim total) specified explicitly */
  111149. quantvals=c->entries*c->dim;
  111150. break;
  111151. default: /* NOT_REACHABLE */
  111152. quantvals=-1;
  111153. }
  111154. /* quantized values */
  111155. for(i=0;i<quantvals;i++)
  111156. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111157. }
  111158. break;
  111159. default:
  111160. /* error case; we don't have any other map types now */
  111161. return(-1);
  111162. }
  111163. return(0);
  111164. }
  111165. /* unpacks a codebook from the packet buffer into the codebook struct,
  111166. readies the codebook auxiliary structures for decode *************/
  111167. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111168. long i,j;
  111169. memset(s,0,sizeof(*s));
  111170. s->allocedp=1;
  111171. /* make sure alignment is correct */
  111172. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111173. /* first the basic parameters */
  111174. s->dim=oggpack_read(opb,16);
  111175. s->entries=oggpack_read(opb,24);
  111176. if(s->entries==-1)goto _eofout;
  111177. /* codeword ordering.... length ordered or unordered? */
  111178. switch((int)oggpack_read(opb,1)){
  111179. case 0:
  111180. /* unordered */
  111181. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111182. /* allocated but unused entries? */
  111183. if(oggpack_read(opb,1)){
  111184. /* yes, unused entries */
  111185. for(i=0;i<s->entries;i++){
  111186. if(oggpack_read(opb,1)){
  111187. long num=oggpack_read(opb,5);
  111188. if(num==-1)goto _eofout;
  111189. s->lengthlist[i]=num+1;
  111190. }else
  111191. s->lengthlist[i]=0;
  111192. }
  111193. }else{
  111194. /* all entries used; no tagging */
  111195. for(i=0;i<s->entries;i++){
  111196. long num=oggpack_read(opb,5);
  111197. if(num==-1)goto _eofout;
  111198. s->lengthlist[i]=num+1;
  111199. }
  111200. }
  111201. break;
  111202. case 1:
  111203. /* ordered */
  111204. {
  111205. long length=oggpack_read(opb,5)+1;
  111206. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111207. for(i=0;i<s->entries;){
  111208. long num=oggpack_read(opb,_ilog(s->entries-i));
  111209. if(num==-1)goto _eofout;
  111210. for(j=0;j<num && i<s->entries;j++,i++)
  111211. s->lengthlist[i]=length;
  111212. length++;
  111213. }
  111214. }
  111215. break;
  111216. default:
  111217. /* EOF */
  111218. return(-1);
  111219. }
  111220. /* Do we have a mapping to unpack? */
  111221. switch((s->maptype=oggpack_read(opb,4))){
  111222. case 0:
  111223. /* no mapping */
  111224. break;
  111225. case 1: case 2:
  111226. /* implicitly populated value mapping */
  111227. /* explicitly populated value mapping */
  111228. s->q_min=oggpack_read(opb,32);
  111229. s->q_delta=oggpack_read(opb,32);
  111230. s->q_quant=oggpack_read(opb,4)+1;
  111231. s->q_sequencep=oggpack_read(opb,1);
  111232. {
  111233. int quantvals=0;
  111234. switch(s->maptype){
  111235. case 1:
  111236. quantvals=_book_maptype1_quantvals(s);
  111237. break;
  111238. case 2:
  111239. quantvals=s->entries*s->dim;
  111240. break;
  111241. }
  111242. /* quantized values */
  111243. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111244. for(i=0;i<quantvals;i++)
  111245. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111246. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111247. }
  111248. break;
  111249. default:
  111250. goto _errout;
  111251. }
  111252. /* all set */
  111253. return(0);
  111254. _errout:
  111255. _eofout:
  111256. vorbis_staticbook_clear(s);
  111257. return(-1);
  111258. }
  111259. /* returns the number of bits ************************************************/
  111260. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111261. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111262. return(book->c->lengthlist[a]);
  111263. }
  111264. /* One the encode side, our vector writers are each designed for a
  111265. specific purpose, and the encoder is not flexible without modification:
  111266. The LSP vector coder uses a single stage nearest-match with no
  111267. interleave, so no step and no error return. This is specced by floor0
  111268. and doesn't change.
  111269. Residue0 encoding interleaves, uses multiple stages, and each stage
  111270. peels of a specific amount of resolution from a lattice (thus we want
  111271. to match by threshold, not nearest match). Residue doesn't *have* to
  111272. be encoded that way, but to change it, one will need to add more
  111273. infrastructure on the encode side (decode side is specced and simpler) */
  111274. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111275. /* returns entry number and *modifies a* to the quantization value *****/
  111276. int vorbis_book_errorv(codebook *book,float *a){
  111277. int dim=book->dim,k;
  111278. int best=_best(book,a,1);
  111279. for(k=0;k<dim;k++)
  111280. a[k]=(book->valuelist+best*dim)[k];
  111281. return(best);
  111282. }
  111283. /* returns the number of bits and *modifies a* to the quantization value *****/
  111284. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111285. int k,dim=book->dim;
  111286. for(k=0;k<dim;k++)
  111287. a[k]=(book->valuelist+best*dim)[k];
  111288. return(vorbis_book_encode(book,best,b));
  111289. }
  111290. /* the 'eliminate the decode tree' optimization actually requires the
  111291. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111292. (and one of the first places where carefully thought out design
  111293. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111294. to an MSb bitpacker), but not actually the huge hit it appears to
  111295. be. The first-stage decode table catches most words so that
  111296. bitreverse is not in the main execution path. */
  111297. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111298. int read=book->dec_maxlength;
  111299. long lo,hi;
  111300. long lok = oggpack_look(b,book->dec_firsttablen);
  111301. if (lok >= 0) {
  111302. long entry = book->dec_firsttable[lok];
  111303. if(entry&0x80000000UL){
  111304. lo=(entry>>15)&0x7fff;
  111305. hi=book->used_entries-(entry&0x7fff);
  111306. }else{
  111307. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111308. return(entry-1);
  111309. }
  111310. }else{
  111311. lo=0;
  111312. hi=book->used_entries;
  111313. }
  111314. lok = oggpack_look(b, read);
  111315. while(lok<0 && read>1)
  111316. lok = oggpack_look(b, --read);
  111317. if(lok<0)return -1;
  111318. /* bisect search for the codeword in the ordered list */
  111319. {
  111320. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111321. while(hi-lo>1){
  111322. long p=(hi-lo)>>1;
  111323. long test=book->codelist[lo+p]>testword;
  111324. lo+=p&(test-1);
  111325. hi-=p&(-test);
  111326. }
  111327. if(book->dec_codelengths[lo]<=read){
  111328. oggpack_adv(b, book->dec_codelengths[lo]);
  111329. return(lo);
  111330. }
  111331. }
  111332. oggpack_adv(b, read);
  111333. return(-1);
  111334. }
  111335. /* Decode side is specced and easier, because we don't need to find
  111336. matches using different criteria; we simply read and map. There are
  111337. two things we need to do 'depending':
  111338. We may need to support interleave. We don't really, but it's
  111339. convenient to do it here rather than rebuild the vector later.
  111340. Cascades may be additive or multiplicitive; this is not inherent in
  111341. the codebook, but set in the code using the codebook. Like
  111342. interleaving, it's easiest to do it here.
  111343. addmul==0 -> declarative (set the value)
  111344. addmul==1 -> additive
  111345. addmul==2 -> multiplicitive */
  111346. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111347. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111348. long packed_entry=decode_packed_entry_number(book,b);
  111349. if(packed_entry>=0)
  111350. return(book->dec_index[packed_entry]);
  111351. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111352. return(packed_entry);
  111353. }
  111354. /* returns 0 on OK or -1 on eof *************************************/
  111355. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111356. int step=n/book->dim;
  111357. long *entry = (long*)alloca(sizeof(*entry)*step);
  111358. float **t = (float**)alloca(sizeof(*t)*step);
  111359. int i,j,o;
  111360. for (i = 0; i < step; i++) {
  111361. entry[i]=decode_packed_entry_number(book,b);
  111362. if(entry[i]==-1)return(-1);
  111363. t[i] = book->valuelist+entry[i]*book->dim;
  111364. }
  111365. for(i=0,o=0;i<book->dim;i++,o+=step)
  111366. for (j=0;j<step;j++)
  111367. a[o+j]+=t[j][i];
  111368. return(0);
  111369. }
  111370. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111371. int i,j,entry;
  111372. float *t;
  111373. if(book->dim>8){
  111374. for(i=0;i<n;){
  111375. entry = decode_packed_entry_number(book,b);
  111376. if(entry==-1)return(-1);
  111377. t = book->valuelist+entry*book->dim;
  111378. for (j=0;j<book->dim;)
  111379. a[i++]+=t[j++];
  111380. }
  111381. }else{
  111382. for(i=0;i<n;){
  111383. entry = decode_packed_entry_number(book,b);
  111384. if(entry==-1)return(-1);
  111385. t = book->valuelist+entry*book->dim;
  111386. j=0;
  111387. switch((int)book->dim){
  111388. case 8:
  111389. a[i++]+=t[j++];
  111390. case 7:
  111391. a[i++]+=t[j++];
  111392. case 6:
  111393. a[i++]+=t[j++];
  111394. case 5:
  111395. a[i++]+=t[j++];
  111396. case 4:
  111397. a[i++]+=t[j++];
  111398. case 3:
  111399. a[i++]+=t[j++];
  111400. case 2:
  111401. a[i++]+=t[j++];
  111402. case 1:
  111403. a[i++]+=t[j++];
  111404. case 0:
  111405. break;
  111406. }
  111407. }
  111408. }
  111409. return(0);
  111410. }
  111411. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111412. int i,j,entry;
  111413. float *t;
  111414. for(i=0;i<n;){
  111415. entry = decode_packed_entry_number(book,b);
  111416. if(entry==-1)return(-1);
  111417. t = book->valuelist+entry*book->dim;
  111418. for (j=0;j<book->dim;)
  111419. a[i++]=t[j++];
  111420. }
  111421. return(0);
  111422. }
  111423. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111424. oggpack_buffer *b,int n){
  111425. long i,j,entry;
  111426. int chptr=0;
  111427. for(i=offset/ch;i<(offset+n)/ch;){
  111428. entry = decode_packed_entry_number(book,b);
  111429. if(entry==-1)return(-1);
  111430. {
  111431. const float *t = book->valuelist+entry*book->dim;
  111432. for (j=0;j<book->dim;j++){
  111433. a[chptr++][i]+=t[j];
  111434. if(chptr==ch){
  111435. chptr=0;
  111436. i++;
  111437. }
  111438. }
  111439. }
  111440. }
  111441. return(0);
  111442. }
  111443. #ifdef _V_SELFTEST
  111444. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111445. number of vectors through (keeping track of the quantized values),
  111446. and decode using the unpacked book. quantized version of in should
  111447. exactly equal out */
  111448. #include <stdio.h>
  111449. #include "vorbis/book/lsp20_0.vqh"
  111450. #include "vorbis/book/res0a_13.vqh"
  111451. #define TESTSIZE 40
  111452. float test1[TESTSIZE]={
  111453. 0.105939f,
  111454. 0.215373f,
  111455. 0.429117f,
  111456. 0.587974f,
  111457. 0.181173f,
  111458. 0.296583f,
  111459. 0.515707f,
  111460. 0.715261f,
  111461. 0.162327f,
  111462. 0.263834f,
  111463. 0.342876f,
  111464. 0.406025f,
  111465. 0.103571f,
  111466. 0.223561f,
  111467. 0.368513f,
  111468. 0.540313f,
  111469. 0.136672f,
  111470. 0.395882f,
  111471. 0.587183f,
  111472. 0.652476f,
  111473. 0.114338f,
  111474. 0.417300f,
  111475. 0.525486f,
  111476. 0.698679f,
  111477. 0.147492f,
  111478. 0.324481f,
  111479. 0.643089f,
  111480. 0.757582f,
  111481. 0.139556f,
  111482. 0.215795f,
  111483. 0.324559f,
  111484. 0.399387f,
  111485. 0.120236f,
  111486. 0.267420f,
  111487. 0.446940f,
  111488. 0.608760f,
  111489. 0.115587f,
  111490. 0.287234f,
  111491. 0.571081f,
  111492. 0.708603f,
  111493. };
  111494. float test3[TESTSIZE]={
  111495. 0,1,-2,3,4,-5,6,7,8,9,
  111496. 8,-2,7,-1,4,6,8,3,1,-9,
  111497. 10,11,12,13,14,15,26,17,18,19,
  111498. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111499. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111500. &_vq_book_res0a_13,NULL};
  111501. float *testvec[]={test1,test3};
  111502. int main(){
  111503. oggpack_buffer write;
  111504. oggpack_buffer read;
  111505. long ptr=0,i;
  111506. oggpack_writeinit(&write);
  111507. fprintf(stderr,"Testing codebook abstraction...:\n");
  111508. while(testlist[ptr]){
  111509. codebook c;
  111510. static_codebook s;
  111511. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111512. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111513. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111514. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111515. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111516. /* pack the codebook, write the testvector */
  111517. oggpack_reset(&write);
  111518. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111519. we can write */
  111520. vorbis_staticbook_pack(testlist[ptr],&write);
  111521. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111522. for(i=0;i<TESTSIZE;i+=c.dim){
  111523. int best=_best(&c,qv+i,1);
  111524. vorbis_book_encodev(&c,best,qv+i,&write);
  111525. }
  111526. vorbis_book_clear(&c);
  111527. fprintf(stderr,"OK.\n");
  111528. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111529. /* transfer the write data to a read buffer and unpack/read */
  111530. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111531. if(vorbis_staticbook_unpack(&read,&s)){
  111532. fprintf(stderr,"Error unpacking codebook.\n");
  111533. exit(1);
  111534. }
  111535. if(vorbis_book_init_decode(&c,&s)){
  111536. fprintf(stderr,"Error initializing codebook.\n");
  111537. exit(1);
  111538. }
  111539. for(i=0;i<TESTSIZE;i+=c.dim)
  111540. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111541. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111542. exit(1);
  111543. }
  111544. for(i=0;i<TESTSIZE;i++)
  111545. if(fabs(qv[i]-iv[i])>.000001){
  111546. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111547. iv[i],qv[i],i);
  111548. exit(1);
  111549. }
  111550. fprintf(stderr,"OK\n");
  111551. ptr++;
  111552. }
  111553. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111554. exit(0);
  111555. }
  111556. #endif
  111557. #endif
  111558. /*** End of inlined file: codebook.c ***/
  111559. /*** Start of inlined file: envelope.c ***/
  111560. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111561. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111562. // tasks..
  111563. #if JUCE_MSVC
  111564. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111565. #endif
  111566. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111567. #if JUCE_USE_OGGVORBIS
  111568. #include <stdlib.h>
  111569. #include <string.h>
  111570. #include <stdio.h>
  111571. #include <math.h>
  111572. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111574. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111575. int ch=vi->channels;
  111576. int i,j;
  111577. int n=e->winlength=128;
  111578. e->searchstep=64; /* not random */
  111579. e->minenergy=gi->preecho_minenergy;
  111580. e->ch=ch;
  111581. e->storage=128;
  111582. e->cursor=ci->blocksizes[1]/2;
  111583. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111584. mdct_init(&e->mdct,n);
  111585. for(i=0;i<n;i++){
  111586. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111587. e->mdct_win[i]*=e->mdct_win[i];
  111588. }
  111589. /* magic follows */
  111590. e->band[0].begin=2; e->band[0].end=4;
  111591. e->band[1].begin=4; e->band[1].end=5;
  111592. e->band[2].begin=6; e->band[2].end=6;
  111593. e->band[3].begin=9; e->band[3].end=8;
  111594. e->band[4].begin=13; e->band[4].end=8;
  111595. e->band[5].begin=17; e->band[5].end=8;
  111596. e->band[6].begin=22; e->band[6].end=8;
  111597. for(j=0;j<VE_BANDS;j++){
  111598. n=e->band[j].end;
  111599. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111600. for(i=0;i<n;i++){
  111601. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111602. e->band[j].total+=e->band[j].window[i];
  111603. }
  111604. e->band[j].total=1./e->band[j].total;
  111605. }
  111606. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111607. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111608. }
  111609. void _ve_envelope_clear(envelope_lookup *e){
  111610. int i;
  111611. mdct_clear(&e->mdct);
  111612. for(i=0;i<VE_BANDS;i++)
  111613. _ogg_free(e->band[i].window);
  111614. _ogg_free(e->mdct_win);
  111615. _ogg_free(e->filter);
  111616. _ogg_free(e->mark);
  111617. memset(e,0,sizeof(*e));
  111618. }
  111619. /* fairly straight threshhold-by-band based until we find something
  111620. that works better and isn't patented. */
  111621. static int _ve_amp(envelope_lookup *ve,
  111622. vorbis_info_psy_global *gi,
  111623. float *data,
  111624. envelope_band *bands,
  111625. envelope_filter_state *filters,
  111626. long pos){
  111627. long n=ve->winlength;
  111628. int ret=0;
  111629. long i,j;
  111630. float decay;
  111631. /* we want to have a 'minimum bar' for energy, else we're just
  111632. basing blocks on quantization noise that outweighs the signal
  111633. itself (for low power signals) */
  111634. float minV=ve->minenergy;
  111635. float *vec=(float*) alloca(n*sizeof(*vec));
  111636. /* stretch is used to gradually lengthen the number of windows
  111637. considered prevoius-to-potential-trigger */
  111638. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111639. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111640. if(penalty<0.f)penalty=0.f;
  111641. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111642. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111643. totalshift+pos*ve->searchstep);*/
  111644. /* window and transform */
  111645. for(i=0;i<n;i++)
  111646. vec[i]=data[i]*ve->mdct_win[i];
  111647. mdct_forward(&ve->mdct,vec,vec);
  111648. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111649. /* near-DC spreading function; this has nothing to do with
  111650. psychoacoustics, just sidelobe leakage and window size */
  111651. {
  111652. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111653. int ptr=filters->nearptr;
  111654. /* the accumulation is regularly refreshed from scratch to avoid
  111655. floating point creep */
  111656. if(ptr==0){
  111657. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111658. filters->nearDC_partialacc=temp;
  111659. }else{
  111660. decay=filters->nearDC_acc+=temp;
  111661. filters->nearDC_partialacc+=temp;
  111662. }
  111663. filters->nearDC_acc-=filters->nearDC[ptr];
  111664. filters->nearDC[ptr]=temp;
  111665. decay*=(1./(VE_NEARDC+1));
  111666. filters->nearptr++;
  111667. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111668. decay=todB(&decay)*.5-15.f;
  111669. }
  111670. /* perform spreading and limiting, also smooth the spectrum. yes,
  111671. the MDCT results in all real coefficients, but it still *behaves*
  111672. like real/imaginary pairs */
  111673. for(i=0;i<n/2;i+=2){
  111674. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111675. val=todB(&val)*.5f;
  111676. if(val<decay)val=decay;
  111677. if(val<minV)val=minV;
  111678. vec[i>>1]=val;
  111679. decay-=8.;
  111680. }
  111681. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111682. /* perform preecho/postecho triggering by band */
  111683. for(j=0;j<VE_BANDS;j++){
  111684. float acc=0.;
  111685. float valmax,valmin;
  111686. /* accumulate amplitude */
  111687. for(i=0;i<bands[j].end;i++)
  111688. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111689. acc*=bands[j].total;
  111690. /* convert amplitude to delta */
  111691. {
  111692. int p,thisx=filters[j].ampptr;
  111693. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111694. p=thisx;
  111695. p--;
  111696. if(p<0)p+=VE_AMP;
  111697. postmax=max(acc,filters[j].ampbuf[p]);
  111698. postmin=min(acc,filters[j].ampbuf[p]);
  111699. for(i=0;i<stretch;i++){
  111700. p--;
  111701. if(p<0)p+=VE_AMP;
  111702. premax=max(premax,filters[j].ampbuf[p]);
  111703. premin=min(premin,filters[j].ampbuf[p]);
  111704. }
  111705. valmin=postmin-premin;
  111706. valmax=postmax-premax;
  111707. /*filters[j].markers[pos]=valmax;*/
  111708. filters[j].ampbuf[thisx]=acc;
  111709. filters[j].ampptr++;
  111710. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111711. }
  111712. /* look at min/max, decide trigger */
  111713. if(valmax>gi->preecho_thresh[j]+penalty){
  111714. ret|=1;
  111715. ret|=4;
  111716. }
  111717. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111718. }
  111719. return(ret);
  111720. }
  111721. #if 0
  111722. static int seq=0;
  111723. static ogg_int64_t totalshift=-1024;
  111724. #endif
  111725. long _ve_envelope_search(vorbis_dsp_state *v){
  111726. vorbis_info *vi=v->vi;
  111727. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111728. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111729. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111730. long i,j;
  111731. int first=ve->current/ve->searchstep;
  111732. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111733. if(first<0)first=0;
  111734. /* make sure we have enough storage to match the PCM */
  111735. if(last+VE_WIN+VE_POST>ve->storage){
  111736. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111737. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111738. }
  111739. for(j=first;j<last;j++){
  111740. int ret=0;
  111741. ve->stretch++;
  111742. if(ve->stretch>VE_MAXSTRETCH*2)
  111743. ve->stretch=VE_MAXSTRETCH*2;
  111744. for(i=0;i<ve->ch;i++){
  111745. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111746. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111747. }
  111748. ve->mark[j+VE_POST]=0;
  111749. if(ret&1){
  111750. ve->mark[j]=1;
  111751. ve->mark[j+1]=1;
  111752. }
  111753. if(ret&2){
  111754. ve->mark[j]=1;
  111755. if(j>0)ve->mark[j-1]=1;
  111756. }
  111757. if(ret&4)ve->stretch=-1;
  111758. }
  111759. ve->current=last*ve->searchstep;
  111760. {
  111761. long centerW=v->centerW;
  111762. long testW=
  111763. centerW+
  111764. ci->blocksizes[v->W]/4+
  111765. ci->blocksizes[1]/2+
  111766. ci->blocksizes[0]/4;
  111767. j=ve->cursor;
  111768. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111769. working back one window */
  111770. if(j>=testW)return(1);
  111771. ve->cursor=j;
  111772. if(ve->mark[j/ve->searchstep]){
  111773. if(j>centerW){
  111774. #if 0
  111775. if(j>ve->curmark){
  111776. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111777. int l,m;
  111778. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111779. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111780. seq,
  111781. (totalshift+ve->cursor)/44100.,
  111782. (totalshift+j)/44100.);
  111783. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111784. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111785. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111786. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111787. for(m=0;m<VE_BANDS;m++){
  111788. char buf[80];
  111789. sprintf(buf,"delL%d",m);
  111790. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111791. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111792. }
  111793. for(m=0;m<VE_BANDS;m++){
  111794. char buf[80];
  111795. sprintf(buf,"delR%d",m);
  111796. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111797. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111798. }
  111799. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111800. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111801. seq++;
  111802. }
  111803. #endif
  111804. ve->curmark=j;
  111805. if(j>=testW)return(1);
  111806. return(0);
  111807. }
  111808. }
  111809. j+=ve->searchstep;
  111810. }
  111811. }
  111812. return(-1);
  111813. }
  111814. int _ve_envelope_mark(vorbis_dsp_state *v){
  111815. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111816. vorbis_info *vi=v->vi;
  111817. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111818. long centerW=v->centerW;
  111819. long beginW=centerW-ci->blocksizes[v->W]/4;
  111820. long endW=centerW+ci->blocksizes[v->W]/4;
  111821. if(v->W){
  111822. beginW-=ci->blocksizes[v->lW]/4;
  111823. endW+=ci->blocksizes[v->nW]/4;
  111824. }else{
  111825. beginW-=ci->blocksizes[0]/4;
  111826. endW+=ci->blocksizes[0]/4;
  111827. }
  111828. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  111829. {
  111830. long first=beginW/ve->searchstep;
  111831. long last=endW/ve->searchstep;
  111832. long i;
  111833. for(i=first;i<last;i++)
  111834. if(ve->mark[i])return(1);
  111835. }
  111836. return(0);
  111837. }
  111838. void _ve_envelope_shift(envelope_lookup *e,long shift){
  111839. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  111840. ahead of ve->current */
  111841. int smallshift=shift/e->searchstep;
  111842. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  111843. #if 0
  111844. for(i=0;i<VE_BANDS*e->ch;i++)
  111845. memmove(e->filter[i].markers,
  111846. e->filter[i].markers+smallshift,
  111847. (1024-smallshift)*sizeof(*(*e->filter).markers));
  111848. totalshift+=shift;
  111849. #endif
  111850. e->current-=shift;
  111851. if(e->curmark>=0)
  111852. e->curmark-=shift;
  111853. e->cursor-=shift;
  111854. }
  111855. #endif
  111856. /*** End of inlined file: envelope.c ***/
  111857. /*** Start of inlined file: floor0.c ***/
  111858. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111859. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111860. // tasks..
  111861. #if JUCE_MSVC
  111862. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111863. #endif
  111864. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111865. #if JUCE_USE_OGGVORBIS
  111866. #include <stdlib.h>
  111867. #include <string.h>
  111868. #include <math.h>
  111869. /*** Start of inlined file: lsp.h ***/
  111870. #ifndef _V_LSP_H_
  111871. #define _V_LSP_H_
  111872. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  111873. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  111874. float *lsp,int m,
  111875. float amp,float ampoffset);
  111876. #endif
  111877. /*** End of inlined file: lsp.h ***/
  111878. #include <stdio.h>
  111879. typedef struct {
  111880. int ln;
  111881. int m;
  111882. int **linearmap;
  111883. int n[2];
  111884. vorbis_info_floor0 *vi;
  111885. long bits;
  111886. long frames;
  111887. } vorbis_look_floor0;
  111888. /***********************************************/
  111889. static void floor0_free_info(vorbis_info_floor *i){
  111890. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  111891. if(info){
  111892. memset(info,0,sizeof(*info));
  111893. _ogg_free(info);
  111894. }
  111895. }
  111896. static void floor0_free_look(vorbis_look_floor *i){
  111897. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111898. if(look){
  111899. if(look->linearmap){
  111900. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  111901. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  111902. _ogg_free(look->linearmap);
  111903. }
  111904. memset(look,0,sizeof(*look));
  111905. _ogg_free(look);
  111906. }
  111907. }
  111908. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111909. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111910. int j;
  111911. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  111912. info->order=oggpack_read(opb,8);
  111913. info->rate=oggpack_read(opb,16);
  111914. info->barkmap=oggpack_read(opb,16);
  111915. info->ampbits=oggpack_read(opb,6);
  111916. info->ampdB=oggpack_read(opb,8);
  111917. info->numbooks=oggpack_read(opb,4)+1;
  111918. if(info->order<1)goto err_out;
  111919. if(info->rate<1)goto err_out;
  111920. if(info->barkmap<1)goto err_out;
  111921. if(info->numbooks<1)goto err_out;
  111922. for(j=0;j<info->numbooks;j++){
  111923. info->books[j]=oggpack_read(opb,8);
  111924. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  111925. }
  111926. return(info);
  111927. err_out:
  111928. floor0_free_info(info);
  111929. return(NULL);
  111930. }
  111931. /* initialize Bark scale and normalization lookups. We could do this
  111932. with static tables, but Vorbis allows a number of possible
  111933. combinations, so it's best to do it computationally.
  111934. The below is authoritative in terms of defining scale mapping.
  111935. Note that the scale depends on the sampling rate as well as the
  111936. linear block and mapping sizes */
  111937. static void floor0_map_lazy_init(vorbis_block *vb,
  111938. vorbis_info_floor *infoX,
  111939. vorbis_look_floor0 *look){
  111940. if(!look->linearmap[vb->W]){
  111941. vorbis_dsp_state *vd=vb->vd;
  111942. vorbis_info *vi=vd->vi;
  111943. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111944. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  111945. int W=vb->W;
  111946. int n=ci->blocksizes[W]/2,j;
  111947. /* we choose a scaling constant so that:
  111948. floor(bark(rate/2-1)*C)=mapped-1
  111949. floor(bark(rate/2)*C)=mapped */
  111950. float scale=look->ln/toBARK(info->rate/2.f);
  111951. /* the mapping from a linear scale to a smaller bark scale is
  111952. straightforward. We do *not* make sure that the linear mapping
  111953. does not skip bark-scale bins; the decoder simply skips them and
  111954. the encoder may do what it wishes in filling them. They're
  111955. necessary in some mapping combinations to keep the scale spacing
  111956. accurate */
  111957. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  111958. for(j=0;j<n;j++){
  111959. int val=floor( toBARK((info->rate/2.f)/n*j)
  111960. *scale); /* bark numbers represent band edges */
  111961. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  111962. look->linearmap[W][j]=val;
  111963. }
  111964. look->linearmap[W][j]=-1;
  111965. look->n[W]=n;
  111966. }
  111967. }
  111968. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  111969. vorbis_info_floor *i){
  111970. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  111971. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  111972. look->m=info->order;
  111973. look->ln=info->barkmap;
  111974. look->vi=info;
  111975. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  111976. return look;
  111977. }
  111978. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  111979. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111980. vorbis_info_floor0 *info=look->vi;
  111981. int j,k;
  111982. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  111983. if(ampraw>0){ /* also handles the -1 out of data case */
  111984. long maxval=(1<<info->ampbits)-1;
  111985. float amp=(float)ampraw/maxval*info->ampdB;
  111986. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  111987. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  111988. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  111989. codebook *b=ci->fullbooks+info->books[booknum];
  111990. float last=0.f;
  111991. /* the additional b->dim is a guard against any possible stack
  111992. smash; b->dim is provably more than we can overflow the
  111993. vector */
  111994. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  111995. for(j=0;j<look->m;j+=b->dim)
  111996. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  111997. for(j=0;j<look->m;){
  111998. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  111999. last=lsp[j-1];
  112000. }
  112001. lsp[look->m]=amp;
  112002. return(lsp);
  112003. }
  112004. }
  112005. eop:
  112006. return(NULL);
  112007. }
  112008. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112009. void *memo,float *out){
  112010. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112011. vorbis_info_floor0 *info=look->vi;
  112012. floor0_map_lazy_init(vb,info,look);
  112013. if(memo){
  112014. float *lsp=(float *)memo;
  112015. float amp=lsp[look->m];
  112016. /* take the coefficients back to a spectral envelope curve */
  112017. vorbis_lsp_to_curve(out,
  112018. look->linearmap[vb->W],
  112019. look->n[vb->W],
  112020. look->ln,
  112021. lsp,look->m,amp,(float)info->ampdB);
  112022. return(1);
  112023. }
  112024. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112025. return(0);
  112026. }
  112027. /* export hooks */
  112028. vorbis_func_floor floor0_exportbundle={
  112029. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112030. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112031. };
  112032. #endif
  112033. /*** End of inlined file: floor0.c ***/
  112034. /*** Start of inlined file: floor1.c ***/
  112035. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112036. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112037. // tasks..
  112038. #if JUCE_MSVC
  112039. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112040. #endif
  112041. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112042. #if JUCE_USE_OGGVORBIS
  112043. #include <stdlib.h>
  112044. #include <string.h>
  112045. #include <math.h>
  112046. #include <stdio.h>
  112047. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112048. typedef struct {
  112049. int sorted_index[VIF_POSIT+2];
  112050. int forward_index[VIF_POSIT+2];
  112051. int reverse_index[VIF_POSIT+2];
  112052. int hineighbor[VIF_POSIT];
  112053. int loneighbor[VIF_POSIT];
  112054. int posts;
  112055. int n;
  112056. int quant_q;
  112057. vorbis_info_floor1 *vi;
  112058. long phrasebits;
  112059. long postbits;
  112060. long frames;
  112061. } vorbis_look_floor1;
  112062. typedef struct lsfit_acc{
  112063. long x0;
  112064. long x1;
  112065. long xa;
  112066. long ya;
  112067. long x2a;
  112068. long y2a;
  112069. long xya;
  112070. long an;
  112071. } lsfit_acc;
  112072. /***********************************************/
  112073. static void floor1_free_info(vorbis_info_floor *i){
  112074. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112075. if(info){
  112076. memset(info,0,sizeof(*info));
  112077. _ogg_free(info);
  112078. }
  112079. }
  112080. static void floor1_free_look(vorbis_look_floor *i){
  112081. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112082. if(look){
  112083. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112084. (float)look->phrasebits/look->frames,
  112085. (float)look->postbits/look->frames,
  112086. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112087. memset(look,0,sizeof(*look));
  112088. _ogg_free(look);
  112089. }
  112090. }
  112091. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112092. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112093. int j,k;
  112094. int count=0;
  112095. int rangebits;
  112096. int maxposit=info->postlist[1];
  112097. int maxclass=-1;
  112098. /* save out partitions */
  112099. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112100. for(j=0;j<info->partitions;j++){
  112101. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112102. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112103. }
  112104. /* save out partition classes */
  112105. for(j=0;j<maxclass+1;j++){
  112106. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112107. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112108. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112109. for(k=0;k<(1<<info->class_subs[j]);k++)
  112110. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112111. }
  112112. /* save out the post list */
  112113. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112114. oggpack_write(opb,ilog2(maxposit),4);
  112115. rangebits=ilog2(maxposit);
  112116. for(j=0,k=0;j<info->partitions;j++){
  112117. count+=info->class_dim[info->partitionclass[j]];
  112118. for(;k<count;k++)
  112119. oggpack_write(opb,info->postlist[k+2],rangebits);
  112120. }
  112121. }
  112122. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112123. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112124. int j,k,count=0,maxclass=-1,rangebits;
  112125. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112126. /* read partitions */
  112127. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112128. for(j=0;j<info->partitions;j++){
  112129. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112130. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112131. }
  112132. /* read partition classes */
  112133. for(j=0;j<maxclass+1;j++){
  112134. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112135. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112136. if(info->class_subs[j]<0)
  112137. goto err_out;
  112138. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112139. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112140. goto err_out;
  112141. for(k=0;k<(1<<info->class_subs[j]);k++){
  112142. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112143. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112144. goto err_out;
  112145. }
  112146. }
  112147. /* read the post list */
  112148. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112149. rangebits=oggpack_read(opb,4);
  112150. for(j=0,k=0;j<info->partitions;j++){
  112151. count+=info->class_dim[info->partitionclass[j]];
  112152. for(;k<count;k++){
  112153. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112154. if(t<0 || t>=(1<<rangebits))
  112155. goto err_out;
  112156. }
  112157. }
  112158. info->postlist[0]=0;
  112159. info->postlist[1]=1<<rangebits;
  112160. return(info);
  112161. err_out:
  112162. floor1_free_info(info);
  112163. return(NULL);
  112164. }
  112165. static int icomp(const void *a,const void *b){
  112166. return(**(int **)a-**(int **)b);
  112167. }
  112168. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112169. vorbis_info_floor *in){
  112170. int *sortpointer[VIF_POSIT+2];
  112171. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112172. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112173. int i,j,n=0;
  112174. look->vi=info;
  112175. look->n=info->postlist[1];
  112176. /* we drop each position value in-between already decoded values,
  112177. and use linear interpolation to predict each new value past the
  112178. edges. The positions are read in the order of the position
  112179. list... we precompute the bounding positions in the lookup. Of
  112180. course, the neighbors can change (if a position is declined), but
  112181. this is an initial mapping */
  112182. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112183. n+=2;
  112184. look->posts=n;
  112185. /* also store a sorted position index */
  112186. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112187. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112188. /* points from sort order back to range number */
  112189. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112190. /* points from range order to sorted position */
  112191. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112192. /* we actually need the post values too */
  112193. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112194. /* quantize values to multiplier spec */
  112195. switch(info->mult){
  112196. case 1: /* 1024 -> 256 */
  112197. look->quant_q=256;
  112198. break;
  112199. case 2: /* 1024 -> 128 */
  112200. look->quant_q=128;
  112201. break;
  112202. case 3: /* 1024 -> 86 */
  112203. look->quant_q=86;
  112204. break;
  112205. case 4: /* 1024 -> 64 */
  112206. look->quant_q=64;
  112207. break;
  112208. }
  112209. /* discover our neighbors for decode where we don't use fit flags
  112210. (that would push the neighbors outward) */
  112211. for(i=0;i<n-2;i++){
  112212. int lo=0;
  112213. int hi=1;
  112214. int lx=0;
  112215. int hx=look->n;
  112216. int currentx=info->postlist[i+2];
  112217. for(j=0;j<i+2;j++){
  112218. int x=info->postlist[j];
  112219. if(x>lx && x<currentx){
  112220. lo=j;
  112221. lx=x;
  112222. }
  112223. if(x<hx && x>currentx){
  112224. hi=j;
  112225. hx=x;
  112226. }
  112227. }
  112228. look->loneighbor[i]=lo;
  112229. look->hineighbor[i]=hi;
  112230. }
  112231. return(look);
  112232. }
  112233. static int render_point(int x0,int x1,int y0,int y1,int x){
  112234. y0&=0x7fff; /* mask off flag */
  112235. y1&=0x7fff;
  112236. {
  112237. int dy=y1-y0;
  112238. int adx=x1-x0;
  112239. int ady=abs(dy);
  112240. int err=ady*(x-x0);
  112241. int off=err/adx;
  112242. if(dy<0)return(y0-off);
  112243. return(y0+off);
  112244. }
  112245. }
  112246. static int vorbis_dBquant(const float *x){
  112247. int i= *x*7.3142857f+1023.5f;
  112248. if(i>1023)return(1023);
  112249. if(i<0)return(0);
  112250. return i;
  112251. }
  112252. static float FLOOR1_fromdB_LOOKUP[256]={
  112253. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112254. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112255. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112256. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112257. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112258. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112259. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112260. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112261. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112262. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112263. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112264. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112265. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112266. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112267. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112268. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112269. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112270. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112271. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112272. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112273. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112274. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112275. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112276. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112277. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112278. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112279. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112280. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112281. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112282. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112283. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112284. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112285. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112286. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112287. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112288. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112289. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112290. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112291. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112292. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112293. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112294. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112295. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112296. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112297. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112298. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112299. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112300. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112301. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112302. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112303. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112304. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112305. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112306. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112307. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112308. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112309. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112310. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112311. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112312. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112313. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112314. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112315. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112316. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112317. };
  112318. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112319. int dy=y1-y0;
  112320. int adx=x1-x0;
  112321. int ady=abs(dy);
  112322. int base=dy/adx;
  112323. int sy=(dy<0?base-1:base+1);
  112324. int x=x0;
  112325. int y=y0;
  112326. int err=0;
  112327. ady-=abs(base*adx);
  112328. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112329. while(++x<x1){
  112330. err=err+ady;
  112331. if(err>=adx){
  112332. err-=adx;
  112333. y+=sy;
  112334. }else{
  112335. y+=base;
  112336. }
  112337. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112338. }
  112339. }
  112340. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112341. int dy=y1-y0;
  112342. int adx=x1-x0;
  112343. int ady=abs(dy);
  112344. int base=dy/adx;
  112345. int sy=(dy<0?base-1:base+1);
  112346. int x=x0;
  112347. int y=y0;
  112348. int err=0;
  112349. ady-=abs(base*adx);
  112350. d[x]=y;
  112351. while(++x<x1){
  112352. err=err+ady;
  112353. if(err>=adx){
  112354. err-=adx;
  112355. y+=sy;
  112356. }else{
  112357. y+=base;
  112358. }
  112359. d[x]=y;
  112360. }
  112361. }
  112362. /* the floor has already been filtered to only include relevant sections */
  112363. static int accumulate_fit(const float *flr,const float *mdct,
  112364. int x0, int x1,lsfit_acc *a,
  112365. int n,vorbis_info_floor1 *info){
  112366. long i;
  112367. 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;
  112368. memset(a,0,sizeof(*a));
  112369. a->x0=x0;
  112370. a->x1=x1;
  112371. if(x1>=n)x1=n-1;
  112372. for(i=x0;i<=x1;i++){
  112373. int quantized=vorbis_dBquant(flr+i);
  112374. if(quantized){
  112375. if(mdct[i]+info->twofitatten>=flr[i]){
  112376. xa += i;
  112377. ya += quantized;
  112378. x2a += i*i;
  112379. y2a += quantized*quantized;
  112380. xya += i*quantized;
  112381. na++;
  112382. }else{
  112383. xb += i;
  112384. yb += quantized;
  112385. x2b += i*i;
  112386. y2b += quantized*quantized;
  112387. xyb += i*quantized;
  112388. nb++;
  112389. }
  112390. }
  112391. }
  112392. xb+=xa;
  112393. yb+=ya;
  112394. x2b+=x2a;
  112395. y2b+=y2a;
  112396. xyb+=xya;
  112397. nb+=na;
  112398. /* weight toward the actually used frequencies if we meet the threshhold */
  112399. {
  112400. int weight=nb*info->twofitweight/(na+1);
  112401. a->xa=xa*weight+xb;
  112402. a->ya=ya*weight+yb;
  112403. a->x2a=x2a*weight+x2b;
  112404. a->y2a=y2a*weight+y2b;
  112405. a->xya=xya*weight+xyb;
  112406. a->an=na*weight+nb;
  112407. }
  112408. return(na);
  112409. }
  112410. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112411. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112412. long x0=a[0].x0;
  112413. long x1=a[fits-1].x1;
  112414. for(i=0;i<fits;i++){
  112415. x+=a[i].xa;
  112416. y+=a[i].ya;
  112417. x2+=a[i].x2a;
  112418. y2+=a[i].y2a;
  112419. xy+=a[i].xya;
  112420. an+=a[i].an;
  112421. }
  112422. if(*y0>=0){
  112423. x+= x0;
  112424. y+= *y0;
  112425. x2+= x0 * x0;
  112426. y2+= *y0 * *y0;
  112427. xy+= *y0 * x0;
  112428. an++;
  112429. }
  112430. if(*y1>=0){
  112431. x+= x1;
  112432. y+= *y1;
  112433. x2+= x1 * x1;
  112434. y2+= *y1 * *y1;
  112435. xy+= *y1 * x1;
  112436. an++;
  112437. }
  112438. if(an){
  112439. /* need 64 bit multiplies, which C doesn't give portably as int */
  112440. double fx=x;
  112441. double fy=y;
  112442. double fx2=x2;
  112443. double fxy=xy;
  112444. double denom=1./(an*fx2-fx*fx);
  112445. double a=(fy*fx2-fxy*fx)*denom;
  112446. double b=(an*fxy-fx*fy)*denom;
  112447. *y0=rint(a+b*x0);
  112448. *y1=rint(a+b*x1);
  112449. /* limit to our range! */
  112450. if(*y0>1023)*y0=1023;
  112451. if(*y1>1023)*y1=1023;
  112452. if(*y0<0)*y0=0;
  112453. if(*y1<0)*y1=0;
  112454. }else{
  112455. *y0=0;
  112456. *y1=0;
  112457. }
  112458. }
  112459. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112460. long y=0;
  112461. int i;
  112462. for(i=0;i<fits && y==0;i++)
  112463. y+=a[i].ya;
  112464. *y0=*y1=y;
  112465. }*/
  112466. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112467. const float *mdct,
  112468. vorbis_info_floor1 *info){
  112469. int dy=y1-y0;
  112470. int adx=x1-x0;
  112471. int ady=abs(dy);
  112472. int base=dy/adx;
  112473. int sy=(dy<0?base-1:base+1);
  112474. int x=x0;
  112475. int y=y0;
  112476. int err=0;
  112477. int val=vorbis_dBquant(mask+x);
  112478. int mse=0;
  112479. int n=0;
  112480. ady-=abs(base*adx);
  112481. mse=(y-val);
  112482. mse*=mse;
  112483. n++;
  112484. if(mdct[x]+info->twofitatten>=mask[x]){
  112485. if(y+info->maxover<val)return(1);
  112486. if(y-info->maxunder>val)return(1);
  112487. }
  112488. while(++x<x1){
  112489. err=err+ady;
  112490. if(err>=adx){
  112491. err-=adx;
  112492. y+=sy;
  112493. }else{
  112494. y+=base;
  112495. }
  112496. val=vorbis_dBquant(mask+x);
  112497. mse+=((y-val)*(y-val));
  112498. n++;
  112499. if(mdct[x]+info->twofitatten>=mask[x]){
  112500. if(val){
  112501. if(y+info->maxover<val)return(1);
  112502. if(y-info->maxunder>val)return(1);
  112503. }
  112504. }
  112505. }
  112506. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112507. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112508. if(mse/n>info->maxerr)return(1);
  112509. return(0);
  112510. }
  112511. static int post_Y(int *A,int *B,int pos){
  112512. if(A[pos]<0)
  112513. return B[pos];
  112514. if(B[pos]<0)
  112515. return A[pos];
  112516. return (A[pos]+B[pos])>>1;
  112517. }
  112518. int *floor1_fit(vorbis_block *vb,void *look_,
  112519. const float *logmdct, /* in */
  112520. const float *logmask){
  112521. long i,j;
  112522. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112523. vorbis_info_floor1 *info=look->vi;
  112524. long n=look->n;
  112525. long posts=look->posts;
  112526. long nonzero=0;
  112527. lsfit_acc fits[VIF_POSIT+1];
  112528. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112529. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112530. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112531. int hineighbor[VIF_POSIT+2];
  112532. int *output=NULL;
  112533. int memo[VIF_POSIT+2];
  112534. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112535. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112536. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112537. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112538. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112539. /* quantize the relevant floor points and collect them into line fit
  112540. structures (one per minimal division) at the same time */
  112541. if(posts==0){
  112542. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112543. }else{
  112544. for(i=0;i<posts-1;i++)
  112545. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112546. look->sorted_index[i+1],fits+i,
  112547. n,info);
  112548. }
  112549. if(nonzero){
  112550. /* start by fitting the implicit base case.... */
  112551. int y0=-200;
  112552. int y1=-200;
  112553. fit_line(fits,posts-1,&y0,&y1);
  112554. fit_valueA[0]=y0;
  112555. fit_valueB[0]=y0;
  112556. fit_valueB[1]=y1;
  112557. fit_valueA[1]=y1;
  112558. /* Non degenerate case */
  112559. /* start progressive splitting. This is a greedy, non-optimal
  112560. algorithm, but simple and close enough to the best
  112561. answer. */
  112562. for(i=2;i<posts;i++){
  112563. int sortpos=look->reverse_index[i];
  112564. int ln=loneighbor[sortpos];
  112565. int hn=hineighbor[sortpos];
  112566. /* eliminate repeat searches of a particular range with a memo */
  112567. if(memo[ln]!=hn){
  112568. /* haven't performed this error search yet */
  112569. int lsortpos=look->reverse_index[ln];
  112570. int hsortpos=look->reverse_index[hn];
  112571. memo[ln]=hn;
  112572. {
  112573. /* A note: we want to bound/minimize *local*, not global, error */
  112574. int lx=info->postlist[ln];
  112575. int hx=info->postlist[hn];
  112576. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112577. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112578. if(ly==-1 || hy==-1){
  112579. exit(1);
  112580. }
  112581. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112582. /* outside error bounds/begin search area. Split it. */
  112583. int ly0=-200;
  112584. int ly1=-200;
  112585. int hy0=-200;
  112586. int hy1=-200;
  112587. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112588. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112589. /* store new edge values */
  112590. fit_valueB[ln]=ly0;
  112591. if(ln==0)fit_valueA[ln]=ly0;
  112592. fit_valueA[i]=ly1;
  112593. fit_valueB[i]=hy0;
  112594. fit_valueA[hn]=hy1;
  112595. if(hn==1)fit_valueB[hn]=hy1;
  112596. if(ly1>=0 || hy0>=0){
  112597. /* store new neighbor values */
  112598. for(j=sortpos-1;j>=0;j--)
  112599. if(hineighbor[j]==hn)
  112600. hineighbor[j]=i;
  112601. else
  112602. break;
  112603. for(j=sortpos+1;j<posts;j++)
  112604. if(loneighbor[j]==ln)
  112605. loneighbor[j]=i;
  112606. else
  112607. break;
  112608. }
  112609. }else{
  112610. fit_valueA[i]=-200;
  112611. fit_valueB[i]=-200;
  112612. }
  112613. }
  112614. }
  112615. }
  112616. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112617. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112618. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112619. /* fill in posts marked as not using a fit; we will zero
  112620. back out to 'unused' when encoding them so long as curve
  112621. interpolation doesn't force them into use */
  112622. for(i=2;i<posts;i++){
  112623. int ln=look->loneighbor[i-2];
  112624. int hn=look->hineighbor[i-2];
  112625. int x0=info->postlist[ln];
  112626. int x1=info->postlist[hn];
  112627. int y0=output[ln];
  112628. int y1=output[hn];
  112629. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112630. int vx=post_Y(fit_valueA,fit_valueB,i);
  112631. if(vx>=0 && predicted!=vx){
  112632. output[i]=vx;
  112633. }else{
  112634. output[i]= predicted|0x8000;
  112635. }
  112636. }
  112637. }
  112638. return(output);
  112639. }
  112640. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112641. int *A,int *B,
  112642. int del){
  112643. long i;
  112644. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112645. long posts=look->posts;
  112646. int *output=NULL;
  112647. if(A && B){
  112648. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112649. for(i=0;i<posts;i++){
  112650. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112651. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112652. }
  112653. }
  112654. return(output);
  112655. }
  112656. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112657. void*look_,
  112658. int *post,int *ilogmask){
  112659. long i,j;
  112660. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112661. vorbis_info_floor1 *info=look->vi;
  112662. long posts=look->posts;
  112663. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112664. int out[VIF_POSIT+2];
  112665. static_codebook **sbooks=ci->book_param;
  112666. codebook *books=ci->fullbooks;
  112667. static long seq=0;
  112668. /* quantize values to multiplier spec */
  112669. if(post){
  112670. for(i=0;i<posts;i++){
  112671. int val=post[i]&0x7fff;
  112672. switch(info->mult){
  112673. case 1: /* 1024 -> 256 */
  112674. val>>=2;
  112675. break;
  112676. case 2: /* 1024 -> 128 */
  112677. val>>=3;
  112678. break;
  112679. case 3: /* 1024 -> 86 */
  112680. val/=12;
  112681. break;
  112682. case 4: /* 1024 -> 64 */
  112683. val>>=4;
  112684. break;
  112685. }
  112686. post[i]=val | (post[i]&0x8000);
  112687. }
  112688. out[0]=post[0];
  112689. out[1]=post[1];
  112690. /* find prediction values for each post and subtract them */
  112691. for(i=2;i<posts;i++){
  112692. int ln=look->loneighbor[i-2];
  112693. int hn=look->hineighbor[i-2];
  112694. int x0=info->postlist[ln];
  112695. int x1=info->postlist[hn];
  112696. int y0=post[ln];
  112697. int y1=post[hn];
  112698. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112699. if((post[i]&0x8000) || (predicted==post[i])){
  112700. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112701. in interpolation */
  112702. out[i]=0;
  112703. }else{
  112704. int headroom=(look->quant_q-predicted<predicted?
  112705. look->quant_q-predicted:predicted);
  112706. int val=post[i]-predicted;
  112707. /* at this point the 'deviation' value is in the range +/- max
  112708. range, but the real, unique range can always be mapped to
  112709. only [0-maxrange). So we want to wrap the deviation into
  112710. this limited range, but do it in the way that least screws
  112711. an essentially gaussian probability distribution. */
  112712. if(val<0)
  112713. if(val<-headroom)
  112714. val=headroom-val-1;
  112715. else
  112716. val=-1-(val<<1);
  112717. else
  112718. if(val>=headroom)
  112719. val= val+headroom;
  112720. else
  112721. val<<=1;
  112722. out[i]=val;
  112723. post[ln]&=0x7fff;
  112724. post[hn]&=0x7fff;
  112725. }
  112726. }
  112727. /* we have everything we need. pack it out */
  112728. /* mark nontrivial floor */
  112729. oggpack_write(opb,1,1);
  112730. /* beginning/end post */
  112731. look->frames++;
  112732. look->postbits+=ilog(look->quant_q-1)*2;
  112733. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112734. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112735. /* partition by partition */
  112736. for(i=0,j=2;i<info->partitions;i++){
  112737. int classx=info->partitionclass[i];
  112738. int cdim=info->class_dim[classx];
  112739. int csubbits=info->class_subs[classx];
  112740. int csub=1<<csubbits;
  112741. int bookas[8]={0,0,0,0,0,0,0,0};
  112742. int cval=0;
  112743. int cshift=0;
  112744. int k,l;
  112745. /* generate the partition's first stage cascade value */
  112746. if(csubbits){
  112747. int maxval[8];
  112748. for(k=0;k<csub;k++){
  112749. int booknum=info->class_subbook[classx][k];
  112750. if(booknum<0){
  112751. maxval[k]=1;
  112752. }else{
  112753. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112754. }
  112755. }
  112756. for(k=0;k<cdim;k++){
  112757. for(l=0;l<csub;l++){
  112758. int val=out[j+k];
  112759. if(val<maxval[l]){
  112760. bookas[k]=l;
  112761. break;
  112762. }
  112763. }
  112764. cval|= bookas[k]<<cshift;
  112765. cshift+=csubbits;
  112766. }
  112767. /* write it */
  112768. look->phrasebits+=
  112769. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112770. #ifdef TRAIN_FLOOR1
  112771. {
  112772. FILE *of;
  112773. char buffer[80];
  112774. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112775. vb->pcmend/2,posts-2,class);
  112776. of=fopen(buffer,"a");
  112777. fprintf(of,"%d\n",cval);
  112778. fclose(of);
  112779. }
  112780. #endif
  112781. }
  112782. /* write post values */
  112783. for(k=0;k<cdim;k++){
  112784. int book=info->class_subbook[classx][bookas[k]];
  112785. if(book>=0){
  112786. /* hack to allow training with 'bad' books */
  112787. if(out[j+k]<(books+book)->entries)
  112788. look->postbits+=vorbis_book_encode(books+book,
  112789. out[j+k],opb);
  112790. /*else
  112791. fprintf(stderr,"+!");*/
  112792. #ifdef TRAIN_FLOOR1
  112793. {
  112794. FILE *of;
  112795. char buffer[80];
  112796. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112797. vb->pcmend/2,posts-2,class,bookas[k]);
  112798. of=fopen(buffer,"a");
  112799. fprintf(of,"%d\n",out[j+k]);
  112800. fclose(of);
  112801. }
  112802. #endif
  112803. }
  112804. }
  112805. j+=cdim;
  112806. }
  112807. {
  112808. /* generate quantized floor equivalent to what we'd unpack in decode */
  112809. /* render the lines */
  112810. int hx=0;
  112811. int lx=0;
  112812. int ly=post[0]*info->mult;
  112813. for(j=1;j<look->posts;j++){
  112814. int current=look->forward_index[j];
  112815. int hy=post[current]&0x7fff;
  112816. if(hy==post[current]){
  112817. hy*=info->mult;
  112818. hx=info->postlist[current];
  112819. render_line0(lx,hx,ly,hy,ilogmask);
  112820. lx=hx;
  112821. ly=hy;
  112822. }
  112823. }
  112824. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  112825. seq++;
  112826. return(1);
  112827. }
  112828. }else{
  112829. oggpack_write(opb,0,1);
  112830. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  112831. seq++;
  112832. return(0);
  112833. }
  112834. }
  112835. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  112836. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112837. vorbis_info_floor1 *info=look->vi;
  112838. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112839. int i,j,k;
  112840. codebook *books=ci->fullbooks;
  112841. /* unpack wrapped/predicted values from stream */
  112842. if(oggpack_read(&vb->opb,1)==1){
  112843. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  112844. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112845. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112846. /* partition by partition */
  112847. for(i=0,j=2;i<info->partitions;i++){
  112848. int classx=info->partitionclass[i];
  112849. int cdim=info->class_dim[classx];
  112850. int csubbits=info->class_subs[classx];
  112851. int csub=1<<csubbits;
  112852. int cval=0;
  112853. /* decode the partition's first stage cascade value */
  112854. if(csubbits){
  112855. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  112856. if(cval==-1)goto eop;
  112857. }
  112858. for(k=0;k<cdim;k++){
  112859. int book=info->class_subbook[classx][cval&(csub-1)];
  112860. cval>>=csubbits;
  112861. if(book>=0){
  112862. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  112863. goto eop;
  112864. }else{
  112865. fit_value[j+k]=0;
  112866. }
  112867. }
  112868. j+=cdim;
  112869. }
  112870. /* unwrap positive values and reconsitute via linear interpolation */
  112871. for(i=2;i<look->posts;i++){
  112872. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  112873. info->postlist[look->hineighbor[i-2]],
  112874. fit_value[look->loneighbor[i-2]],
  112875. fit_value[look->hineighbor[i-2]],
  112876. info->postlist[i]);
  112877. int hiroom=look->quant_q-predicted;
  112878. int loroom=predicted;
  112879. int room=(hiroom<loroom?hiroom:loroom)<<1;
  112880. int val=fit_value[i];
  112881. if(val){
  112882. if(val>=room){
  112883. if(hiroom>loroom){
  112884. val = val-loroom;
  112885. }else{
  112886. val = -1-(val-hiroom);
  112887. }
  112888. }else{
  112889. if(val&1){
  112890. val= -((val+1)>>1);
  112891. }else{
  112892. val>>=1;
  112893. }
  112894. }
  112895. fit_value[i]=val+predicted;
  112896. fit_value[look->loneighbor[i-2]]&=0x7fff;
  112897. fit_value[look->hineighbor[i-2]]&=0x7fff;
  112898. }else{
  112899. fit_value[i]=predicted|0x8000;
  112900. }
  112901. }
  112902. return(fit_value);
  112903. }
  112904. eop:
  112905. return(NULL);
  112906. }
  112907. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  112908. float *out){
  112909. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112910. vorbis_info_floor1 *info=look->vi;
  112911. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112912. int n=ci->blocksizes[vb->W]/2;
  112913. int j;
  112914. if(memo){
  112915. /* render the lines */
  112916. int *fit_value=(int *)memo;
  112917. int hx=0;
  112918. int lx=0;
  112919. int ly=fit_value[0]*info->mult;
  112920. for(j=1;j<look->posts;j++){
  112921. int current=look->forward_index[j];
  112922. int hy=fit_value[current]&0x7fff;
  112923. if(hy==fit_value[current]){
  112924. hy*=info->mult;
  112925. hx=info->postlist[current];
  112926. render_line(lx,hx,ly,hy,out);
  112927. lx=hx;
  112928. ly=hy;
  112929. }
  112930. }
  112931. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  112932. return(1);
  112933. }
  112934. memset(out,0,sizeof(*out)*n);
  112935. return(0);
  112936. }
  112937. /* export hooks */
  112938. vorbis_func_floor floor1_exportbundle={
  112939. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  112940. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  112941. };
  112942. #endif
  112943. /*** End of inlined file: floor1.c ***/
  112944. /*** Start of inlined file: info.c ***/
  112945. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112946. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112947. // tasks..
  112948. #if JUCE_MSVC
  112949. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112950. #endif
  112951. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112952. #if JUCE_USE_OGGVORBIS
  112953. /* general handling of the header and the vorbis_info structure (and
  112954. substructures) */
  112955. #include <stdlib.h>
  112956. #include <string.h>
  112957. #include <ctype.h>
  112958. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  112959. while(bytes--){
  112960. oggpack_write(o,*s++,8);
  112961. }
  112962. }
  112963. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  112964. while(bytes--){
  112965. *buf++=oggpack_read(o,8);
  112966. }
  112967. }
  112968. void vorbis_comment_init(vorbis_comment *vc){
  112969. memset(vc,0,sizeof(*vc));
  112970. }
  112971. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  112972. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  112973. (vc->comments+2)*sizeof(*vc->user_comments));
  112974. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  112975. (vc->comments+2)*sizeof(*vc->comment_lengths));
  112976. vc->comment_lengths[vc->comments]=strlen(comment);
  112977. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  112978. strcpy(vc->user_comments[vc->comments], comment);
  112979. vc->comments++;
  112980. vc->user_comments[vc->comments]=NULL;
  112981. }
  112982. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  112983. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  112984. strcpy(comment, tag);
  112985. strcat(comment, "=");
  112986. strcat(comment, contents);
  112987. vorbis_comment_add(vc, comment);
  112988. }
  112989. /* This is more or less the same as strncasecmp - but that doesn't exist
  112990. * everywhere, and this is a fairly trivial function, so we include it */
  112991. static int tagcompare(const char *s1, const char *s2, int n){
  112992. int c=0;
  112993. while(c < n){
  112994. if(toupper(s1[c]) != toupper(s2[c]))
  112995. return !0;
  112996. c++;
  112997. }
  112998. return 0;
  112999. }
  113000. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113001. long i;
  113002. int found = 0;
  113003. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113004. char *fulltag = (char*)alloca(taglen+ 1);
  113005. strcpy(fulltag, tag);
  113006. strcat(fulltag, "=");
  113007. for(i=0;i<vc->comments;i++){
  113008. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113009. if(count == found)
  113010. /* We return a pointer to the data, not a copy */
  113011. return vc->user_comments[i] + taglen;
  113012. else
  113013. found++;
  113014. }
  113015. }
  113016. return NULL; /* didn't find anything */
  113017. }
  113018. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113019. int i,count=0;
  113020. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113021. char *fulltag = (char*)alloca(taglen+1);
  113022. strcpy(fulltag,tag);
  113023. strcat(fulltag, "=");
  113024. for(i=0;i<vc->comments;i++){
  113025. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113026. count++;
  113027. }
  113028. return count;
  113029. }
  113030. void vorbis_comment_clear(vorbis_comment *vc){
  113031. if(vc){
  113032. long i;
  113033. for(i=0;i<vc->comments;i++)
  113034. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113035. if(vc->user_comments)_ogg_free(vc->user_comments);
  113036. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113037. if(vc->vendor)_ogg_free(vc->vendor);
  113038. }
  113039. memset(vc,0,sizeof(*vc));
  113040. }
  113041. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113042. They may be equal, but short will never ge greater than long */
  113043. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113044. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113045. return ci ? ci->blocksizes[zo] : -1;
  113046. }
  113047. /* used by synthesis, which has a full, alloced vi */
  113048. void vorbis_info_init(vorbis_info *vi){
  113049. memset(vi,0,sizeof(*vi));
  113050. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113051. }
  113052. void vorbis_info_clear(vorbis_info *vi){
  113053. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113054. int i;
  113055. if(ci){
  113056. for(i=0;i<ci->modes;i++)
  113057. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113058. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113059. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113060. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113061. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113062. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113063. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113064. for(i=0;i<ci->books;i++){
  113065. if(ci->book_param[i]){
  113066. /* knows if the book was not alloced */
  113067. vorbis_staticbook_destroy(ci->book_param[i]);
  113068. }
  113069. if(ci->fullbooks)
  113070. vorbis_book_clear(ci->fullbooks+i);
  113071. }
  113072. if(ci->fullbooks)
  113073. _ogg_free(ci->fullbooks);
  113074. for(i=0;i<ci->psys;i++)
  113075. _vi_psy_free(ci->psy_param[i]);
  113076. _ogg_free(ci);
  113077. }
  113078. memset(vi,0,sizeof(*vi));
  113079. }
  113080. /* Header packing/unpacking ********************************************/
  113081. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113082. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113083. if(!ci)return(OV_EFAULT);
  113084. vi->version=oggpack_read(opb,32);
  113085. if(vi->version!=0)return(OV_EVERSION);
  113086. vi->channels=oggpack_read(opb,8);
  113087. vi->rate=oggpack_read(opb,32);
  113088. vi->bitrate_upper=oggpack_read(opb,32);
  113089. vi->bitrate_nominal=oggpack_read(opb,32);
  113090. vi->bitrate_lower=oggpack_read(opb,32);
  113091. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113092. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113093. if(vi->rate<1)goto err_out;
  113094. if(vi->channels<1)goto err_out;
  113095. if(ci->blocksizes[0]<8)goto err_out;
  113096. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113097. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113098. return(0);
  113099. err_out:
  113100. vorbis_info_clear(vi);
  113101. return(OV_EBADHEADER);
  113102. }
  113103. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113104. int i;
  113105. int vendorlen=oggpack_read(opb,32);
  113106. if(vendorlen<0)goto err_out;
  113107. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113108. _v_readstring(opb,vc->vendor,vendorlen);
  113109. vc->comments=oggpack_read(opb,32);
  113110. if(vc->comments<0)goto err_out;
  113111. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113112. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113113. for(i=0;i<vc->comments;i++){
  113114. int len=oggpack_read(opb,32);
  113115. if(len<0)goto err_out;
  113116. vc->comment_lengths[i]=len;
  113117. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113118. _v_readstring(opb,vc->user_comments[i],len);
  113119. }
  113120. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113121. return(0);
  113122. err_out:
  113123. vorbis_comment_clear(vc);
  113124. return(OV_EBADHEADER);
  113125. }
  113126. /* all of the real encoding details are here. The modes, books,
  113127. everything */
  113128. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113129. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113130. int i;
  113131. if(!ci)return(OV_EFAULT);
  113132. /* codebooks */
  113133. ci->books=oggpack_read(opb,8)+1;
  113134. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113135. for(i=0;i<ci->books;i++){
  113136. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113137. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113138. }
  113139. /* time backend settings; hooks are unused */
  113140. {
  113141. int times=oggpack_read(opb,6)+1;
  113142. for(i=0;i<times;i++){
  113143. int test=oggpack_read(opb,16);
  113144. if(test<0 || test>=VI_TIMEB)goto err_out;
  113145. }
  113146. }
  113147. /* floor backend settings */
  113148. ci->floors=oggpack_read(opb,6)+1;
  113149. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113150. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113151. for(i=0;i<ci->floors;i++){
  113152. ci->floor_type[i]=oggpack_read(opb,16);
  113153. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113154. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113155. if(!ci->floor_param[i])goto err_out;
  113156. }
  113157. /* residue backend settings */
  113158. ci->residues=oggpack_read(opb,6)+1;
  113159. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113160. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113161. for(i=0;i<ci->residues;i++){
  113162. ci->residue_type[i]=oggpack_read(opb,16);
  113163. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113164. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113165. if(!ci->residue_param[i])goto err_out;
  113166. }
  113167. /* map backend settings */
  113168. ci->maps=oggpack_read(opb,6)+1;
  113169. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113170. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113171. for(i=0;i<ci->maps;i++){
  113172. ci->map_type[i]=oggpack_read(opb,16);
  113173. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113174. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113175. if(!ci->map_param[i])goto err_out;
  113176. }
  113177. /* mode settings */
  113178. ci->modes=oggpack_read(opb,6)+1;
  113179. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113180. for(i=0;i<ci->modes;i++){
  113181. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113182. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113183. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113184. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113185. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113186. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113187. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113188. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113189. }
  113190. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113191. return(0);
  113192. err_out:
  113193. vorbis_info_clear(vi);
  113194. return(OV_EBADHEADER);
  113195. }
  113196. /* The Vorbis header is in three packets; the initial small packet in
  113197. the first page that identifies basic parameters, a second packet
  113198. with bitstream comments and a third packet that holds the
  113199. codebook. */
  113200. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113201. oggpack_buffer opb;
  113202. if(op){
  113203. oggpack_readinit(&opb,op->packet,op->bytes);
  113204. /* Which of the three types of header is this? */
  113205. /* Also verify header-ness, vorbis */
  113206. {
  113207. char buffer[6];
  113208. int packtype=oggpack_read(&opb,8);
  113209. memset(buffer,0,6);
  113210. _v_readstring(&opb,buffer,6);
  113211. if(memcmp(buffer,"vorbis",6)){
  113212. /* not a vorbis header */
  113213. return(OV_ENOTVORBIS);
  113214. }
  113215. switch(packtype){
  113216. case 0x01: /* least significant *bit* is read first */
  113217. if(!op->b_o_s){
  113218. /* Not the initial packet */
  113219. return(OV_EBADHEADER);
  113220. }
  113221. if(vi->rate!=0){
  113222. /* previously initialized info header */
  113223. return(OV_EBADHEADER);
  113224. }
  113225. return(_vorbis_unpack_info(vi,&opb));
  113226. case 0x03: /* least significant *bit* is read first */
  113227. if(vi->rate==0){
  113228. /* um... we didn't get the initial header */
  113229. return(OV_EBADHEADER);
  113230. }
  113231. return(_vorbis_unpack_comment(vc,&opb));
  113232. case 0x05: /* least significant *bit* is read first */
  113233. if(vi->rate==0 || vc->vendor==NULL){
  113234. /* um... we didn;t get the initial header or comments yet */
  113235. return(OV_EBADHEADER);
  113236. }
  113237. return(_vorbis_unpack_books(vi,&opb));
  113238. default:
  113239. /* Not a valid vorbis header type */
  113240. return(OV_EBADHEADER);
  113241. break;
  113242. }
  113243. }
  113244. }
  113245. return(OV_EBADHEADER);
  113246. }
  113247. /* pack side **********************************************************/
  113248. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113249. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113250. if(!ci)return(OV_EFAULT);
  113251. /* preamble */
  113252. oggpack_write(opb,0x01,8);
  113253. _v_writestring(opb,"vorbis", 6);
  113254. /* basic information about the stream */
  113255. oggpack_write(opb,0x00,32);
  113256. oggpack_write(opb,vi->channels,8);
  113257. oggpack_write(opb,vi->rate,32);
  113258. oggpack_write(opb,vi->bitrate_upper,32);
  113259. oggpack_write(opb,vi->bitrate_nominal,32);
  113260. oggpack_write(opb,vi->bitrate_lower,32);
  113261. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113262. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113263. oggpack_write(opb,1,1);
  113264. return(0);
  113265. }
  113266. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113267. char temp[]="Xiph.Org libVorbis I 20050304";
  113268. int bytes = strlen(temp);
  113269. /* preamble */
  113270. oggpack_write(opb,0x03,8);
  113271. _v_writestring(opb,"vorbis", 6);
  113272. /* vendor */
  113273. oggpack_write(opb,bytes,32);
  113274. _v_writestring(opb,temp, bytes);
  113275. /* comments */
  113276. oggpack_write(opb,vc->comments,32);
  113277. if(vc->comments){
  113278. int i;
  113279. for(i=0;i<vc->comments;i++){
  113280. if(vc->user_comments[i]){
  113281. oggpack_write(opb,vc->comment_lengths[i],32);
  113282. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113283. }else{
  113284. oggpack_write(opb,0,32);
  113285. }
  113286. }
  113287. }
  113288. oggpack_write(opb,1,1);
  113289. return(0);
  113290. }
  113291. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113292. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113293. int i;
  113294. if(!ci)return(OV_EFAULT);
  113295. oggpack_write(opb,0x05,8);
  113296. _v_writestring(opb,"vorbis", 6);
  113297. /* books */
  113298. oggpack_write(opb,ci->books-1,8);
  113299. for(i=0;i<ci->books;i++)
  113300. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113301. /* times; hook placeholders */
  113302. oggpack_write(opb,0,6);
  113303. oggpack_write(opb,0,16);
  113304. /* floors */
  113305. oggpack_write(opb,ci->floors-1,6);
  113306. for(i=0;i<ci->floors;i++){
  113307. oggpack_write(opb,ci->floor_type[i],16);
  113308. if(_floor_P[ci->floor_type[i]]->pack)
  113309. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113310. else
  113311. goto err_out;
  113312. }
  113313. /* residues */
  113314. oggpack_write(opb,ci->residues-1,6);
  113315. for(i=0;i<ci->residues;i++){
  113316. oggpack_write(opb,ci->residue_type[i],16);
  113317. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113318. }
  113319. /* maps */
  113320. oggpack_write(opb,ci->maps-1,6);
  113321. for(i=0;i<ci->maps;i++){
  113322. oggpack_write(opb,ci->map_type[i],16);
  113323. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113324. }
  113325. /* modes */
  113326. oggpack_write(opb,ci->modes-1,6);
  113327. for(i=0;i<ci->modes;i++){
  113328. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113329. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113330. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113331. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113332. }
  113333. oggpack_write(opb,1,1);
  113334. return(0);
  113335. err_out:
  113336. return(-1);
  113337. }
  113338. int vorbis_commentheader_out(vorbis_comment *vc,
  113339. ogg_packet *op){
  113340. oggpack_buffer opb;
  113341. oggpack_writeinit(&opb);
  113342. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113343. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113344. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113345. op->bytes=oggpack_bytes(&opb);
  113346. op->b_o_s=0;
  113347. op->e_o_s=0;
  113348. op->granulepos=0;
  113349. op->packetno=1;
  113350. return 0;
  113351. }
  113352. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113353. vorbis_comment *vc,
  113354. ogg_packet *op,
  113355. ogg_packet *op_comm,
  113356. ogg_packet *op_code){
  113357. int ret=OV_EIMPL;
  113358. vorbis_info *vi=v->vi;
  113359. oggpack_buffer opb;
  113360. private_state *b=(private_state*)v->backend_state;
  113361. if(!b){
  113362. ret=OV_EFAULT;
  113363. goto err_out;
  113364. }
  113365. /* first header packet **********************************************/
  113366. oggpack_writeinit(&opb);
  113367. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113368. /* build the packet */
  113369. if(b->header)_ogg_free(b->header);
  113370. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113371. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113372. op->packet=b->header;
  113373. op->bytes=oggpack_bytes(&opb);
  113374. op->b_o_s=1;
  113375. op->e_o_s=0;
  113376. op->granulepos=0;
  113377. op->packetno=0;
  113378. /* second header packet (comments) **********************************/
  113379. oggpack_reset(&opb);
  113380. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113381. if(b->header1)_ogg_free(b->header1);
  113382. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113383. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113384. op_comm->packet=b->header1;
  113385. op_comm->bytes=oggpack_bytes(&opb);
  113386. op_comm->b_o_s=0;
  113387. op_comm->e_o_s=0;
  113388. op_comm->granulepos=0;
  113389. op_comm->packetno=1;
  113390. /* third header packet (modes/codebooks) ****************************/
  113391. oggpack_reset(&opb);
  113392. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113393. if(b->header2)_ogg_free(b->header2);
  113394. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113395. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113396. op_code->packet=b->header2;
  113397. op_code->bytes=oggpack_bytes(&opb);
  113398. op_code->b_o_s=0;
  113399. op_code->e_o_s=0;
  113400. op_code->granulepos=0;
  113401. op_code->packetno=2;
  113402. oggpack_writeclear(&opb);
  113403. return(0);
  113404. err_out:
  113405. oggpack_writeclear(&opb);
  113406. memset(op,0,sizeof(*op));
  113407. memset(op_comm,0,sizeof(*op_comm));
  113408. memset(op_code,0,sizeof(*op_code));
  113409. if(b->header)_ogg_free(b->header);
  113410. if(b->header1)_ogg_free(b->header1);
  113411. if(b->header2)_ogg_free(b->header2);
  113412. b->header=NULL;
  113413. b->header1=NULL;
  113414. b->header2=NULL;
  113415. return(ret);
  113416. }
  113417. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113418. if(granulepos>=0)
  113419. return((double)granulepos/v->vi->rate);
  113420. return(-1);
  113421. }
  113422. #endif
  113423. /*** End of inlined file: info.c ***/
  113424. /*** Start of inlined file: lpc.c ***/
  113425. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113426. are derived from code written by Jutta Degener and Carsten Bormann;
  113427. thus we include their copyright below. The entirety of this file
  113428. is freely redistributable on the condition that both of these
  113429. copyright notices are preserved without modification. */
  113430. /* Preserved Copyright: *********************************************/
  113431. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113432. Technische Universita"t Berlin
  113433. Any use of this software is permitted provided that this notice is not
  113434. removed and that neither the authors nor the Technische Universita"t
  113435. Berlin are deemed to have made any representations as to the
  113436. suitability of this software for any purpose nor are held responsible
  113437. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113438. THIS SOFTWARE.
  113439. As a matter of courtesy, the authors request to be informed about uses
  113440. this software has found, about bugs in this software, and about any
  113441. improvements that may be of general interest.
  113442. Berlin, 28.11.1994
  113443. Jutta Degener
  113444. Carsten Bormann
  113445. *********************************************************************/
  113446. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113447. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113448. // tasks..
  113449. #if JUCE_MSVC
  113450. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113451. #endif
  113452. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113453. #if JUCE_USE_OGGVORBIS
  113454. #include <stdlib.h>
  113455. #include <string.h>
  113456. #include <math.h>
  113457. /* Autocorrelation LPC coeff generation algorithm invented by
  113458. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113459. /* Input : n elements of time doamin data
  113460. Output: m lpc coefficients, excitation energy */
  113461. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113462. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113463. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113464. double error;
  113465. int i,j;
  113466. /* autocorrelation, p+1 lag coefficients */
  113467. j=m+1;
  113468. while(j--){
  113469. double d=0; /* double needed for accumulator depth */
  113470. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113471. aut[j]=d;
  113472. }
  113473. /* Generate lpc coefficients from autocorr values */
  113474. error=aut[0];
  113475. for(i=0;i<m;i++){
  113476. double r= -aut[i+1];
  113477. if(error==0){
  113478. memset(lpci,0,m*sizeof(*lpci));
  113479. return 0;
  113480. }
  113481. /* Sum up this iteration's reflection coefficient; note that in
  113482. Vorbis we don't save it. If anyone wants to recycle this code
  113483. and needs reflection coefficients, save the results of 'r' from
  113484. each iteration. */
  113485. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113486. r/=error;
  113487. /* Update LPC coefficients and total error */
  113488. lpc[i]=r;
  113489. for(j=0;j<i/2;j++){
  113490. double tmp=lpc[j];
  113491. lpc[j]+=r*lpc[i-1-j];
  113492. lpc[i-1-j]+=r*tmp;
  113493. }
  113494. if(i%2)lpc[j]+=lpc[j]*r;
  113495. error*=1.f-r*r;
  113496. }
  113497. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113498. /* we need the error value to know how big an impulse to hit the
  113499. filter with later */
  113500. return error;
  113501. }
  113502. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113503. float *data,long n){
  113504. /* in: coeff[0...m-1] LPC coefficients
  113505. prime[0...m-1] initial values (allocated size of n+m-1)
  113506. out: data[0...n-1] data samples */
  113507. long i,j,o,p;
  113508. float y;
  113509. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113510. if(!prime)
  113511. for(i=0;i<m;i++)
  113512. work[i]=0.f;
  113513. else
  113514. for(i=0;i<m;i++)
  113515. work[i]=prime[i];
  113516. for(i=0;i<n;i++){
  113517. y=0;
  113518. o=i;
  113519. p=m;
  113520. for(j=0;j<m;j++)
  113521. y-=work[o++]*coeff[--p];
  113522. data[i]=work[o]=y;
  113523. }
  113524. }
  113525. #endif
  113526. /*** End of inlined file: lpc.c ***/
  113527. /*** Start of inlined file: lsp.c ***/
  113528. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113529. an iterative root polisher (CACM algorithm 283). It *is* possible
  113530. to confuse this algorithm into not converging; that should only
  113531. happen with absurdly closely spaced roots (very sharp peaks in the
  113532. LPC f response) which in turn should be impossible in our use of
  113533. the code. If this *does* happen anyway, it's a bug in the floor
  113534. finder; find the cause of the confusion (probably a single bin
  113535. spike or accidental near-float-limit resolution problems) and
  113536. correct it. */
  113537. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113538. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113539. // tasks..
  113540. #if JUCE_MSVC
  113541. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113542. #endif
  113543. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113544. #if JUCE_USE_OGGVORBIS
  113545. #include <math.h>
  113546. #include <string.h>
  113547. #include <stdlib.h>
  113548. /*** Start of inlined file: lookup.h ***/
  113549. #ifndef _V_LOOKUP_H_
  113550. #ifdef FLOAT_LOOKUP
  113551. extern float vorbis_coslook(float a);
  113552. extern float vorbis_invsqlook(float a);
  113553. extern float vorbis_invsq2explook(int a);
  113554. extern float vorbis_fromdBlook(float a);
  113555. #endif
  113556. #ifdef INT_LOOKUP
  113557. extern long vorbis_invsqlook_i(long a,long e);
  113558. extern long vorbis_coslook_i(long a);
  113559. extern float vorbis_fromdBlook_i(long a);
  113560. #endif
  113561. #endif
  113562. /*** End of inlined file: lookup.h ***/
  113563. /* three possible LSP to f curve functions; the exact computation
  113564. (float), a lookup based float implementation, and an integer
  113565. implementation. The float lookup is likely the optimal choice on
  113566. any machine with an FPU. The integer implementation is *not* fixed
  113567. point (due to the need for a large dynamic range and thus a
  113568. seperately tracked exponent) and thus much more complex than the
  113569. relatively simple float implementations. It's mostly for future
  113570. work on a fully fixed point implementation for processors like the
  113571. ARM family. */
  113572. /* undefine both for the 'old' but more precise implementation */
  113573. #define FLOAT_LOOKUP
  113574. #undef INT_LOOKUP
  113575. #ifdef FLOAT_LOOKUP
  113576. /*** Start of inlined file: lookup.c ***/
  113577. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113578. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113579. // tasks..
  113580. #if JUCE_MSVC
  113581. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113582. #endif
  113583. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113584. #if JUCE_USE_OGGVORBIS
  113585. #include <math.h>
  113586. /*** Start of inlined file: lookup.h ***/
  113587. #ifndef _V_LOOKUP_H_
  113588. #ifdef FLOAT_LOOKUP
  113589. extern float vorbis_coslook(float a);
  113590. extern float vorbis_invsqlook(float a);
  113591. extern float vorbis_invsq2explook(int a);
  113592. extern float vorbis_fromdBlook(float a);
  113593. #endif
  113594. #ifdef INT_LOOKUP
  113595. extern long vorbis_invsqlook_i(long a,long e);
  113596. extern long vorbis_coslook_i(long a);
  113597. extern float vorbis_fromdBlook_i(long a);
  113598. #endif
  113599. #endif
  113600. /*** End of inlined file: lookup.h ***/
  113601. /*** Start of inlined file: lookup_data.h ***/
  113602. #ifndef _V_LOOKUP_DATA_H_
  113603. #ifdef FLOAT_LOOKUP
  113604. #define COS_LOOKUP_SZ 128
  113605. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113606. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113607. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113608. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113609. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113610. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113611. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113612. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113613. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113614. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113615. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113616. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113617. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113618. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113619. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113620. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113621. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113622. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113623. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113624. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113625. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113626. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113627. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113628. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113629. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113630. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113631. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113632. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113633. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113634. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113635. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113636. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113637. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113638. -1.0000000000000f,
  113639. };
  113640. #define INVSQ_LOOKUP_SZ 32
  113641. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113642. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113643. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113644. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113645. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113646. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113647. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113648. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113649. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113650. 1.000000000000f,
  113651. };
  113652. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113653. #define INVSQ2EXP_LOOKUP_MAX 32
  113654. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113655. INVSQ2EXP_LOOKUP_MIN+1]={
  113656. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113657. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113658. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113659. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113660. 256.f, 181.019336f, 128.f, 90.50966799f,
  113661. 64.f, 45.254834f, 32.f, 22.627417f,
  113662. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113663. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113664. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113665. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113666. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113667. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113668. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113669. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113670. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113671. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113672. 1.525878906e-05f,
  113673. };
  113674. #endif
  113675. #define FROMdB_LOOKUP_SZ 35
  113676. #define FROMdB2_LOOKUP_SZ 32
  113677. #define FROMdB_SHIFT 5
  113678. #define FROMdB2_SHIFT 3
  113679. #define FROMdB2_MASK 31
  113680. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113681. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113682. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113683. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113684. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113685. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113686. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113687. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113688. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113689. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113690. };
  113691. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113692. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113693. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113694. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113695. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113696. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113697. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113698. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113699. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113700. };
  113701. #ifdef INT_LOOKUP
  113702. #define INVSQ_LOOKUP_I_SHIFT 10
  113703. #define INVSQ_LOOKUP_I_MASK 1023
  113704. static long INVSQ_LOOKUP_I[64+1]={
  113705. 92682l, 91966l, 91267l, 90583l,
  113706. 89915l, 89261l, 88621l, 87995l,
  113707. 87381l, 86781l, 86192l, 85616l,
  113708. 85051l, 84497l, 83953l, 83420l,
  113709. 82897l, 82384l, 81880l, 81385l,
  113710. 80899l, 80422l, 79953l, 79492l,
  113711. 79039l, 78594l, 78156l, 77726l,
  113712. 77302l, 76885l, 76475l, 76072l,
  113713. 75674l, 75283l, 74898l, 74519l,
  113714. 74146l, 73778l, 73415l, 73058l,
  113715. 72706l, 72359l, 72016l, 71679l,
  113716. 71347l, 71019l, 70695l, 70376l,
  113717. 70061l, 69750l, 69444l, 69141l,
  113718. 68842l, 68548l, 68256l, 67969l,
  113719. 67685l, 67405l, 67128l, 66855l,
  113720. 66585l, 66318l, 66054l, 65794l,
  113721. 65536l,
  113722. };
  113723. #define COS_LOOKUP_I_SHIFT 9
  113724. #define COS_LOOKUP_I_MASK 511
  113725. #define COS_LOOKUP_I_SZ 128
  113726. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113727. 16384l, 16379l, 16364l, 16340l,
  113728. 16305l, 16261l, 16207l, 16143l,
  113729. 16069l, 15986l, 15893l, 15791l,
  113730. 15679l, 15557l, 15426l, 15286l,
  113731. 15137l, 14978l, 14811l, 14635l,
  113732. 14449l, 14256l, 14053l, 13842l,
  113733. 13623l, 13395l, 13160l, 12916l,
  113734. 12665l, 12406l, 12140l, 11866l,
  113735. 11585l, 11297l, 11003l, 10702l,
  113736. 10394l, 10080l, 9760l, 9434l,
  113737. 9102l, 8765l, 8423l, 8076l,
  113738. 7723l, 7366l, 7005l, 6639l,
  113739. 6270l, 5897l, 5520l, 5139l,
  113740. 4756l, 4370l, 3981l, 3590l,
  113741. 3196l, 2801l, 2404l, 2006l,
  113742. 1606l, 1205l, 804l, 402l,
  113743. 0l, -401l, -803l, -1204l,
  113744. -1605l, -2005l, -2403l, -2800l,
  113745. -3195l, -3589l, -3980l, -4369l,
  113746. -4755l, -5138l, -5519l, -5896l,
  113747. -6269l, -6638l, -7004l, -7365l,
  113748. -7722l, -8075l, -8422l, -8764l,
  113749. -9101l, -9433l, -9759l, -10079l,
  113750. -10393l, -10701l, -11002l, -11296l,
  113751. -11584l, -11865l, -12139l, -12405l,
  113752. -12664l, -12915l, -13159l, -13394l,
  113753. -13622l, -13841l, -14052l, -14255l,
  113754. -14448l, -14634l, -14810l, -14977l,
  113755. -15136l, -15285l, -15425l, -15556l,
  113756. -15678l, -15790l, -15892l, -15985l,
  113757. -16068l, -16142l, -16206l, -16260l,
  113758. -16304l, -16339l, -16363l, -16378l,
  113759. -16383l,
  113760. };
  113761. #endif
  113762. #endif
  113763. /*** End of inlined file: lookup_data.h ***/
  113764. #ifdef FLOAT_LOOKUP
  113765. /* interpolated lookup based cos function, domain 0 to PI only */
  113766. float vorbis_coslook(float a){
  113767. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113768. int i=vorbis_ftoi(d-.5);
  113769. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113770. }
  113771. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113772. float vorbis_invsqlook(float a){
  113773. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113774. int i=vorbis_ftoi(d-.5f);
  113775. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113776. }
  113777. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113778. float vorbis_invsq2explook(int a){
  113779. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113780. }
  113781. #include <stdio.h>
  113782. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113783. float vorbis_fromdBlook(float a){
  113784. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113785. return (i<0)?1.f:
  113786. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113787. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113788. }
  113789. #endif
  113790. #ifdef INT_LOOKUP
  113791. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113792. 16.16 format
  113793. returns in m.8 format */
  113794. long vorbis_invsqlook_i(long a,long e){
  113795. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113796. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113797. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113798. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113799. d)>>16); /* result 1.16 */
  113800. e+=32;
  113801. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113802. e=(e>>1)-8;
  113803. return(val>>e);
  113804. }
  113805. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113806. /* a is in n.12 format */
  113807. float vorbis_fromdBlook_i(long a){
  113808. int i=(-a)>>(12-FROMdB2_SHIFT);
  113809. return (i<0)?1.f:
  113810. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113811. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113812. }
  113813. /* interpolated lookup based cos function, domain 0 to PI only */
  113814. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113815. long vorbis_coslook_i(long a){
  113816. int i=a>>COS_LOOKUP_I_SHIFT;
  113817. int d=a&COS_LOOKUP_I_MASK;
  113818. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113819. COS_LOOKUP_I_SHIFT);
  113820. }
  113821. #endif
  113822. #endif
  113823. /*** End of inlined file: lookup.c ***/
  113824. /* catch this in the build system; we #include for
  113825. compilers (like gcc) that can't inline across
  113826. modules */
  113827. /* side effect: changes *lsp to cosines of lsp */
  113828. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113829. float amp,float ampoffset){
  113830. int i;
  113831. float wdel=M_PI/ln;
  113832. vorbis_fpu_control fpu;
  113833. (void) fpu; // to avoid an unused variable warning
  113834. vorbis_fpu_setround(&fpu);
  113835. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  113836. i=0;
  113837. while(i<n){
  113838. int k=map[i];
  113839. int qexp;
  113840. float p=.7071067812f;
  113841. float q=.7071067812f;
  113842. float w=vorbis_coslook(wdel*k);
  113843. float *ftmp=lsp;
  113844. int c=m>>1;
  113845. do{
  113846. q*=ftmp[0]-w;
  113847. p*=ftmp[1]-w;
  113848. ftmp+=2;
  113849. }while(--c);
  113850. if(m&1){
  113851. /* odd order filter; slightly assymetric */
  113852. /* the last coefficient */
  113853. q*=ftmp[0]-w;
  113854. q*=q;
  113855. p*=p*(1.f-w*w);
  113856. }else{
  113857. /* even order filter; still symmetric */
  113858. q*=q*(1.f+w);
  113859. p*=p*(1.f-w);
  113860. }
  113861. q=frexp(p+q,&qexp);
  113862. q=vorbis_fromdBlook(amp*
  113863. vorbis_invsqlook(q)*
  113864. vorbis_invsq2explook(qexp+m)-
  113865. ampoffset);
  113866. do{
  113867. curve[i++]*=q;
  113868. }while(map[i]==k);
  113869. }
  113870. vorbis_fpu_restore(fpu);
  113871. }
  113872. #else
  113873. #ifdef INT_LOOKUP
  113874. /*** Start of inlined file: lookup.c ***/
  113875. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113876. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113877. // tasks..
  113878. #if JUCE_MSVC
  113879. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113880. #endif
  113881. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113882. #if JUCE_USE_OGGVORBIS
  113883. #include <math.h>
  113884. /*** Start of inlined file: lookup.h ***/
  113885. #ifndef _V_LOOKUP_H_
  113886. #ifdef FLOAT_LOOKUP
  113887. extern float vorbis_coslook(float a);
  113888. extern float vorbis_invsqlook(float a);
  113889. extern float vorbis_invsq2explook(int a);
  113890. extern float vorbis_fromdBlook(float a);
  113891. #endif
  113892. #ifdef INT_LOOKUP
  113893. extern long vorbis_invsqlook_i(long a,long e);
  113894. extern long vorbis_coslook_i(long a);
  113895. extern float vorbis_fromdBlook_i(long a);
  113896. #endif
  113897. #endif
  113898. /*** End of inlined file: lookup.h ***/
  113899. /*** Start of inlined file: lookup_data.h ***/
  113900. #ifndef _V_LOOKUP_DATA_H_
  113901. #ifdef FLOAT_LOOKUP
  113902. #define COS_LOOKUP_SZ 128
  113903. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113904. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113905. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113906. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113907. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113908. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113909. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113910. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113911. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113912. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113913. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113914. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113915. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113916. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113917. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113918. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113919. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113920. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113921. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113922. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113923. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113924. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113925. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113926. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113927. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113928. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113929. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113930. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113931. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113932. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113933. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113934. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113935. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113936. -1.0000000000000f,
  113937. };
  113938. #define INVSQ_LOOKUP_SZ 32
  113939. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113940. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113941. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113942. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113943. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113944. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113945. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113946. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113947. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113948. 1.000000000000f,
  113949. };
  113950. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113951. #define INVSQ2EXP_LOOKUP_MAX 32
  113952. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113953. INVSQ2EXP_LOOKUP_MIN+1]={
  113954. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113955. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113956. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113957. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113958. 256.f, 181.019336f, 128.f, 90.50966799f,
  113959. 64.f, 45.254834f, 32.f, 22.627417f,
  113960. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113961. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113962. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113963. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113964. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113965. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113966. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113967. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113968. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113969. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113970. 1.525878906e-05f,
  113971. };
  113972. #endif
  113973. #define FROMdB_LOOKUP_SZ 35
  113974. #define FROMdB2_LOOKUP_SZ 32
  113975. #define FROMdB_SHIFT 5
  113976. #define FROMdB2_SHIFT 3
  113977. #define FROMdB2_MASK 31
  113978. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113979. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113980. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113981. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113982. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113983. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113984. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113985. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113986. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113987. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113988. };
  113989. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113990. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113991. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113992. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113993. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113994. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113995. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113996. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113997. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113998. };
  113999. #ifdef INT_LOOKUP
  114000. #define INVSQ_LOOKUP_I_SHIFT 10
  114001. #define INVSQ_LOOKUP_I_MASK 1023
  114002. static long INVSQ_LOOKUP_I[64+1]={
  114003. 92682l, 91966l, 91267l, 90583l,
  114004. 89915l, 89261l, 88621l, 87995l,
  114005. 87381l, 86781l, 86192l, 85616l,
  114006. 85051l, 84497l, 83953l, 83420l,
  114007. 82897l, 82384l, 81880l, 81385l,
  114008. 80899l, 80422l, 79953l, 79492l,
  114009. 79039l, 78594l, 78156l, 77726l,
  114010. 77302l, 76885l, 76475l, 76072l,
  114011. 75674l, 75283l, 74898l, 74519l,
  114012. 74146l, 73778l, 73415l, 73058l,
  114013. 72706l, 72359l, 72016l, 71679l,
  114014. 71347l, 71019l, 70695l, 70376l,
  114015. 70061l, 69750l, 69444l, 69141l,
  114016. 68842l, 68548l, 68256l, 67969l,
  114017. 67685l, 67405l, 67128l, 66855l,
  114018. 66585l, 66318l, 66054l, 65794l,
  114019. 65536l,
  114020. };
  114021. #define COS_LOOKUP_I_SHIFT 9
  114022. #define COS_LOOKUP_I_MASK 511
  114023. #define COS_LOOKUP_I_SZ 128
  114024. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114025. 16384l, 16379l, 16364l, 16340l,
  114026. 16305l, 16261l, 16207l, 16143l,
  114027. 16069l, 15986l, 15893l, 15791l,
  114028. 15679l, 15557l, 15426l, 15286l,
  114029. 15137l, 14978l, 14811l, 14635l,
  114030. 14449l, 14256l, 14053l, 13842l,
  114031. 13623l, 13395l, 13160l, 12916l,
  114032. 12665l, 12406l, 12140l, 11866l,
  114033. 11585l, 11297l, 11003l, 10702l,
  114034. 10394l, 10080l, 9760l, 9434l,
  114035. 9102l, 8765l, 8423l, 8076l,
  114036. 7723l, 7366l, 7005l, 6639l,
  114037. 6270l, 5897l, 5520l, 5139l,
  114038. 4756l, 4370l, 3981l, 3590l,
  114039. 3196l, 2801l, 2404l, 2006l,
  114040. 1606l, 1205l, 804l, 402l,
  114041. 0l, -401l, -803l, -1204l,
  114042. -1605l, -2005l, -2403l, -2800l,
  114043. -3195l, -3589l, -3980l, -4369l,
  114044. -4755l, -5138l, -5519l, -5896l,
  114045. -6269l, -6638l, -7004l, -7365l,
  114046. -7722l, -8075l, -8422l, -8764l,
  114047. -9101l, -9433l, -9759l, -10079l,
  114048. -10393l, -10701l, -11002l, -11296l,
  114049. -11584l, -11865l, -12139l, -12405l,
  114050. -12664l, -12915l, -13159l, -13394l,
  114051. -13622l, -13841l, -14052l, -14255l,
  114052. -14448l, -14634l, -14810l, -14977l,
  114053. -15136l, -15285l, -15425l, -15556l,
  114054. -15678l, -15790l, -15892l, -15985l,
  114055. -16068l, -16142l, -16206l, -16260l,
  114056. -16304l, -16339l, -16363l, -16378l,
  114057. -16383l,
  114058. };
  114059. #endif
  114060. #endif
  114061. /*** End of inlined file: lookup_data.h ***/
  114062. #ifdef FLOAT_LOOKUP
  114063. /* interpolated lookup based cos function, domain 0 to PI only */
  114064. float vorbis_coslook(float a){
  114065. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114066. int i=vorbis_ftoi(d-.5);
  114067. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114068. }
  114069. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114070. float vorbis_invsqlook(float a){
  114071. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114072. int i=vorbis_ftoi(d-.5f);
  114073. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114074. }
  114075. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114076. float vorbis_invsq2explook(int a){
  114077. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114078. }
  114079. #include <stdio.h>
  114080. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114081. float vorbis_fromdBlook(float a){
  114082. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114083. return (i<0)?1.f:
  114084. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114085. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114086. }
  114087. #endif
  114088. #ifdef INT_LOOKUP
  114089. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114090. 16.16 format
  114091. returns in m.8 format */
  114092. long vorbis_invsqlook_i(long a,long e){
  114093. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114094. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114095. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114096. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114097. d)>>16); /* result 1.16 */
  114098. e+=32;
  114099. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114100. e=(e>>1)-8;
  114101. return(val>>e);
  114102. }
  114103. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114104. /* a is in n.12 format */
  114105. float vorbis_fromdBlook_i(long a){
  114106. int i=(-a)>>(12-FROMdB2_SHIFT);
  114107. return (i<0)?1.f:
  114108. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114109. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114110. }
  114111. /* interpolated lookup based cos function, domain 0 to PI only */
  114112. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114113. long vorbis_coslook_i(long a){
  114114. int i=a>>COS_LOOKUP_I_SHIFT;
  114115. int d=a&COS_LOOKUP_I_MASK;
  114116. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114117. COS_LOOKUP_I_SHIFT);
  114118. }
  114119. #endif
  114120. #endif
  114121. /*** End of inlined file: lookup.c ***/
  114122. /* catch this in the build system; we #include for
  114123. compilers (like gcc) that can't inline across
  114124. modules */
  114125. static int MLOOP_1[64]={
  114126. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114127. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114128. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114129. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114130. };
  114131. static int MLOOP_2[64]={
  114132. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114133. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114134. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114135. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114136. };
  114137. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114138. /* side effect: changes *lsp to cosines of lsp */
  114139. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114140. float amp,float ampoffset){
  114141. /* 0 <= m < 256 */
  114142. /* set up for using all int later */
  114143. int i;
  114144. int ampoffseti=rint(ampoffset*4096.f);
  114145. int ampi=rint(amp*16.f);
  114146. long *ilsp=alloca(m*sizeof(*ilsp));
  114147. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114148. i=0;
  114149. while(i<n){
  114150. int j,k=map[i];
  114151. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114152. unsigned long qi=46341;
  114153. int qexp=0,shift;
  114154. long wi=vorbis_coslook_i(k*65536/ln);
  114155. qi*=labs(ilsp[0]-wi);
  114156. pi*=labs(ilsp[1]-wi);
  114157. for(j=3;j<m;j+=2){
  114158. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114159. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114160. shift=MLOOP_3[(pi|qi)>>16];
  114161. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114162. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114163. qexp+=shift;
  114164. }
  114165. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114166. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114167. shift=MLOOP_3[(pi|qi)>>16];
  114168. /* pi,qi normalized collectively, both tracked using qexp */
  114169. if(m&1){
  114170. /* odd order filter; slightly assymetric */
  114171. /* the last coefficient */
  114172. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114173. pi=(pi>>shift)<<14;
  114174. qexp+=shift;
  114175. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114176. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114177. shift=MLOOP_3[(pi|qi)>>16];
  114178. pi>>=shift;
  114179. qi>>=shift;
  114180. qexp+=shift-14*((m+1)>>1);
  114181. pi=((pi*pi)>>16);
  114182. qi=((qi*qi)>>16);
  114183. qexp=qexp*2+m;
  114184. pi*=(1<<14)-((wi*wi)>>14);
  114185. qi+=pi>>14;
  114186. }else{
  114187. /* even order filter; still symmetric */
  114188. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114189. worth tracking step by step */
  114190. pi>>=shift;
  114191. qi>>=shift;
  114192. qexp+=shift-7*m;
  114193. pi=((pi*pi)>>16);
  114194. qi=((qi*qi)>>16);
  114195. qexp=qexp*2+m;
  114196. pi*=(1<<14)-wi;
  114197. qi*=(1<<14)+wi;
  114198. qi=(qi+pi)>>14;
  114199. }
  114200. /* we've let the normalization drift because it wasn't important;
  114201. however, for the lookup, things must be normalized again. We
  114202. need at most one right shift or a number of left shifts */
  114203. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114204. qi>>=1; qexp++;
  114205. }else
  114206. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114207. qi<<=1; qexp--;
  114208. }
  114209. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114210. vorbis_invsqlook_i(qi,qexp)-
  114211. /* m.8, m+n<=8 */
  114212. ampoffseti); /* 8.12[0] */
  114213. curve[i]*=amp;
  114214. while(map[++i]==k)curve[i]*=amp;
  114215. }
  114216. }
  114217. #else
  114218. /* old, nonoptimized but simple version for any poor sap who needs to
  114219. figure out what the hell this code does, or wants the other
  114220. fraction of a dB precision */
  114221. /* side effect: changes *lsp to cosines of lsp */
  114222. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114223. float amp,float ampoffset){
  114224. int i;
  114225. float wdel=M_PI/ln;
  114226. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114227. i=0;
  114228. while(i<n){
  114229. int j,k=map[i];
  114230. float p=.5f;
  114231. float q=.5f;
  114232. float w=2.f*cos(wdel*k);
  114233. for(j=1;j<m;j+=2){
  114234. q *= w-lsp[j-1];
  114235. p *= w-lsp[j];
  114236. }
  114237. if(j==m){
  114238. /* odd order filter; slightly assymetric */
  114239. /* the last coefficient */
  114240. q*=w-lsp[j-1];
  114241. p*=p*(4.f-w*w);
  114242. q*=q;
  114243. }else{
  114244. /* even order filter; still symmetric */
  114245. p*=p*(2.f-w);
  114246. q*=q*(2.f+w);
  114247. }
  114248. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114249. curve[i]*=q;
  114250. while(map[++i]==k)curve[i]*=q;
  114251. }
  114252. }
  114253. #endif
  114254. #endif
  114255. static void cheby(float *g, int ord) {
  114256. int i, j;
  114257. g[0] *= .5f;
  114258. for(i=2; i<= ord; i++) {
  114259. for(j=ord; j >= i; j--) {
  114260. g[j-2] -= g[j];
  114261. g[j] += g[j];
  114262. }
  114263. }
  114264. }
  114265. static int comp(const void *a,const void *b){
  114266. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114267. }
  114268. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114269. but there are root sets for which it gets into limit cycles
  114270. (exacerbated by zero suppression) and fails. We can't afford to
  114271. fail, even if the failure is 1 in 100,000,000, so we now use
  114272. Laguerre and later polish with Newton-Raphson (which can then
  114273. afford to fail) */
  114274. #define EPSILON 10e-7
  114275. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114276. int i,m;
  114277. double lastdelta=0.f;
  114278. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114279. for(i=0;i<=ord;i++)defl[i]=a[i];
  114280. for(m=ord;m>0;m--){
  114281. double newx=0.f,delta;
  114282. /* iterate a root */
  114283. while(1){
  114284. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114285. /* eval the polynomial and its first two derivatives */
  114286. for(i=m;i>0;i--){
  114287. ppp = newx*ppp + pp;
  114288. pp = newx*pp + p;
  114289. p = newx*p + defl[i-1];
  114290. }
  114291. /* Laguerre's method */
  114292. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114293. if(denom<0)
  114294. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114295. if(pp>0){
  114296. denom = pp + sqrt(denom);
  114297. if(denom<EPSILON)denom=EPSILON;
  114298. }else{
  114299. denom = pp - sqrt(denom);
  114300. if(denom>-(EPSILON))denom=-(EPSILON);
  114301. }
  114302. delta = m*p/denom;
  114303. newx -= delta;
  114304. if(delta<0.f)delta*=-1;
  114305. if(fabs(delta/newx)<10e-12)break;
  114306. lastdelta=delta;
  114307. }
  114308. r[m-1]=newx;
  114309. /* forward deflation */
  114310. for(i=m;i>0;i--)
  114311. defl[i-1]+=newx*defl[i];
  114312. defl++;
  114313. }
  114314. return(0);
  114315. }
  114316. /* for spit-and-polish only */
  114317. static int Newton_Raphson(float *a,int ord,float *r){
  114318. int i, k, count=0;
  114319. double error=1.f;
  114320. double *root=(double*)alloca(ord*sizeof(*root));
  114321. for(i=0; i<ord;i++) root[i] = r[i];
  114322. while(error>1e-20){
  114323. error=0;
  114324. for(i=0; i<ord; i++) { /* Update each point. */
  114325. double pp=0.,delta;
  114326. double rooti=root[i];
  114327. double p=a[ord];
  114328. for(k=ord-1; k>= 0; k--) {
  114329. pp= pp* rooti + p;
  114330. p = p * rooti + a[k];
  114331. }
  114332. delta = p/pp;
  114333. root[i] -= delta;
  114334. error+= delta*delta;
  114335. }
  114336. if(count>40)return(-1);
  114337. count++;
  114338. }
  114339. /* Replaced the original bubble sort with a real sort. With your
  114340. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114341. for(i=0; i<ord;i++) r[i] = root[i];
  114342. return(0);
  114343. }
  114344. /* Convert lpc coefficients to lsp coefficients */
  114345. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114346. int order2=(m+1)>>1;
  114347. int g1_order,g2_order;
  114348. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114349. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114350. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114351. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114352. int i;
  114353. /* even and odd are slightly different base cases */
  114354. g1_order=(m+1)>>1;
  114355. g2_order=(m) >>1;
  114356. /* Compute the lengths of the x polynomials. */
  114357. /* Compute the first half of K & R F1 & F2 polynomials. */
  114358. /* Compute half of the symmetric and antisymmetric polynomials. */
  114359. /* Remove the roots at +1 and -1. */
  114360. g1[g1_order] = 1.f;
  114361. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114362. g2[g2_order] = 1.f;
  114363. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114364. if(g1_order>g2_order){
  114365. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114366. }else{
  114367. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114368. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114369. }
  114370. /* Convert into polynomials in cos(alpha) */
  114371. cheby(g1,g1_order);
  114372. cheby(g2,g2_order);
  114373. /* Find the roots of the 2 even polynomials.*/
  114374. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114375. Laguerre_With_Deflation(g2,g2_order,g2r))
  114376. return(-1);
  114377. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114378. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114379. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114380. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114381. for(i=0;i<g1_order;i++)
  114382. lsp[i*2] = acos(g1r[i]);
  114383. for(i=0;i<g2_order;i++)
  114384. lsp[i*2+1] = acos(g2r[i]);
  114385. return(0);
  114386. }
  114387. #endif
  114388. /*** End of inlined file: lsp.c ***/
  114389. /*** Start of inlined file: mapping0.c ***/
  114390. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114391. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114392. // tasks..
  114393. #if JUCE_MSVC
  114394. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114395. #endif
  114396. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114397. #if JUCE_USE_OGGVORBIS
  114398. #include <stdlib.h>
  114399. #include <stdio.h>
  114400. #include <string.h>
  114401. #include <math.h>
  114402. /* simplistic, wasteful way of doing this (unique lookup for each
  114403. mode/submapping); there should be a central repository for
  114404. identical lookups. That will require minor work, so I'm putting it
  114405. off as low priority.
  114406. Why a lookup for each backend in a given mode? Because the
  114407. blocksize is set by the mode, and low backend lookups may require
  114408. parameters from other areas of the mode/mapping */
  114409. static void mapping0_free_info(vorbis_info_mapping *i){
  114410. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114411. if(info){
  114412. memset(info,0,sizeof(*info));
  114413. _ogg_free(info);
  114414. }
  114415. }
  114416. static int ilog3(unsigned int v){
  114417. int ret=0;
  114418. if(v)--v;
  114419. while(v){
  114420. ret++;
  114421. v>>=1;
  114422. }
  114423. return(ret);
  114424. }
  114425. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114426. oggpack_buffer *opb){
  114427. int i;
  114428. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114429. /* another 'we meant to do it this way' hack... up to beta 4, we
  114430. packed 4 binary zeros here to signify one submapping in use. We
  114431. now redefine that to mean four bitflags that indicate use of
  114432. deeper features; bit0:submappings, bit1:coupling,
  114433. bit2,3:reserved. This is backward compatable with all actual uses
  114434. of the beta code. */
  114435. if(info->submaps>1){
  114436. oggpack_write(opb,1,1);
  114437. oggpack_write(opb,info->submaps-1,4);
  114438. }else
  114439. oggpack_write(opb,0,1);
  114440. if(info->coupling_steps>0){
  114441. oggpack_write(opb,1,1);
  114442. oggpack_write(opb,info->coupling_steps-1,8);
  114443. for(i=0;i<info->coupling_steps;i++){
  114444. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114445. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114446. }
  114447. }else
  114448. oggpack_write(opb,0,1);
  114449. oggpack_write(opb,0,2); /* 2,3:reserved */
  114450. /* we don't write the channel submappings if we only have one... */
  114451. if(info->submaps>1){
  114452. for(i=0;i<vi->channels;i++)
  114453. oggpack_write(opb,info->chmuxlist[i],4);
  114454. }
  114455. for(i=0;i<info->submaps;i++){
  114456. oggpack_write(opb,0,8); /* time submap unused */
  114457. oggpack_write(opb,info->floorsubmap[i],8);
  114458. oggpack_write(opb,info->residuesubmap[i],8);
  114459. }
  114460. }
  114461. /* also responsible for range checking */
  114462. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114463. int i;
  114464. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114465. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114466. memset(info,0,sizeof(*info));
  114467. if(oggpack_read(opb,1))
  114468. info->submaps=oggpack_read(opb,4)+1;
  114469. else
  114470. info->submaps=1;
  114471. if(oggpack_read(opb,1)){
  114472. info->coupling_steps=oggpack_read(opb,8)+1;
  114473. for(i=0;i<info->coupling_steps;i++){
  114474. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114475. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114476. if(testM<0 ||
  114477. testA<0 ||
  114478. testM==testA ||
  114479. testM>=vi->channels ||
  114480. testA>=vi->channels) goto err_out;
  114481. }
  114482. }
  114483. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114484. if(info->submaps>1){
  114485. for(i=0;i<vi->channels;i++){
  114486. info->chmuxlist[i]=oggpack_read(opb,4);
  114487. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114488. }
  114489. }
  114490. for(i=0;i<info->submaps;i++){
  114491. oggpack_read(opb,8); /* time submap unused */
  114492. info->floorsubmap[i]=oggpack_read(opb,8);
  114493. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114494. info->residuesubmap[i]=oggpack_read(opb,8);
  114495. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114496. }
  114497. return info;
  114498. err_out:
  114499. mapping0_free_info(info);
  114500. return(NULL);
  114501. }
  114502. #if 0
  114503. static long seq=0;
  114504. static ogg_int64_t total=0;
  114505. static float FLOOR1_fromdB_LOOKUP[256]={
  114506. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114507. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114508. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114509. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114510. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114511. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114512. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114513. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114514. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114515. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114516. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114517. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114518. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114519. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114520. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114521. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114522. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114523. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114524. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114525. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114526. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114527. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114528. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114529. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114530. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114531. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114532. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114533. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114534. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114535. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114536. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114537. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114538. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114539. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114540. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114541. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114542. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114543. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114544. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114545. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114546. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114547. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114548. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114549. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114550. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114551. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114552. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114553. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114554. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114555. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114556. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114557. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114558. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114559. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114560. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114561. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114562. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114563. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114564. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114565. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114566. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114567. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114568. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114569. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114570. };
  114571. #endif
  114572. extern int *floor1_fit(vorbis_block *vb,void *look,
  114573. const float *logmdct, /* in */
  114574. const float *logmask);
  114575. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114576. int *A,int *B,
  114577. int del);
  114578. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114579. void*look,
  114580. int *post,int *ilogmask);
  114581. static int mapping0_forward(vorbis_block *vb){
  114582. vorbis_dsp_state *vd=vb->vd;
  114583. vorbis_info *vi=vd->vi;
  114584. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114585. private_state *b=(private_state*)vb->vd->backend_state;
  114586. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114587. int n=vb->pcmend;
  114588. int i,j,k;
  114589. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114590. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114591. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114592. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114593. float global_ampmax=vbi->ampmax;
  114594. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114595. int blocktype=vbi->blocktype;
  114596. int modenumber=vb->W;
  114597. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114598. vorbis_look_psy *psy_look=
  114599. b->psy+blocktype+(vb->W?2:0);
  114600. vb->mode=modenumber;
  114601. for(i=0;i<vi->channels;i++){
  114602. float scale=4.f/n;
  114603. float scale_dB;
  114604. float *pcm =vb->pcm[i];
  114605. float *logfft =pcm;
  114606. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114607. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114608. todB estimation used on IEEE 754
  114609. compliant machines had a bug that
  114610. returned dB values about a third
  114611. of a decibel too high. The bug
  114612. was harmless because tunings
  114613. implicitly took that into
  114614. account. However, fixing the bug
  114615. in the estimator requires
  114616. changing all the tunings as well.
  114617. For now, it's easier to sync
  114618. things back up here, and
  114619. recalibrate the tunings in the
  114620. next major model upgrade. */
  114621. #if 0
  114622. if(vi->channels==2)
  114623. if(i==0)
  114624. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114625. else
  114626. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114627. #endif
  114628. /* window the PCM data */
  114629. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114630. #if 0
  114631. if(vi->channels==2)
  114632. if(i==0)
  114633. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114634. else
  114635. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114636. #endif
  114637. /* transform the PCM data */
  114638. /* only MDCT right now.... */
  114639. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114640. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114641. drft_forward(&b->fft_look[vb->W],pcm);
  114642. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114643. original todB estimation used on
  114644. IEEE 754 compliant machines had a
  114645. bug that returned dB values about
  114646. a third of a decibel too high.
  114647. The bug was harmless because
  114648. tunings implicitly took that into
  114649. account. However, fixing the bug
  114650. in the estimator requires
  114651. changing all the tunings as well.
  114652. For now, it's easier to sync
  114653. things back up here, and
  114654. recalibrate the tunings in the
  114655. next major model upgrade. */
  114656. local_ampmax[i]=logfft[0];
  114657. for(j=1;j<n-1;j+=2){
  114658. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114659. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114660. .345 is a hack; the original todB
  114661. estimation used on IEEE 754
  114662. compliant machines had a bug that
  114663. returned dB values about a third
  114664. of a decibel too high. The bug
  114665. was harmless because tunings
  114666. implicitly took that into
  114667. account. However, fixing the bug
  114668. in the estimator requires
  114669. changing all the tunings as well.
  114670. For now, it's easier to sync
  114671. things back up here, and
  114672. recalibrate the tunings in the
  114673. next major model upgrade. */
  114674. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114675. }
  114676. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114677. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114678. #if 0
  114679. if(vi->channels==2){
  114680. if(i==0){
  114681. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114682. }else{
  114683. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114684. }
  114685. }
  114686. #endif
  114687. }
  114688. {
  114689. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114690. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114691. for(i=0;i<vi->channels;i++){
  114692. /* the encoder setup assumes that all the modes used by any
  114693. specific bitrate tweaking use the same floor */
  114694. int submap=info->chmuxlist[i];
  114695. /* the following makes things clearer to *me* anyway */
  114696. float *mdct =gmdct[i];
  114697. float *logfft =vb->pcm[i];
  114698. float *logmdct =logfft+n/2;
  114699. float *logmask =logfft;
  114700. vb->mode=modenumber;
  114701. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114702. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114703. for(j=0;j<n/2;j++)
  114704. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114705. todB estimation used on IEEE 754
  114706. compliant machines had a bug that
  114707. returned dB values about a third
  114708. of a decibel too high. The bug
  114709. was harmless because tunings
  114710. implicitly took that into
  114711. account. However, fixing the bug
  114712. in the estimator requires
  114713. changing all the tunings as well.
  114714. For now, it's easier to sync
  114715. things back up here, and
  114716. recalibrate the tunings in the
  114717. next major model upgrade. */
  114718. #if 0
  114719. if(vi->channels==2){
  114720. if(i==0)
  114721. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114722. else
  114723. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114724. }else{
  114725. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114726. }
  114727. #endif
  114728. /* first step; noise masking. Not only does 'noise masking'
  114729. give us curves from which we can decide how much resolution
  114730. to give noise parts of the spectrum, it also implicitly hands
  114731. us a tonality estimate (the larger the value in the
  114732. 'noise_depth' vector, the more tonal that area is) */
  114733. _vp_noisemask(psy_look,
  114734. logmdct,
  114735. noise); /* noise does not have by-frequency offset
  114736. bias applied yet */
  114737. #if 0
  114738. if(vi->channels==2){
  114739. if(i==0)
  114740. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114741. else
  114742. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114743. }
  114744. #endif
  114745. /* second step: 'all the other crap'; all the stuff that isn't
  114746. computed/fit for bitrate management goes in the second psy
  114747. vector. This includes tone masking, peak limiting and ATH */
  114748. _vp_tonemask(psy_look,
  114749. logfft,
  114750. tone,
  114751. global_ampmax,
  114752. local_ampmax[i]);
  114753. #if 0
  114754. if(vi->channels==2){
  114755. if(i==0)
  114756. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114757. else
  114758. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114759. }
  114760. #endif
  114761. /* third step; we offset the noise vectors, overlay tone
  114762. masking. We then do a floor1-specific line fit. If we're
  114763. performing bitrate management, the line fit is performed
  114764. multiple times for up/down tweakage on demand. */
  114765. #if 0
  114766. {
  114767. float aotuv[psy_look->n];
  114768. #endif
  114769. _vp_offset_and_mix(psy_look,
  114770. noise,
  114771. tone,
  114772. 1,
  114773. logmask,
  114774. mdct,
  114775. logmdct);
  114776. #if 0
  114777. if(vi->channels==2){
  114778. if(i==0)
  114779. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114780. else
  114781. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114782. }
  114783. }
  114784. #endif
  114785. #if 0
  114786. if(vi->channels==2){
  114787. if(i==0)
  114788. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114789. else
  114790. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114791. }
  114792. #endif
  114793. /* this algorithm is hardwired to floor 1 for now; abort out if
  114794. we're *not* floor1. This won't happen unless someone has
  114795. broken the encode setup lib. Guard it anyway. */
  114796. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114797. floor_posts[i][PACKETBLOBS/2]=
  114798. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114799. logmdct,
  114800. logmask);
  114801. /* are we managing bitrate? If so, perform two more fits for
  114802. later rate tweaking (fits represent hi/lo) */
  114803. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114804. /* higher rate by way of lower noise curve */
  114805. _vp_offset_and_mix(psy_look,
  114806. noise,
  114807. tone,
  114808. 2,
  114809. logmask,
  114810. mdct,
  114811. logmdct);
  114812. #if 0
  114813. if(vi->channels==2){
  114814. if(i==0)
  114815. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114816. else
  114817. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114818. }
  114819. #endif
  114820. floor_posts[i][PACKETBLOBS-1]=
  114821. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114822. logmdct,
  114823. logmask);
  114824. /* lower rate by way of higher noise curve */
  114825. _vp_offset_and_mix(psy_look,
  114826. noise,
  114827. tone,
  114828. 0,
  114829. logmask,
  114830. mdct,
  114831. logmdct);
  114832. #if 0
  114833. if(vi->channels==2)
  114834. if(i==0)
  114835. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  114836. else
  114837. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  114838. #endif
  114839. floor_posts[i][0]=
  114840. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114841. logmdct,
  114842. logmask);
  114843. /* we also interpolate a range of intermediate curves for
  114844. intermediate rates */
  114845. for(k=1;k<PACKETBLOBS/2;k++)
  114846. floor_posts[i][k]=
  114847. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114848. floor_posts[i][0],
  114849. floor_posts[i][PACKETBLOBS/2],
  114850. k*65536/(PACKETBLOBS/2));
  114851. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  114852. floor_posts[i][k]=
  114853. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114854. floor_posts[i][PACKETBLOBS/2],
  114855. floor_posts[i][PACKETBLOBS-1],
  114856. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  114857. }
  114858. }
  114859. }
  114860. vbi->ampmax=global_ampmax;
  114861. /*
  114862. the next phases are performed once for vbr-only and PACKETBLOB
  114863. times for bitrate managed modes.
  114864. 1) encode actual mode being used
  114865. 2) encode the floor for each channel, compute coded mask curve/res
  114866. 3) normalize and couple.
  114867. 4) encode residue
  114868. 5) save packet bytes to the packetblob vector
  114869. */
  114870. /* iterate over the many masking curve fits we've created */
  114871. {
  114872. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  114873. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  114874. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114875. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  114876. float **mag_memo;
  114877. int **mag_sort;
  114878. if(info->coupling_steps){
  114879. mag_memo=_vp_quantize_couple_memo(vb,
  114880. &ci->psy_g_param,
  114881. psy_look,
  114882. info,
  114883. gmdct);
  114884. mag_sort=_vp_quantize_couple_sort(vb,
  114885. psy_look,
  114886. info,
  114887. mag_memo);
  114888. hf_reduction(&ci->psy_g_param,
  114889. psy_look,
  114890. info,
  114891. mag_memo);
  114892. }
  114893. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  114894. if(psy_look->vi->normal_channel_p){
  114895. for(i=0;i<vi->channels;i++){
  114896. float *mdct =gmdct[i];
  114897. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  114898. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  114899. }
  114900. }
  114901. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  114902. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  114903. k++){
  114904. oggpack_buffer *opb=vbi->packetblob[k];
  114905. /* start out our new packet blob with packet type and mode */
  114906. /* Encode the packet type */
  114907. oggpack_write(opb,0,1);
  114908. /* Encode the modenumber */
  114909. /* Encode frame mode, pre,post windowsize, then dispatch */
  114910. oggpack_write(opb,modenumber,b->modebits);
  114911. if(vb->W){
  114912. oggpack_write(opb,vb->lW,1);
  114913. oggpack_write(opb,vb->nW,1);
  114914. }
  114915. /* encode floor, compute masking curve, sep out residue */
  114916. for(i=0;i<vi->channels;i++){
  114917. int submap=info->chmuxlist[i];
  114918. float *mdct =gmdct[i];
  114919. float *res =vb->pcm[i];
  114920. int *ilogmask=ilogmaskch[i]=
  114921. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114922. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  114923. floor_posts[i][k],
  114924. ilogmask);
  114925. #if 0
  114926. {
  114927. char buf[80];
  114928. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  114929. float work[n/2];
  114930. for(j=0;j<n/2;j++)
  114931. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  114932. _analysis_output(buf,seq,work,n/2,1,1,0);
  114933. }
  114934. #endif
  114935. _vp_remove_floor(psy_look,
  114936. mdct,
  114937. ilogmask,
  114938. res,
  114939. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114940. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  114941. #if 0
  114942. {
  114943. char buf[80];
  114944. float work[n/2];
  114945. for(j=0;j<n/2;j++)
  114946. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  114947. sprintf(buf,"resI%c%d",i?'R':'L',k);
  114948. _analysis_output(buf,seq,work,n/2,1,1,0);
  114949. }
  114950. #endif
  114951. }
  114952. /* our iteration is now based on masking curve, not prequant and
  114953. coupling. Only one prequant/coupling step */
  114954. /* quantize/couple */
  114955. /* incomplete implementation that assumes the tree is all depth
  114956. one, or no tree at all */
  114957. if(info->coupling_steps){
  114958. _vp_couple(k,
  114959. &ci->psy_g_param,
  114960. psy_look,
  114961. info,
  114962. vb->pcm,
  114963. mag_memo,
  114964. mag_sort,
  114965. ilogmaskch,
  114966. nonzero,
  114967. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114968. }
  114969. /* classify and encode by submap */
  114970. for(i=0;i<info->submaps;i++){
  114971. int ch_in_bundle=0;
  114972. long **classifications;
  114973. int resnum=info->residuesubmap[i];
  114974. for(j=0;j<vi->channels;j++){
  114975. if(info->chmuxlist[j]==i){
  114976. zerobundle[ch_in_bundle]=0;
  114977. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  114978. res_bundle[ch_in_bundle]=vb->pcm[j];
  114979. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  114980. }
  114981. }
  114982. classifications=_residue_P[ci->residue_type[resnum]]->
  114983. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  114984. _residue_P[ci->residue_type[resnum]]->
  114985. forward(opb,vb,b->residue[resnum],
  114986. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  114987. }
  114988. /* ok, done encoding. Next protopacket. */
  114989. }
  114990. }
  114991. #if 0
  114992. seq++;
  114993. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  114994. #endif
  114995. return(0);
  114996. }
  114997. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  114998. vorbis_dsp_state *vd=vb->vd;
  114999. vorbis_info *vi=vd->vi;
  115000. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115001. private_state *b=(private_state*)vd->backend_state;
  115002. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115003. int i,j;
  115004. long n=vb->pcmend=ci->blocksizes[vb->W];
  115005. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115006. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115007. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115008. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115009. /* recover the spectral envelope; store it in the PCM vector for now */
  115010. for(i=0;i<vi->channels;i++){
  115011. int submap=info->chmuxlist[i];
  115012. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115013. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115014. if(floormemo[i])
  115015. nonzero[i]=1;
  115016. else
  115017. nonzero[i]=0;
  115018. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115019. }
  115020. /* channel coupling can 'dirty' the nonzero listing */
  115021. for(i=0;i<info->coupling_steps;i++){
  115022. if(nonzero[info->coupling_mag[i]] ||
  115023. nonzero[info->coupling_ang[i]]){
  115024. nonzero[info->coupling_mag[i]]=1;
  115025. nonzero[info->coupling_ang[i]]=1;
  115026. }
  115027. }
  115028. /* recover the residue into our working vectors */
  115029. for(i=0;i<info->submaps;i++){
  115030. int ch_in_bundle=0;
  115031. for(j=0;j<vi->channels;j++){
  115032. if(info->chmuxlist[j]==i){
  115033. if(nonzero[j])
  115034. zerobundle[ch_in_bundle]=1;
  115035. else
  115036. zerobundle[ch_in_bundle]=0;
  115037. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115038. }
  115039. }
  115040. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115041. inverse(vb,b->residue[info->residuesubmap[i]],
  115042. pcmbundle,zerobundle,ch_in_bundle);
  115043. }
  115044. /* channel coupling */
  115045. for(i=info->coupling_steps-1;i>=0;i--){
  115046. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115047. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115048. for(j=0;j<n/2;j++){
  115049. float mag=pcmM[j];
  115050. float ang=pcmA[j];
  115051. if(mag>0)
  115052. if(ang>0){
  115053. pcmM[j]=mag;
  115054. pcmA[j]=mag-ang;
  115055. }else{
  115056. pcmA[j]=mag;
  115057. pcmM[j]=mag+ang;
  115058. }
  115059. else
  115060. if(ang>0){
  115061. pcmM[j]=mag;
  115062. pcmA[j]=mag+ang;
  115063. }else{
  115064. pcmA[j]=mag;
  115065. pcmM[j]=mag-ang;
  115066. }
  115067. }
  115068. }
  115069. /* compute and apply spectral envelope */
  115070. for(i=0;i<vi->channels;i++){
  115071. float *pcm=vb->pcm[i];
  115072. int submap=info->chmuxlist[i];
  115073. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115074. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115075. floormemo[i],pcm);
  115076. }
  115077. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115078. /* only MDCT right now.... */
  115079. for(i=0;i<vi->channels;i++){
  115080. float *pcm=vb->pcm[i];
  115081. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115082. }
  115083. /* all done! */
  115084. return(0);
  115085. }
  115086. /* export hooks */
  115087. vorbis_func_mapping mapping0_exportbundle={
  115088. &mapping0_pack,
  115089. &mapping0_unpack,
  115090. &mapping0_free_info,
  115091. &mapping0_forward,
  115092. &mapping0_inverse
  115093. };
  115094. #endif
  115095. /*** End of inlined file: mapping0.c ***/
  115096. /*** Start of inlined file: mdct.c ***/
  115097. /* this can also be run as an integer transform by uncommenting a
  115098. define in mdct.h; the integerization is a first pass and although
  115099. it's likely stable for Vorbis, the dynamic range is constrained and
  115100. roundoff isn't done (so it's noisy). Consider it functional, but
  115101. only a starting point. There's no point on a machine with an FPU */
  115102. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115103. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115104. // tasks..
  115105. #if JUCE_MSVC
  115106. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115107. #endif
  115108. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115109. #if JUCE_USE_OGGVORBIS
  115110. #include <stdio.h>
  115111. #include <stdlib.h>
  115112. #include <string.h>
  115113. #include <math.h>
  115114. /* build lookups for trig functions; also pre-figure scaling and
  115115. some window function algebra. */
  115116. void mdct_init(mdct_lookup *lookup,int n){
  115117. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115118. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115119. int i;
  115120. int n2=n>>1;
  115121. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115122. lookup->n=n;
  115123. lookup->trig=T;
  115124. lookup->bitrev=bitrev;
  115125. /* trig lookups... */
  115126. for(i=0;i<n/4;i++){
  115127. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115128. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115129. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115130. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115131. }
  115132. for(i=0;i<n/8;i++){
  115133. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115134. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115135. }
  115136. /* bitreverse lookup... */
  115137. {
  115138. int mask=(1<<(log2n-1))-1,i,j;
  115139. int msb=1<<(log2n-2);
  115140. for(i=0;i<n/8;i++){
  115141. int acc=0;
  115142. for(j=0;msb>>j;j++)
  115143. if((msb>>j)&i)acc|=1<<j;
  115144. bitrev[i*2]=((~acc)&mask)-1;
  115145. bitrev[i*2+1]=acc;
  115146. }
  115147. }
  115148. lookup->scale=FLOAT_CONV(4.f/n);
  115149. }
  115150. /* 8 point butterfly (in place, 4 register) */
  115151. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115152. REG_TYPE r0 = x[6] + x[2];
  115153. REG_TYPE r1 = x[6] - x[2];
  115154. REG_TYPE r2 = x[4] + x[0];
  115155. REG_TYPE r3 = x[4] - x[0];
  115156. x[6] = r0 + r2;
  115157. x[4] = r0 - r2;
  115158. r0 = x[5] - x[1];
  115159. r2 = x[7] - x[3];
  115160. x[0] = r1 + r0;
  115161. x[2] = r1 - r0;
  115162. r0 = x[5] + x[1];
  115163. r1 = x[7] + x[3];
  115164. x[3] = r2 + r3;
  115165. x[1] = r2 - r3;
  115166. x[7] = r1 + r0;
  115167. x[5] = r1 - r0;
  115168. }
  115169. /* 16 point butterfly (in place, 4 register) */
  115170. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115171. REG_TYPE r0 = x[1] - x[9];
  115172. REG_TYPE r1 = x[0] - x[8];
  115173. x[8] += x[0];
  115174. x[9] += x[1];
  115175. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115176. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115177. r0 = x[3] - x[11];
  115178. r1 = x[10] - x[2];
  115179. x[10] += x[2];
  115180. x[11] += x[3];
  115181. x[2] = r0;
  115182. x[3] = r1;
  115183. r0 = x[12] - x[4];
  115184. r1 = x[13] - x[5];
  115185. x[12] += x[4];
  115186. x[13] += x[5];
  115187. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115188. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115189. r0 = x[14] - x[6];
  115190. r1 = x[15] - x[7];
  115191. x[14] += x[6];
  115192. x[15] += x[7];
  115193. x[6] = r0;
  115194. x[7] = r1;
  115195. mdct_butterfly_8(x);
  115196. mdct_butterfly_8(x+8);
  115197. }
  115198. /* 32 point butterfly (in place, 4 register) */
  115199. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115200. REG_TYPE r0 = x[30] - x[14];
  115201. REG_TYPE r1 = x[31] - x[15];
  115202. x[30] += x[14];
  115203. x[31] += x[15];
  115204. x[14] = r0;
  115205. x[15] = r1;
  115206. r0 = x[28] - x[12];
  115207. r1 = x[29] - x[13];
  115208. x[28] += x[12];
  115209. x[29] += x[13];
  115210. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115211. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115212. r0 = x[26] - x[10];
  115213. r1 = x[27] - x[11];
  115214. x[26] += x[10];
  115215. x[27] += x[11];
  115216. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115217. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115218. r0 = x[24] - x[8];
  115219. r1 = x[25] - x[9];
  115220. x[24] += x[8];
  115221. x[25] += x[9];
  115222. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115223. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115224. r0 = x[22] - x[6];
  115225. r1 = x[7] - x[23];
  115226. x[22] += x[6];
  115227. x[23] += x[7];
  115228. x[6] = r1;
  115229. x[7] = r0;
  115230. r0 = x[4] - x[20];
  115231. r1 = x[5] - x[21];
  115232. x[20] += x[4];
  115233. x[21] += x[5];
  115234. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115235. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115236. r0 = x[2] - x[18];
  115237. r1 = x[3] - x[19];
  115238. x[18] += x[2];
  115239. x[19] += x[3];
  115240. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115241. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115242. r0 = x[0] - x[16];
  115243. r1 = x[1] - x[17];
  115244. x[16] += x[0];
  115245. x[17] += x[1];
  115246. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115247. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115248. mdct_butterfly_16(x);
  115249. mdct_butterfly_16(x+16);
  115250. }
  115251. /* N point first stage butterfly (in place, 2 register) */
  115252. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115253. DATA_TYPE *x,
  115254. int points){
  115255. DATA_TYPE *x1 = x + points - 8;
  115256. DATA_TYPE *x2 = x + (points>>1) - 8;
  115257. REG_TYPE r0;
  115258. REG_TYPE r1;
  115259. do{
  115260. r0 = x1[6] - x2[6];
  115261. r1 = x1[7] - x2[7];
  115262. x1[6] += x2[6];
  115263. x1[7] += x2[7];
  115264. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115265. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115266. r0 = x1[4] - x2[4];
  115267. r1 = x1[5] - x2[5];
  115268. x1[4] += x2[4];
  115269. x1[5] += x2[5];
  115270. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115271. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115272. r0 = x1[2] - x2[2];
  115273. r1 = x1[3] - x2[3];
  115274. x1[2] += x2[2];
  115275. x1[3] += x2[3];
  115276. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115277. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115278. r0 = x1[0] - x2[0];
  115279. r1 = x1[1] - x2[1];
  115280. x1[0] += x2[0];
  115281. x1[1] += x2[1];
  115282. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115283. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115284. x1-=8;
  115285. x2-=8;
  115286. T+=16;
  115287. }while(x2>=x);
  115288. }
  115289. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115290. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115291. DATA_TYPE *x,
  115292. int points,
  115293. int trigint){
  115294. DATA_TYPE *x1 = x + points - 8;
  115295. DATA_TYPE *x2 = x + (points>>1) - 8;
  115296. REG_TYPE r0;
  115297. REG_TYPE r1;
  115298. do{
  115299. r0 = x1[6] - x2[6];
  115300. r1 = x1[7] - x2[7];
  115301. x1[6] += x2[6];
  115302. x1[7] += x2[7];
  115303. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115304. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115305. T+=trigint;
  115306. r0 = x1[4] - x2[4];
  115307. r1 = x1[5] - x2[5];
  115308. x1[4] += x2[4];
  115309. x1[5] += x2[5];
  115310. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115311. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115312. T+=trigint;
  115313. r0 = x1[2] - x2[2];
  115314. r1 = x1[3] - x2[3];
  115315. x1[2] += x2[2];
  115316. x1[3] += x2[3];
  115317. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115318. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115319. T+=trigint;
  115320. r0 = x1[0] - x2[0];
  115321. r1 = x1[1] - x2[1];
  115322. x1[0] += x2[0];
  115323. x1[1] += x2[1];
  115324. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115325. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115326. T+=trigint;
  115327. x1-=8;
  115328. x2-=8;
  115329. }while(x2>=x);
  115330. }
  115331. STIN void mdct_butterflies(mdct_lookup *init,
  115332. DATA_TYPE *x,
  115333. int points){
  115334. DATA_TYPE *T=init->trig;
  115335. int stages=init->log2n-5;
  115336. int i,j;
  115337. if(--stages>0){
  115338. mdct_butterfly_first(T,x,points);
  115339. }
  115340. for(i=1;--stages>0;i++){
  115341. for(j=0;j<(1<<i);j++)
  115342. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115343. }
  115344. for(j=0;j<points;j+=32)
  115345. mdct_butterfly_32(x+j);
  115346. }
  115347. void mdct_clear(mdct_lookup *l){
  115348. if(l){
  115349. if(l->trig)_ogg_free(l->trig);
  115350. if(l->bitrev)_ogg_free(l->bitrev);
  115351. memset(l,0,sizeof(*l));
  115352. }
  115353. }
  115354. STIN void mdct_bitreverse(mdct_lookup *init,
  115355. DATA_TYPE *x){
  115356. int n = init->n;
  115357. int *bit = init->bitrev;
  115358. DATA_TYPE *w0 = x;
  115359. DATA_TYPE *w1 = x = w0+(n>>1);
  115360. DATA_TYPE *T = init->trig+n;
  115361. do{
  115362. DATA_TYPE *x0 = x+bit[0];
  115363. DATA_TYPE *x1 = x+bit[1];
  115364. REG_TYPE r0 = x0[1] - x1[1];
  115365. REG_TYPE r1 = x0[0] + x1[0];
  115366. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115367. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115368. w1 -= 4;
  115369. r0 = HALVE(x0[1] + x1[1]);
  115370. r1 = HALVE(x0[0] - x1[0]);
  115371. w0[0] = r0 + r2;
  115372. w1[2] = r0 - r2;
  115373. w0[1] = r1 + r3;
  115374. w1[3] = r3 - r1;
  115375. x0 = x+bit[2];
  115376. x1 = x+bit[3];
  115377. r0 = x0[1] - x1[1];
  115378. r1 = x0[0] + x1[0];
  115379. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115380. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115381. r0 = HALVE(x0[1] + x1[1]);
  115382. r1 = HALVE(x0[0] - x1[0]);
  115383. w0[2] = r0 + r2;
  115384. w1[0] = r0 - r2;
  115385. w0[3] = r1 + r3;
  115386. w1[1] = r3 - r1;
  115387. T += 4;
  115388. bit += 4;
  115389. w0 += 4;
  115390. }while(w0<w1);
  115391. }
  115392. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115393. int n=init->n;
  115394. int n2=n>>1;
  115395. int n4=n>>2;
  115396. /* rotate */
  115397. DATA_TYPE *iX = in+n2-7;
  115398. DATA_TYPE *oX = out+n2+n4;
  115399. DATA_TYPE *T = init->trig+n4;
  115400. do{
  115401. oX -= 4;
  115402. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115403. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115404. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115405. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115406. iX -= 8;
  115407. T += 4;
  115408. }while(iX>=in);
  115409. iX = in+n2-8;
  115410. oX = out+n2+n4;
  115411. T = init->trig+n4;
  115412. do{
  115413. T -= 4;
  115414. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115415. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115416. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115417. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115418. iX -= 8;
  115419. oX += 4;
  115420. }while(iX>=in);
  115421. mdct_butterflies(init,out+n2,n2);
  115422. mdct_bitreverse(init,out);
  115423. /* roatate + window */
  115424. {
  115425. DATA_TYPE *oX1=out+n2+n4;
  115426. DATA_TYPE *oX2=out+n2+n4;
  115427. DATA_TYPE *iX =out;
  115428. T =init->trig+n2;
  115429. do{
  115430. oX1-=4;
  115431. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115432. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115433. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115434. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115435. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115436. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115437. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115438. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115439. oX2+=4;
  115440. iX += 8;
  115441. T += 8;
  115442. }while(iX<oX1);
  115443. iX=out+n2+n4;
  115444. oX1=out+n4;
  115445. oX2=oX1;
  115446. do{
  115447. oX1-=4;
  115448. iX-=4;
  115449. oX2[0] = -(oX1[3] = iX[3]);
  115450. oX2[1] = -(oX1[2] = iX[2]);
  115451. oX2[2] = -(oX1[1] = iX[1]);
  115452. oX2[3] = -(oX1[0] = iX[0]);
  115453. oX2+=4;
  115454. }while(oX2<iX);
  115455. iX=out+n2+n4;
  115456. oX1=out+n2+n4;
  115457. oX2=out+n2;
  115458. do{
  115459. oX1-=4;
  115460. oX1[0]= iX[3];
  115461. oX1[1]= iX[2];
  115462. oX1[2]= iX[1];
  115463. oX1[3]= iX[0];
  115464. iX+=4;
  115465. }while(oX1>oX2);
  115466. }
  115467. }
  115468. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115469. int n=init->n;
  115470. int n2=n>>1;
  115471. int n4=n>>2;
  115472. int n8=n>>3;
  115473. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115474. DATA_TYPE *w2=w+n2;
  115475. /* rotate */
  115476. /* window + rotate + step 1 */
  115477. REG_TYPE r0;
  115478. REG_TYPE r1;
  115479. DATA_TYPE *x0=in+n2+n4;
  115480. DATA_TYPE *x1=x0+1;
  115481. DATA_TYPE *T=init->trig+n2;
  115482. int i=0;
  115483. for(i=0;i<n8;i+=2){
  115484. x0 -=4;
  115485. T-=2;
  115486. r0= x0[2] + x1[0];
  115487. r1= x0[0] + x1[2];
  115488. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115489. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115490. x1 +=4;
  115491. }
  115492. x1=in+1;
  115493. for(;i<n2-n8;i+=2){
  115494. T-=2;
  115495. x0 -=4;
  115496. r0= x0[2] - x1[0];
  115497. r1= x0[0] - x1[2];
  115498. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115499. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115500. x1 +=4;
  115501. }
  115502. x0=in+n;
  115503. for(;i<n2;i+=2){
  115504. T-=2;
  115505. x0 -=4;
  115506. r0= -x0[2] - x1[0];
  115507. r1= -x0[0] - x1[2];
  115508. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115509. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115510. x1 +=4;
  115511. }
  115512. mdct_butterflies(init,w+n2,n2);
  115513. mdct_bitreverse(init,w);
  115514. /* roatate + window */
  115515. T=init->trig+n2;
  115516. x0=out+n2;
  115517. for(i=0;i<n4;i++){
  115518. x0--;
  115519. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115520. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115521. w+=2;
  115522. T+=2;
  115523. }
  115524. }
  115525. #endif
  115526. /*** End of inlined file: mdct.c ***/
  115527. /*** Start of inlined file: psy.c ***/
  115528. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115529. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115530. // tasks..
  115531. #if JUCE_MSVC
  115532. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115533. #endif
  115534. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115535. #if JUCE_USE_OGGVORBIS
  115536. #include <stdlib.h>
  115537. #include <math.h>
  115538. #include <string.h>
  115539. /*** Start of inlined file: masking.h ***/
  115540. #ifndef _V_MASKING_H_
  115541. #define _V_MASKING_H_
  115542. /* more detailed ATH; the bass if flat to save stressing the floor
  115543. overly for only a bin or two of savings. */
  115544. #define MAX_ATH 88
  115545. static float ATH[]={
  115546. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115547. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115548. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115549. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115550. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115551. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115552. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115553. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115554. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115555. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115556. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115557. };
  115558. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115559. replaced by an empirically collected data set. The previously
  115560. published values were, far too often, simply on crack. */
  115561. #define EHMER_OFFSET 16
  115562. #define EHMER_MAX 56
  115563. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115564. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115565. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115566. for collection of these curves) */
  115567. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115568. /* 62.5 Hz */
  115569. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115570. -60, -60, -60, -60, -62, -62, -65, -73,
  115571. -69, -68, -68, -67, -70, -70, -72, -74,
  115572. -75, -79, -79, -80, -83, -88, -93, -100,
  115573. -110, -999, -999, -999, -999, -999, -999, -999,
  115574. -999, -999, -999, -999, -999, -999, -999, -999,
  115575. -999, -999, -999, -999, -999, -999, -999, -999},
  115576. { -48, -48, -48, -48, -48, -48, -48, -48,
  115577. -48, -48, -48, -48, -48, -53, -61, -66,
  115578. -66, -68, -67, -70, -76, -76, -72, -73,
  115579. -75, -76, -78, -79, -83, -88, -93, -100,
  115580. -110, -999, -999, -999, -999, -999, -999, -999,
  115581. -999, -999, -999, -999, -999, -999, -999, -999,
  115582. -999, -999, -999, -999, -999, -999, -999, -999},
  115583. { -37, -37, -37, -37, -37, -37, -37, -37,
  115584. -38, -40, -42, -46, -48, -53, -55, -62,
  115585. -65, -58, -56, -56, -61, -60, -65, -67,
  115586. -69, -71, -77, -77, -78, -80, -82, -84,
  115587. -88, -93, -98, -106, -112, -999, -999, -999,
  115588. -999, -999, -999, -999, -999, -999, -999, -999,
  115589. -999, -999, -999, -999, -999, -999, -999, -999},
  115590. { -25, -25, -25, -25, -25, -25, -25, -25,
  115591. -25, -26, -27, -29, -32, -38, -48, -52,
  115592. -52, -50, -48, -48, -51, -52, -54, -60,
  115593. -67, -67, -66, -68, -69, -73, -73, -76,
  115594. -80, -81, -81, -85, -85, -86, -88, -93,
  115595. -100, -110, -999, -999, -999, -999, -999, -999,
  115596. -999, -999, -999, -999, -999, -999, -999, -999},
  115597. { -16, -16, -16, -16, -16, -16, -16, -16,
  115598. -17, -19, -20, -22, -26, -28, -31, -40,
  115599. -47, -39, -39, -40, -42, -43, -47, -51,
  115600. -57, -52, -55, -55, -60, -58, -62, -63,
  115601. -70, -67, -69, -72, -73, -77, -80, -82,
  115602. -83, -87, -90, -94, -98, -104, -115, -999,
  115603. -999, -999, -999, -999, -999, -999, -999, -999},
  115604. { -8, -8, -8, -8, -8, -8, -8, -8,
  115605. -8, -8, -10, -11, -15, -19, -25, -30,
  115606. -34, -31, -30, -31, -29, -32, -35, -42,
  115607. -48, -42, -44, -46, -50, -50, -51, -52,
  115608. -59, -54, -55, -55, -58, -62, -63, -66,
  115609. -72, -73, -76, -75, -78, -80, -80, -81,
  115610. -84, -88, -90, -94, -98, -101, -106, -110}},
  115611. /* 88Hz */
  115612. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115613. -66, -66, -66, -66, -66, -67, -67, -67,
  115614. -76, -72, -71, -74, -76, -76, -75, -78,
  115615. -79, -79, -81, -83, -86, -89, -93, -97,
  115616. -100, -105, -110, -999, -999, -999, -999, -999,
  115617. -999, -999, -999, -999, -999, -999, -999, -999,
  115618. -999, -999, -999, -999, -999, -999, -999, -999},
  115619. { -47, -47, -47, -47, -47, -47, -47, -47,
  115620. -47, -47, -47, -48, -51, -55, -59, -66,
  115621. -66, -66, -67, -66, -68, -69, -70, -74,
  115622. -79, -77, -77, -78, -80, -81, -82, -84,
  115623. -86, -88, -91, -95, -100, -108, -116, -999,
  115624. -999, -999, -999, -999, -999, -999, -999, -999,
  115625. -999, -999, -999, -999, -999, -999, -999, -999},
  115626. { -36, -36, -36, -36, -36, -36, -36, -36,
  115627. -36, -37, -37, -41, -44, -48, -51, -58,
  115628. -62, -60, -57, -59, -59, -60, -63, -65,
  115629. -72, -71, -70, -72, -74, -77, -76, -78,
  115630. -81, -81, -80, -83, -86, -91, -96, -100,
  115631. -105, -110, -999, -999, -999, -999, -999, -999,
  115632. -999, -999, -999, -999, -999, -999, -999, -999},
  115633. { -28, -28, -28, -28, -28, -28, -28, -28,
  115634. -28, -30, -32, -32, -33, -35, -41, -49,
  115635. -50, -49, -47, -48, -48, -52, -51, -57,
  115636. -65, -61, -59, -61, -64, -69, -70, -74,
  115637. -77, -77, -78, -81, -84, -85, -87, -90,
  115638. -92, -96, -100, -107, -112, -999, -999, -999,
  115639. -999, -999, -999, -999, -999, -999, -999, -999},
  115640. { -19, -19, -19, -19, -19, -19, -19, -19,
  115641. -20, -21, -23, -27, -30, -35, -36, -41,
  115642. -46, -44, -42, -40, -41, -41, -43, -48,
  115643. -55, -53, -52, -53, -56, -59, -58, -60,
  115644. -67, -66, -69, -71, -72, -75, -79, -81,
  115645. -84, -87, -90, -93, -97, -101, -107, -114,
  115646. -999, -999, -999, -999, -999, -999, -999, -999},
  115647. { -9, -9, -9, -9, -9, -9, -9, -9,
  115648. -11, -12, -12, -15, -16, -20, -23, -30,
  115649. -37, -34, -33, -34, -31, -32, -32, -38,
  115650. -47, -44, -41, -40, -47, -49, -46, -46,
  115651. -58, -50, -50, -54, -58, -62, -64, -67,
  115652. -67, -70, -72, -76, -79, -83, -87, -91,
  115653. -96, -100, -104, -110, -999, -999, -999, -999}},
  115654. /* 125 Hz */
  115655. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115656. -62, -62, -63, -64, -66, -67, -66, -68,
  115657. -75, -72, -76, -75, -76, -78, -79, -82,
  115658. -84, -85, -90, -94, -101, -110, -999, -999,
  115659. -999, -999, -999, -999, -999, -999, -999, -999,
  115660. -999, -999, -999, -999, -999, -999, -999, -999,
  115661. -999, -999, -999, -999, -999, -999, -999, -999},
  115662. { -59, -59, -59, -59, -59, -59, -59, -59,
  115663. -59, -59, -59, -60, -60, -61, -63, -66,
  115664. -71, -68, -70, -70, -71, -72, -72, -75,
  115665. -81, -78, -79, -82, -83, -86, -90, -97,
  115666. -103, -113, -999, -999, -999, -999, -999, -999,
  115667. -999, -999, -999, -999, -999, -999, -999, -999,
  115668. -999, -999, -999, -999, -999, -999, -999, -999},
  115669. { -53, -53, -53, -53, -53, -53, -53, -53,
  115670. -53, -54, -55, -57, -56, -57, -55, -61,
  115671. -65, -60, -60, -62, -63, -63, -66, -68,
  115672. -74, -73, -75, -75, -78, -80, -80, -82,
  115673. -85, -90, -96, -101, -108, -999, -999, -999,
  115674. -999, -999, -999, -999, -999, -999, -999, -999,
  115675. -999, -999, -999, -999, -999, -999, -999, -999},
  115676. { -46, -46, -46, -46, -46, -46, -46, -46,
  115677. -46, -46, -47, -47, -47, -47, -48, -51,
  115678. -57, -51, -49, -50, -51, -53, -54, -59,
  115679. -66, -60, -62, -67, -67, -70, -72, -75,
  115680. -76, -78, -81, -85, -88, -94, -97, -104,
  115681. -112, -999, -999, -999, -999, -999, -999, -999,
  115682. -999, -999, -999, -999, -999, -999, -999, -999},
  115683. { -36, -36, -36, -36, -36, -36, -36, -36,
  115684. -39, -41, -42, -42, -39, -38, -41, -43,
  115685. -52, -44, -40, -39, -37, -37, -40, -47,
  115686. -54, -50, -48, -50, -55, -61, -59, -62,
  115687. -66, -66, -66, -69, -69, -73, -74, -74,
  115688. -75, -77, -79, -82, -87, -91, -95, -100,
  115689. -108, -115, -999, -999, -999, -999, -999, -999},
  115690. { -28, -26, -24, -22, -20, -20, -23, -29,
  115691. -30, -31, -28, -27, -28, -28, -28, -35,
  115692. -40, -33, -32, -29, -30, -30, -30, -37,
  115693. -45, -41, -37, -38, -45, -47, -47, -48,
  115694. -53, -49, -48, -50, -49, -49, -51, -52,
  115695. -58, -56, -57, -56, -60, -61, -62, -70,
  115696. -72, -74, -78, -83, -88, -93, -100, -106}},
  115697. /* 177 Hz */
  115698. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115699. -999, -110, -105, -100, -95, -91, -87, -83,
  115700. -80, -78, -76, -78, -78, -81, -83, -85,
  115701. -86, -85, -86, -87, -90, -97, -107, -999,
  115702. -999, -999, -999, -999, -999, -999, -999, -999,
  115703. -999, -999, -999, -999, -999, -999, -999, -999,
  115704. -999, -999, -999, -999, -999, -999, -999, -999},
  115705. {-999, -999, -999, -110, -105, -100, -95, -90,
  115706. -85, -81, -77, -73, -70, -67, -67, -68,
  115707. -75, -73, -70, -69, -70, -72, -75, -79,
  115708. -84, -83, -84, -86, -88, -89, -89, -93,
  115709. -98, -105, -112, -999, -999, -999, -999, -999,
  115710. -999, -999, -999, -999, -999, -999, -999, -999,
  115711. -999, -999, -999, -999, -999, -999, -999, -999},
  115712. {-105, -100, -95, -90, -85, -80, -76, -71,
  115713. -68, -68, -65, -63, -63, -62, -62, -64,
  115714. -65, -64, -61, -62, -63, -64, -66, -68,
  115715. -73, -73, -74, -75, -76, -81, -83, -85,
  115716. -88, -89, -92, -95, -100, -108, -999, -999,
  115717. -999, -999, -999, -999, -999, -999, -999, -999,
  115718. -999, -999, -999, -999, -999, -999, -999, -999},
  115719. { -80, -75, -71, -68, -65, -63, -62, -61,
  115720. -61, -61, -61, -59, -56, -57, -53, -50,
  115721. -58, -52, -50, -50, -52, -53, -54, -58,
  115722. -67, -63, -67, -68, -72, -75, -78, -80,
  115723. -81, -81, -82, -85, -89, -90, -93, -97,
  115724. -101, -107, -114, -999, -999, -999, -999, -999,
  115725. -999, -999, -999, -999, -999, -999, -999, -999},
  115726. { -65, -61, -59, -57, -56, -55, -55, -56,
  115727. -56, -57, -55, -53, -52, -47, -44, -44,
  115728. -50, -44, -41, -39, -39, -42, -40, -46,
  115729. -51, -49, -50, -53, -54, -63, -60, -61,
  115730. -62, -66, -66, -66, -70, -73, -74, -75,
  115731. -76, -75, -79, -85, -89, -91, -96, -102,
  115732. -110, -999, -999, -999, -999, -999, -999, -999},
  115733. { -52, -50, -49, -49, -48, -48, -48, -49,
  115734. -50, -50, -49, -46, -43, -39, -35, -33,
  115735. -38, -36, -32, -29, -32, -32, -32, -35,
  115736. -44, -39, -38, -38, -46, -50, -45, -46,
  115737. -53, -50, -50, -50, -54, -54, -53, -53,
  115738. -56, -57, -59, -66, -70, -72, -74, -79,
  115739. -83, -85, -90, -97, -114, -999, -999, -999}},
  115740. /* 250 Hz */
  115741. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115742. -100, -95, -90, -86, -80, -75, -75, -79,
  115743. -80, -79, -80, -81, -82, -88, -95, -103,
  115744. -110, -999, -999, -999, -999, -999, -999, -999,
  115745. -999, -999, -999, -999, -999, -999, -999, -999,
  115746. -999, -999, -999, -999, -999, -999, -999, -999,
  115747. -999, -999, -999, -999, -999, -999, -999, -999},
  115748. {-999, -999, -999, -999, -108, -103, -98, -93,
  115749. -88, -83, -79, -78, -75, -71, -67, -68,
  115750. -73, -73, -72, -73, -75, -77, -80, -82,
  115751. -88, -93, -100, -107, -114, -999, -999, -999,
  115752. -999, -999, -999, -999, -999, -999, -999, -999,
  115753. -999, -999, -999, -999, -999, -999, -999, -999,
  115754. -999, -999, -999, -999, -999, -999, -999, -999},
  115755. {-999, -999, -999, -110, -105, -101, -96, -90,
  115756. -86, -81, -77, -73, -69, -66, -61, -62,
  115757. -66, -64, -62, -65, -66, -70, -72, -76,
  115758. -81, -80, -84, -90, -95, -102, -110, -999,
  115759. -999, -999, -999, -999, -999, -999, -999, -999,
  115760. -999, -999, -999, -999, -999, -999, -999, -999,
  115761. -999, -999, -999, -999, -999, -999, -999, -999},
  115762. {-999, -999, -999, -107, -103, -97, -92, -88,
  115763. -83, -79, -74, -70, -66, -59, -53, -58,
  115764. -62, -55, -54, -54, -54, -58, -61, -62,
  115765. -72, -70, -72, -75, -78, -80, -81, -80,
  115766. -83, -83, -88, -93, -100, -107, -115, -999,
  115767. -999, -999, -999, -999, -999, -999, -999, -999,
  115768. -999, -999, -999, -999, -999, -999, -999, -999},
  115769. {-999, -999, -999, -105, -100, -95, -90, -85,
  115770. -80, -75, -70, -66, -62, -56, -48, -44,
  115771. -48, -46, -46, -43, -46, -48, -48, -51,
  115772. -58, -58, -59, -60, -62, -62, -61, -61,
  115773. -65, -64, -65, -68, -70, -74, -75, -78,
  115774. -81, -86, -95, -110, -999, -999, -999, -999,
  115775. -999, -999, -999, -999, -999, -999, -999, -999},
  115776. {-999, -999, -105, -100, -95, -90, -85, -80,
  115777. -75, -70, -65, -61, -55, -49, -39, -33,
  115778. -40, -35, -32, -38, -40, -33, -35, -37,
  115779. -46, -41, -45, -44, -46, -42, -45, -46,
  115780. -52, -50, -50, -50, -54, -54, -55, -57,
  115781. -62, -64, -66, -68, -70, -76, -81, -90,
  115782. -100, -110, -999, -999, -999, -999, -999, -999}},
  115783. /* 354 hz */
  115784. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115785. -105, -98, -90, -85, -82, -83, -80, -78,
  115786. -84, -79, -80, -83, -87, -89, -91, -93,
  115787. -99, -106, -117, -999, -999, -999, -999, -999,
  115788. -999, -999, -999, -999, -999, -999, -999, -999,
  115789. -999, -999, -999, -999, -999, -999, -999, -999,
  115790. -999, -999, -999, -999, -999, -999, -999, -999},
  115791. {-999, -999, -999, -999, -999, -999, -999, -999,
  115792. -105, -98, -90, -85, -80, -75, -70, -68,
  115793. -74, -72, -74, -77, -80, -82, -85, -87,
  115794. -92, -89, -91, -95, -100, -106, -112, -999,
  115795. -999, -999, -999, -999, -999, -999, -999, -999,
  115796. -999, -999, -999, -999, -999, -999, -999, -999,
  115797. -999, -999, -999, -999, -999, -999, -999, -999},
  115798. {-999, -999, -999, -999, -999, -999, -999, -999,
  115799. -105, -98, -90, -83, -75, -71, -63, -64,
  115800. -67, -62, -64, -67, -70, -73, -77, -81,
  115801. -84, -83, -85, -89, -90, -93, -98, -104,
  115802. -109, -114, -999, -999, -999, -999, -999, -999,
  115803. -999, -999, -999, -999, -999, -999, -999, -999,
  115804. -999, -999, -999, -999, -999, -999, -999, -999},
  115805. {-999, -999, -999, -999, -999, -999, -999, -999,
  115806. -103, -96, -88, -81, -75, -68, -58, -54,
  115807. -56, -54, -56, -56, -58, -60, -63, -66,
  115808. -74, -69, -72, -72, -75, -74, -77, -81,
  115809. -81, -82, -84, -87, -93, -96, -99, -104,
  115810. -110, -999, -999, -999, -999, -999, -999, -999,
  115811. -999, -999, -999, -999, -999, -999, -999, -999},
  115812. {-999, -999, -999, -999, -999, -108, -102, -96,
  115813. -91, -85, -80, -74, -68, -60, -51, -46,
  115814. -48, -46, -43, -45, -47, -47, -49, -48,
  115815. -56, -53, -55, -58, -57, -63, -58, -60,
  115816. -66, -64, -67, -70, -70, -74, -77, -84,
  115817. -86, -89, -91, -93, -94, -101, -109, -118,
  115818. -999, -999, -999, -999, -999, -999, -999, -999},
  115819. {-999, -999, -999, -108, -103, -98, -93, -88,
  115820. -83, -78, -73, -68, -60, -53, -44, -35,
  115821. -38, -38, -34, -34, -36, -40, -41, -44,
  115822. -51, -45, -46, -47, -46, -54, -50, -49,
  115823. -50, -50, -50, -51, -54, -57, -58, -60,
  115824. -66, -66, -66, -64, -65, -68, -77, -82,
  115825. -87, -95, -110, -999, -999, -999, -999, -999}},
  115826. /* 500 Hz */
  115827. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115828. -107, -102, -97, -92, -87, -83, -78, -75,
  115829. -82, -79, -83, -85, -89, -92, -95, -98,
  115830. -101, -105, -109, -113, -999, -999, -999, -999,
  115831. -999, -999, -999, -999, -999, -999, -999, -999,
  115832. -999, -999, -999, -999, -999, -999, -999, -999,
  115833. -999, -999, -999, -999, -999, -999, -999, -999},
  115834. {-999, -999, -999, -999, -999, -999, -999, -106,
  115835. -100, -95, -90, -86, -81, -78, -74, -69,
  115836. -74, -74, -76, -79, -83, -84, -86, -89,
  115837. -92, -97, -93, -100, -103, -107, -110, -999,
  115838. -999, -999, -999, -999, -999, -999, -999, -999,
  115839. -999, -999, -999, -999, -999, -999, -999, -999,
  115840. -999, -999, -999, -999, -999, -999, -999, -999},
  115841. {-999, -999, -999, -999, -999, -999, -106, -100,
  115842. -95, -90, -87, -83, -80, -75, -69, -60,
  115843. -66, -66, -68, -70, -74, -78, -79, -81,
  115844. -81, -83, -84, -87, -93, -96, -99, -103,
  115845. -107, -110, -999, -999, -999, -999, -999, -999,
  115846. -999, -999, -999, -999, -999, -999, -999, -999,
  115847. -999, -999, -999, -999, -999, -999, -999, -999},
  115848. {-999, -999, -999, -999, -999, -108, -103, -98,
  115849. -93, -89, -85, -82, -78, -71, -62, -55,
  115850. -58, -58, -54, -54, -55, -59, -61, -62,
  115851. -70, -66, -66, -67, -70, -72, -75, -78,
  115852. -84, -84, -84, -88, -91, -90, -95, -98,
  115853. -102, -103, -106, -110, -999, -999, -999, -999,
  115854. -999, -999, -999, -999, -999, -999, -999, -999},
  115855. {-999, -999, -999, -999, -108, -103, -98, -94,
  115856. -90, -87, -82, -79, -73, -67, -58, -47,
  115857. -50, -45, -41, -45, -48, -44, -44, -49,
  115858. -54, -51, -48, -47, -49, -50, -51, -57,
  115859. -58, -60, -63, -69, -70, -69, -71, -74,
  115860. -78, -82, -90, -95, -101, -105, -110, -999,
  115861. -999, -999, -999, -999, -999, -999, -999, -999},
  115862. {-999, -999, -999, -105, -101, -97, -93, -90,
  115863. -85, -80, -77, -72, -65, -56, -48, -37,
  115864. -40, -36, -34, -40, -50, -47, -38, -41,
  115865. -47, -38, -35, -39, -38, -43, -40, -45,
  115866. -50, -45, -44, -47, -50, -55, -48, -48,
  115867. -52, -66, -70, -76, -82, -90, -97, -105,
  115868. -110, -999, -999, -999, -999, -999, -999, -999}},
  115869. /* 707 Hz */
  115870. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115871. -999, -108, -103, -98, -93, -86, -79, -76,
  115872. -83, -81, -85, -87, -89, -93, -98, -102,
  115873. -107, -112, -999, -999, -999, -999, -999, -999,
  115874. -999, -999, -999, -999, -999, -999, -999, -999,
  115875. -999, -999, -999, -999, -999, -999, -999, -999,
  115876. -999, -999, -999, -999, -999, -999, -999, -999},
  115877. {-999, -999, -999, -999, -999, -999, -999, -999,
  115878. -999, -108, -103, -98, -93, -86, -79, -71,
  115879. -77, -74, -77, -79, -81, -84, -85, -90,
  115880. -92, -93, -92, -98, -101, -108, -112, -999,
  115881. -999, -999, -999, -999, -999, -999, -999, -999,
  115882. -999, -999, -999, -999, -999, -999, -999, -999,
  115883. -999, -999, -999, -999, -999, -999, -999, -999},
  115884. {-999, -999, -999, -999, -999, -999, -999, -999,
  115885. -108, -103, -98, -93, -87, -78, -68, -65,
  115886. -66, -62, -65, -67, -70, -73, -75, -78,
  115887. -82, -82, -83, -84, -91, -93, -98, -102,
  115888. -106, -110, -999, -999, -999, -999, -999, -999,
  115889. -999, -999, -999, -999, -999, -999, -999, -999,
  115890. -999, -999, -999, -999, -999, -999, -999, -999},
  115891. {-999, -999, -999, -999, -999, -999, -999, -999,
  115892. -105, -100, -95, -90, -82, -74, -62, -57,
  115893. -58, -56, -51, -52, -52, -54, -54, -58,
  115894. -66, -59, -60, -63, -66, -69, -73, -79,
  115895. -83, -84, -80, -81, -81, -82, -88, -92,
  115896. -98, -105, -113, -999, -999, -999, -999, -999,
  115897. -999, -999, -999, -999, -999, -999, -999, -999},
  115898. {-999, -999, -999, -999, -999, -999, -999, -107,
  115899. -102, -97, -92, -84, -79, -69, -57, -47,
  115900. -52, -47, -44, -45, -50, -52, -42, -42,
  115901. -53, -43, -43, -48, -51, -56, -55, -52,
  115902. -57, -59, -61, -62, -67, -71, -78, -83,
  115903. -86, -94, -98, -103, -110, -999, -999, -999,
  115904. -999, -999, -999, -999, -999, -999, -999, -999},
  115905. {-999, -999, -999, -999, -999, -999, -105, -100,
  115906. -95, -90, -84, -78, -70, -61, -51, -41,
  115907. -40, -38, -40, -46, -52, -51, -41, -40,
  115908. -46, -40, -38, -38, -41, -46, -41, -46,
  115909. -47, -43, -43, -45, -41, -45, -56, -67,
  115910. -68, -83, -87, -90, -95, -102, -107, -113,
  115911. -999, -999, -999, -999, -999, -999, -999, -999}},
  115912. /* 1000 Hz */
  115913. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115914. -999, -109, -105, -101, -96, -91, -84, -77,
  115915. -82, -82, -85, -89, -94, -100, -106, -110,
  115916. -999, -999, -999, -999, -999, -999, -999, -999,
  115917. -999, -999, -999, -999, -999, -999, -999, -999,
  115918. -999, -999, -999, -999, -999, -999, -999, -999,
  115919. -999, -999, -999, -999, -999, -999, -999, -999},
  115920. {-999, -999, -999, -999, -999, -999, -999, -999,
  115921. -999, -106, -103, -98, -92, -85, -80, -71,
  115922. -75, -72, -76, -80, -84, -86, -89, -93,
  115923. -100, -107, -113, -999, -999, -999, -999, -999,
  115924. -999, -999, -999, -999, -999, -999, -999, -999,
  115925. -999, -999, -999, -999, -999, -999, -999, -999,
  115926. -999, -999, -999, -999, -999, -999, -999, -999},
  115927. {-999, -999, -999, -999, -999, -999, -999, -107,
  115928. -104, -101, -97, -92, -88, -84, -80, -64,
  115929. -66, -63, -64, -66, -69, -73, -77, -83,
  115930. -83, -86, -91, -98, -104, -111, -999, -999,
  115931. -999, -999, -999, -999, -999, -999, -999, -999,
  115932. -999, -999, -999, -999, -999, -999, -999, -999,
  115933. -999, -999, -999, -999, -999, -999, -999, -999},
  115934. {-999, -999, -999, -999, -999, -999, -999, -107,
  115935. -104, -101, -97, -92, -90, -84, -74, -57,
  115936. -58, -52, -55, -54, -50, -52, -50, -52,
  115937. -63, -62, -69, -76, -77, -78, -78, -79,
  115938. -82, -88, -94, -100, -106, -111, -999, -999,
  115939. -999, -999, -999, -999, -999, -999, -999, -999,
  115940. -999, -999, -999, -999, -999, -999, -999, -999},
  115941. {-999, -999, -999, -999, -999, -999, -106, -102,
  115942. -98, -95, -90, -85, -83, -78, -70, -50,
  115943. -50, -41, -44, -49, -47, -50, -50, -44,
  115944. -55, -46, -47, -48, -48, -54, -49, -49,
  115945. -58, -62, -71, -81, -87, -92, -97, -102,
  115946. -108, -114, -999, -999, -999, -999, -999, -999,
  115947. -999, -999, -999, -999, -999, -999, -999, -999},
  115948. {-999, -999, -999, -999, -999, -999, -106, -102,
  115949. -98, -95, -90, -85, -83, -78, -70, -45,
  115950. -43, -41, -47, -50, -51, -50, -49, -45,
  115951. -47, -41, -44, -41, -39, -43, -38, -37,
  115952. -40, -41, -44, -50, -58, -65, -73, -79,
  115953. -85, -92, -97, -101, -105, -109, -113, -999,
  115954. -999, -999, -999, -999, -999, -999, -999, -999}},
  115955. /* 1414 Hz */
  115956. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115957. -999, -999, -999, -107, -100, -95, -87, -81,
  115958. -85, -83, -88, -93, -100, -107, -114, -999,
  115959. -999, -999, -999, -999, -999, -999, -999, -999,
  115960. -999, -999, -999, -999, -999, -999, -999, -999,
  115961. -999, -999, -999, -999, -999, -999, -999, -999,
  115962. -999, -999, -999, -999, -999, -999, -999, -999},
  115963. {-999, -999, -999, -999, -999, -999, -999, -999,
  115964. -999, -999, -107, -101, -95, -88, -83, -76,
  115965. -73, -72, -79, -84, -90, -95, -100, -105,
  115966. -110, -115, -999, -999, -999, -999, -999, -999,
  115967. -999, -999, -999, -999, -999, -999, -999, -999,
  115968. -999, -999, -999, -999, -999, -999, -999, -999,
  115969. -999, -999, -999, -999, -999, -999, -999, -999},
  115970. {-999, -999, -999, -999, -999, -999, -999, -999,
  115971. -999, -999, -104, -98, -92, -87, -81, -70,
  115972. -65, -62, -67, -71, -74, -80, -85, -91,
  115973. -95, -99, -103, -108, -111, -114, -999, -999,
  115974. -999, -999, -999, -999, -999, -999, -999, -999,
  115975. -999, -999, -999, -999, -999, -999, -999, -999,
  115976. -999, -999, -999, -999, -999, -999, -999, -999},
  115977. {-999, -999, -999, -999, -999, -999, -999, -999,
  115978. -999, -999, -103, -97, -90, -85, -76, -60,
  115979. -56, -54, -60, -62, -61, -56, -63, -65,
  115980. -73, -74, -77, -75, -78, -81, -86, -87,
  115981. -88, -91, -94, -98, -103, -110, -999, -999,
  115982. -999, -999, -999, -999, -999, -999, -999, -999,
  115983. -999, -999, -999, -999, -999, -999, -999, -999},
  115984. {-999, -999, -999, -999, -999, -999, -999, -105,
  115985. -100, -97, -92, -86, -81, -79, -70, -57,
  115986. -51, -47, -51, -58, -60, -56, -53, -50,
  115987. -58, -52, -50, -50, -53, -55, -64, -69,
  115988. -71, -85, -82, -78, -81, -85, -95, -102,
  115989. -112, -999, -999, -999, -999, -999, -999, -999,
  115990. -999, -999, -999, -999, -999, -999, -999, -999},
  115991. {-999, -999, -999, -999, -999, -999, -999, -105,
  115992. -100, -97, -92, -85, -83, -79, -72, -49,
  115993. -40, -43, -43, -54, -56, -51, -50, -40,
  115994. -43, -38, -36, -35, -37, -38, -37, -44,
  115995. -54, -60, -57, -60, -70, -75, -84, -92,
  115996. -103, -112, -999, -999, -999, -999, -999, -999,
  115997. -999, -999, -999, -999, -999, -999, -999, -999}},
  115998. /* 2000 Hz */
  115999. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116000. -999, -999, -999, -110, -102, -95, -89, -82,
  116001. -83, -84, -90, -92, -99, -107, -113, -999,
  116002. -999, -999, -999, -999, -999, -999, -999, -999,
  116003. -999, -999, -999, -999, -999, -999, -999, -999,
  116004. -999, -999, -999, -999, -999, -999, -999, -999,
  116005. -999, -999, -999, -999, -999, -999, -999, -999},
  116006. {-999, -999, -999, -999, -999, -999, -999, -999,
  116007. -999, -999, -107, -101, -95, -89, -83, -72,
  116008. -74, -78, -85, -88, -88, -90, -92, -98,
  116009. -105, -111, -999, -999, -999, -999, -999, -999,
  116010. -999, -999, -999, -999, -999, -999, -999, -999,
  116011. -999, -999, -999, -999, -999, -999, -999, -999,
  116012. -999, -999, -999, -999, -999, -999, -999, -999},
  116013. {-999, -999, -999, -999, -999, -999, -999, -999,
  116014. -999, -109, -103, -97, -93, -87, -81, -70,
  116015. -70, -67, -75, -73, -76, -79, -81, -83,
  116016. -88, -89, -97, -103, -110, -999, -999, -999,
  116017. -999, -999, -999, -999, -999, -999, -999, -999,
  116018. -999, -999, -999, -999, -999, -999, -999, -999,
  116019. -999, -999, -999, -999, -999, -999, -999, -999},
  116020. {-999, -999, -999, -999, -999, -999, -999, -999,
  116021. -999, -107, -100, -94, -88, -83, -75, -63,
  116022. -59, -59, -63, -66, -60, -62, -67, -67,
  116023. -77, -76, -81, -88, -86, -92, -96, -102,
  116024. -109, -116, -999, -999, -999, -999, -999, -999,
  116025. -999, -999, -999, -999, -999, -999, -999, -999,
  116026. -999, -999, -999, -999, -999, -999, -999, -999},
  116027. {-999, -999, -999, -999, -999, -999, -999, -999,
  116028. -999, -105, -98, -92, -86, -81, -73, -56,
  116029. -52, -47, -55, -60, -58, -52, -51, -45,
  116030. -49, -50, -53, -54, -61, -71, -70, -69,
  116031. -78, -79, -87, -90, -96, -104, -112, -999,
  116032. -999, -999, -999, -999, -999, -999, -999, -999,
  116033. -999, -999, -999, -999, -999, -999, -999, -999},
  116034. {-999, -999, -999, -999, -999, -999, -999, -999,
  116035. -999, -103, -96, -90, -86, -78, -70, -51,
  116036. -42, -47, -48, -55, -54, -54, -53, -42,
  116037. -35, -28, -33, -38, -37, -44, -47, -49,
  116038. -54, -63, -68, -78, -82, -89, -94, -99,
  116039. -104, -109, -114, -999, -999, -999, -999, -999,
  116040. -999, -999, -999, -999, -999, -999, -999, -999}},
  116041. /* 2828 Hz */
  116042. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116043. -999, -999, -999, -999, -110, -100, -90, -79,
  116044. -85, -81, -82, -82, -89, -94, -99, -103,
  116045. -109, -115, -999, -999, -999, -999, -999, -999,
  116046. -999, -999, -999, -999, -999, -999, -999, -999,
  116047. -999, -999, -999, -999, -999, -999, -999, -999,
  116048. -999, -999, -999, -999, -999, -999, -999, -999},
  116049. {-999, -999, -999, -999, -999, -999, -999, -999,
  116050. -999, -999, -999, -999, -105, -97, -85, -72,
  116051. -74, -70, -70, -70, -76, -85, -91, -93,
  116052. -97, -103, -109, -115, -999, -999, -999, -999,
  116053. -999, -999, -999, -999, -999, -999, -999, -999,
  116054. -999, -999, -999, -999, -999, -999, -999, -999,
  116055. -999, -999, -999, -999, -999, -999, -999, -999},
  116056. {-999, -999, -999, -999, -999, -999, -999, -999,
  116057. -999, -999, -999, -999, -112, -93, -81, -68,
  116058. -62, -60, -60, -57, -63, -70, -77, -82,
  116059. -90, -93, -98, -104, -109, -113, -999, -999,
  116060. -999, -999, -999, -999, -999, -999, -999, -999,
  116061. -999, -999, -999, -999, -999, -999, -999, -999,
  116062. -999, -999, -999, -999, -999, -999, -999, -999},
  116063. {-999, -999, -999, -999, -999, -999, -999, -999,
  116064. -999, -999, -999, -113, -100, -93, -84, -63,
  116065. -58, -48, -53, -54, -52, -52, -57, -64,
  116066. -66, -76, -83, -81, -85, -85, -90, -95,
  116067. -98, -101, -103, -106, -108, -111, -999, -999,
  116068. -999, -999, -999, -999, -999, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999},
  116070. {-999, -999, -999, -999, -999, -999, -999, -999,
  116071. -999, -999, -999, -105, -95, -86, -74, -53,
  116072. -50, -38, -43, -49, -43, -42, -39, -39,
  116073. -46, -52, -57, -56, -72, -69, -74, -81,
  116074. -87, -92, -94, -97, -99, -102, -105, -108,
  116075. -999, -999, -999, -999, -999, -999, -999, -999,
  116076. -999, -999, -999, -999, -999, -999, -999, -999},
  116077. {-999, -999, -999, -999, -999, -999, -999, -999,
  116078. -999, -999, -108, -99, -90, -76, -66, -45,
  116079. -43, -41, -44, -47, -43, -47, -40, -30,
  116080. -31, -31, -39, -33, -40, -41, -43, -53,
  116081. -59, -70, -73, -77, -79, -82, -84, -87,
  116082. -999, -999, -999, -999, -999, -999, -999, -999,
  116083. -999, -999, -999, -999, -999, -999, -999, -999}},
  116084. /* 4000 Hz */
  116085. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116086. -999, -999, -999, -999, -999, -110, -91, -76,
  116087. -75, -85, -93, -98, -104, -110, -999, -999,
  116088. -999, -999, -999, -999, -999, -999, -999, -999,
  116089. -999, -999, -999, -999, -999, -999, -999, -999,
  116090. -999, -999, -999, -999, -999, -999, -999, -999,
  116091. -999, -999, -999, -999, -999, -999, -999, -999},
  116092. {-999, -999, -999, -999, -999, -999, -999, -999,
  116093. -999, -999, -999, -999, -999, -110, -91, -70,
  116094. -70, -75, -86, -89, -94, -98, -101, -106,
  116095. -110, -999, -999, -999, -999, -999, -999, -999,
  116096. -999, -999, -999, -999, -999, -999, -999, -999,
  116097. -999, -999, -999, -999, -999, -999, -999, -999,
  116098. -999, -999, -999, -999, -999, -999, -999, -999},
  116099. {-999, -999, -999, -999, -999, -999, -999, -999,
  116100. -999, -999, -999, -999, -110, -95, -80, -60,
  116101. -65, -64, -74, -83, -88, -91, -95, -99,
  116102. -103, -107, -110, -999, -999, -999, -999, -999,
  116103. -999, -999, -999, -999, -999, -999, -999, -999,
  116104. -999, -999, -999, -999, -999, -999, -999, -999,
  116105. -999, -999, -999, -999, -999, -999, -999, -999},
  116106. {-999, -999, -999, -999, -999, -999, -999, -999,
  116107. -999, -999, -999, -999, -110, -95, -80, -58,
  116108. -55, -49, -66, -68, -71, -78, -78, -80,
  116109. -88, -85, -89, -97, -100, -105, -110, -999,
  116110. -999, -999, -999, -999, -999, -999, -999, -999,
  116111. -999, -999, -999, -999, -999, -999, -999, -999,
  116112. -999, -999, -999, -999, -999, -999, -999, -999},
  116113. {-999, -999, -999, -999, -999, -999, -999, -999,
  116114. -999, -999, -999, -999, -110, -95, -80, -53,
  116115. -52, -41, -59, -59, -49, -58, -56, -63,
  116116. -86, -79, -90, -93, -98, -103, -107, -112,
  116117. -999, -999, -999, -999, -999, -999, -999, -999,
  116118. -999, -999, -999, -999, -999, -999, -999, -999,
  116119. -999, -999, -999, -999, -999, -999, -999, -999},
  116120. {-999, -999, -999, -999, -999, -999, -999, -999,
  116121. -999, -999, -999, -110, -97, -91, -73, -45,
  116122. -40, -33, -53, -61, -49, -54, -50, -50,
  116123. -60, -52, -67, -74, -81, -92, -96, -100,
  116124. -105, -110, -999, -999, -999, -999, -999, -999,
  116125. -999, -999, -999, -999, -999, -999, -999, -999,
  116126. -999, -999, -999, -999, -999, -999, -999, -999}},
  116127. /* 5657 Hz */
  116128. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116129. -999, -999, -999, -113, -106, -99, -92, -77,
  116130. -80, -88, -97, -106, -115, -999, -999, -999,
  116131. -999, -999, -999, -999, -999, -999, -999, -999,
  116132. -999, -999, -999, -999, -999, -999, -999, -999,
  116133. -999, -999, -999, -999, -999, -999, -999, -999,
  116134. -999, -999, -999, -999, -999, -999, -999, -999},
  116135. {-999, -999, -999, -999, -999, -999, -999, -999,
  116136. -999, -999, -116, -109, -102, -95, -89, -74,
  116137. -72, -88, -87, -95, -102, -109, -116, -999,
  116138. -999, -999, -999, -999, -999, -999, -999, -999,
  116139. -999, -999, -999, -999, -999, -999, -999, -999,
  116140. -999, -999, -999, -999, -999, -999, -999, -999,
  116141. -999, -999, -999, -999, -999, -999, -999, -999},
  116142. {-999, -999, -999, -999, -999, -999, -999, -999,
  116143. -999, -999, -116, -109, -102, -95, -89, -75,
  116144. -66, -74, -77, -78, -86, -87, -90, -96,
  116145. -105, -115, -999, -999, -999, -999, -999, -999,
  116146. -999, -999, -999, -999, -999, -999, -999, -999,
  116147. -999, -999, -999, -999, -999, -999, -999, -999,
  116148. -999, -999, -999, -999, -999, -999, -999, -999},
  116149. {-999, -999, -999, -999, -999, -999, -999, -999,
  116150. -999, -999, -115, -108, -101, -94, -88, -66,
  116151. -56, -61, -70, -65, -78, -72, -83, -84,
  116152. -93, -98, -105, -110, -999, -999, -999, -999,
  116153. -999, -999, -999, -999, -999, -999, -999, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999,
  116155. -999, -999, -999, -999, -999, -999, -999, -999},
  116156. {-999, -999, -999, -999, -999, -999, -999, -999,
  116157. -999, -999, -110, -105, -95, -89, -82, -57,
  116158. -52, -52, -59, -56, -59, -58, -69, -67,
  116159. -88, -82, -82, -89, -94, -100, -108, -999,
  116160. -999, -999, -999, -999, -999, -999, -999, -999,
  116161. -999, -999, -999, -999, -999, -999, -999, -999,
  116162. -999, -999, -999, -999, -999, -999, -999, -999},
  116163. {-999, -999, -999, -999, -999, -999, -999, -999,
  116164. -999, -110, -101, -96, -90, -83, -77, -54,
  116165. -43, -38, -50, -48, -52, -48, -42, -42,
  116166. -51, -52, -53, -59, -65, -71, -78, -85,
  116167. -95, -999, -999, -999, -999, -999, -999, -999,
  116168. -999, -999, -999, -999, -999, -999, -999, -999,
  116169. -999, -999, -999, -999, -999, -999, -999, -999}},
  116170. /* 8000 Hz */
  116171. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116172. -999, -999, -999, -999, -120, -105, -86, -68,
  116173. -78, -79, -90, -100, -110, -999, -999, -999,
  116174. -999, -999, -999, -999, -999, -999, -999, -999,
  116175. -999, -999, -999, -999, -999, -999, -999, -999,
  116176. -999, -999, -999, -999, -999, -999, -999, -999,
  116177. -999, -999, -999, -999, -999, -999, -999, -999},
  116178. {-999, -999, -999, -999, -999, -999, -999, -999,
  116179. -999, -999, -999, -999, -120, -105, -86, -66,
  116180. -73, -77, -88, -96, -105, -115, -999, -999,
  116181. -999, -999, -999, -999, -999, -999, -999, -999,
  116182. -999, -999, -999, -999, -999, -999, -999, -999,
  116183. -999, -999, -999, -999, -999, -999, -999, -999,
  116184. -999, -999, -999, -999, -999, -999, -999, -999},
  116185. {-999, -999, -999, -999, -999, -999, -999, -999,
  116186. -999, -999, -999, -120, -105, -92, -80, -61,
  116187. -64, -68, -80, -87, -92, -100, -110, -999,
  116188. -999, -999, -999, -999, -999, -999, -999, -999,
  116189. -999, -999, -999, -999, -999, -999, -999, -999,
  116190. -999, -999, -999, -999, -999, -999, -999, -999,
  116191. -999, -999, -999, -999, -999, -999, -999, -999},
  116192. {-999, -999, -999, -999, -999, -999, -999, -999,
  116193. -999, -999, -999, -120, -104, -91, -79, -52,
  116194. -60, -54, -64, -69, -77, -80, -82, -84,
  116195. -85, -87, -88, -90, -999, -999, -999, -999,
  116196. -999, -999, -999, -999, -999, -999, -999, -999,
  116197. -999, -999, -999, -999, -999, -999, -999, -999,
  116198. -999, -999, -999, -999, -999, -999, -999, -999},
  116199. {-999, -999, -999, -999, -999, -999, -999, -999,
  116200. -999, -999, -999, -118, -100, -87, -77, -49,
  116201. -50, -44, -58, -61, -61, -67, -65, -62,
  116202. -62, -62, -65, -68, -999, -999, -999, -999,
  116203. -999, -999, -999, -999, -999, -999, -999, -999,
  116204. -999, -999, -999, -999, -999, -999, -999, -999,
  116205. -999, -999, -999, -999, -999, -999, -999, -999},
  116206. {-999, -999, -999, -999, -999, -999, -999, -999,
  116207. -999, -999, -999, -115, -98, -84, -62, -49,
  116208. -44, -38, -46, -49, -49, -46, -39, -37,
  116209. -39, -40, -42, -43, -999, -999, -999, -999,
  116210. -999, -999, -999, -999, -999, -999, -999, -999,
  116211. -999, -999, -999, -999, -999, -999, -999, -999,
  116212. -999, -999, -999, -999, -999, -999, -999, -999}},
  116213. /* 11314 Hz */
  116214. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116215. -999, -999, -999, -999, -999, -110, -88, -74,
  116216. -77, -82, -82, -85, -90, -94, -99, -104,
  116217. -999, -999, -999, -999, -999, -999, -999, -999,
  116218. -999, -999, -999, -999, -999, -999, -999, -999,
  116219. -999, -999, -999, -999, -999, -999, -999, -999,
  116220. -999, -999, -999, -999, -999, -999, -999, -999},
  116221. {-999, -999, -999, -999, -999, -999, -999, -999,
  116222. -999, -999, -999, -999, -999, -110, -88, -66,
  116223. -70, -81, -80, -81, -84, -88, -91, -93,
  116224. -999, -999, -999, -999, -999, -999, -999, -999,
  116225. -999, -999, -999, -999, -999, -999, -999, -999,
  116226. -999, -999, -999, -999, -999, -999, -999, -999,
  116227. -999, -999, -999, -999, -999, -999, -999, -999},
  116228. {-999, -999, -999, -999, -999, -999, -999, -999,
  116229. -999, -999, -999, -999, -999, -110, -88, -61,
  116230. -63, -70, -71, -74, -77, -80, -83, -85,
  116231. -999, -999, -999, -999, -999, -999, -999, -999,
  116232. -999, -999, -999, -999, -999, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999,
  116234. -999, -999, -999, -999, -999, -999, -999, -999},
  116235. {-999, -999, -999, -999, -999, -999, -999, -999,
  116236. -999, -999, -999, -999, -999, -110, -86, -62,
  116237. -63, -62, -62, -58, -52, -50, -50, -52,
  116238. -54, -999, -999, -999, -999, -999, -999, -999,
  116239. -999, -999, -999, -999, -999, -999, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999,
  116241. -999, -999, -999, -999, -999, -999, -999, -999},
  116242. {-999, -999, -999, -999, -999, -999, -999, -999,
  116243. -999, -999, -999, -999, -118, -108, -84, -53,
  116244. -50, -50, -50, -55, -47, -45, -40, -40,
  116245. -40, -999, -999, -999, -999, -999, -999, -999,
  116246. -999, -999, -999, -999, -999, -999, -999, -999,
  116247. -999, -999, -999, -999, -999, -999, -999, -999,
  116248. -999, -999, -999, -999, -999, -999, -999, -999},
  116249. {-999, -999, -999, -999, -999, -999, -999, -999,
  116250. -999, -999, -999, -999, -118, -100, -73, -43,
  116251. -37, -42, -43, -53, -38, -37, -35, -35,
  116252. -38, -999, -999, -999, -999, -999, -999, -999,
  116253. -999, -999, -999, -999, -999, -999, -999, -999,
  116254. -999, -999, -999, -999, -999, -999, -999, -999,
  116255. -999, -999, -999, -999, -999, -999, -999, -999}},
  116256. /* 16000 Hz */
  116257. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116258. -999, -999, -999, -110, -100, -91, -84, -74,
  116259. -80, -80, -80, -80, -80, -999, -999, -999,
  116260. -999, -999, -999, -999, -999, -999, -999, -999,
  116261. -999, -999, -999, -999, -999, -999, -999, -999,
  116262. -999, -999, -999, -999, -999, -999, -999, -999,
  116263. -999, -999, -999, -999, -999, -999, -999, -999},
  116264. {-999, -999, -999, -999, -999, -999, -999, -999,
  116265. -999, -999, -999, -110, -100, -91, -84, -74,
  116266. -68, -68, -68, -68, -68, -999, -999, -999,
  116267. -999, -999, -999, -999, -999, -999, -999, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999,
  116269. -999, -999, -999, -999, -999, -999, -999, -999,
  116270. -999, -999, -999, -999, -999, -999, -999, -999},
  116271. {-999, -999, -999, -999, -999, -999, -999, -999,
  116272. -999, -999, -999, -110, -100, -86, -78, -70,
  116273. -60, -45, -30, -21, -999, -999, -999, -999,
  116274. -999, -999, -999, -999, -999, -999, -999, -999,
  116275. -999, -999, -999, -999, -999, -999, -999, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999,
  116277. -999, -999, -999, -999, -999, -999, -999, -999},
  116278. {-999, -999, -999, -999, -999, -999, -999, -999,
  116279. -999, -999, -999, -110, -100, -87, -78, -67,
  116280. -48, -38, -29, -21, -999, -999, -999, -999,
  116281. -999, -999, -999, -999, -999, -999, -999, -999,
  116282. -999, -999, -999, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999,
  116284. -999, -999, -999, -999, -999, -999, -999, -999},
  116285. {-999, -999, -999, -999, -999, -999, -999, -999,
  116286. -999, -999, -999, -110, -100, -86, -69, -56,
  116287. -45, -35, -33, -29, -999, -999, -999, -999,
  116288. -999, -999, -999, -999, -999, -999, -999, -999,
  116289. -999, -999, -999, -999, -999, -999, -999, -999,
  116290. -999, -999, -999, -999, -999, -999, -999, -999,
  116291. -999, -999, -999, -999, -999, -999, -999, -999},
  116292. {-999, -999, -999, -999, -999, -999, -999, -999,
  116293. -999, -999, -999, -110, -100, -83, -71, -48,
  116294. -27, -38, -37, -34, -999, -999, -999, -999,
  116295. -999, -999, -999, -999, -999, -999, -999, -999,
  116296. -999, -999, -999, -999, -999, -999, -999, -999,
  116297. -999, -999, -999, -999, -999, -999, -999, -999,
  116298. -999, -999, -999, -999, -999, -999, -999, -999}}
  116299. };
  116300. #endif
  116301. /*** End of inlined file: masking.h ***/
  116302. #define NEGINF -9999.f
  116303. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116304. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116305. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116306. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116307. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116308. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116309. look->channels=vi->channels;
  116310. look->ampmax=-9999.;
  116311. look->gi=gi;
  116312. return(look);
  116313. }
  116314. void _vp_global_free(vorbis_look_psy_global *look){
  116315. if(look){
  116316. memset(look,0,sizeof(*look));
  116317. _ogg_free(look);
  116318. }
  116319. }
  116320. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116321. if(i){
  116322. memset(i,0,sizeof(*i));
  116323. _ogg_free(i);
  116324. }
  116325. }
  116326. void _vi_psy_free(vorbis_info_psy *i){
  116327. if(i){
  116328. memset(i,0,sizeof(*i));
  116329. _ogg_free(i);
  116330. }
  116331. }
  116332. static void min_curve(float *c,
  116333. float *c2){
  116334. int i;
  116335. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116336. }
  116337. static void max_curve(float *c,
  116338. float *c2){
  116339. int i;
  116340. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116341. }
  116342. static void attenuate_curve(float *c,float att){
  116343. int i;
  116344. for(i=0;i<EHMER_MAX;i++)
  116345. c[i]+=att;
  116346. }
  116347. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116348. float center_boost, float center_decay_rate){
  116349. int i,j,k,m;
  116350. float ath[EHMER_MAX];
  116351. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116352. float athc[P_LEVELS][EHMER_MAX];
  116353. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116354. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116355. memset(workc,0,sizeof(workc));
  116356. for(i=0;i<P_BANDS;i++){
  116357. /* we add back in the ATH to avoid low level curves falling off to
  116358. -infinity and unnecessarily cutting off high level curves in the
  116359. curve limiting (last step). */
  116360. /* A half-band's settings must be valid over the whole band, and
  116361. it's better to mask too little than too much */
  116362. int ath_offset=i*4;
  116363. for(j=0;j<EHMER_MAX;j++){
  116364. float min=999.;
  116365. for(k=0;k<4;k++)
  116366. if(j+k+ath_offset<MAX_ATH){
  116367. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116368. }else{
  116369. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116370. }
  116371. ath[j]=min;
  116372. }
  116373. /* copy curves into working space, replicate the 50dB curve to 30
  116374. and 40, replicate the 100dB curve to 110 */
  116375. for(j=0;j<6;j++)
  116376. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116377. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116378. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116379. /* apply centered curve boost/decay */
  116380. for(j=0;j<P_LEVELS;j++){
  116381. for(k=0;k<EHMER_MAX;k++){
  116382. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116383. if(adj<0. && center_boost>0)adj=0.;
  116384. if(adj>0. && center_boost<0)adj=0.;
  116385. workc[i][j][k]+=adj;
  116386. }
  116387. }
  116388. /* normalize curves so the driving amplitude is 0dB */
  116389. /* make temp curves with the ATH overlayed */
  116390. for(j=0;j<P_LEVELS;j++){
  116391. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116392. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116393. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116394. max_curve(athc[j],workc[i][j]);
  116395. }
  116396. /* Now limit the louder curves.
  116397. the idea is this: We don't know what the playback attenuation
  116398. will be; 0dB SL moves every time the user twiddles the volume
  116399. knob. So that means we have to use a single 'most pessimal' curve
  116400. for all masking amplitudes, right? Wrong. The *loudest* sound
  116401. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116402. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116403. etc... */
  116404. for(j=1;j<P_LEVELS;j++){
  116405. min_curve(athc[j],athc[j-1]);
  116406. min_curve(workc[i][j],athc[j]);
  116407. }
  116408. }
  116409. for(i=0;i<P_BANDS;i++){
  116410. int hi_curve,lo_curve,bin;
  116411. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116412. /* low frequency curves are measured with greater resolution than
  116413. the MDCT/FFT will actually give us; we want the curve applied
  116414. to the tone data to be pessimistic and thus apply the minimum
  116415. masking possible for a given bin. That means that a single bin
  116416. could span more than one octave and that the curve will be a
  116417. composite of multiple octaves. It also may mean that a single
  116418. bin may span > an eighth of an octave and that the eighth
  116419. octave values may also be composited. */
  116420. /* which octave curves will we be compositing? */
  116421. bin=floor(fromOC(i*.5)/binHz);
  116422. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116423. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116424. if(lo_curve>i)lo_curve=i;
  116425. if(lo_curve<0)lo_curve=0;
  116426. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116427. for(m=0;m<P_LEVELS;m++){
  116428. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116429. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116430. /* render the curve into bins, then pull values back into curve.
  116431. The point is that any inherent subsampling aliasing results in
  116432. a safe minimum */
  116433. for(k=lo_curve;k<=hi_curve;k++){
  116434. int l=0;
  116435. for(j=0;j<EHMER_MAX;j++){
  116436. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116437. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116438. if(lo_bin<0)lo_bin=0;
  116439. if(lo_bin>n)lo_bin=n;
  116440. if(lo_bin<l)l=lo_bin;
  116441. if(hi_bin<0)hi_bin=0;
  116442. if(hi_bin>n)hi_bin=n;
  116443. for(;l<hi_bin && l<n;l++)
  116444. if(brute_buffer[l]>workc[k][m][j])
  116445. brute_buffer[l]=workc[k][m][j];
  116446. }
  116447. for(;l<n;l++)
  116448. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116449. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116450. }
  116451. /* be equally paranoid about being valid up to next half ocatve */
  116452. if(i+1<P_BANDS){
  116453. int l=0;
  116454. k=i+1;
  116455. for(j=0;j<EHMER_MAX;j++){
  116456. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116457. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116458. if(lo_bin<0)lo_bin=0;
  116459. if(lo_bin>n)lo_bin=n;
  116460. if(lo_bin<l)l=lo_bin;
  116461. if(hi_bin<0)hi_bin=0;
  116462. if(hi_bin>n)hi_bin=n;
  116463. for(;l<hi_bin && l<n;l++)
  116464. if(brute_buffer[l]>workc[k][m][j])
  116465. brute_buffer[l]=workc[k][m][j];
  116466. }
  116467. for(;l<n;l++)
  116468. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116469. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116470. }
  116471. for(j=0;j<EHMER_MAX;j++){
  116472. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116473. if(bin<0){
  116474. ret[i][m][j+2]=-999.;
  116475. }else{
  116476. if(bin>=n){
  116477. ret[i][m][j+2]=-999.;
  116478. }else{
  116479. ret[i][m][j+2]=brute_buffer[bin];
  116480. }
  116481. }
  116482. }
  116483. /* add fenceposts */
  116484. for(j=0;j<EHMER_OFFSET;j++)
  116485. if(ret[i][m][j+2]>-200.f)break;
  116486. ret[i][m][0]=j;
  116487. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116488. if(ret[i][m][j+2]>-200.f)
  116489. break;
  116490. ret[i][m][1]=j;
  116491. }
  116492. }
  116493. return(ret);
  116494. }
  116495. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116496. vorbis_info_psy_global *gi,int n,long rate){
  116497. long i,j,lo=-99,hi=1;
  116498. long maxoc;
  116499. memset(p,0,sizeof(*p));
  116500. p->eighth_octave_lines=gi->eighth_octave_lines;
  116501. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116502. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116503. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116504. p->total_octave_lines=maxoc-p->firstoc+1;
  116505. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116506. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116507. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116508. p->vi=vi;
  116509. p->n=n;
  116510. p->rate=rate;
  116511. /* AoTuV HF weighting */
  116512. p->m_val = 1.;
  116513. if(rate < 26000) p->m_val = 0;
  116514. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116515. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116516. /* set up the lookups for a given blocksize and sample rate */
  116517. for(i=0,j=0;i<MAX_ATH-1;i++){
  116518. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116519. float base=ATH[i];
  116520. if(j<endpos){
  116521. float delta=(ATH[i+1]-base)/(endpos-j);
  116522. for(;j<endpos && j<n;j++){
  116523. p->ath[j]=base+100.;
  116524. base+=delta;
  116525. }
  116526. }
  116527. }
  116528. for(i=0;i<n;i++){
  116529. float bark=toBARK(rate/(2*n)*i);
  116530. for(;lo+vi->noisewindowlomin<i &&
  116531. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116532. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116533. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116534. p->bark[i]=((lo-1)<<16)+(hi-1);
  116535. }
  116536. for(i=0;i<n;i++)
  116537. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116538. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116539. vi->tone_centerboost,vi->tone_decay);
  116540. /* set up rolling noise median */
  116541. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116542. for(i=0;i<P_NOISECURVES;i++)
  116543. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116544. for(i=0;i<n;i++){
  116545. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116546. int inthalfoc;
  116547. float del;
  116548. if(halfoc<0)halfoc=0;
  116549. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116550. inthalfoc=(int)halfoc;
  116551. del=halfoc-inthalfoc;
  116552. for(j=0;j<P_NOISECURVES;j++)
  116553. p->noiseoffset[j][i]=
  116554. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116555. p->vi->noiseoff[j][inthalfoc+1]*del;
  116556. }
  116557. #if 0
  116558. {
  116559. static int ls=0;
  116560. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116561. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116562. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116563. }
  116564. #endif
  116565. }
  116566. void _vp_psy_clear(vorbis_look_psy *p){
  116567. int i,j;
  116568. if(p){
  116569. if(p->ath)_ogg_free(p->ath);
  116570. if(p->octave)_ogg_free(p->octave);
  116571. if(p->bark)_ogg_free(p->bark);
  116572. if(p->tonecurves){
  116573. for(i=0;i<P_BANDS;i++){
  116574. for(j=0;j<P_LEVELS;j++){
  116575. _ogg_free(p->tonecurves[i][j]);
  116576. }
  116577. _ogg_free(p->tonecurves[i]);
  116578. }
  116579. _ogg_free(p->tonecurves);
  116580. }
  116581. if(p->noiseoffset){
  116582. for(i=0;i<P_NOISECURVES;i++){
  116583. _ogg_free(p->noiseoffset[i]);
  116584. }
  116585. _ogg_free(p->noiseoffset);
  116586. }
  116587. memset(p,0,sizeof(*p));
  116588. }
  116589. }
  116590. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116591. static void seed_curve(float *seed,
  116592. const float **curves,
  116593. float amp,
  116594. int oc, int n,
  116595. int linesper,float dBoffset){
  116596. int i,post1;
  116597. int seedptr;
  116598. const float *posts,*curve;
  116599. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116600. choice=max(choice,0);
  116601. choice=min(choice,P_LEVELS-1);
  116602. posts=curves[choice];
  116603. curve=posts+2;
  116604. post1=(int)posts[1];
  116605. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116606. for(i=posts[0];i<post1;i++){
  116607. if(seedptr>0){
  116608. float lin=amp+curve[i];
  116609. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116610. }
  116611. seedptr+=linesper;
  116612. if(seedptr>=n)break;
  116613. }
  116614. }
  116615. static void seed_loop(vorbis_look_psy *p,
  116616. const float ***curves,
  116617. const float *f,
  116618. const float *flr,
  116619. float *seed,
  116620. float specmax){
  116621. vorbis_info_psy *vi=p->vi;
  116622. long n=p->n,i;
  116623. float dBoffset=vi->max_curve_dB-specmax;
  116624. /* prime the working vector with peak values */
  116625. for(i=0;i<n;i++){
  116626. float max=f[i];
  116627. long oc=p->octave[i];
  116628. while(i+1<n && p->octave[i+1]==oc){
  116629. i++;
  116630. if(f[i]>max)max=f[i];
  116631. }
  116632. if(max+6.f>flr[i]){
  116633. oc=oc>>p->shiftoc;
  116634. if(oc>=P_BANDS)oc=P_BANDS-1;
  116635. if(oc<0)oc=0;
  116636. seed_curve(seed,
  116637. curves[oc],
  116638. max,
  116639. p->octave[i]-p->firstoc,
  116640. p->total_octave_lines,
  116641. p->eighth_octave_lines,
  116642. dBoffset);
  116643. }
  116644. }
  116645. }
  116646. static void seed_chase(float *seeds, int linesper, long n){
  116647. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116648. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116649. long stack=0;
  116650. long pos=0;
  116651. long i;
  116652. for(i=0;i<n;i++){
  116653. if(stack<2){
  116654. posstack[stack]=i;
  116655. ampstack[stack++]=seeds[i];
  116656. }else{
  116657. while(1){
  116658. if(seeds[i]<ampstack[stack-1]){
  116659. posstack[stack]=i;
  116660. ampstack[stack++]=seeds[i];
  116661. break;
  116662. }else{
  116663. if(i<posstack[stack-1]+linesper){
  116664. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116665. i<posstack[stack-2]+linesper){
  116666. /* we completely overlap, making stack-1 irrelevant. pop it */
  116667. stack--;
  116668. continue;
  116669. }
  116670. }
  116671. posstack[stack]=i;
  116672. ampstack[stack++]=seeds[i];
  116673. break;
  116674. }
  116675. }
  116676. }
  116677. }
  116678. /* the stack now contains only the positions that are relevant. Scan
  116679. 'em straight through */
  116680. for(i=0;i<stack;i++){
  116681. long endpos;
  116682. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116683. endpos=posstack[i+1];
  116684. }else{
  116685. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116686. discarded in short frames */
  116687. }
  116688. if(endpos>n)endpos=n;
  116689. for(;pos<endpos;pos++)
  116690. seeds[pos]=ampstack[i];
  116691. }
  116692. /* there. Linear time. I now remember this was on a problem set I
  116693. had in Grad Skool... I didn't solve it at the time ;-) */
  116694. }
  116695. /* bleaugh, this is more complicated than it needs to be */
  116696. #include<stdio.h>
  116697. static void max_seeds(vorbis_look_psy *p,
  116698. float *seed,
  116699. float *flr){
  116700. long n=p->total_octave_lines;
  116701. int linesper=p->eighth_octave_lines;
  116702. long linpos=0;
  116703. long pos;
  116704. seed_chase(seed,linesper,n); /* for masking */
  116705. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116706. while(linpos+1<p->n){
  116707. float minV=seed[pos];
  116708. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116709. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116710. while(pos+1<=end){
  116711. pos++;
  116712. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116713. minV=seed[pos];
  116714. }
  116715. end=pos+p->firstoc;
  116716. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116717. if(flr[linpos]<minV)flr[linpos]=minV;
  116718. }
  116719. {
  116720. float minV=seed[p->total_octave_lines-1];
  116721. for(;linpos<p->n;linpos++)
  116722. if(flr[linpos]<minV)flr[linpos]=minV;
  116723. }
  116724. }
  116725. static void bark_noise_hybridmp(int n,const long *b,
  116726. const float *f,
  116727. float *noise,
  116728. const float offset,
  116729. const int fixed){
  116730. float *N=(float*) alloca(n*sizeof(*N));
  116731. float *X=(float*) alloca(n*sizeof(*N));
  116732. float *XX=(float*) alloca(n*sizeof(*N));
  116733. float *Y=(float*) alloca(n*sizeof(*N));
  116734. float *XY=(float*) alloca(n*sizeof(*N));
  116735. float tN, tX, tXX, tY, tXY;
  116736. int i;
  116737. int lo, hi;
  116738. float R, A, B, D;
  116739. float w, x, y;
  116740. tN = tX = tXX = tY = tXY = 0.f;
  116741. y = f[0] + offset;
  116742. if (y < 1.f) y = 1.f;
  116743. w = y * y * .5;
  116744. tN += w;
  116745. tX += w;
  116746. tY += w * y;
  116747. N[0] = tN;
  116748. X[0] = tX;
  116749. XX[0] = tXX;
  116750. Y[0] = tY;
  116751. XY[0] = tXY;
  116752. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116753. y = f[i] + offset;
  116754. if (y < 1.f) y = 1.f;
  116755. w = y * y;
  116756. tN += w;
  116757. tX += w * x;
  116758. tXX += w * x * x;
  116759. tY += w * y;
  116760. tXY += w * x * y;
  116761. N[i] = tN;
  116762. X[i] = tX;
  116763. XX[i] = tXX;
  116764. Y[i] = tY;
  116765. XY[i] = tXY;
  116766. }
  116767. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116768. lo = b[i] >> 16;
  116769. if( lo>=0 ) break;
  116770. hi = b[i] & 0xffff;
  116771. tN = N[hi] + N[-lo];
  116772. tX = X[hi] - X[-lo];
  116773. tXX = XX[hi] + XX[-lo];
  116774. tY = Y[hi] + Y[-lo];
  116775. tXY = XY[hi] - XY[-lo];
  116776. A = tY * tXX - tX * tXY;
  116777. B = tN * tXY - tX * tY;
  116778. D = tN * tXX - tX * tX;
  116779. R = (A + x * B) / D;
  116780. if (R < 0.f)
  116781. R = 0.f;
  116782. noise[i] = R - offset;
  116783. }
  116784. for ( ;; i++, x += 1.f) {
  116785. lo = b[i] >> 16;
  116786. hi = b[i] & 0xffff;
  116787. if(hi>=n)break;
  116788. tN = N[hi] - N[lo];
  116789. tX = X[hi] - X[lo];
  116790. tXX = XX[hi] - XX[lo];
  116791. tY = Y[hi] - Y[lo];
  116792. tXY = XY[hi] - XY[lo];
  116793. A = tY * tXX - tX * tXY;
  116794. B = tN * tXY - tX * tY;
  116795. D = tN * tXX - tX * tX;
  116796. R = (A + x * B) / D;
  116797. if (R < 0.f) R = 0.f;
  116798. noise[i] = R - offset;
  116799. }
  116800. for ( ; i < n; i++, x += 1.f) {
  116801. R = (A + x * B) / D;
  116802. if (R < 0.f) R = 0.f;
  116803. noise[i] = R - offset;
  116804. }
  116805. if (fixed <= 0) return;
  116806. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116807. hi = i + fixed / 2;
  116808. lo = hi - fixed;
  116809. if(lo>=0)break;
  116810. tN = N[hi] + N[-lo];
  116811. tX = X[hi] - X[-lo];
  116812. tXX = XX[hi] + XX[-lo];
  116813. tY = Y[hi] + Y[-lo];
  116814. tXY = XY[hi] - XY[-lo];
  116815. A = tY * tXX - tX * tXY;
  116816. B = tN * tXY - tX * tY;
  116817. D = tN * tXX - tX * tX;
  116818. R = (A + x * B) / D;
  116819. if (R - offset < noise[i]) noise[i] = R - offset;
  116820. }
  116821. for ( ;; i++, x += 1.f) {
  116822. hi = i + fixed / 2;
  116823. lo = hi - fixed;
  116824. if(hi>=n)break;
  116825. tN = N[hi] - N[lo];
  116826. tX = X[hi] - X[lo];
  116827. tXX = XX[hi] - XX[lo];
  116828. tY = Y[hi] - Y[lo];
  116829. tXY = XY[hi] - XY[lo];
  116830. A = tY * tXX - tX * tXY;
  116831. B = tN * tXY - tX * tY;
  116832. D = tN * tXX - tX * tX;
  116833. R = (A + x * B) / D;
  116834. if (R - offset < noise[i]) noise[i] = R - offset;
  116835. }
  116836. for ( ; i < n; i++, x += 1.f) {
  116837. R = (A + x * B) / D;
  116838. if (R - offset < noise[i]) noise[i] = R - offset;
  116839. }
  116840. }
  116841. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  116842. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  116843. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  116844. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  116845. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  116846. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  116847. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  116848. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  116849. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  116850. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  116851. 973377.F, 913981.F, 858210.F, 805842.F,
  116852. 756669.F, 710497.F, 667142.F, 626433.F,
  116853. 588208.F, 552316.F, 518613.F, 486967.F,
  116854. 457252.F, 429351.F, 403152.F, 378551.F,
  116855. 355452.F, 333762.F, 313396.F, 294273.F,
  116856. 276316.F, 259455.F, 243623.F, 228757.F,
  116857. 214798.F, 201691.F, 189384.F, 177828.F,
  116858. 166977.F, 156788.F, 147221.F, 138237.F,
  116859. 129802.F, 121881.F, 114444.F, 107461.F,
  116860. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  116861. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  116862. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  116863. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  116864. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  116865. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  116866. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  116867. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  116868. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  116869. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  116870. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  116871. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  116872. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  116873. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  116874. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  116875. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  116876. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  116877. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  116878. 1084.32F, 1018.15F, 956.024F, 897.687F,
  116879. 842.910F, 791.475F, 743.179F, 697.830F,
  116880. 655.249F, 615.265F, 577.722F, 542.469F,
  116881. 509.367F, 478.286F, 449.101F, 421.696F,
  116882. 395.964F, 371.803F, 349.115F, 327.812F,
  116883. 307.809F, 289.026F, 271.390F, 254.830F,
  116884. 239.280F, 224.679F, 210.969F, 198.096F,
  116885. 186.008F, 174.658F, 164.000F, 153.993F,
  116886. 144.596F, 135.773F, 127.488F, 119.708F,
  116887. 112.404F, 105.545F, 99.1046F, 93.0572F,
  116888. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  116889. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  116890. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  116891. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  116892. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  116893. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  116894. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  116895. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  116896. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  116897. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  116898. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  116899. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  116900. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  116901. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  116902. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  116903. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  116904. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  116905. 1.20790F, 1.13419F, 1.06499F, 1.F
  116906. };
  116907. void _vp_remove_floor(vorbis_look_psy *p,
  116908. float *mdct,
  116909. int *codedflr,
  116910. float *residue,
  116911. int sliding_lowpass){
  116912. int i,n=p->n;
  116913. if(sliding_lowpass>n)sliding_lowpass=n;
  116914. for(i=0;i<sliding_lowpass;i++){
  116915. residue[i]=
  116916. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  116917. }
  116918. for(;i<n;i++)
  116919. residue[i]=0.;
  116920. }
  116921. void _vp_noisemask(vorbis_look_psy *p,
  116922. float *logmdct,
  116923. float *logmask){
  116924. int i,n=p->n;
  116925. float *work=(float*) alloca(n*sizeof(*work));
  116926. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  116927. 140.,-1);
  116928. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  116929. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  116930. p->vi->noisewindowfixed);
  116931. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  116932. #if 0
  116933. {
  116934. static int seq=0;
  116935. float work2[n];
  116936. for(i=0;i<n;i++){
  116937. work2[i]=logmask[i]+work[i];
  116938. }
  116939. if(seq&1)
  116940. _analysis_output("median2R",seq/2,work,n,1,0,0);
  116941. else
  116942. _analysis_output("median2L",seq/2,work,n,1,0,0);
  116943. if(seq&1)
  116944. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  116945. else
  116946. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  116947. seq++;
  116948. }
  116949. #endif
  116950. for(i=0;i<n;i++){
  116951. int dB=logmask[i]+.5;
  116952. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  116953. if(dB<0)dB=0;
  116954. logmask[i]= work[i]+p->vi->noisecompand[dB];
  116955. }
  116956. }
  116957. void _vp_tonemask(vorbis_look_psy *p,
  116958. float *logfft,
  116959. float *logmask,
  116960. float global_specmax,
  116961. float local_specmax){
  116962. int i,n=p->n;
  116963. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  116964. float att=local_specmax+p->vi->ath_adjatt;
  116965. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  116966. /* set the ATH (floating below localmax, not global max by a
  116967. specified att) */
  116968. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  116969. for(i=0;i<n;i++)
  116970. logmask[i]=p->ath[i]+att;
  116971. /* tone masking */
  116972. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  116973. max_seeds(p,seed,logmask);
  116974. }
  116975. void _vp_offset_and_mix(vorbis_look_psy *p,
  116976. float *noise,
  116977. float *tone,
  116978. int offset_select,
  116979. float *logmask,
  116980. float *mdct,
  116981. float *logmdct){
  116982. int i,n=p->n;
  116983. float de, coeffi, cx;/* AoTuV */
  116984. float toneatt=p->vi->tone_masteratt[offset_select];
  116985. cx = p->m_val;
  116986. for(i=0;i<n;i++){
  116987. float val= noise[i]+p->noiseoffset[offset_select][i];
  116988. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  116989. logmask[i]=max(val,tone[i]+toneatt);
  116990. /* AoTuV */
  116991. /** @ M1 **
  116992. The following codes improve a noise problem.
  116993. A fundamental idea uses the value of masking and carries out
  116994. the relative compensation of the MDCT.
  116995. However, this code is not perfect and all noise problems cannot be solved.
  116996. by Aoyumi @ 2004/04/18
  116997. */
  116998. if(offset_select == 1) {
  116999. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117000. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117001. if(val > coeffi){
  117002. /* mdct value is > -17.2 dB below floor */
  117003. de = 1.0-((val-coeffi)*0.005*cx);
  117004. /* pro-rated attenuation:
  117005. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117006. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117007. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117008. etc... */
  117009. if(de < 0) de = 0.0001;
  117010. }else
  117011. /* mdct value is <= -17.2 dB below floor */
  117012. de = 1.0-((val-coeffi)*0.0003*cx);
  117013. /* pro-rated attenuation:
  117014. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117015. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117016. etc... */
  117017. mdct[i] *= de;
  117018. }
  117019. }
  117020. }
  117021. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117022. vorbis_info *vi=vd->vi;
  117023. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117024. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117025. int n=ci->blocksizes[vd->W]/2;
  117026. float secs=(float)n/vi->rate;
  117027. amp+=secs*gi->ampmax_att_per_sec;
  117028. if(amp<-9999)amp=-9999;
  117029. return(amp);
  117030. }
  117031. static void couple_lossless(float A, float B,
  117032. float *qA, float *qB){
  117033. int test1=fabs(*qA)>fabs(*qB);
  117034. test1-= fabs(*qA)<fabs(*qB);
  117035. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117036. if(test1==1){
  117037. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117038. }else{
  117039. float temp=*qB;
  117040. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117041. *qA=temp;
  117042. }
  117043. if(*qB>fabs(*qA)*1.9999f){
  117044. *qB= -fabs(*qA)*2.f;
  117045. *qA= -*qA;
  117046. }
  117047. }
  117048. static float hypot_lookup[32]={
  117049. -0.009935, -0.011245, -0.012726, -0.014397,
  117050. -0.016282, -0.018407, -0.020800, -0.023494,
  117051. -0.026522, -0.029923, -0.033737, -0.038010,
  117052. -0.042787, -0.048121, -0.054064, -0.060671,
  117053. -0.068000, -0.076109, -0.085054, -0.094892,
  117054. -0.105675, -0.117451, -0.130260, -0.144134,
  117055. -0.159093, -0.175146, -0.192286, -0.210490,
  117056. -0.229718, -0.249913, -0.271001, -0.292893};
  117057. static void precomputed_couple_point(float premag,
  117058. int floorA,int floorB,
  117059. float *mag, float *ang){
  117060. int test=(floorA>floorB)-1;
  117061. int offset=31-abs(floorA-floorB);
  117062. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117063. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117064. *mag=premag*floormag;
  117065. *ang=0.f;
  117066. }
  117067. /* just like below, this is currently set up to only do
  117068. single-step-depth coupling. Otherwise, we'd have to do more
  117069. copying (which will be inevitable later) */
  117070. /* doing the real circular magnitude calculation is audibly superior
  117071. to (A+B)/sqrt(2) */
  117072. static float dipole_hypot(float a, float b){
  117073. if(a>0.){
  117074. if(b>0.)return sqrt(a*a+b*b);
  117075. if(a>-b)return sqrt(a*a-b*b);
  117076. return -sqrt(b*b-a*a);
  117077. }
  117078. if(b<0.)return -sqrt(a*a+b*b);
  117079. if(-a>b)return -sqrt(a*a-b*b);
  117080. return sqrt(b*b-a*a);
  117081. }
  117082. static float round_hypot(float a, float b){
  117083. if(a>0.){
  117084. if(b>0.)return sqrt(a*a+b*b);
  117085. if(a>-b)return sqrt(a*a+b*b);
  117086. return -sqrt(b*b+a*a);
  117087. }
  117088. if(b<0.)return -sqrt(a*a+b*b);
  117089. if(-a>b)return -sqrt(a*a+b*b);
  117090. return sqrt(b*b+a*a);
  117091. }
  117092. /* revert to round hypot for now */
  117093. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117094. vorbis_info_psy_global *g,
  117095. vorbis_look_psy *p,
  117096. vorbis_info_mapping0 *vi,
  117097. float **mdct){
  117098. int i,j,n=p->n;
  117099. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117100. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117101. for(i=0;i<vi->coupling_steps;i++){
  117102. float *mdctM=mdct[vi->coupling_mag[i]];
  117103. float *mdctA=mdct[vi->coupling_ang[i]];
  117104. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117105. for(j=0;j<limit;j++)
  117106. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117107. for(;j<n;j++)
  117108. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117109. }
  117110. return(ret);
  117111. }
  117112. /* this is for per-channel noise normalization */
  117113. static int apsort(const void *a, const void *b){
  117114. float f1=fabs(**(float**)a);
  117115. float f2=fabs(**(float**)b);
  117116. return (f1<f2)-(f1>f2);
  117117. }
  117118. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117119. vorbis_look_psy *p,
  117120. vorbis_info_mapping0 *vi,
  117121. float **mags){
  117122. if(p->vi->normal_point_p){
  117123. int i,j,k,n=p->n;
  117124. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117125. int partition=p->vi->normal_partition;
  117126. float **work=(float**) alloca(sizeof(*work)*partition);
  117127. for(i=0;i<vi->coupling_steps;i++){
  117128. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117129. for(j=0;j<n;j+=partition){
  117130. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117131. qsort(work,partition,sizeof(*work),apsort);
  117132. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117133. }
  117134. }
  117135. return(ret);
  117136. }
  117137. return(NULL);
  117138. }
  117139. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117140. float *magnitudes,int *sortedindex){
  117141. int i,j,n=p->n;
  117142. vorbis_info_psy *vi=p->vi;
  117143. int partition=vi->normal_partition;
  117144. float **work=(float**) alloca(sizeof(*work)*partition);
  117145. int start=vi->normal_start;
  117146. for(j=start;j<n;j+=partition){
  117147. if(j+partition>n)partition=n-j;
  117148. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117149. qsort(work,partition,sizeof(*work),apsort);
  117150. for(i=0;i<partition;i++){
  117151. sortedindex[i+j-start]=work[i]-magnitudes;
  117152. }
  117153. }
  117154. }
  117155. void _vp_noise_normalize(vorbis_look_psy *p,
  117156. float *in,float *out,int *sortedindex){
  117157. int flag=0,i,j=0,n=p->n;
  117158. vorbis_info_psy *vi=p->vi;
  117159. int partition=vi->normal_partition;
  117160. int start=vi->normal_start;
  117161. if(start>n)start=n;
  117162. if(vi->normal_channel_p){
  117163. for(;j<start;j++)
  117164. out[j]=rint(in[j]);
  117165. for(;j+partition<=n;j+=partition){
  117166. float acc=0.;
  117167. int k;
  117168. for(i=j;i<j+partition;i++)
  117169. acc+=in[i]*in[i];
  117170. for(i=0;i<partition;i++){
  117171. k=sortedindex[i+j-start];
  117172. if(in[k]*in[k]>=.25f){
  117173. out[k]=rint(in[k]);
  117174. acc-=in[k]*in[k];
  117175. flag=1;
  117176. }else{
  117177. if(acc<vi->normal_thresh)break;
  117178. out[k]=unitnorm(in[k]);
  117179. acc-=1.;
  117180. }
  117181. }
  117182. for(;i<partition;i++){
  117183. k=sortedindex[i+j-start];
  117184. out[k]=0.;
  117185. }
  117186. }
  117187. }
  117188. for(;j<n;j++)
  117189. out[j]=rint(in[j]);
  117190. }
  117191. void _vp_couple(int blobno,
  117192. vorbis_info_psy_global *g,
  117193. vorbis_look_psy *p,
  117194. vorbis_info_mapping0 *vi,
  117195. float **res,
  117196. float **mag_memo,
  117197. int **mag_sort,
  117198. int **ifloor,
  117199. int *nonzero,
  117200. int sliding_lowpass){
  117201. int i,j,k,n=p->n;
  117202. /* perform any requested channel coupling */
  117203. /* point stereo can only be used in a first stage (in this encoder)
  117204. because of the dependency on floor lookups */
  117205. for(i=0;i<vi->coupling_steps;i++){
  117206. /* once we're doing multistage coupling in which a channel goes
  117207. through more than one coupling step, the floor vector
  117208. magnitudes will also have to be recalculated an propogated
  117209. along with PCM. Right now, we're not (that will wait until 5.1
  117210. most likely), so the code isn't here yet. The memory management
  117211. here is all assuming single depth couplings anyway. */
  117212. /* make sure coupling a zero and a nonzero channel results in two
  117213. nonzero channels. */
  117214. if(nonzero[vi->coupling_mag[i]] ||
  117215. nonzero[vi->coupling_ang[i]]){
  117216. float *rM=res[vi->coupling_mag[i]];
  117217. float *rA=res[vi->coupling_ang[i]];
  117218. float *qM=rM+n;
  117219. float *qA=rA+n;
  117220. int *floorM=ifloor[vi->coupling_mag[i]];
  117221. int *floorA=ifloor[vi->coupling_ang[i]];
  117222. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117223. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117224. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117225. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117226. int pointlimit=limit;
  117227. nonzero[vi->coupling_mag[i]]=1;
  117228. nonzero[vi->coupling_ang[i]]=1;
  117229. /* The threshold of a stereo is changed with the size of n */
  117230. if(n > 1000)
  117231. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117232. for(j=0;j<p->n;j+=partition){
  117233. float acc=0.f;
  117234. for(k=0;k<partition;k++){
  117235. int l=k+j;
  117236. if(l<sliding_lowpass){
  117237. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117238. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117239. precomputed_couple_point(mag_memo[i][l],
  117240. floorM[l],floorA[l],
  117241. qM+l,qA+l);
  117242. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117243. }else{
  117244. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117245. }
  117246. }else{
  117247. qM[l]=0.;
  117248. qA[l]=0.;
  117249. }
  117250. }
  117251. if(p->vi->normal_point_p){
  117252. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117253. int l=mag_sort[i][j+k];
  117254. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117255. qM[l]=unitnorm(qM[l]);
  117256. acc-=1.f;
  117257. }
  117258. }
  117259. }
  117260. }
  117261. }
  117262. }
  117263. }
  117264. /* AoTuV */
  117265. /** @ M2 **
  117266. The boost problem by the combination of noise normalization and point stereo is eased.
  117267. However, this is a temporary patch.
  117268. by Aoyumi @ 2004/04/18
  117269. */
  117270. void hf_reduction(vorbis_info_psy_global *g,
  117271. vorbis_look_psy *p,
  117272. vorbis_info_mapping0 *vi,
  117273. float **mdct){
  117274. int i,j,n=p->n, de=0.3*p->m_val;
  117275. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117276. for(i=0; i<vi->coupling_steps; i++){
  117277. /* for(j=start; j<limit; j++){} // ???*/
  117278. for(j=limit; j<n; j++)
  117279. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117280. }
  117281. }
  117282. #endif
  117283. /*** End of inlined file: psy.c ***/
  117284. /*** Start of inlined file: registry.c ***/
  117285. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117286. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117287. // tasks..
  117288. #if JUCE_MSVC
  117289. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117290. #endif
  117291. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117292. #if JUCE_USE_OGGVORBIS
  117293. /* seems like major overkill now; the backend numbers will grow into
  117294. the infrastructure soon enough */
  117295. extern vorbis_func_floor floor0_exportbundle;
  117296. extern vorbis_func_floor floor1_exportbundle;
  117297. extern vorbis_func_residue residue0_exportbundle;
  117298. extern vorbis_func_residue residue1_exportbundle;
  117299. extern vorbis_func_residue residue2_exportbundle;
  117300. extern vorbis_func_mapping mapping0_exportbundle;
  117301. vorbis_func_floor *_floor_P[]={
  117302. &floor0_exportbundle,
  117303. &floor1_exportbundle,
  117304. };
  117305. vorbis_func_residue *_residue_P[]={
  117306. &residue0_exportbundle,
  117307. &residue1_exportbundle,
  117308. &residue2_exportbundle,
  117309. };
  117310. vorbis_func_mapping *_mapping_P[]={
  117311. &mapping0_exportbundle,
  117312. };
  117313. #endif
  117314. /*** End of inlined file: registry.c ***/
  117315. /*** Start of inlined file: res0.c ***/
  117316. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117317. encode/decode loops are coded for clarity and performance is not
  117318. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117319. it's slow. */
  117320. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117321. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117322. // tasks..
  117323. #if JUCE_MSVC
  117324. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117325. #endif
  117326. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117327. #if JUCE_USE_OGGVORBIS
  117328. #include <stdlib.h>
  117329. #include <string.h>
  117330. #include <math.h>
  117331. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117332. #include <stdio.h>
  117333. #endif
  117334. typedef struct {
  117335. vorbis_info_residue0 *info;
  117336. int parts;
  117337. int stages;
  117338. codebook *fullbooks;
  117339. codebook *phrasebook;
  117340. codebook ***partbooks;
  117341. int partvals;
  117342. int **decodemap;
  117343. long postbits;
  117344. long phrasebits;
  117345. long frames;
  117346. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117347. int train_seq;
  117348. long *training_data[8][64];
  117349. float training_max[8][64];
  117350. float training_min[8][64];
  117351. float tmin;
  117352. float tmax;
  117353. #endif
  117354. } vorbis_look_residue0;
  117355. void res0_free_info(vorbis_info_residue *i){
  117356. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117357. if(info){
  117358. memset(info,0,sizeof(*info));
  117359. _ogg_free(info);
  117360. }
  117361. }
  117362. void res0_free_look(vorbis_look_residue *i){
  117363. int j;
  117364. if(i){
  117365. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117366. #ifdef TRAIN_RES
  117367. {
  117368. int j,k,l;
  117369. for(j=0;j<look->parts;j++){
  117370. /*fprintf(stderr,"partition %d: ",j);*/
  117371. for(k=0;k<8;k++)
  117372. if(look->training_data[k][j]){
  117373. char buffer[80];
  117374. FILE *of;
  117375. codebook *statebook=look->partbooks[j][k];
  117376. /* long and short into the same bucket by current convention */
  117377. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117378. of=fopen(buffer,"a");
  117379. for(l=0;l<statebook->entries;l++)
  117380. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117381. fclose(of);
  117382. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117383. look->training_min[k][j],look->training_max[k][j]);*/
  117384. _ogg_free(look->training_data[k][j]);
  117385. look->training_data[k][j]=NULL;
  117386. }
  117387. /*fprintf(stderr,"\n");*/
  117388. }
  117389. }
  117390. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117391. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117392. (float)look->phrasebits/look->frames,
  117393. (float)look->postbits/look->frames,
  117394. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117395. #endif
  117396. /*vorbis_info_residue0 *info=look->info;
  117397. fprintf(stderr,
  117398. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117399. "(%g/frame) \n",look->frames,look->phrasebits,
  117400. look->resbitsflat,
  117401. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117402. for(j=0;j<look->parts;j++){
  117403. long acc=0;
  117404. fprintf(stderr,"\t[%d] == ",j);
  117405. for(k=0;k<look->stages;k++)
  117406. if((info->secondstages[j]>>k)&1){
  117407. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117408. acc+=look->resbits[j][k];
  117409. }
  117410. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117411. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117412. }
  117413. fprintf(stderr,"\n");*/
  117414. for(j=0;j<look->parts;j++)
  117415. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117416. _ogg_free(look->partbooks);
  117417. for(j=0;j<look->partvals;j++)
  117418. _ogg_free(look->decodemap[j]);
  117419. _ogg_free(look->decodemap);
  117420. memset(look,0,sizeof(*look));
  117421. _ogg_free(look);
  117422. }
  117423. }
  117424. static int icount(unsigned int v){
  117425. int ret=0;
  117426. while(v){
  117427. ret+=v&1;
  117428. v>>=1;
  117429. }
  117430. return(ret);
  117431. }
  117432. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117433. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117434. int j,acc=0;
  117435. oggpack_write(opb,info->begin,24);
  117436. oggpack_write(opb,info->end,24);
  117437. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117438. code with a partitioned book */
  117439. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117440. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117441. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117442. bitmask of one indicates this partition class has bits to write
  117443. this pass */
  117444. for(j=0;j<info->partitions;j++){
  117445. if(ilog(info->secondstages[j])>3){
  117446. /* yes, this is a minor hack due to not thinking ahead */
  117447. oggpack_write(opb,info->secondstages[j],3);
  117448. oggpack_write(opb,1,1);
  117449. oggpack_write(opb,info->secondstages[j]>>3,5);
  117450. }else
  117451. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117452. acc+=icount(info->secondstages[j]);
  117453. }
  117454. for(j=0;j<acc;j++)
  117455. oggpack_write(opb,info->booklist[j],8);
  117456. }
  117457. /* vorbis_info is for range checking */
  117458. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117459. int j,acc=0;
  117460. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117461. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117462. info->begin=oggpack_read(opb,24);
  117463. info->end=oggpack_read(opb,24);
  117464. info->grouping=oggpack_read(opb,24)+1;
  117465. info->partitions=oggpack_read(opb,6)+1;
  117466. info->groupbook=oggpack_read(opb,8);
  117467. for(j=0;j<info->partitions;j++){
  117468. int cascade=oggpack_read(opb,3);
  117469. if(oggpack_read(opb,1))
  117470. cascade|=(oggpack_read(opb,5)<<3);
  117471. info->secondstages[j]=cascade;
  117472. acc+=icount(cascade);
  117473. }
  117474. for(j=0;j<acc;j++)
  117475. info->booklist[j]=oggpack_read(opb,8);
  117476. if(info->groupbook>=ci->books)goto errout;
  117477. for(j=0;j<acc;j++)
  117478. if(info->booklist[j]>=ci->books)goto errout;
  117479. return(info);
  117480. errout:
  117481. res0_free_info(info);
  117482. return(NULL);
  117483. }
  117484. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117485. vorbis_info_residue *vr){
  117486. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117487. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117488. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117489. int j,k,acc=0;
  117490. int dim;
  117491. int maxstage=0;
  117492. look->info=info;
  117493. look->parts=info->partitions;
  117494. look->fullbooks=ci->fullbooks;
  117495. look->phrasebook=ci->fullbooks+info->groupbook;
  117496. dim=look->phrasebook->dim;
  117497. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117498. for(j=0;j<look->parts;j++){
  117499. int stages=ilog(info->secondstages[j]);
  117500. if(stages){
  117501. if(stages>maxstage)maxstage=stages;
  117502. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117503. for(k=0;k<stages;k++)
  117504. if(info->secondstages[j]&(1<<k)){
  117505. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117506. #ifdef TRAIN_RES
  117507. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117508. sizeof(***look->training_data));
  117509. #endif
  117510. }
  117511. }
  117512. }
  117513. look->partvals=rint(pow((float)look->parts,(float)dim));
  117514. look->stages=maxstage;
  117515. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117516. for(j=0;j<look->partvals;j++){
  117517. long val=j;
  117518. long mult=look->partvals/look->parts;
  117519. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117520. for(k=0;k<dim;k++){
  117521. long deco=val/mult;
  117522. val-=deco*mult;
  117523. mult/=look->parts;
  117524. look->decodemap[j][k]=deco;
  117525. }
  117526. }
  117527. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117528. {
  117529. static int train_seq=0;
  117530. look->train_seq=train_seq++;
  117531. }
  117532. #endif
  117533. return(look);
  117534. }
  117535. /* break an abstraction and copy some code for performance purposes */
  117536. static int local_book_besterror(codebook *book,float *a){
  117537. int dim=book->dim,i,k,o;
  117538. int best=0;
  117539. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117540. /* find the quant val of each scalar */
  117541. for(k=0,o=dim;k<dim;++k){
  117542. float val=a[--o];
  117543. i=tt->threshvals>>1;
  117544. if(val<tt->quantthresh[i]){
  117545. if(val<tt->quantthresh[i-1]){
  117546. for(--i;i>0;--i)
  117547. if(val>=tt->quantthresh[i-1])
  117548. break;
  117549. }
  117550. }else{
  117551. for(++i;i<tt->threshvals-1;++i)
  117552. if(val<tt->quantthresh[i])break;
  117553. }
  117554. best=(best*tt->quantvals)+tt->quantmap[i];
  117555. }
  117556. /* regular lattices are easy :-) */
  117557. if(book->c->lengthlist[best]<=0){
  117558. const static_codebook *c=book->c;
  117559. int i,j;
  117560. float bestf=0.f;
  117561. float *e=book->valuelist;
  117562. best=-1;
  117563. for(i=0;i<book->entries;i++){
  117564. if(c->lengthlist[i]>0){
  117565. float thisx=0.f;
  117566. for(j=0;j<dim;j++){
  117567. float val=(e[j]-a[j]);
  117568. thisx+=val*val;
  117569. }
  117570. if(best==-1 || thisx<bestf){
  117571. bestf=thisx;
  117572. best=i;
  117573. }
  117574. }
  117575. e+=dim;
  117576. }
  117577. }
  117578. {
  117579. float *ptr=book->valuelist+best*dim;
  117580. for(i=0;i<dim;i++)
  117581. *a++ -= *ptr++;
  117582. }
  117583. return(best);
  117584. }
  117585. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117586. codebook *book,long *acc){
  117587. int i,bits=0;
  117588. int dim=book->dim;
  117589. int step=n/dim;
  117590. for(i=0;i<step;i++){
  117591. int entry=local_book_besterror(book,vec+i*dim);
  117592. #ifdef TRAIN_RES
  117593. acc[entry]++;
  117594. #endif
  117595. bits+=vorbis_book_encode(book,entry,opb);
  117596. }
  117597. return(bits);
  117598. }
  117599. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117600. float **in,int ch){
  117601. long i,j,k;
  117602. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117603. vorbis_info_residue0 *info=look->info;
  117604. /* move all this setup out later */
  117605. int samples_per_partition=info->grouping;
  117606. int possible_partitions=info->partitions;
  117607. int n=info->end-info->begin;
  117608. int partvals=n/samples_per_partition;
  117609. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117610. float scale=100./samples_per_partition;
  117611. /* we find the partition type for each partition of each
  117612. channel. We'll go back and do the interleaved encoding in a
  117613. bit. For now, clarity */
  117614. for(i=0;i<ch;i++){
  117615. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117616. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117617. }
  117618. for(i=0;i<partvals;i++){
  117619. int offset=i*samples_per_partition+info->begin;
  117620. for(j=0;j<ch;j++){
  117621. float max=0.;
  117622. float ent=0.;
  117623. for(k=0;k<samples_per_partition;k++){
  117624. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117625. ent+=fabs(rint(in[j][offset+k]));
  117626. }
  117627. ent*=scale;
  117628. for(k=0;k<possible_partitions-1;k++)
  117629. if(max<=info->classmetric1[k] &&
  117630. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117631. break;
  117632. partword[j][i]=k;
  117633. }
  117634. }
  117635. #ifdef TRAIN_RESAUX
  117636. {
  117637. FILE *of;
  117638. char buffer[80];
  117639. for(i=0;i<ch;i++){
  117640. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117641. of=fopen(buffer,"a");
  117642. for(j=0;j<partvals;j++)
  117643. fprintf(of,"%ld, ",partword[i][j]);
  117644. fprintf(of,"\n");
  117645. fclose(of);
  117646. }
  117647. }
  117648. #endif
  117649. look->frames++;
  117650. return(partword);
  117651. }
  117652. /* designed for stereo or other modes where the partition size is an
  117653. integer multiple of the number of channels encoded in the current
  117654. submap */
  117655. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117656. int ch){
  117657. long i,j,k,l;
  117658. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117659. vorbis_info_residue0 *info=look->info;
  117660. /* move all this setup out later */
  117661. int samples_per_partition=info->grouping;
  117662. int possible_partitions=info->partitions;
  117663. int n=info->end-info->begin;
  117664. int partvals=n/samples_per_partition;
  117665. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117666. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117667. FILE *of;
  117668. char buffer[80];
  117669. #endif
  117670. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117671. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117672. for(i=0,l=info->begin/ch;i<partvals;i++){
  117673. float magmax=0.f;
  117674. float angmax=0.f;
  117675. for(j=0;j<samples_per_partition;j+=ch){
  117676. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117677. for(k=1;k<ch;k++)
  117678. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117679. l++;
  117680. }
  117681. for(j=0;j<possible_partitions-1;j++)
  117682. if(magmax<=info->classmetric1[j] &&
  117683. angmax<=info->classmetric2[j])
  117684. break;
  117685. partword[0][i]=j;
  117686. }
  117687. #ifdef TRAIN_RESAUX
  117688. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117689. of=fopen(buffer,"a");
  117690. for(i=0;i<partvals;i++)
  117691. fprintf(of,"%ld, ",partword[0][i]);
  117692. fprintf(of,"\n");
  117693. fclose(of);
  117694. #endif
  117695. look->frames++;
  117696. return(partword);
  117697. }
  117698. static int _01forward(oggpack_buffer *opb,
  117699. vorbis_block *vb,vorbis_look_residue *vl,
  117700. float **in,int ch,
  117701. long **partword,
  117702. int (*encode)(oggpack_buffer *,float *,int,
  117703. codebook *,long *)){
  117704. long i,j,k,s;
  117705. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117706. vorbis_info_residue0 *info=look->info;
  117707. /* move all this setup out later */
  117708. int samples_per_partition=info->grouping;
  117709. int possible_partitions=info->partitions;
  117710. int partitions_per_word=look->phrasebook->dim;
  117711. int n=info->end-info->begin;
  117712. int partvals=n/samples_per_partition;
  117713. long resbits[128];
  117714. long resvals[128];
  117715. #ifdef TRAIN_RES
  117716. for(i=0;i<ch;i++)
  117717. for(j=info->begin;j<info->end;j++){
  117718. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117719. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117720. }
  117721. #endif
  117722. memset(resbits,0,sizeof(resbits));
  117723. memset(resvals,0,sizeof(resvals));
  117724. /* we code the partition words for each channel, then the residual
  117725. words for a partition per channel until we've written all the
  117726. residual words for that partition word. Then write the next
  117727. partition channel words... */
  117728. for(s=0;s<look->stages;s++){
  117729. for(i=0;i<partvals;){
  117730. /* first we encode a partition codeword for each channel */
  117731. if(s==0){
  117732. for(j=0;j<ch;j++){
  117733. long val=partword[j][i];
  117734. for(k=1;k<partitions_per_word;k++){
  117735. val*=possible_partitions;
  117736. if(i+k<partvals)
  117737. val+=partword[j][i+k];
  117738. }
  117739. /* training hack */
  117740. if(val<look->phrasebook->entries)
  117741. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117742. #if 0 /*def TRAIN_RES*/
  117743. else
  117744. fprintf(stderr,"!");
  117745. #endif
  117746. }
  117747. }
  117748. /* now we encode interleaved residual values for the partitions */
  117749. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117750. long offset=i*samples_per_partition+info->begin;
  117751. for(j=0;j<ch;j++){
  117752. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117753. if(info->secondstages[partword[j][i]]&(1<<s)){
  117754. codebook *statebook=look->partbooks[partword[j][i]][s];
  117755. if(statebook){
  117756. int ret;
  117757. long *accumulator=NULL;
  117758. #ifdef TRAIN_RES
  117759. accumulator=look->training_data[s][partword[j][i]];
  117760. {
  117761. int l;
  117762. float *samples=in[j]+offset;
  117763. for(l=0;l<samples_per_partition;l++){
  117764. if(samples[l]<look->training_min[s][partword[j][i]])
  117765. look->training_min[s][partword[j][i]]=samples[l];
  117766. if(samples[l]>look->training_max[s][partword[j][i]])
  117767. look->training_max[s][partword[j][i]]=samples[l];
  117768. }
  117769. }
  117770. #endif
  117771. ret=encode(opb,in[j]+offset,samples_per_partition,
  117772. statebook,accumulator);
  117773. look->postbits+=ret;
  117774. resbits[partword[j][i]]+=ret;
  117775. }
  117776. }
  117777. }
  117778. }
  117779. }
  117780. }
  117781. /*{
  117782. long total=0;
  117783. long totalbits=0;
  117784. fprintf(stderr,"%d :: ",vb->mode);
  117785. for(k=0;k<possible_partitions;k++){
  117786. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117787. total+=resvals[k];
  117788. totalbits+=resbits[k];
  117789. }
  117790. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117791. }*/
  117792. return(0);
  117793. }
  117794. /* a truncated packet here just means 'stop working'; it's not an error */
  117795. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117796. float **in,int ch,
  117797. long (*decodepart)(codebook *, float *,
  117798. oggpack_buffer *,int)){
  117799. long i,j,k,l,s;
  117800. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117801. vorbis_info_residue0 *info=look->info;
  117802. /* move all this setup out later */
  117803. int samples_per_partition=info->grouping;
  117804. int partitions_per_word=look->phrasebook->dim;
  117805. int n=info->end-info->begin;
  117806. int partvals=n/samples_per_partition;
  117807. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117808. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117809. for(j=0;j<ch;j++)
  117810. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117811. for(s=0;s<look->stages;s++){
  117812. /* each loop decodes on partition codeword containing
  117813. partitions_pre_word partitions */
  117814. for(i=0,l=0;i<partvals;l++){
  117815. if(s==0){
  117816. /* fetch the partition word for each channel */
  117817. for(j=0;j<ch;j++){
  117818. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117819. if(temp==-1)goto eopbreak;
  117820. partword[j][l]=look->decodemap[temp];
  117821. if(partword[j][l]==NULL)goto errout;
  117822. }
  117823. }
  117824. /* now we decode residual values for the partitions */
  117825. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117826. for(j=0;j<ch;j++){
  117827. long offset=info->begin+i*samples_per_partition;
  117828. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  117829. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  117830. if(stagebook){
  117831. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  117832. samples_per_partition)==-1)goto eopbreak;
  117833. }
  117834. }
  117835. }
  117836. }
  117837. }
  117838. errout:
  117839. eopbreak:
  117840. return(0);
  117841. }
  117842. #if 0
  117843. /* residue 0 and 1 are just slight variants of one another. 0 is
  117844. interleaved, 1 is not */
  117845. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  117846. float **in,int *nonzero,int ch){
  117847. /* we encode only the nonzero parts of a bundle */
  117848. int i,used=0;
  117849. for(i=0;i<ch;i++)
  117850. if(nonzero[i])
  117851. in[used++]=in[i];
  117852. if(used)
  117853. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  117854. return(_01class(vb,vl,in,used));
  117855. else
  117856. return(0);
  117857. }
  117858. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  117859. float **in,float **out,int *nonzero,int ch,
  117860. long **partword){
  117861. /* we encode only the nonzero parts of a bundle */
  117862. int i,j,used=0,n=vb->pcmend/2;
  117863. for(i=0;i<ch;i++)
  117864. if(nonzero[i]){
  117865. if(out)
  117866. for(j=0;j<n;j++)
  117867. out[i][j]+=in[i][j];
  117868. in[used++]=in[i];
  117869. }
  117870. if(used){
  117871. int ret=_01forward(vb,vl,in,used,partword,
  117872. _interleaved_encodepart);
  117873. if(out){
  117874. used=0;
  117875. for(i=0;i<ch;i++)
  117876. if(nonzero[i]){
  117877. for(j=0;j<n;j++)
  117878. out[i][j]-=in[used][j];
  117879. used++;
  117880. }
  117881. }
  117882. return(ret);
  117883. }else{
  117884. return(0);
  117885. }
  117886. }
  117887. #endif
  117888. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117889. float **in,int *nonzero,int ch){
  117890. int i,used=0;
  117891. for(i=0;i<ch;i++)
  117892. if(nonzero[i])
  117893. in[used++]=in[i];
  117894. if(used)
  117895. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  117896. else
  117897. return(0);
  117898. }
  117899. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  117900. float **in,float **out,int *nonzero,int ch,
  117901. long **partword){
  117902. int i,j,used=0,n=vb->pcmend/2;
  117903. for(i=0;i<ch;i++)
  117904. if(nonzero[i]){
  117905. if(out)
  117906. for(j=0;j<n;j++)
  117907. out[i][j]+=in[i][j];
  117908. in[used++]=in[i];
  117909. }
  117910. if(used){
  117911. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  117912. if(out){
  117913. used=0;
  117914. for(i=0;i<ch;i++)
  117915. if(nonzero[i]){
  117916. for(j=0;j<n;j++)
  117917. out[i][j]-=in[used][j];
  117918. used++;
  117919. }
  117920. }
  117921. return(ret);
  117922. }else{
  117923. return(0);
  117924. }
  117925. }
  117926. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  117927. float **in,int *nonzero,int ch){
  117928. int i,used=0;
  117929. for(i=0;i<ch;i++)
  117930. if(nonzero[i])
  117931. in[used++]=in[i];
  117932. if(used)
  117933. return(_01class(vb,vl,in,used));
  117934. else
  117935. return(0);
  117936. }
  117937. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117938. float **in,int *nonzero,int ch){
  117939. int i,used=0;
  117940. for(i=0;i<ch;i++)
  117941. if(nonzero[i])
  117942. in[used++]=in[i];
  117943. if(used)
  117944. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  117945. else
  117946. return(0);
  117947. }
  117948. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  117949. float **in,int *nonzero,int ch){
  117950. int i,used=0;
  117951. for(i=0;i<ch;i++)
  117952. if(nonzero[i])used++;
  117953. if(used)
  117954. return(_2class(vb,vl,in,ch));
  117955. else
  117956. return(0);
  117957. }
  117958. /* res2 is slightly more different; all the channels are interleaved
  117959. into a single vector and encoded. */
  117960. int res2_forward(oggpack_buffer *opb,
  117961. vorbis_block *vb,vorbis_look_residue *vl,
  117962. float **in,float **out,int *nonzero,int ch,
  117963. long **partword){
  117964. long i,j,k,n=vb->pcmend/2,used=0;
  117965. /* don't duplicate the code; use a working vector hack for now and
  117966. reshape ourselves into a single channel res1 */
  117967. /* ugly; reallocs for each coupling pass :-( */
  117968. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  117969. for(i=0;i<ch;i++){
  117970. float *pcm=in[i];
  117971. if(nonzero[i])used++;
  117972. for(j=0,k=i;j<n;j++,k+=ch)
  117973. work[k]=pcm[j];
  117974. }
  117975. if(used){
  117976. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  117977. /* update the sofar vector */
  117978. if(out){
  117979. for(i=0;i<ch;i++){
  117980. float *pcm=in[i];
  117981. float *sofar=out[i];
  117982. for(j=0,k=i;j<n;j++,k+=ch)
  117983. sofar[j]+=pcm[j]-work[k];
  117984. }
  117985. }
  117986. return(ret);
  117987. }else{
  117988. return(0);
  117989. }
  117990. }
  117991. /* duplicate code here as speed is somewhat more important */
  117992. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117993. float **in,int *nonzero,int ch){
  117994. long i,k,l,s;
  117995. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117996. vorbis_info_residue0 *info=look->info;
  117997. /* move all this setup out later */
  117998. int samples_per_partition=info->grouping;
  117999. int partitions_per_word=look->phrasebook->dim;
  118000. int n=info->end-info->begin;
  118001. int partvals=n/samples_per_partition;
  118002. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118003. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118004. for(i=0;i<ch;i++)if(nonzero[i])break;
  118005. if(i==ch)return(0); /* no nonzero vectors */
  118006. for(s=0;s<look->stages;s++){
  118007. for(i=0,l=0;i<partvals;l++){
  118008. if(s==0){
  118009. /* fetch the partition word */
  118010. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118011. if(temp==-1)goto eopbreak;
  118012. partword[l]=look->decodemap[temp];
  118013. if(partword[l]==NULL)goto errout;
  118014. }
  118015. /* now we decode residual values for the partitions */
  118016. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118017. if(info->secondstages[partword[l][k]]&(1<<s)){
  118018. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118019. if(stagebook){
  118020. if(vorbis_book_decodevv_add(stagebook,in,
  118021. i*samples_per_partition+info->begin,ch,
  118022. &vb->opb,samples_per_partition)==-1)
  118023. goto eopbreak;
  118024. }
  118025. }
  118026. }
  118027. }
  118028. errout:
  118029. eopbreak:
  118030. return(0);
  118031. }
  118032. vorbis_func_residue residue0_exportbundle={
  118033. NULL,
  118034. &res0_unpack,
  118035. &res0_look,
  118036. &res0_free_info,
  118037. &res0_free_look,
  118038. NULL,
  118039. NULL,
  118040. &res0_inverse
  118041. };
  118042. vorbis_func_residue residue1_exportbundle={
  118043. &res0_pack,
  118044. &res0_unpack,
  118045. &res0_look,
  118046. &res0_free_info,
  118047. &res0_free_look,
  118048. &res1_class,
  118049. &res1_forward,
  118050. &res1_inverse
  118051. };
  118052. vorbis_func_residue residue2_exportbundle={
  118053. &res0_pack,
  118054. &res0_unpack,
  118055. &res0_look,
  118056. &res0_free_info,
  118057. &res0_free_look,
  118058. &res2_class,
  118059. &res2_forward,
  118060. &res2_inverse
  118061. };
  118062. #endif
  118063. /*** End of inlined file: res0.c ***/
  118064. /*** Start of inlined file: sharedbook.c ***/
  118065. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118066. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118067. // tasks..
  118068. #if JUCE_MSVC
  118069. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118070. #endif
  118071. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118072. #if JUCE_USE_OGGVORBIS
  118073. #include <stdlib.h>
  118074. #include <math.h>
  118075. #include <string.h>
  118076. /**** pack/unpack helpers ******************************************/
  118077. int _ilog(unsigned int v){
  118078. int ret=0;
  118079. while(v){
  118080. ret++;
  118081. v>>=1;
  118082. }
  118083. return(ret);
  118084. }
  118085. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118086. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118087. Why not IEEE? It's just not that important here. */
  118088. #define VQ_FEXP 10
  118089. #define VQ_FMAN 21
  118090. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118091. /* doesn't currently guard under/overflow */
  118092. long _float32_pack(float val){
  118093. int sign=0;
  118094. long exp;
  118095. long mant;
  118096. if(val<0){
  118097. sign=0x80000000;
  118098. val= -val;
  118099. }
  118100. exp= floor(log(val)/log(2.f));
  118101. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118102. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118103. return(sign|exp|mant);
  118104. }
  118105. float _float32_unpack(long val){
  118106. double mant=val&0x1fffff;
  118107. int sign=val&0x80000000;
  118108. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118109. if(sign)mant= -mant;
  118110. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118111. }
  118112. /* given a list of word lengths, generate a list of codewords. Works
  118113. for length ordered or unordered, always assigns the lowest valued
  118114. codewords first. Extended to handle unused entries (length 0) */
  118115. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118116. long i,j,count=0;
  118117. ogg_uint32_t marker[33];
  118118. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118119. memset(marker,0,sizeof(marker));
  118120. for(i=0;i<n;i++){
  118121. long length=l[i];
  118122. if(length>0){
  118123. ogg_uint32_t entry=marker[length];
  118124. /* when we claim a node for an entry, we also claim the nodes
  118125. below it (pruning off the imagined tree that may have dangled
  118126. from it) as well as blocking the use of any nodes directly
  118127. above for leaves */
  118128. /* update ourself */
  118129. if(length<32 && (entry>>length)){
  118130. /* error condition; the lengths must specify an overpopulated tree */
  118131. _ogg_free(r);
  118132. return(NULL);
  118133. }
  118134. r[count++]=entry;
  118135. /* Look to see if the next shorter marker points to the node
  118136. above. if so, update it and repeat. */
  118137. {
  118138. for(j=length;j>0;j--){
  118139. if(marker[j]&1){
  118140. /* have to jump branches */
  118141. if(j==1)
  118142. marker[1]++;
  118143. else
  118144. marker[j]=marker[j-1]<<1;
  118145. break; /* invariant says next upper marker would already
  118146. have been moved if it was on the same path */
  118147. }
  118148. marker[j]++;
  118149. }
  118150. }
  118151. /* prune the tree; the implicit invariant says all the longer
  118152. markers were dangling from our just-taken node. Dangle them
  118153. from our *new* node. */
  118154. for(j=length+1;j<33;j++)
  118155. if((marker[j]>>1) == entry){
  118156. entry=marker[j];
  118157. marker[j]=marker[j-1]<<1;
  118158. }else
  118159. break;
  118160. }else
  118161. if(sparsecount==0)count++;
  118162. }
  118163. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118164. endian */
  118165. for(i=0,count=0;i<n;i++){
  118166. ogg_uint32_t temp=0;
  118167. for(j=0;j<l[i];j++){
  118168. temp<<=1;
  118169. temp|=(r[count]>>j)&1;
  118170. }
  118171. if(sparsecount){
  118172. if(l[i])
  118173. r[count++]=temp;
  118174. }else
  118175. r[count++]=temp;
  118176. }
  118177. return(r);
  118178. }
  118179. /* there might be a straightforward one-line way to do the below
  118180. that's portable and totally safe against roundoff, but I haven't
  118181. thought of it. Therefore, we opt on the side of caution */
  118182. long _book_maptype1_quantvals(const static_codebook *b){
  118183. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118184. /* the above *should* be reliable, but we'll not assume that FP is
  118185. ever reliable when bitstream sync is at stake; verify via integer
  118186. means that vals really is the greatest value of dim for which
  118187. vals^b->bim <= b->entries */
  118188. /* treat the above as an initial guess */
  118189. while(1){
  118190. long acc=1;
  118191. long acc1=1;
  118192. int i;
  118193. for(i=0;i<b->dim;i++){
  118194. acc*=vals;
  118195. acc1*=vals+1;
  118196. }
  118197. if(acc<=b->entries && acc1>b->entries){
  118198. return(vals);
  118199. }else{
  118200. if(acc>b->entries){
  118201. vals--;
  118202. }else{
  118203. vals++;
  118204. }
  118205. }
  118206. }
  118207. }
  118208. /* unpack the quantized list of values for encode/decode ***********/
  118209. /* we need to deal with two map types: in map type 1, the values are
  118210. generated algorithmically (each column of the vector counts through
  118211. the values in the quant vector). in map type 2, all the values came
  118212. in in an explicit list. Both value lists must be unpacked */
  118213. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118214. long j,k,count=0;
  118215. if(b->maptype==1 || b->maptype==2){
  118216. int quantvals;
  118217. float mindel=_float32_unpack(b->q_min);
  118218. float delta=_float32_unpack(b->q_delta);
  118219. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118220. /* maptype 1 and 2 both use a quantized value vector, but
  118221. different sizes */
  118222. switch(b->maptype){
  118223. case 1:
  118224. /* most of the time, entries%dimensions == 0, but we need to be
  118225. well defined. We define that the possible vales at each
  118226. scalar is values == entries/dim. If entries%dim != 0, we'll
  118227. have 'too few' values (values*dim<entries), which means that
  118228. we'll have 'left over' entries; left over entries use zeroed
  118229. values (and are wasted). So don't generate codebooks like
  118230. that */
  118231. quantvals=_book_maptype1_quantvals(b);
  118232. for(j=0;j<b->entries;j++){
  118233. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118234. float last=0.f;
  118235. int indexdiv=1;
  118236. for(k=0;k<b->dim;k++){
  118237. int index= (j/indexdiv)%quantvals;
  118238. float val=b->quantlist[index];
  118239. val=fabs(val)*delta+mindel+last;
  118240. if(b->q_sequencep)last=val;
  118241. if(sparsemap)
  118242. r[sparsemap[count]*b->dim+k]=val;
  118243. else
  118244. r[count*b->dim+k]=val;
  118245. indexdiv*=quantvals;
  118246. }
  118247. count++;
  118248. }
  118249. }
  118250. break;
  118251. case 2:
  118252. for(j=0;j<b->entries;j++){
  118253. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118254. float last=0.f;
  118255. for(k=0;k<b->dim;k++){
  118256. float val=b->quantlist[j*b->dim+k];
  118257. val=fabs(val)*delta+mindel+last;
  118258. if(b->q_sequencep)last=val;
  118259. if(sparsemap)
  118260. r[sparsemap[count]*b->dim+k]=val;
  118261. else
  118262. r[count*b->dim+k]=val;
  118263. }
  118264. count++;
  118265. }
  118266. }
  118267. break;
  118268. }
  118269. return(r);
  118270. }
  118271. return(NULL);
  118272. }
  118273. void vorbis_staticbook_clear(static_codebook *b){
  118274. if(b->allocedp){
  118275. if(b->quantlist)_ogg_free(b->quantlist);
  118276. if(b->lengthlist)_ogg_free(b->lengthlist);
  118277. if(b->nearest_tree){
  118278. _ogg_free(b->nearest_tree->ptr0);
  118279. _ogg_free(b->nearest_tree->ptr1);
  118280. _ogg_free(b->nearest_tree->p);
  118281. _ogg_free(b->nearest_tree->q);
  118282. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118283. _ogg_free(b->nearest_tree);
  118284. }
  118285. if(b->thresh_tree){
  118286. _ogg_free(b->thresh_tree->quantthresh);
  118287. _ogg_free(b->thresh_tree->quantmap);
  118288. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118289. _ogg_free(b->thresh_tree);
  118290. }
  118291. memset(b,0,sizeof(*b));
  118292. }
  118293. }
  118294. void vorbis_staticbook_destroy(static_codebook *b){
  118295. if(b->allocedp){
  118296. vorbis_staticbook_clear(b);
  118297. _ogg_free(b);
  118298. }
  118299. }
  118300. void vorbis_book_clear(codebook *b){
  118301. /* static book is not cleared; we're likely called on the lookup and
  118302. the static codebook belongs to the info struct */
  118303. if(b->valuelist)_ogg_free(b->valuelist);
  118304. if(b->codelist)_ogg_free(b->codelist);
  118305. if(b->dec_index)_ogg_free(b->dec_index);
  118306. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118307. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118308. memset(b,0,sizeof(*b));
  118309. }
  118310. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118311. memset(c,0,sizeof(*c));
  118312. c->c=s;
  118313. c->entries=s->entries;
  118314. c->used_entries=s->entries;
  118315. c->dim=s->dim;
  118316. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118317. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118318. return(0);
  118319. }
  118320. static int sort32a(const void *a,const void *b){
  118321. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118322. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118323. }
  118324. /* decode codebook arrangement is more heavily optimized than encode */
  118325. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118326. int i,j,n=0,tabn;
  118327. int *sortindex;
  118328. memset(c,0,sizeof(*c));
  118329. /* count actually used entries */
  118330. for(i=0;i<s->entries;i++)
  118331. if(s->lengthlist[i]>0)
  118332. n++;
  118333. c->entries=s->entries;
  118334. c->used_entries=n;
  118335. c->dim=s->dim;
  118336. /* two different remappings go on here.
  118337. First, we collapse the likely sparse codebook down only to
  118338. actually represented values/words. This collapsing needs to be
  118339. indexed as map-valueless books are used to encode original entry
  118340. positions as integers.
  118341. Second, we reorder all vectors, including the entry index above,
  118342. by sorted bitreversed codeword to allow treeless decode. */
  118343. {
  118344. /* perform sort */
  118345. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118346. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118347. if(codes==NULL)goto err_out;
  118348. for(i=0;i<n;i++){
  118349. codes[i]=ogg_bitreverse(codes[i]);
  118350. codep[i]=codes+i;
  118351. }
  118352. qsort(codep,n,sizeof(*codep),sort32a);
  118353. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118354. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118355. /* the index is a reverse index */
  118356. for(i=0;i<n;i++){
  118357. int position=codep[i]-codes;
  118358. sortindex[position]=i;
  118359. }
  118360. for(i=0;i<n;i++)
  118361. c->codelist[sortindex[i]]=codes[i];
  118362. _ogg_free(codes);
  118363. }
  118364. c->valuelist=_book_unquantize(s,n,sortindex);
  118365. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118366. for(n=0,i=0;i<s->entries;i++)
  118367. if(s->lengthlist[i]>0)
  118368. c->dec_index[sortindex[n++]]=i;
  118369. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118370. for(n=0,i=0;i<s->entries;i++)
  118371. if(s->lengthlist[i]>0)
  118372. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118373. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118374. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118375. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118376. tabn=1<<c->dec_firsttablen;
  118377. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118378. c->dec_maxlength=0;
  118379. for(i=0;i<n;i++){
  118380. if(c->dec_maxlength<c->dec_codelengths[i])
  118381. c->dec_maxlength=c->dec_codelengths[i];
  118382. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118383. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118384. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118385. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118386. }
  118387. }
  118388. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118389. hints for the non-direct-hits */
  118390. {
  118391. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118392. long lo=0,hi=0;
  118393. for(i=0;i<tabn;i++){
  118394. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118395. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118396. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118397. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118398. /* we only actually have 15 bits per hint to play with here.
  118399. In order to overflow gracefully (nothing breaks, efficiency
  118400. just drops), encode as the difference from the extremes. */
  118401. {
  118402. unsigned long loval=lo;
  118403. unsigned long hival=n-hi;
  118404. if(loval>0x7fff)loval=0x7fff;
  118405. if(hival>0x7fff)hival=0x7fff;
  118406. c->dec_firsttable[ogg_bitreverse(word)]=
  118407. 0x80000000UL | (loval<<15) | hival;
  118408. }
  118409. }
  118410. }
  118411. }
  118412. return(0);
  118413. err_out:
  118414. vorbis_book_clear(c);
  118415. return(-1);
  118416. }
  118417. static float _dist(int el,float *ref, float *b,int step){
  118418. int i;
  118419. float acc=0.f;
  118420. for(i=0;i<el;i++){
  118421. float val=(ref[i]-b[i*step]);
  118422. acc+=val*val;
  118423. }
  118424. return(acc);
  118425. }
  118426. int _best(codebook *book, float *a, int step){
  118427. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118428. #if 0
  118429. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118430. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118431. #endif
  118432. int dim=book->dim;
  118433. int k,o;
  118434. /*int savebest=-1;
  118435. float saverr;*/
  118436. /* do we have a threshhold encode hint? */
  118437. if(tt){
  118438. int index=0,i;
  118439. /* find the quant val of each scalar */
  118440. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118441. i=tt->threshvals>>1;
  118442. if(a[o]<tt->quantthresh[i]){
  118443. for(;i>0;i--)
  118444. if(a[o]>=tt->quantthresh[i-1])
  118445. break;
  118446. }else{
  118447. for(i++;i<tt->threshvals-1;i++)
  118448. if(a[o]<tt->quantthresh[i])break;
  118449. }
  118450. index=(index*tt->quantvals)+tt->quantmap[i];
  118451. }
  118452. /* regular lattices are easy :-) */
  118453. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118454. use a decision tree after all
  118455. and fall through*/
  118456. return(index);
  118457. }
  118458. #if 0
  118459. /* do we have a pigeonhole encode hint? */
  118460. if(pt){
  118461. const static_codebook *c=book->c;
  118462. int i,besti=-1;
  118463. float best=0.f;
  118464. int entry=0;
  118465. /* dealing with sequentialness is a pain in the ass */
  118466. if(c->q_sequencep){
  118467. int pv;
  118468. long mul=1;
  118469. float qlast=0;
  118470. for(k=0,o=0;k<dim;k++,o+=step){
  118471. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118472. if(pv<0 || pv>=pt->mapentries)break;
  118473. entry+=pt->pigeonmap[pv]*mul;
  118474. mul*=pt->quantvals;
  118475. qlast+=pv*pt->del+pt->min;
  118476. }
  118477. }else{
  118478. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118479. int pv=(int)((a[o]-pt->min)/pt->del);
  118480. if(pv<0 || pv>=pt->mapentries)break;
  118481. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118482. }
  118483. }
  118484. /* must be within the pigeonholable range; if we quant outside (or
  118485. in an entry that we define no list for), brute force it */
  118486. if(k==dim && pt->fitlength[entry]){
  118487. /* search the abbreviated list */
  118488. long *list=pt->fitlist+pt->fitmap[entry];
  118489. for(i=0;i<pt->fitlength[entry];i++){
  118490. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118491. if(besti==-1 || this<best){
  118492. best=this;
  118493. besti=list[i];
  118494. }
  118495. }
  118496. return(besti);
  118497. }
  118498. }
  118499. if(nt){
  118500. /* optimized using the decision tree */
  118501. while(1){
  118502. float c=0.f;
  118503. float *p=book->valuelist+nt->p[ptr];
  118504. float *q=book->valuelist+nt->q[ptr];
  118505. for(k=0,o=0;k<dim;k++,o+=step)
  118506. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118507. if(c>0.f) /* in A */
  118508. ptr= -nt->ptr0[ptr];
  118509. else /* in B */
  118510. ptr= -nt->ptr1[ptr];
  118511. if(ptr<=0)break;
  118512. }
  118513. return(-ptr);
  118514. }
  118515. #endif
  118516. /* brute force it! */
  118517. {
  118518. const static_codebook *c=book->c;
  118519. int i,besti=-1;
  118520. float best=0.f;
  118521. float *e=book->valuelist;
  118522. for(i=0;i<book->entries;i++){
  118523. if(c->lengthlist[i]>0){
  118524. float thisx=_dist(dim,e,a,step);
  118525. if(besti==-1 || thisx<best){
  118526. best=thisx;
  118527. besti=i;
  118528. }
  118529. }
  118530. e+=dim;
  118531. }
  118532. /*if(savebest!=-1 && savebest!=besti){
  118533. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118534. "original:");
  118535. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118536. fprintf(stderr,"\n"
  118537. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118538. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118539. (book->valuelist+savebest*dim)[i]);
  118540. fprintf(stderr,"\n"
  118541. "bruteforce (entry %d, err %g):",besti,best);
  118542. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118543. (book->valuelist+besti*dim)[i]);
  118544. fprintf(stderr,"\n");
  118545. }*/
  118546. return(besti);
  118547. }
  118548. }
  118549. long vorbis_book_codeword(codebook *book,int entry){
  118550. if(book->c) /* only use with encode; decode optimizations are
  118551. allowed to break this */
  118552. return book->codelist[entry];
  118553. return -1;
  118554. }
  118555. long vorbis_book_codelen(codebook *book,int entry){
  118556. if(book->c) /* only use with encode; decode optimizations are
  118557. allowed to break this */
  118558. return book->c->lengthlist[entry];
  118559. return -1;
  118560. }
  118561. #ifdef _V_SELFTEST
  118562. /* Unit tests of the dequantizer; this stuff will be OK
  118563. cross-platform, I simply want to be sure that special mapping cases
  118564. actually work properly; a bug could go unnoticed for a while */
  118565. #include <stdio.h>
  118566. /* cases:
  118567. no mapping
  118568. full, explicit mapping
  118569. algorithmic mapping
  118570. nonsequential
  118571. sequential
  118572. */
  118573. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118574. static long partial_quantlist1[]={0,7,2};
  118575. /* no mapping */
  118576. static_codebook test1={
  118577. 4,16,
  118578. NULL,
  118579. 0,
  118580. 0,0,0,0,
  118581. NULL,
  118582. NULL,NULL
  118583. };
  118584. static float *test1_result=NULL;
  118585. /* linear, full mapping, nonsequential */
  118586. static_codebook test2={
  118587. 4,3,
  118588. NULL,
  118589. 2,
  118590. -533200896,1611661312,4,0,
  118591. full_quantlist1,
  118592. NULL,NULL
  118593. };
  118594. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118595. /* linear, full mapping, sequential */
  118596. static_codebook test3={
  118597. 4,3,
  118598. NULL,
  118599. 2,
  118600. -533200896,1611661312,4,1,
  118601. full_quantlist1,
  118602. NULL,NULL
  118603. };
  118604. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118605. /* linear, algorithmic mapping, nonsequential */
  118606. static_codebook test4={
  118607. 3,27,
  118608. NULL,
  118609. 1,
  118610. -533200896,1611661312,4,0,
  118611. partial_quantlist1,
  118612. NULL,NULL
  118613. };
  118614. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118615. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118616. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118617. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118618. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118619. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118620. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118621. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118622. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118623. /* linear, algorithmic mapping, sequential */
  118624. static_codebook test5={
  118625. 3,27,
  118626. NULL,
  118627. 1,
  118628. -533200896,1611661312,4,1,
  118629. partial_quantlist1,
  118630. NULL,NULL
  118631. };
  118632. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118633. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118634. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118635. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118636. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118637. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118638. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118639. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118640. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118641. void run_test(static_codebook *b,float *comp){
  118642. float *out=_book_unquantize(b,b->entries,NULL);
  118643. int i;
  118644. if(comp){
  118645. if(!out){
  118646. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118647. exit(1);
  118648. }
  118649. for(i=0;i<b->entries*b->dim;i++)
  118650. if(fabs(out[i]-comp[i])>.0001){
  118651. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118652. "position %d, %g != %g\n",i,out[i],comp[i]);
  118653. exit(1);
  118654. }
  118655. }else{
  118656. if(out){
  118657. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118658. " correct result should have been NULL\n");
  118659. exit(1);
  118660. }
  118661. }
  118662. }
  118663. int main(){
  118664. /* run the nine dequant tests, and compare to the hand-rolled results */
  118665. fprintf(stderr,"Dequant test 1... ");
  118666. run_test(&test1,test1_result);
  118667. fprintf(stderr,"OK\nDequant test 2... ");
  118668. run_test(&test2,test2_result);
  118669. fprintf(stderr,"OK\nDequant test 3... ");
  118670. run_test(&test3,test3_result);
  118671. fprintf(stderr,"OK\nDequant test 4... ");
  118672. run_test(&test4,test4_result);
  118673. fprintf(stderr,"OK\nDequant test 5... ");
  118674. run_test(&test5,test5_result);
  118675. fprintf(stderr,"OK\n\n");
  118676. return(0);
  118677. }
  118678. #endif
  118679. #endif
  118680. /*** End of inlined file: sharedbook.c ***/
  118681. /*** Start of inlined file: smallft.c ***/
  118682. /* FFT implementation from OggSquish, minus cosine transforms,
  118683. * minus all but radix 2/4 case. In Vorbis we only need this
  118684. * cut-down version.
  118685. *
  118686. * To do more than just power-of-two sized vectors, see the full
  118687. * version I wrote for NetLib.
  118688. *
  118689. * Note that the packing is a little strange; rather than the FFT r/i
  118690. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118691. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118692. * FORTRAN version
  118693. */
  118694. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118695. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118696. // tasks..
  118697. #if JUCE_MSVC
  118698. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118699. #endif
  118700. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118701. #if JUCE_USE_OGGVORBIS
  118702. #include <stdlib.h>
  118703. #include <string.h>
  118704. #include <math.h>
  118705. static void drfti1(int n, float *wa, int *ifac){
  118706. static int ntryh[4] = { 4,2,3,5 };
  118707. static float tpi = 6.28318530717958648f;
  118708. float arg,argh,argld,fi;
  118709. int ntry=0,i,j=-1;
  118710. int k1, l1, l2, ib;
  118711. int ld, ii, ip, is, nq, nr;
  118712. int ido, ipm, nfm1;
  118713. int nl=n;
  118714. int nf=0;
  118715. L101:
  118716. j++;
  118717. if (j < 4)
  118718. ntry=ntryh[j];
  118719. else
  118720. ntry+=2;
  118721. L104:
  118722. nq=nl/ntry;
  118723. nr=nl-ntry*nq;
  118724. if (nr!=0) goto L101;
  118725. nf++;
  118726. ifac[nf+1]=ntry;
  118727. nl=nq;
  118728. if(ntry!=2)goto L107;
  118729. if(nf==1)goto L107;
  118730. for (i=1;i<nf;i++){
  118731. ib=nf-i+1;
  118732. ifac[ib+1]=ifac[ib];
  118733. }
  118734. ifac[2] = 2;
  118735. L107:
  118736. if(nl!=1)goto L104;
  118737. ifac[0]=n;
  118738. ifac[1]=nf;
  118739. argh=tpi/n;
  118740. is=0;
  118741. nfm1=nf-1;
  118742. l1=1;
  118743. if(nfm1==0)return;
  118744. for (k1=0;k1<nfm1;k1++){
  118745. ip=ifac[k1+2];
  118746. ld=0;
  118747. l2=l1*ip;
  118748. ido=n/l2;
  118749. ipm=ip-1;
  118750. for (j=0;j<ipm;j++){
  118751. ld+=l1;
  118752. i=is;
  118753. argld=(float)ld*argh;
  118754. fi=0.f;
  118755. for (ii=2;ii<ido;ii+=2){
  118756. fi+=1.f;
  118757. arg=fi*argld;
  118758. wa[i++]=cos(arg);
  118759. wa[i++]=sin(arg);
  118760. }
  118761. is+=ido;
  118762. }
  118763. l1=l2;
  118764. }
  118765. }
  118766. static void fdrffti(int n, float *wsave, int *ifac){
  118767. if (n == 1) return;
  118768. drfti1(n, wsave+n, ifac);
  118769. }
  118770. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118771. int i,k;
  118772. float ti2,tr2;
  118773. int t0,t1,t2,t3,t4,t5,t6;
  118774. t1=0;
  118775. t0=(t2=l1*ido);
  118776. t3=ido<<1;
  118777. for(k=0;k<l1;k++){
  118778. ch[t1<<1]=cc[t1]+cc[t2];
  118779. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118780. t1+=ido;
  118781. t2+=ido;
  118782. }
  118783. if(ido<2)return;
  118784. if(ido==2)goto L105;
  118785. t1=0;
  118786. t2=t0;
  118787. for(k=0;k<l1;k++){
  118788. t3=t2;
  118789. t4=(t1<<1)+(ido<<1);
  118790. t5=t1;
  118791. t6=t1+t1;
  118792. for(i=2;i<ido;i+=2){
  118793. t3+=2;
  118794. t4-=2;
  118795. t5+=2;
  118796. t6+=2;
  118797. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118798. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118799. ch[t6]=cc[t5]+ti2;
  118800. ch[t4]=ti2-cc[t5];
  118801. ch[t6-1]=cc[t5-1]+tr2;
  118802. ch[t4-1]=cc[t5-1]-tr2;
  118803. }
  118804. t1+=ido;
  118805. t2+=ido;
  118806. }
  118807. if(ido%2==1)return;
  118808. L105:
  118809. t3=(t2=(t1=ido)-1);
  118810. t2+=t0;
  118811. for(k=0;k<l1;k++){
  118812. ch[t1]=-cc[t2];
  118813. ch[t1-1]=cc[t3];
  118814. t1+=ido<<1;
  118815. t2+=ido;
  118816. t3+=ido;
  118817. }
  118818. }
  118819. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  118820. float *wa2,float *wa3){
  118821. static float hsqt2 = .70710678118654752f;
  118822. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118823. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  118824. t0=l1*ido;
  118825. t1=t0;
  118826. t4=t1<<1;
  118827. t2=t1+(t1<<1);
  118828. t3=0;
  118829. for(k=0;k<l1;k++){
  118830. tr1=cc[t1]+cc[t2];
  118831. tr2=cc[t3]+cc[t4];
  118832. ch[t5=t3<<2]=tr1+tr2;
  118833. ch[(ido<<2)+t5-1]=tr2-tr1;
  118834. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  118835. ch[t5]=cc[t2]-cc[t1];
  118836. t1+=ido;
  118837. t2+=ido;
  118838. t3+=ido;
  118839. t4+=ido;
  118840. }
  118841. if(ido<2)return;
  118842. if(ido==2)goto L105;
  118843. t1=0;
  118844. for(k=0;k<l1;k++){
  118845. t2=t1;
  118846. t4=t1<<2;
  118847. t5=(t6=ido<<1)+t4;
  118848. for(i=2;i<ido;i+=2){
  118849. t3=(t2+=2);
  118850. t4+=2;
  118851. t5-=2;
  118852. t3+=t0;
  118853. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118854. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118855. t3+=t0;
  118856. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  118857. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  118858. t3+=t0;
  118859. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  118860. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  118861. tr1=cr2+cr4;
  118862. tr4=cr4-cr2;
  118863. ti1=ci2+ci4;
  118864. ti4=ci2-ci4;
  118865. ti2=cc[t2]+ci3;
  118866. ti3=cc[t2]-ci3;
  118867. tr2=cc[t2-1]+cr3;
  118868. tr3=cc[t2-1]-cr3;
  118869. ch[t4-1]=tr1+tr2;
  118870. ch[t4]=ti1+ti2;
  118871. ch[t5-1]=tr3-ti4;
  118872. ch[t5]=tr4-ti3;
  118873. ch[t4+t6-1]=ti4+tr3;
  118874. ch[t4+t6]=tr4+ti3;
  118875. ch[t5+t6-1]=tr2-tr1;
  118876. ch[t5+t6]=ti1-ti2;
  118877. }
  118878. t1+=ido;
  118879. }
  118880. if(ido&1)return;
  118881. L105:
  118882. t2=(t1=t0+ido-1)+(t0<<1);
  118883. t3=ido<<2;
  118884. t4=ido;
  118885. t5=ido<<1;
  118886. t6=ido;
  118887. for(k=0;k<l1;k++){
  118888. ti1=-hsqt2*(cc[t1]+cc[t2]);
  118889. tr1=hsqt2*(cc[t1]-cc[t2]);
  118890. ch[t4-1]=tr1+cc[t6-1];
  118891. ch[t4+t5-1]=cc[t6-1]-tr1;
  118892. ch[t4]=ti1-cc[t1+t0];
  118893. ch[t4+t5]=ti1+cc[t1+t0];
  118894. t1+=ido;
  118895. t2+=ido;
  118896. t4+=t3;
  118897. t6+=ido;
  118898. }
  118899. }
  118900. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  118901. float *c2,float *ch,float *ch2,float *wa){
  118902. static float tpi=6.283185307179586f;
  118903. int idij,ipph,i,j,k,l,ic,ik,is;
  118904. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118905. float dc2,ai1,ai2,ar1,ar2,ds2;
  118906. int nbd;
  118907. float dcp,arg,dsp,ar1h,ar2h;
  118908. int idp2,ipp2;
  118909. arg=tpi/(float)ip;
  118910. dcp=cos(arg);
  118911. dsp=sin(arg);
  118912. ipph=(ip+1)>>1;
  118913. ipp2=ip;
  118914. idp2=ido;
  118915. nbd=(ido-1)>>1;
  118916. t0=l1*ido;
  118917. t10=ip*ido;
  118918. if(ido==1)goto L119;
  118919. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  118920. t1=0;
  118921. for(j=1;j<ip;j++){
  118922. t1+=t0;
  118923. t2=t1;
  118924. for(k=0;k<l1;k++){
  118925. ch[t2]=c1[t2];
  118926. t2+=ido;
  118927. }
  118928. }
  118929. is=-ido;
  118930. t1=0;
  118931. if(nbd>l1){
  118932. for(j=1;j<ip;j++){
  118933. t1+=t0;
  118934. is+=ido;
  118935. t2= -ido+t1;
  118936. for(k=0;k<l1;k++){
  118937. idij=is-1;
  118938. t2+=ido;
  118939. t3=t2;
  118940. for(i=2;i<ido;i+=2){
  118941. idij+=2;
  118942. t3+=2;
  118943. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118944. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118945. }
  118946. }
  118947. }
  118948. }else{
  118949. for(j=1;j<ip;j++){
  118950. is+=ido;
  118951. idij=is-1;
  118952. t1+=t0;
  118953. t2=t1;
  118954. for(i=2;i<ido;i+=2){
  118955. idij+=2;
  118956. t2+=2;
  118957. t3=t2;
  118958. for(k=0;k<l1;k++){
  118959. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118960. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118961. t3+=ido;
  118962. }
  118963. }
  118964. }
  118965. }
  118966. t1=0;
  118967. t2=ipp2*t0;
  118968. if(nbd<l1){
  118969. for(j=1;j<ipph;j++){
  118970. t1+=t0;
  118971. t2-=t0;
  118972. t3=t1;
  118973. t4=t2;
  118974. for(i=2;i<ido;i+=2){
  118975. t3+=2;
  118976. t4+=2;
  118977. t5=t3-ido;
  118978. t6=t4-ido;
  118979. for(k=0;k<l1;k++){
  118980. t5+=ido;
  118981. t6+=ido;
  118982. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118983. c1[t6-1]=ch[t5]-ch[t6];
  118984. c1[t5]=ch[t5]+ch[t6];
  118985. c1[t6]=ch[t6-1]-ch[t5-1];
  118986. }
  118987. }
  118988. }
  118989. }else{
  118990. for(j=1;j<ipph;j++){
  118991. t1+=t0;
  118992. t2-=t0;
  118993. t3=t1;
  118994. t4=t2;
  118995. for(k=0;k<l1;k++){
  118996. t5=t3;
  118997. t6=t4;
  118998. for(i=2;i<ido;i+=2){
  118999. t5+=2;
  119000. t6+=2;
  119001. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119002. c1[t6-1]=ch[t5]-ch[t6];
  119003. c1[t5]=ch[t5]+ch[t6];
  119004. c1[t6]=ch[t6-1]-ch[t5-1];
  119005. }
  119006. t3+=ido;
  119007. t4+=ido;
  119008. }
  119009. }
  119010. }
  119011. L119:
  119012. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119013. t1=0;
  119014. t2=ipp2*idl1;
  119015. for(j=1;j<ipph;j++){
  119016. t1+=t0;
  119017. t2-=t0;
  119018. t3=t1-ido;
  119019. t4=t2-ido;
  119020. for(k=0;k<l1;k++){
  119021. t3+=ido;
  119022. t4+=ido;
  119023. c1[t3]=ch[t3]+ch[t4];
  119024. c1[t4]=ch[t4]-ch[t3];
  119025. }
  119026. }
  119027. ar1=1.f;
  119028. ai1=0.f;
  119029. t1=0;
  119030. t2=ipp2*idl1;
  119031. t3=(ip-1)*idl1;
  119032. for(l=1;l<ipph;l++){
  119033. t1+=idl1;
  119034. t2-=idl1;
  119035. ar1h=dcp*ar1-dsp*ai1;
  119036. ai1=dcp*ai1+dsp*ar1;
  119037. ar1=ar1h;
  119038. t4=t1;
  119039. t5=t2;
  119040. t6=t3;
  119041. t7=idl1;
  119042. for(ik=0;ik<idl1;ik++){
  119043. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119044. ch2[t5++]=ai1*c2[t6++];
  119045. }
  119046. dc2=ar1;
  119047. ds2=ai1;
  119048. ar2=ar1;
  119049. ai2=ai1;
  119050. t4=idl1;
  119051. t5=(ipp2-1)*idl1;
  119052. for(j=2;j<ipph;j++){
  119053. t4+=idl1;
  119054. t5-=idl1;
  119055. ar2h=dc2*ar2-ds2*ai2;
  119056. ai2=dc2*ai2+ds2*ar2;
  119057. ar2=ar2h;
  119058. t6=t1;
  119059. t7=t2;
  119060. t8=t4;
  119061. t9=t5;
  119062. for(ik=0;ik<idl1;ik++){
  119063. ch2[t6++]+=ar2*c2[t8++];
  119064. ch2[t7++]+=ai2*c2[t9++];
  119065. }
  119066. }
  119067. }
  119068. t1=0;
  119069. for(j=1;j<ipph;j++){
  119070. t1+=idl1;
  119071. t2=t1;
  119072. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119073. }
  119074. if(ido<l1)goto L132;
  119075. t1=0;
  119076. t2=0;
  119077. for(k=0;k<l1;k++){
  119078. t3=t1;
  119079. t4=t2;
  119080. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119081. t1+=ido;
  119082. t2+=t10;
  119083. }
  119084. goto L135;
  119085. L132:
  119086. for(i=0;i<ido;i++){
  119087. t1=i;
  119088. t2=i;
  119089. for(k=0;k<l1;k++){
  119090. cc[t2]=ch[t1];
  119091. t1+=ido;
  119092. t2+=t10;
  119093. }
  119094. }
  119095. L135:
  119096. t1=0;
  119097. t2=ido<<1;
  119098. t3=0;
  119099. t4=ipp2*t0;
  119100. for(j=1;j<ipph;j++){
  119101. t1+=t2;
  119102. t3+=t0;
  119103. t4-=t0;
  119104. t5=t1;
  119105. t6=t3;
  119106. t7=t4;
  119107. for(k=0;k<l1;k++){
  119108. cc[t5-1]=ch[t6];
  119109. cc[t5]=ch[t7];
  119110. t5+=t10;
  119111. t6+=ido;
  119112. t7+=ido;
  119113. }
  119114. }
  119115. if(ido==1)return;
  119116. if(nbd<l1)goto L141;
  119117. t1=-ido;
  119118. t3=0;
  119119. t4=0;
  119120. t5=ipp2*t0;
  119121. for(j=1;j<ipph;j++){
  119122. t1+=t2;
  119123. t3+=t2;
  119124. t4+=t0;
  119125. t5-=t0;
  119126. t6=t1;
  119127. t7=t3;
  119128. t8=t4;
  119129. t9=t5;
  119130. for(k=0;k<l1;k++){
  119131. for(i=2;i<ido;i+=2){
  119132. ic=idp2-i;
  119133. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119134. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119135. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119136. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119137. }
  119138. t6+=t10;
  119139. t7+=t10;
  119140. t8+=ido;
  119141. t9+=ido;
  119142. }
  119143. }
  119144. return;
  119145. L141:
  119146. t1=-ido;
  119147. t3=0;
  119148. t4=0;
  119149. t5=ipp2*t0;
  119150. for(j=1;j<ipph;j++){
  119151. t1+=t2;
  119152. t3+=t2;
  119153. t4+=t0;
  119154. t5-=t0;
  119155. for(i=2;i<ido;i+=2){
  119156. t6=idp2+t1-i;
  119157. t7=i+t3;
  119158. t8=i+t4;
  119159. t9=i+t5;
  119160. for(k=0;k<l1;k++){
  119161. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119162. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119163. cc[t7]=ch[t8]+ch[t9];
  119164. cc[t6]=ch[t9]-ch[t8];
  119165. t6+=t10;
  119166. t7+=t10;
  119167. t8+=ido;
  119168. t9+=ido;
  119169. }
  119170. }
  119171. }
  119172. }
  119173. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119174. int i,k1,l1,l2;
  119175. int na,kh,nf;
  119176. int ip,iw,ido,idl1,ix2,ix3;
  119177. nf=ifac[1];
  119178. na=1;
  119179. l2=n;
  119180. iw=n;
  119181. for(k1=0;k1<nf;k1++){
  119182. kh=nf-k1;
  119183. ip=ifac[kh+1];
  119184. l1=l2/ip;
  119185. ido=n/l2;
  119186. idl1=ido*l1;
  119187. iw-=(ip-1)*ido;
  119188. na=1-na;
  119189. if(ip!=4)goto L102;
  119190. ix2=iw+ido;
  119191. ix3=ix2+ido;
  119192. if(na!=0)
  119193. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119194. else
  119195. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119196. goto L110;
  119197. L102:
  119198. if(ip!=2)goto L104;
  119199. if(na!=0)goto L103;
  119200. dradf2(ido,l1,c,ch,wa+iw-1);
  119201. goto L110;
  119202. L103:
  119203. dradf2(ido,l1,ch,c,wa+iw-1);
  119204. goto L110;
  119205. L104:
  119206. if(ido==1)na=1-na;
  119207. if(na!=0)goto L109;
  119208. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119209. na=1;
  119210. goto L110;
  119211. L109:
  119212. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119213. na=0;
  119214. L110:
  119215. l2=l1;
  119216. }
  119217. if(na==1)return;
  119218. for(i=0;i<n;i++)c[i]=ch[i];
  119219. }
  119220. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119221. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119222. float ti2,tr2;
  119223. t0=l1*ido;
  119224. t1=0;
  119225. t2=0;
  119226. t3=(ido<<1)-1;
  119227. for(k=0;k<l1;k++){
  119228. ch[t1]=cc[t2]+cc[t3+t2];
  119229. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119230. t2=(t1+=ido)<<1;
  119231. }
  119232. if(ido<2)return;
  119233. if(ido==2)goto L105;
  119234. t1=0;
  119235. t2=0;
  119236. for(k=0;k<l1;k++){
  119237. t3=t1;
  119238. t5=(t4=t2)+(ido<<1);
  119239. t6=t0+t1;
  119240. for(i=2;i<ido;i+=2){
  119241. t3+=2;
  119242. t4+=2;
  119243. t5-=2;
  119244. t6+=2;
  119245. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119246. tr2=cc[t4-1]-cc[t5-1];
  119247. ch[t3]=cc[t4]-cc[t5];
  119248. ti2=cc[t4]+cc[t5];
  119249. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119250. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119251. }
  119252. t2=(t1+=ido)<<1;
  119253. }
  119254. if(ido%2==1)return;
  119255. L105:
  119256. t1=ido-1;
  119257. t2=ido-1;
  119258. for(k=0;k<l1;k++){
  119259. ch[t1]=cc[t2]+cc[t2];
  119260. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119261. t1+=ido;
  119262. t2+=ido<<1;
  119263. }
  119264. }
  119265. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119266. float *wa2){
  119267. static float taur = -.5f;
  119268. static float taui = .8660254037844386f;
  119269. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119270. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119271. t0=l1*ido;
  119272. t1=0;
  119273. t2=t0<<1;
  119274. t3=ido<<1;
  119275. t4=ido+(ido<<1);
  119276. t5=0;
  119277. for(k=0;k<l1;k++){
  119278. tr2=cc[t3-1]+cc[t3-1];
  119279. cr2=cc[t5]+(taur*tr2);
  119280. ch[t1]=cc[t5]+tr2;
  119281. ci3=taui*(cc[t3]+cc[t3]);
  119282. ch[t1+t0]=cr2-ci3;
  119283. ch[t1+t2]=cr2+ci3;
  119284. t1+=ido;
  119285. t3+=t4;
  119286. t5+=t4;
  119287. }
  119288. if(ido==1)return;
  119289. t1=0;
  119290. t3=ido<<1;
  119291. for(k=0;k<l1;k++){
  119292. t7=t1+(t1<<1);
  119293. t6=(t5=t7+t3);
  119294. t8=t1;
  119295. t10=(t9=t1+t0)+t0;
  119296. for(i=2;i<ido;i+=2){
  119297. t5+=2;
  119298. t6-=2;
  119299. t7+=2;
  119300. t8+=2;
  119301. t9+=2;
  119302. t10+=2;
  119303. tr2=cc[t5-1]+cc[t6-1];
  119304. cr2=cc[t7-1]+(taur*tr2);
  119305. ch[t8-1]=cc[t7-1]+tr2;
  119306. ti2=cc[t5]-cc[t6];
  119307. ci2=cc[t7]+(taur*ti2);
  119308. ch[t8]=cc[t7]+ti2;
  119309. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119310. ci3=taui*(cc[t5]+cc[t6]);
  119311. dr2=cr2-ci3;
  119312. dr3=cr2+ci3;
  119313. di2=ci2+cr3;
  119314. di3=ci2-cr3;
  119315. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119316. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119317. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119318. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119319. }
  119320. t1+=ido;
  119321. }
  119322. }
  119323. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119324. float *wa2,float *wa3){
  119325. static float sqrt2=1.414213562373095f;
  119326. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119327. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119328. t0=l1*ido;
  119329. t1=0;
  119330. t2=ido<<2;
  119331. t3=0;
  119332. t6=ido<<1;
  119333. for(k=0;k<l1;k++){
  119334. t4=t3+t6;
  119335. t5=t1;
  119336. tr3=cc[t4-1]+cc[t4-1];
  119337. tr4=cc[t4]+cc[t4];
  119338. tr1=cc[t3]-cc[(t4+=t6)-1];
  119339. tr2=cc[t3]+cc[t4-1];
  119340. ch[t5]=tr2+tr3;
  119341. ch[t5+=t0]=tr1-tr4;
  119342. ch[t5+=t0]=tr2-tr3;
  119343. ch[t5+=t0]=tr1+tr4;
  119344. t1+=ido;
  119345. t3+=t2;
  119346. }
  119347. if(ido<2)return;
  119348. if(ido==2)goto L105;
  119349. t1=0;
  119350. for(k=0;k<l1;k++){
  119351. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119352. t7=t1;
  119353. for(i=2;i<ido;i+=2){
  119354. t2+=2;
  119355. t3+=2;
  119356. t4-=2;
  119357. t5-=2;
  119358. t7+=2;
  119359. ti1=cc[t2]+cc[t5];
  119360. ti2=cc[t2]-cc[t5];
  119361. ti3=cc[t3]-cc[t4];
  119362. tr4=cc[t3]+cc[t4];
  119363. tr1=cc[t2-1]-cc[t5-1];
  119364. tr2=cc[t2-1]+cc[t5-1];
  119365. ti4=cc[t3-1]-cc[t4-1];
  119366. tr3=cc[t3-1]+cc[t4-1];
  119367. ch[t7-1]=tr2+tr3;
  119368. cr3=tr2-tr3;
  119369. ch[t7]=ti2+ti3;
  119370. ci3=ti2-ti3;
  119371. cr2=tr1-tr4;
  119372. cr4=tr1+tr4;
  119373. ci2=ti1+ti4;
  119374. ci4=ti1-ti4;
  119375. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119376. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119377. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119378. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119379. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119380. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119381. }
  119382. t1+=ido;
  119383. }
  119384. if(ido%2 == 1)return;
  119385. L105:
  119386. t1=ido;
  119387. t2=ido<<2;
  119388. t3=ido-1;
  119389. t4=ido+(ido<<1);
  119390. for(k=0;k<l1;k++){
  119391. t5=t3;
  119392. ti1=cc[t1]+cc[t4];
  119393. ti2=cc[t4]-cc[t1];
  119394. tr1=cc[t1-1]-cc[t4-1];
  119395. tr2=cc[t1-1]+cc[t4-1];
  119396. ch[t5]=tr2+tr2;
  119397. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119398. ch[t5+=t0]=ti2+ti2;
  119399. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119400. t3+=ido;
  119401. t1+=t2;
  119402. t4+=t2;
  119403. }
  119404. }
  119405. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119406. float *c2,float *ch,float *ch2,float *wa){
  119407. static float tpi=6.283185307179586f;
  119408. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119409. t11,t12;
  119410. float dc2,ai1,ai2,ar1,ar2,ds2;
  119411. int nbd;
  119412. float dcp,arg,dsp,ar1h,ar2h;
  119413. int ipp2;
  119414. t10=ip*ido;
  119415. t0=l1*ido;
  119416. arg=tpi/(float)ip;
  119417. dcp=cos(arg);
  119418. dsp=sin(arg);
  119419. nbd=(ido-1)>>1;
  119420. ipp2=ip;
  119421. ipph=(ip+1)>>1;
  119422. if(ido<l1)goto L103;
  119423. t1=0;
  119424. t2=0;
  119425. for(k=0;k<l1;k++){
  119426. t3=t1;
  119427. t4=t2;
  119428. for(i=0;i<ido;i++){
  119429. ch[t3]=cc[t4];
  119430. t3++;
  119431. t4++;
  119432. }
  119433. t1+=ido;
  119434. t2+=t10;
  119435. }
  119436. goto L106;
  119437. L103:
  119438. t1=0;
  119439. for(i=0;i<ido;i++){
  119440. t2=t1;
  119441. t3=t1;
  119442. for(k=0;k<l1;k++){
  119443. ch[t2]=cc[t3];
  119444. t2+=ido;
  119445. t3+=t10;
  119446. }
  119447. t1++;
  119448. }
  119449. L106:
  119450. t1=0;
  119451. t2=ipp2*t0;
  119452. t7=(t5=ido<<1);
  119453. for(j=1;j<ipph;j++){
  119454. t1+=t0;
  119455. t2-=t0;
  119456. t3=t1;
  119457. t4=t2;
  119458. t6=t5;
  119459. for(k=0;k<l1;k++){
  119460. ch[t3]=cc[t6-1]+cc[t6-1];
  119461. ch[t4]=cc[t6]+cc[t6];
  119462. t3+=ido;
  119463. t4+=ido;
  119464. t6+=t10;
  119465. }
  119466. t5+=t7;
  119467. }
  119468. if (ido == 1)goto L116;
  119469. if(nbd<l1)goto L112;
  119470. t1=0;
  119471. t2=ipp2*t0;
  119472. t7=0;
  119473. for(j=1;j<ipph;j++){
  119474. t1+=t0;
  119475. t2-=t0;
  119476. t3=t1;
  119477. t4=t2;
  119478. t7+=(ido<<1);
  119479. t8=t7;
  119480. for(k=0;k<l1;k++){
  119481. t5=t3;
  119482. t6=t4;
  119483. t9=t8;
  119484. t11=t8;
  119485. for(i=2;i<ido;i+=2){
  119486. t5+=2;
  119487. t6+=2;
  119488. t9+=2;
  119489. t11-=2;
  119490. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119491. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119492. ch[t5]=cc[t9]-cc[t11];
  119493. ch[t6]=cc[t9]+cc[t11];
  119494. }
  119495. t3+=ido;
  119496. t4+=ido;
  119497. t8+=t10;
  119498. }
  119499. }
  119500. goto L116;
  119501. L112:
  119502. t1=0;
  119503. t2=ipp2*t0;
  119504. t7=0;
  119505. for(j=1;j<ipph;j++){
  119506. t1+=t0;
  119507. t2-=t0;
  119508. t3=t1;
  119509. t4=t2;
  119510. t7+=(ido<<1);
  119511. t8=t7;
  119512. t9=t7;
  119513. for(i=2;i<ido;i+=2){
  119514. t3+=2;
  119515. t4+=2;
  119516. t8+=2;
  119517. t9-=2;
  119518. t5=t3;
  119519. t6=t4;
  119520. t11=t8;
  119521. t12=t9;
  119522. for(k=0;k<l1;k++){
  119523. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119524. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119525. ch[t5]=cc[t11]-cc[t12];
  119526. ch[t6]=cc[t11]+cc[t12];
  119527. t5+=ido;
  119528. t6+=ido;
  119529. t11+=t10;
  119530. t12+=t10;
  119531. }
  119532. }
  119533. }
  119534. L116:
  119535. ar1=1.f;
  119536. ai1=0.f;
  119537. t1=0;
  119538. t9=(t2=ipp2*idl1);
  119539. t3=(ip-1)*idl1;
  119540. for(l=1;l<ipph;l++){
  119541. t1+=idl1;
  119542. t2-=idl1;
  119543. ar1h=dcp*ar1-dsp*ai1;
  119544. ai1=dcp*ai1+dsp*ar1;
  119545. ar1=ar1h;
  119546. t4=t1;
  119547. t5=t2;
  119548. t6=0;
  119549. t7=idl1;
  119550. t8=t3;
  119551. for(ik=0;ik<idl1;ik++){
  119552. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119553. c2[t5++]=ai1*ch2[t8++];
  119554. }
  119555. dc2=ar1;
  119556. ds2=ai1;
  119557. ar2=ar1;
  119558. ai2=ai1;
  119559. t6=idl1;
  119560. t7=t9-idl1;
  119561. for(j=2;j<ipph;j++){
  119562. t6+=idl1;
  119563. t7-=idl1;
  119564. ar2h=dc2*ar2-ds2*ai2;
  119565. ai2=dc2*ai2+ds2*ar2;
  119566. ar2=ar2h;
  119567. t4=t1;
  119568. t5=t2;
  119569. t11=t6;
  119570. t12=t7;
  119571. for(ik=0;ik<idl1;ik++){
  119572. c2[t4++]+=ar2*ch2[t11++];
  119573. c2[t5++]+=ai2*ch2[t12++];
  119574. }
  119575. }
  119576. }
  119577. t1=0;
  119578. for(j=1;j<ipph;j++){
  119579. t1+=idl1;
  119580. t2=t1;
  119581. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119582. }
  119583. t1=0;
  119584. t2=ipp2*t0;
  119585. for(j=1;j<ipph;j++){
  119586. t1+=t0;
  119587. t2-=t0;
  119588. t3=t1;
  119589. t4=t2;
  119590. for(k=0;k<l1;k++){
  119591. ch[t3]=c1[t3]-c1[t4];
  119592. ch[t4]=c1[t3]+c1[t4];
  119593. t3+=ido;
  119594. t4+=ido;
  119595. }
  119596. }
  119597. if(ido==1)goto L132;
  119598. if(nbd<l1)goto L128;
  119599. t1=0;
  119600. t2=ipp2*t0;
  119601. for(j=1;j<ipph;j++){
  119602. t1+=t0;
  119603. t2-=t0;
  119604. t3=t1;
  119605. t4=t2;
  119606. for(k=0;k<l1;k++){
  119607. t5=t3;
  119608. t6=t4;
  119609. for(i=2;i<ido;i+=2){
  119610. t5+=2;
  119611. t6+=2;
  119612. ch[t5-1]=c1[t5-1]-c1[t6];
  119613. ch[t6-1]=c1[t5-1]+c1[t6];
  119614. ch[t5]=c1[t5]+c1[t6-1];
  119615. ch[t6]=c1[t5]-c1[t6-1];
  119616. }
  119617. t3+=ido;
  119618. t4+=ido;
  119619. }
  119620. }
  119621. goto L132;
  119622. L128:
  119623. t1=0;
  119624. t2=ipp2*t0;
  119625. for(j=1;j<ipph;j++){
  119626. t1+=t0;
  119627. t2-=t0;
  119628. t3=t1;
  119629. t4=t2;
  119630. for(i=2;i<ido;i+=2){
  119631. t3+=2;
  119632. t4+=2;
  119633. t5=t3;
  119634. t6=t4;
  119635. for(k=0;k<l1;k++){
  119636. ch[t5-1]=c1[t5-1]-c1[t6];
  119637. ch[t6-1]=c1[t5-1]+c1[t6];
  119638. ch[t5]=c1[t5]+c1[t6-1];
  119639. ch[t6]=c1[t5]-c1[t6-1];
  119640. t5+=ido;
  119641. t6+=ido;
  119642. }
  119643. }
  119644. }
  119645. L132:
  119646. if(ido==1)return;
  119647. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119648. t1=0;
  119649. for(j=1;j<ip;j++){
  119650. t2=(t1+=t0);
  119651. for(k=0;k<l1;k++){
  119652. c1[t2]=ch[t2];
  119653. t2+=ido;
  119654. }
  119655. }
  119656. if(nbd>l1)goto L139;
  119657. is= -ido-1;
  119658. t1=0;
  119659. for(j=1;j<ip;j++){
  119660. is+=ido;
  119661. t1+=t0;
  119662. idij=is;
  119663. t2=t1;
  119664. for(i=2;i<ido;i+=2){
  119665. t2+=2;
  119666. idij+=2;
  119667. t3=t2;
  119668. for(k=0;k<l1;k++){
  119669. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119670. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119671. t3+=ido;
  119672. }
  119673. }
  119674. }
  119675. return;
  119676. L139:
  119677. is= -ido-1;
  119678. t1=0;
  119679. for(j=1;j<ip;j++){
  119680. is+=ido;
  119681. t1+=t0;
  119682. t2=t1;
  119683. for(k=0;k<l1;k++){
  119684. idij=is;
  119685. t3=t2;
  119686. for(i=2;i<ido;i+=2){
  119687. idij+=2;
  119688. t3+=2;
  119689. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119690. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119691. }
  119692. t2+=ido;
  119693. }
  119694. }
  119695. }
  119696. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119697. int i,k1,l1,l2;
  119698. int na;
  119699. int nf,ip,iw,ix2,ix3,ido,idl1;
  119700. nf=ifac[1];
  119701. na=0;
  119702. l1=1;
  119703. iw=1;
  119704. for(k1=0;k1<nf;k1++){
  119705. ip=ifac[k1 + 2];
  119706. l2=ip*l1;
  119707. ido=n/l2;
  119708. idl1=ido*l1;
  119709. if(ip!=4)goto L103;
  119710. ix2=iw+ido;
  119711. ix3=ix2+ido;
  119712. if(na!=0)
  119713. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119714. else
  119715. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119716. na=1-na;
  119717. goto L115;
  119718. L103:
  119719. if(ip!=2)goto L106;
  119720. if(na!=0)
  119721. dradb2(ido,l1,ch,c,wa+iw-1);
  119722. else
  119723. dradb2(ido,l1,c,ch,wa+iw-1);
  119724. na=1-na;
  119725. goto L115;
  119726. L106:
  119727. if(ip!=3)goto L109;
  119728. ix2=iw+ido;
  119729. if(na!=0)
  119730. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119731. else
  119732. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119733. na=1-na;
  119734. goto L115;
  119735. L109:
  119736. /* The radix five case can be translated later..... */
  119737. /* if(ip!=5)goto L112;
  119738. ix2=iw+ido;
  119739. ix3=ix2+ido;
  119740. ix4=ix3+ido;
  119741. if(na!=0)
  119742. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119743. else
  119744. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119745. na=1-na;
  119746. goto L115;
  119747. L112:*/
  119748. if(na!=0)
  119749. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119750. else
  119751. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119752. if(ido==1)na=1-na;
  119753. L115:
  119754. l1=l2;
  119755. iw+=(ip-1)*ido;
  119756. }
  119757. if(na==0)return;
  119758. for(i=0;i<n;i++)c[i]=ch[i];
  119759. }
  119760. void drft_forward(drft_lookup *l,float *data){
  119761. if(l->n==1)return;
  119762. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119763. }
  119764. void drft_backward(drft_lookup *l,float *data){
  119765. if (l->n==1)return;
  119766. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119767. }
  119768. void drft_init(drft_lookup *l,int n){
  119769. l->n=n;
  119770. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119771. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119772. fdrffti(n, l->trigcache, l->splitcache);
  119773. }
  119774. void drft_clear(drft_lookup *l){
  119775. if(l){
  119776. if(l->trigcache)_ogg_free(l->trigcache);
  119777. if(l->splitcache)_ogg_free(l->splitcache);
  119778. memset(l,0,sizeof(*l));
  119779. }
  119780. }
  119781. #endif
  119782. /*** End of inlined file: smallft.c ***/
  119783. /*** Start of inlined file: synthesis.c ***/
  119784. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119785. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119786. // tasks..
  119787. #if JUCE_MSVC
  119788. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119789. #endif
  119790. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119791. #if JUCE_USE_OGGVORBIS
  119792. #include <stdio.h>
  119793. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119794. vorbis_dsp_state *vd=vb->vd;
  119795. private_state *b=(private_state*)vd->backend_state;
  119796. vorbis_info *vi=vd->vi;
  119797. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119798. oggpack_buffer *opb=&vb->opb;
  119799. int type,mode,i;
  119800. /* first things first. Make sure decode is ready */
  119801. _vorbis_block_ripcord(vb);
  119802. oggpack_readinit(opb,op->packet,op->bytes);
  119803. /* Check the packet type */
  119804. if(oggpack_read(opb,1)!=0){
  119805. /* Oops. This is not an audio data packet */
  119806. return(OV_ENOTAUDIO);
  119807. }
  119808. /* read our mode and pre/post windowsize */
  119809. mode=oggpack_read(opb,b->modebits);
  119810. if(mode==-1)return(OV_EBADPACKET);
  119811. vb->mode=mode;
  119812. vb->W=ci->mode_param[mode]->blockflag;
  119813. if(vb->W){
  119814. /* this doesn;t get mapped through mode selection as it's used
  119815. only for window selection */
  119816. vb->lW=oggpack_read(opb,1);
  119817. vb->nW=oggpack_read(opb,1);
  119818. if(vb->nW==-1) return(OV_EBADPACKET);
  119819. }else{
  119820. vb->lW=0;
  119821. vb->nW=0;
  119822. }
  119823. /* more setup */
  119824. vb->granulepos=op->granulepos;
  119825. vb->sequence=op->packetno;
  119826. vb->eofflag=op->e_o_s;
  119827. /* alloc pcm passback storage */
  119828. vb->pcmend=ci->blocksizes[vb->W];
  119829. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  119830. for(i=0;i<vi->channels;i++)
  119831. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  119832. /* unpack_header enforces range checking */
  119833. type=ci->map_type[ci->mode_param[mode]->mapping];
  119834. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  119835. mapping]));
  119836. }
  119837. /* used to track pcm position without actually performing decode.
  119838. Useful for sequential 'fast forward' */
  119839. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  119840. vorbis_dsp_state *vd=vb->vd;
  119841. private_state *b=(private_state*)vd->backend_state;
  119842. vorbis_info *vi=vd->vi;
  119843. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119844. oggpack_buffer *opb=&vb->opb;
  119845. int mode;
  119846. /* first things first. Make sure decode is ready */
  119847. _vorbis_block_ripcord(vb);
  119848. oggpack_readinit(opb,op->packet,op->bytes);
  119849. /* Check the packet type */
  119850. if(oggpack_read(opb,1)!=0){
  119851. /* Oops. This is not an audio data packet */
  119852. return(OV_ENOTAUDIO);
  119853. }
  119854. /* read our mode and pre/post windowsize */
  119855. mode=oggpack_read(opb,b->modebits);
  119856. if(mode==-1)return(OV_EBADPACKET);
  119857. vb->mode=mode;
  119858. vb->W=ci->mode_param[mode]->blockflag;
  119859. if(vb->W){
  119860. vb->lW=oggpack_read(opb,1);
  119861. vb->nW=oggpack_read(opb,1);
  119862. if(vb->nW==-1) return(OV_EBADPACKET);
  119863. }else{
  119864. vb->lW=0;
  119865. vb->nW=0;
  119866. }
  119867. /* more setup */
  119868. vb->granulepos=op->granulepos;
  119869. vb->sequence=op->packetno;
  119870. vb->eofflag=op->e_o_s;
  119871. /* no pcm */
  119872. vb->pcmend=0;
  119873. vb->pcm=NULL;
  119874. return(0);
  119875. }
  119876. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  119877. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119878. oggpack_buffer opb;
  119879. int mode;
  119880. oggpack_readinit(&opb,op->packet,op->bytes);
  119881. /* Check the packet type */
  119882. if(oggpack_read(&opb,1)!=0){
  119883. /* Oops. This is not an audio data packet */
  119884. return(OV_ENOTAUDIO);
  119885. }
  119886. {
  119887. int modebits=0;
  119888. int v=ci->modes;
  119889. while(v>1){
  119890. modebits++;
  119891. v>>=1;
  119892. }
  119893. /* read our mode and pre/post windowsize */
  119894. mode=oggpack_read(&opb,modebits);
  119895. }
  119896. if(mode==-1)return(OV_EBADPACKET);
  119897. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  119898. }
  119899. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  119900. /* set / clear half-sample-rate mode */
  119901. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119902. /* right now, our MDCT can't handle < 64 sample windows. */
  119903. if(ci->blocksizes[0]<=64 && flag)return -1;
  119904. ci->halfrate_flag=(flag?1:0);
  119905. return 0;
  119906. }
  119907. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  119908. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119909. return ci->halfrate_flag;
  119910. }
  119911. #endif
  119912. /*** End of inlined file: synthesis.c ***/
  119913. /*** Start of inlined file: vorbisenc.c ***/
  119914. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119915. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119916. // tasks..
  119917. #if JUCE_MSVC
  119918. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119919. #endif
  119920. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119921. #if JUCE_USE_OGGVORBIS
  119922. #include <stdlib.h>
  119923. #include <string.h>
  119924. #include <math.h>
  119925. /* careful with this; it's using static array sizing to make managing
  119926. all the modes a little less annoying. If we use a residue backend
  119927. with > 12 partition types, or a different division of iteration,
  119928. this needs to be updated. */
  119929. typedef struct {
  119930. static_codebook *books[12][3];
  119931. } static_bookblock;
  119932. typedef struct {
  119933. int res_type;
  119934. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  119935. vorbis_info_residue0 *res;
  119936. static_codebook *book_aux;
  119937. static_codebook *book_aux_managed;
  119938. static_bookblock *books_base;
  119939. static_bookblock *books_base_managed;
  119940. } vorbis_residue_template;
  119941. typedef struct {
  119942. vorbis_info_mapping0 *map;
  119943. vorbis_residue_template *res;
  119944. } vorbis_mapping_template;
  119945. typedef struct vp_adjblock{
  119946. int block[P_BANDS];
  119947. } vp_adjblock;
  119948. typedef struct {
  119949. int data[NOISE_COMPAND_LEVELS];
  119950. } compandblock;
  119951. /* high level configuration information for setting things up
  119952. step-by-step with the detailed vorbis_encode_ctl interface.
  119953. There's a fair amount of redundancy such that interactive setup
  119954. does not directly deal with any vorbis_info or codec_setup_info
  119955. initialization; it's all stored (until full init) in this highlevel
  119956. setup, then flushed out to the real codec setup structs later. */
  119957. typedef struct {
  119958. int att[P_NOISECURVES];
  119959. float boost;
  119960. float decay;
  119961. } att3;
  119962. typedef struct { int data[P_NOISECURVES]; } adj3;
  119963. typedef struct {
  119964. int pre[PACKETBLOBS];
  119965. int post[PACKETBLOBS];
  119966. float kHz[PACKETBLOBS];
  119967. float lowpasskHz[PACKETBLOBS];
  119968. } adj_stereo;
  119969. typedef struct {
  119970. int lo;
  119971. int hi;
  119972. int fixed;
  119973. } noiseguard;
  119974. typedef struct {
  119975. int data[P_NOISECURVES][17];
  119976. } noise3;
  119977. typedef struct {
  119978. int mappings;
  119979. double *rate_mapping;
  119980. double *quality_mapping;
  119981. int coupling_restriction;
  119982. long samplerate_min_restriction;
  119983. long samplerate_max_restriction;
  119984. int *blocksize_short;
  119985. int *blocksize_long;
  119986. att3 *psy_tone_masteratt;
  119987. int *psy_tone_0dB;
  119988. int *psy_tone_dBsuppress;
  119989. vp_adjblock *psy_tone_adj_impulse;
  119990. vp_adjblock *psy_tone_adj_long;
  119991. vp_adjblock *psy_tone_adj_other;
  119992. noiseguard *psy_noiseguards;
  119993. noise3 *psy_noise_bias_impulse;
  119994. noise3 *psy_noise_bias_padding;
  119995. noise3 *psy_noise_bias_trans;
  119996. noise3 *psy_noise_bias_long;
  119997. int *psy_noise_dBsuppress;
  119998. compandblock *psy_noise_compand;
  119999. double *psy_noise_compand_short_mapping;
  120000. double *psy_noise_compand_long_mapping;
  120001. int *psy_noise_normal_start[2];
  120002. int *psy_noise_normal_partition[2];
  120003. double *psy_noise_normal_thresh;
  120004. int *psy_ath_float;
  120005. int *psy_ath_abs;
  120006. double *psy_lowpass;
  120007. vorbis_info_psy_global *global_params;
  120008. double *global_mapping;
  120009. adj_stereo *stereo_modes;
  120010. static_codebook ***floor_books;
  120011. vorbis_info_floor1 *floor_params;
  120012. int *floor_short_mapping;
  120013. int *floor_long_mapping;
  120014. vorbis_mapping_template *maps;
  120015. } ve_setup_data_template;
  120016. /* a few static coder conventions */
  120017. static vorbis_info_mode _mode_template[2]={
  120018. {0,0,0,0},
  120019. {1,0,0,1}
  120020. };
  120021. static vorbis_info_mapping0 _map_nominal[2]={
  120022. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120023. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120024. };
  120025. /*** Start of inlined file: setup_44.h ***/
  120026. /*** Start of inlined file: floor_all.h ***/
  120027. /*** Start of inlined file: floor_books.h ***/
  120028. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120029. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120030. };
  120031. static static_codebook _huff_book_line_256x7_0sub1 = {
  120032. 1, 9,
  120033. _huff_lengthlist_line_256x7_0sub1,
  120034. 0, 0, 0, 0, 0,
  120035. NULL,
  120036. NULL,
  120037. NULL,
  120038. NULL,
  120039. 0
  120040. };
  120041. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120043. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120044. };
  120045. static static_codebook _huff_book_line_256x7_0sub2 = {
  120046. 1, 25,
  120047. _huff_lengthlist_line_256x7_0sub2,
  120048. 0, 0, 0, 0, 0,
  120049. NULL,
  120050. NULL,
  120051. NULL,
  120052. NULL,
  120053. 0
  120054. };
  120055. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120058. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120059. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120060. };
  120061. static static_codebook _huff_book_line_256x7_0sub3 = {
  120062. 1, 64,
  120063. _huff_lengthlist_line_256x7_0sub3,
  120064. 0, 0, 0, 0, 0,
  120065. NULL,
  120066. NULL,
  120067. NULL,
  120068. NULL,
  120069. 0
  120070. };
  120071. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120072. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120073. };
  120074. static static_codebook _huff_book_line_256x7_1sub1 = {
  120075. 1, 9,
  120076. _huff_lengthlist_line_256x7_1sub1,
  120077. 0, 0, 0, 0, 0,
  120078. NULL,
  120079. NULL,
  120080. NULL,
  120081. NULL,
  120082. 0
  120083. };
  120084. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120086. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120087. };
  120088. static static_codebook _huff_book_line_256x7_1sub2 = {
  120089. 1, 25,
  120090. _huff_lengthlist_line_256x7_1sub2,
  120091. 0, 0, 0, 0, 0,
  120092. NULL,
  120093. NULL,
  120094. NULL,
  120095. NULL,
  120096. 0
  120097. };
  120098. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120101. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120102. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120103. };
  120104. static static_codebook _huff_book_line_256x7_1sub3 = {
  120105. 1, 64,
  120106. _huff_lengthlist_line_256x7_1sub3,
  120107. 0, 0, 0, 0, 0,
  120108. NULL,
  120109. NULL,
  120110. NULL,
  120111. NULL,
  120112. 0
  120113. };
  120114. static long _huff_lengthlist_line_256x7_class0[] = {
  120115. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120116. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120117. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120118. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120119. };
  120120. static static_codebook _huff_book_line_256x7_class0 = {
  120121. 1, 64,
  120122. _huff_lengthlist_line_256x7_class0,
  120123. 0, 0, 0, 0, 0,
  120124. NULL,
  120125. NULL,
  120126. NULL,
  120127. NULL,
  120128. 0
  120129. };
  120130. static long _huff_lengthlist_line_256x7_class1[] = {
  120131. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120132. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120133. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120134. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120135. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120136. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120137. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120138. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120139. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120140. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120141. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120142. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120143. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120144. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120145. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120146. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120147. };
  120148. static static_codebook _huff_book_line_256x7_class1 = {
  120149. 1, 256,
  120150. _huff_lengthlist_line_256x7_class1,
  120151. 0, 0, 0, 0, 0,
  120152. NULL,
  120153. NULL,
  120154. NULL,
  120155. NULL,
  120156. 0
  120157. };
  120158. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120159. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120160. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120161. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120162. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120163. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120164. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120165. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120166. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120167. };
  120168. static static_codebook _huff_book_line_512x17_0sub0 = {
  120169. 1, 128,
  120170. _huff_lengthlist_line_512x17_0sub0,
  120171. 0, 0, 0, 0, 0,
  120172. NULL,
  120173. NULL,
  120174. NULL,
  120175. NULL,
  120176. 0
  120177. };
  120178. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120179. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120180. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120181. };
  120182. static static_codebook _huff_book_line_512x17_1sub0 = {
  120183. 1, 32,
  120184. _huff_lengthlist_line_512x17_1sub0,
  120185. 0, 0, 0, 0, 0,
  120186. NULL,
  120187. NULL,
  120188. NULL,
  120189. NULL,
  120190. 0
  120191. };
  120192. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120195. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120196. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120197. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120198. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120199. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120200. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120201. };
  120202. static static_codebook _huff_book_line_512x17_1sub1 = {
  120203. 1, 128,
  120204. _huff_lengthlist_line_512x17_1sub1,
  120205. 0, 0, 0, 0, 0,
  120206. NULL,
  120207. NULL,
  120208. NULL,
  120209. NULL,
  120210. 0
  120211. };
  120212. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120213. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120214. 5, 3,
  120215. };
  120216. static static_codebook _huff_book_line_512x17_2sub1 = {
  120217. 1, 18,
  120218. _huff_lengthlist_line_512x17_2sub1,
  120219. 0, 0, 0, 0, 0,
  120220. NULL,
  120221. NULL,
  120222. NULL,
  120223. NULL,
  120224. 0
  120225. };
  120226. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120228. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120229. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120230. 9, 8,
  120231. };
  120232. static static_codebook _huff_book_line_512x17_2sub2 = {
  120233. 1, 50,
  120234. _huff_lengthlist_line_512x17_2sub2,
  120235. 0, 0, 0, 0, 0,
  120236. NULL,
  120237. NULL,
  120238. NULL,
  120239. NULL,
  120240. 0
  120241. };
  120242. static long _huff_lengthlist_line_512x17_2sub3[] = {
  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, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120247. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120248. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120249. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120250. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120251. };
  120252. static static_codebook _huff_book_line_512x17_2sub3 = {
  120253. 1, 128,
  120254. _huff_lengthlist_line_512x17_2sub3,
  120255. 0, 0, 0, 0, 0,
  120256. NULL,
  120257. NULL,
  120258. NULL,
  120259. NULL,
  120260. 0
  120261. };
  120262. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120263. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120264. 5, 5,
  120265. };
  120266. static static_codebook _huff_book_line_512x17_3sub1 = {
  120267. 1, 18,
  120268. _huff_lengthlist_line_512x17_3sub1,
  120269. 0, 0, 0, 0, 0,
  120270. NULL,
  120271. NULL,
  120272. NULL,
  120273. NULL,
  120274. 0
  120275. };
  120276. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120278. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120279. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120280. 11,14,
  120281. };
  120282. static static_codebook _huff_book_line_512x17_3sub2 = {
  120283. 1, 50,
  120284. _huff_lengthlist_line_512x17_3sub2,
  120285. 0, 0, 0, 0, 0,
  120286. NULL,
  120287. NULL,
  120288. NULL,
  120289. NULL,
  120290. 0
  120291. };
  120292. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120296. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120297. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120298. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120299. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120300. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120301. };
  120302. static static_codebook _huff_book_line_512x17_3sub3 = {
  120303. 1, 128,
  120304. _huff_lengthlist_line_512x17_3sub3,
  120305. 0, 0, 0, 0, 0,
  120306. NULL,
  120307. NULL,
  120308. NULL,
  120309. NULL,
  120310. 0
  120311. };
  120312. static long _huff_lengthlist_line_512x17_class1[] = {
  120313. 1, 2, 3, 6, 5, 4, 7, 7,
  120314. };
  120315. static static_codebook _huff_book_line_512x17_class1 = {
  120316. 1, 8,
  120317. _huff_lengthlist_line_512x17_class1,
  120318. 0, 0, 0, 0, 0,
  120319. NULL,
  120320. NULL,
  120321. NULL,
  120322. NULL,
  120323. 0
  120324. };
  120325. static long _huff_lengthlist_line_512x17_class2[] = {
  120326. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120327. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120328. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120329. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120330. };
  120331. static static_codebook _huff_book_line_512x17_class2 = {
  120332. 1, 64,
  120333. _huff_lengthlist_line_512x17_class2,
  120334. 0, 0, 0, 0, 0,
  120335. NULL,
  120336. NULL,
  120337. NULL,
  120338. NULL,
  120339. 0
  120340. };
  120341. static long _huff_lengthlist_line_512x17_class3[] = {
  120342. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120343. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120344. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120345. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120346. };
  120347. static static_codebook _huff_book_line_512x17_class3 = {
  120348. 1, 64,
  120349. _huff_lengthlist_line_512x17_class3,
  120350. 0, 0, 0, 0, 0,
  120351. NULL,
  120352. NULL,
  120353. NULL,
  120354. NULL,
  120355. 0
  120356. };
  120357. static long _huff_lengthlist_line_128x4_class0[] = {
  120358. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120359. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120360. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120361. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120362. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120363. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120364. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120365. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120366. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120367. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120368. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120369. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120370. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120371. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120372. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120373. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120374. };
  120375. static static_codebook _huff_book_line_128x4_class0 = {
  120376. 1, 256,
  120377. _huff_lengthlist_line_128x4_class0,
  120378. 0, 0, 0, 0, 0,
  120379. NULL,
  120380. NULL,
  120381. NULL,
  120382. NULL,
  120383. 0
  120384. };
  120385. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120386. 2, 2, 2, 2,
  120387. };
  120388. static static_codebook _huff_book_line_128x4_0sub0 = {
  120389. 1, 4,
  120390. _huff_lengthlist_line_128x4_0sub0,
  120391. 0, 0, 0, 0, 0,
  120392. NULL,
  120393. NULL,
  120394. NULL,
  120395. NULL,
  120396. 0
  120397. };
  120398. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120399. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120400. };
  120401. static static_codebook _huff_book_line_128x4_0sub1 = {
  120402. 1, 10,
  120403. _huff_lengthlist_line_128x4_0sub1,
  120404. 0, 0, 0, 0, 0,
  120405. NULL,
  120406. NULL,
  120407. NULL,
  120408. NULL,
  120409. 0
  120410. };
  120411. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120413. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120414. };
  120415. static static_codebook _huff_book_line_128x4_0sub2 = {
  120416. 1, 25,
  120417. _huff_lengthlist_line_128x4_0sub2,
  120418. 0, 0, 0, 0, 0,
  120419. NULL,
  120420. NULL,
  120421. NULL,
  120422. NULL,
  120423. 0
  120424. };
  120425. static long _huff_lengthlist_line_128x4_0sub3[] = {
  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, 2, 4, 3, 5, 3, 5, 3,
  120428. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120429. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120430. };
  120431. static static_codebook _huff_book_line_128x4_0sub3 = {
  120432. 1, 64,
  120433. _huff_lengthlist_line_128x4_0sub3,
  120434. 0, 0, 0, 0, 0,
  120435. NULL,
  120436. NULL,
  120437. NULL,
  120438. NULL,
  120439. 0
  120440. };
  120441. static long _huff_lengthlist_line_256x4_class0[] = {
  120442. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120443. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120444. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120445. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120446. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120447. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120448. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120449. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120450. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120451. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120452. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120453. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120454. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120455. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120456. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120457. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120458. };
  120459. static static_codebook _huff_book_line_256x4_class0 = {
  120460. 1, 256,
  120461. _huff_lengthlist_line_256x4_class0,
  120462. 0, 0, 0, 0, 0,
  120463. NULL,
  120464. NULL,
  120465. NULL,
  120466. NULL,
  120467. 0
  120468. };
  120469. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120470. 2, 2, 2, 2,
  120471. };
  120472. static static_codebook _huff_book_line_256x4_0sub0 = {
  120473. 1, 4,
  120474. _huff_lengthlist_line_256x4_0sub0,
  120475. 0, 0, 0, 0, 0,
  120476. NULL,
  120477. NULL,
  120478. NULL,
  120479. NULL,
  120480. 0
  120481. };
  120482. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120483. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120484. };
  120485. static static_codebook _huff_book_line_256x4_0sub1 = {
  120486. 1, 10,
  120487. _huff_lengthlist_line_256x4_0sub1,
  120488. 0, 0, 0, 0, 0,
  120489. NULL,
  120490. NULL,
  120491. NULL,
  120492. NULL,
  120493. 0
  120494. };
  120495. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120497. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120498. };
  120499. static static_codebook _huff_book_line_256x4_0sub2 = {
  120500. 1, 25,
  120501. _huff_lengthlist_line_256x4_0sub2,
  120502. 0, 0, 0, 0, 0,
  120503. NULL,
  120504. NULL,
  120505. NULL,
  120506. NULL,
  120507. 0
  120508. };
  120509. static long _huff_lengthlist_line_256x4_0sub3[] = {
  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, 2, 4, 3, 5, 3, 5, 3,
  120512. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120513. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120514. };
  120515. static static_codebook _huff_book_line_256x4_0sub3 = {
  120516. 1, 64,
  120517. _huff_lengthlist_line_256x4_0sub3,
  120518. 0, 0, 0, 0, 0,
  120519. NULL,
  120520. NULL,
  120521. NULL,
  120522. NULL,
  120523. 0
  120524. };
  120525. static long _huff_lengthlist_line_128x7_class0[] = {
  120526. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120527. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120528. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120529. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120530. };
  120531. static static_codebook _huff_book_line_128x7_class0 = {
  120532. 1, 64,
  120533. _huff_lengthlist_line_128x7_class0,
  120534. 0, 0, 0, 0, 0,
  120535. NULL,
  120536. NULL,
  120537. NULL,
  120538. NULL,
  120539. 0
  120540. };
  120541. static long _huff_lengthlist_line_128x7_class1[] = {
  120542. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120543. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120544. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120545. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120546. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120547. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120548. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120549. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120550. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120551. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120552. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120553. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120554. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120555. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120556. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120557. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120558. };
  120559. static static_codebook _huff_book_line_128x7_class1 = {
  120560. 1, 256,
  120561. _huff_lengthlist_line_128x7_class1,
  120562. 0, 0, 0, 0, 0,
  120563. NULL,
  120564. NULL,
  120565. NULL,
  120566. NULL,
  120567. 0
  120568. };
  120569. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120570. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120571. };
  120572. static static_codebook _huff_book_line_128x7_0sub1 = {
  120573. 1, 9,
  120574. _huff_lengthlist_line_128x7_0sub1,
  120575. 0, 0, 0, 0, 0,
  120576. NULL,
  120577. NULL,
  120578. NULL,
  120579. NULL,
  120580. 0
  120581. };
  120582. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120584. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120585. };
  120586. static static_codebook _huff_book_line_128x7_0sub2 = {
  120587. 1, 25,
  120588. _huff_lengthlist_line_128x7_0sub2,
  120589. 0, 0, 0, 0, 0,
  120590. NULL,
  120591. NULL,
  120592. NULL,
  120593. NULL,
  120594. 0
  120595. };
  120596. static long _huff_lengthlist_line_128x7_0sub3[] = {
  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, 3, 5, 3, 5, 3, 5, 4,
  120599. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120600. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120601. };
  120602. static static_codebook _huff_book_line_128x7_0sub3 = {
  120603. 1, 64,
  120604. _huff_lengthlist_line_128x7_0sub3,
  120605. 0, 0, 0, 0, 0,
  120606. NULL,
  120607. NULL,
  120608. NULL,
  120609. NULL,
  120610. 0
  120611. };
  120612. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120613. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120614. };
  120615. static static_codebook _huff_book_line_128x7_1sub1 = {
  120616. 1, 9,
  120617. _huff_lengthlist_line_128x7_1sub1,
  120618. 0, 0, 0, 0, 0,
  120619. NULL,
  120620. NULL,
  120621. NULL,
  120622. NULL,
  120623. 0
  120624. };
  120625. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120627. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120628. };
  120629. static static_codebook _huff_book_line_128x7_1sub2 = {
  120630. 1, 25,
  120631. _huff_lengthlist_line_128x7_1sub2,
  120632. 0, 0, 0, 0, 0,
  120633. NULL,
  120634. NULL,
  120635. NULL,
  120636. NULL,
  120637. 0
  120638. };
  120639. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120642. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120643. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120644. };
  120645. static static_codebook _huff_book_line_128x7_1sub3 = {
  120646. 1, 64,
  120647. _huff_lengthlist_line_128x7_1sub3,
  120648. 0, 0, 0, 0, 0,
  120649. NULL,
  120650. NULL,
  120651. NULL,
  120652. NULL,
  120653. 0
  120654. };
  120655. static long _huff_lengthlist_line_128x11_class1[] = {
  120656. 1, 6, 3, 7, 2, 4, 5, 7,
  120657. };
  120658. static static_codebook _huff_book_line_128x11_class1 = {
  120659. 1, 8,
  120660. _huff_lengthlist_line_128x11_class1,
  120661. 0, 0, 0, 0, 0,
  120662. NULL,
  120663. NULL,
  120664. NULL,
  120665. NULL,
  120666. 0
  120667. };
  120668. static long _huff_lengthlist_line_128x11_class2[] = {
  120669. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120670. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120671. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120672. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120673. };
  120674. static static_codebook _huff_book_line_128x11_class2 = {
  120675. 1, 64,
  120676. _huff_lengthlist_line_128x11_class2,
  120677. 0, 0, 0, 0, 0,
  120678. NULL,
  120679. NULL,
  120680. NULL,
  120681. NULL,
  120682. 0
  120683. };
  120684. static long _huff_lengthlist_line_128x11_class3[] = {
  120685. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120686. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120687. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120688. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120689. };
  120690. static static_codebook _huff_book_line_128x11_class3 = {
  120691. 1, 64,
  120692. _huff_lengthlist_line_128x11_class3,
  120693. 0, 0, 0, 0, 0,
  120694. NULL,
  120695. NULL,
  120696. NULL,
  120697. NULL,
  120698. 0
  120699. };
  120700. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120701. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120702. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120703. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120704. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120705. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120706. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120707. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120708. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120709. };
  120710. static static_codebook _huff_book_line_128x11_0sub0 = {
  120711. 1, 128,
  120712. _huff_lengthlist_line_128x11_0sub0,
  120713. 0, 0, 0, 0, 0,
  120714. NULL,
  120715. NULL,
  120716. NULL,
  120717. NULL,
  120718. 0
  120719. };
  120720. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120721. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120722. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120723. };
  120724. static static_codebook _huff_book_line_128x11_1sub0 = {
  120725. 1, 32,
  120726. _huff_lengthlist_line_128x11_1sub0,
  120727. 0, 0, 0, 0, 0,
  120728. NULL,
  120729. NULL,
  120730. NULL,
  120731. NULL,
  120732. 0
  120733. };
  120734. static long _huff_lengthlist_line_128x11_1sub1[] = {
  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. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120738. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120739. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120740. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120741. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120742. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120743. };
  120744. static static_codebook _huff_book_line_128x11_1sub1 = {
  120745. 1, 128,
  120746. _huff_lengthlist_line_128x11_1sub1,
  120747. 0, 0, 0, 0, 0,
  120748. NULL,
  120749. NULL,
  120750. NULL,
  120751. NULL,
  120752. 0
  120753. };
  120754. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120755. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120756. 5, 5,
  120757. };
  120758. static static_codebook _huff_book_line_128x11_2sub1 = {
  120759. 1, 18,
  120760. _huff_lengthlist_line_128x11_2sub1,
  120761. 0, 0, 0, 0, 0,
  120762. NULL,
  120763. NULL,
  120764. NULL,
  120765. NULL,
  120766. 0
  120767. };
  120768. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120771. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120772. 8,11,
  120773. };
  120774. static static_codebook _huff_book_line_128x11_2sub2 = {
  120775. 1, 50,
  120776. _huff_lengthlist_line_128x11_2sub2,
  120777. 0, 0, 0, 0, 0,
  120778. NULL,
  120779. NULL,
  120780. NULL,
  120781. NULL,
  120782. 0
  120783. };
  120784. static long _huff_lengthlist_line_128x11_2sub3[] = {
  120785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120788. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120789. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120790. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120791. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120792. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120793. };
  120794. static static_codebook _huff_book_line_128x11_2sub3 = {
  120795. 1, 128,
  120796. _huff_lengthlist_line_128x11_2sub3,
  120797. 0, 0, 0, 0, 0,
  120798. NULL,
  120799. NULL,
  120800. NULL,
  120801. NULL,
  120802. 0
  120803. };
  120804. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120805. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120806. 5, 4,
  120807. };
  120808. static static_codebook _huff_book_line_128x11_3sub1 = {
  120809. 1, 18,
  120810. _huff_lengthlist_line_128x11_3sub1,
  120811. 0, 0, 0, 0, 0,
  120812. NULL,
  120813. NULL,
  120814. NULL,
  120815. NULL,
  120816. 0
  120817. };
  120818. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120820. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  120821. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  120822. 12, 6,
  120823. };
  120824. static static_codebook _huff_book_line_128x11_3sub2 = {
  120825. 1, 50,
  120826. _huff_lengthlist_line_128x11_3sub2,
  120827. 0, 0, 0, 0, 0,
  120828. NULL,
  120829. NULL,
  120830. NULL,
  120831. NULL,
  120832. 0
  120833. };
  120834. static long _huff_lengthlist_line_128x11_3sub3[] = {
  120835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120838. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  120839. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  120840. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120841. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120842. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  120843. };
  120844. static static_codebook _huff_book_line_128x11_3sub3 = {
  120845. 1, 128,
  120846. _huff_lengthlist_line_128x11_3sub3,
  120847. 0, 0, 0, 0, 0,
  120848. NULL,
  120849. NULL,
  120850. NULL,
  120851. NULL,
  120852. 0
  120853. };
  120854. static long _huff_lengthlist_line_128x17_class1[] = {
  120855. 1, 3, 4, 7, 2, 5, 6, 7,
  120856. };
  120857. static static_codebook _huff_book_line_128x17_class1 = {
  120858. 1, 8,
  120859. _huff_lengthlist_line_128x17_class1,
  120860. 0, 0, 0, 0, 0,
  120861. NULL,
  120862. NULL,
  120863. NULL,
  120864. NULL,
  120865. 0
  120866. };
  120867. static long _huff_lengthlist_line_128x17_class2[] = {
  120868. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  120869. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  120870. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  120871. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120872. };
  120873. static static_codebook _huff_book_line_128x17_class2 = {
  120874. 1, 64,
  120875. _huff_lengthlist_line_128x17_class2,
  120876. 0, 0, 0, 0, 0,
  120877. NULL,
  120878. NULL,
  120879. NULL,
  120880. NULL,
  120881. 0
  120882. };
  120883. static long _huff_lengthlist_line_128x17_class3[] = {
  120884. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  120885. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  120886. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  120887. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  120888. };
  120889. static static_codebook _huff_book_line_128x17_class3 = {
  120890. 1, 64,
  120891. _huff_lengthlist_line_128x17_class3,
  120892. 0, 0, 0, 0, 0,
  120893. NULL,
  120894. NULL,
  120895. NULL,
  120896. NULL,
  120897. 0
  120898. };
  120899. static long _huff_lengthlist_line_128x17_0sub0[] = {
  120900. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120901. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  120902. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  120903. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  120904. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  120905. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  120906. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  120907. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120908. };
  120909. static static_codebook _huff_book_line_128x17_0sub0 = {
  120910. 1, 128,
  120911. _huff_lengthlist_line_128x17_0sub0,
  120912. 0, 0, 0, 0, 0,
  120913. NULL,
  120914. NULL,
  120915. NULL,
  120916. NULL,
  120917. 0
  120918. };
  120919. static long _huff_lengthlist_line_128x17_1sub0[] = {
  120920. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120921. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  120922. };
  120923. static static_codebook _huff_book_line_128x17_1sub0 = {
  120924. 1, 32,
  120925. _huff_lengthlist_line_128x17_1sub0,
  120926. 0, 0, 0, 0, 0,
  120927. NULL,
  120928. NULL,
  120929. NULL,
  120930. NULL,
  120931. 0
  120932. };
  120933. static long _huff_lengthlist_line_128x17_1sub1[] = {
  120934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  120937. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  120938. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  120939. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  120940. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  120941. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  120942. };
  120943. static static_codebook _huff_book_line_128x17_1sub1 = {
  120944. 1, 128,
  120945. _huff_lengthlist_line_128x17_1sub1,
  120946. 0, 0, 0, 0, 0,
  120947. NULL,
  120948. NULL,
  120949. NULL,
  120950. NULL,
  120951. 0
  120952. };
  120953. static long _huff_lengthlist_line_128x17_2sub1[] = {
  120954. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  120955. 9, 4,
  120956. };
  120957. static static_codebook _huff_book_line_128x17_2sub1 = {
  120958. 1, 18,
  120959. _huff_lengthlist_line_128x17_2sub1,
  120960. 0, 0, 0, 0, 0,
  120961. NULL,
  120962. NULL,
  120963. NULL,
  120964. NULL,
  120965. 0
  120966. };
  120967. static long _huff_lengthlist_line_128x17_2sub2[] = {
  120968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120969. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  120970. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  120971. 13,13,
  120972. };
  120973. static static_codebook _huff_book_line_128x17_2sub2 = {
  120974. 1, 50,
  120975. _huff_lengthlist_line_128x17_2sub2,
  120976. 0, 0, 0, 0, 0,
  120977. NULL,
  120978. NULL,
  120979. NULL,
  120980. NULL,
  120981. 0
  120982. };
  120983. static long _huff_lengthlist_line_128x17_2sub3[] = {
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120988. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  120989. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120990. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120991. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120992. };
  120993. static static_codebook _huff_book_line_128x17_2sub3 = {
  120994. 1, 128,
  120995. _huff_lengthlist_line_128x17_2sub3,
  120996. 0, 0, 0, 0, 0,
  120997. NULL,
  120998. NULL,
  120999. NULL,
  121000. NULL,
  121001. 0
  121002. };
  121003. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121004. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121005. 6, 4,
  121006. };
  121007. static static_codebook _huff_book_line_128x17_3sub1 = {
  121008. 1, 18,
  121009. _huff_lengthlist_line_128x17_3sub1,
  121010. 0, 0, 0, 0, 0,
  121011. NULL,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. 0
  121016. };
  121017. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121020. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121021. 10, 8,
  121022. };
  121023. static static_codebook _huff_book_line_128x17_3sub2 = {
  121024. 1, 50,
  121025. _huff_lengthlist_line_128x17_3sub2,
  121026. 0, 0, 0, 0, 0,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. 0
  121032. };
  121033. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121038. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121039. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121042. };
  121043. static static_codebook _huff_book_line_128x17_3sub3 = {
  121044. 1, 128,
  121045. _huff_lengthlist_line_128x17_3sub3,
  121046. 0, 0, 0, 0, 0,
  121047. NULL,
  121048. NULL,
  121049. NULL,
  121050. NULL,
  121051. 0
  121052. };
  121053. static long _huff_lengthlist_line_1024x27_class1[] = {
  121054. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121055. };
  121056. static static_codebook _huff_book_line_1024x27_class1 = {
  121057. 1, 16,
  121058. _huff_lengthlist_line_1024x27_class1,
  121059. 0, 0, 0, 0, 0,
  121060. NULL,
  121061. NULL,
  121062. NULL,
  121063. NULL,
  121064. 0
  121065. };
  121066. static long _huff_lengthlist_line_1024x27_class2[] = {
  121067. 1, 4, 2, 6, 3, 7, 5, 7,
  121068. };
  121069. static static_codebook _huff_book_line_1024x27_class2 = {
  121070. 1, 8,
  121071. _huff_lengthlist_line_1024x27_class2,
  121072. 0, 0, 0, 0, 0,
  121073. NULL,
  121074. NULL,
  121075. NULL,
  121076. NULL,
  121077. 0
  121078. };
  121079. static long _huff_lengthlist_line_1024x27_class3[] = {
  121080. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121081. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121082. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121083. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121084. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121085. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121086. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121087. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121088. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121089. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121090. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121091. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121092. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121093. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121094. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121095. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121096. };
  121097. static static_codebook _huff_book_line_1024x27_class3 = {
  121098. 1, 256,
  121099. _huff_lengthlist_line_1024x27_class3,
  121100. 0, 0, 0, 0, 0,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. NULL,
  121105. 0
  121106. };
  121107. static long _huff_lengthlist_line_1024x27_class4[] = {
  121108. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121109. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121110. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121111. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121112. };
  121113. static static_codebook _huff_book_line_1024x27_class4 = {
  121114. 1, 64,
  121115. _huff_lengthlist_line_1024x27_class4,
  121116. 0, 0, 0, 0, 0,
  121117. NULL,
  121118. NULL,
  121119. NULL,
  121120. NULL,
  121121. 0
  121122. };
  121123. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121124. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121125. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121126. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121127. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121128. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121129. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121130. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121131. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121132. };
  121133. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121134. 1, 128,
  121135. _huff_lengthlist_line_1024x27_0sub0,
  121136. 0, 0, 0, 0, 0,
  121137. NULL,
  121138. NULL,
  121139. NULL,
  121140. NULL,
  121141. 0
  121142. };
  121143. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121144. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121145. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121146. };
  121147. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121148. 1, 32,
  121149. _huff_lengthlist_line_1024x27_1sub0,
  121150. 0, 0, 0, 0, 0,
  121151. NULL,
  121152. NULL,
  121153. NULL,
  121154. NULL,
  121155. 0
  121156. };
  121157. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121160. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121161. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121162. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121163. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121164. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121165. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121166. };
  121167. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121168. 1, 128,
  121169. _huff_lengthlist_line_1024x27_1sub1,
  121170. 0, 0, 0, 0, 0,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. NULL,
  121175. 0
  121176. };
  121177. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121178. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121179. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121180. };
  121181. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121182. 1, 32,
  121183. _huff_lengthlist_line_1024x27_2sub0,
  121184. 0, 0, 0, 0, 0,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. NULL,
  121189. 0
  121190. };
  121191. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121194. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121195. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121196. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121197. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121198. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121199. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121200. };
  121201. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121202. 1, 128,
  121203. _huff_lengthlist_line_1024x27_2sub1,
  121204. 0, 0, 0, 0, 0,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. NULL,
  121209. 0
  121210. };
  121211. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121212. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121213. 5, 5,
  121214. };
  121215. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121216. 1, 18,
  121217. _huff_lengthlist_line_1024x27_3sub1,
  121218. 0, 0, 0, 0, 0,
  121219. NULL,
  121220. NULL,
  121221. NULL,
  121222. NULL,
  121223. 0
  121224. };
  121225. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121227. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121228. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121229. 9,11,
  121230. };
  121231. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121232. 1, 50,
  121233. _huff_lengthlist_line_1024x27_3sub2,
  121234. 0, 0, 0, 0, 0,
  121235. NULL,
  121236. NULL,
  121237. NULL,
  121238. NULL,
  121239. 0
  121240. };
  121241. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121246. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121247. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121249. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121250. };
  121251. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121252. 1, 128,
  121253. _huff_lengthlist_line_1024x27_3sub3,
  121254. 0, 0, 0, 0, 0,
  121255. NULL,
  121256. NULL,
  121257. NULL,
  121258. NULL,
  121259. 0
  121260. };
  121261. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121262. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121263. 5, 4,
  121264. };
  121265. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121266. 1, 18,
  121267. _huff_lengthlist_line_1024x27_4sub1,
  121268. 0, 0, 0, 0, 0,
  121269. NULL,
  121270. NULL,
  121271. NULL,
  121272. NULL,
  121273. 0
  121274. };
  121275. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121277. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121278. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121279. 9,12,
  121280. };
  121281. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121282. 1, 50,
  121283. _huff_lengthlist_line_1024x27_4sub2,
  121284. 0, 0, 0, 0, 0,
  121285. NULL,
  121286. NULL,
  121287. NULL,
  121288. NULL,
  121289. 0
  121290. };
  121291. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121295. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121296. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121299. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121300. };
  121301. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121302. 1, 128,
  121303. _huff_lengthlist_line_1024x27_4sub3,
  121304. 0, 0, 0, 0, 0,
  121305. NULL,
  121306. NULL,
  121307. NULL,
  121308. NULL,
  121309. 0
  121310. };
  121311. static long _huff_lengthlist_line_2048x27_class1[] = {
  121312. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121313. };
  121314. static static_codebook _huff_book_line_2048x27_class1 = {
  121315. 1, 16,
  121316. _huff_lengthlist_line_2048x27_class1,
  121317. 0, 0, 0, 0, 0,
  121318. NULL,
  121319. NULL,
  121320. NULL,
  121321. NULL,
  121322. 0
  121323. };
  121324. static long _huff_lengthlist_line_2048x27_class2[] = {
  121325. 1, 2, 3, 6, 4, 7, 5, 7,
  121326. };
  121327. static static_codebook _huff_book_line_2048x27_class2 = {
  121328. 1, 8,
  121329. _huff_lengthlist_line_2048x27_class2,
  121330. 0, 0, 0, 0, 0,
  121331. NULL,
  121332. NULL,
  121333. NULL,
  121334. NULL,
  121335. 0
  121336. };
  121337. static long _huff_lengthlist_line_2048x27_class3[] = {
  121338. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121339. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121340. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121341. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121342. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121343. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121344. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121345. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121346. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121347. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121348. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121349. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121350. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121351. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121352. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121353. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121354. };
  121355. static static_codebook _huff_book_line_2048x27_class3 = {
  121356. 1, 256,
  121357. _huff_lengthlist_line_2048x27_class3,
  121358. 0, 0, 0, 0, 0,
  121359. NULL,
  121360. NULL,
  121361. NULL,
  121362. NULL,
  121363. 0
  121364. };
  121365. static long _huff_lengthlist_line_2048x27_class4[] = {
  121366. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121367. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121368. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121369. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121370. };
  121371. static static_codebook _huff_book_line_2048x27_class4 = {
  121372. 1, 64,
  121373. _huff_lengthlist_line_2048x27_class4,
  121374. 0, 0, 0, 0, 0,
  121375. NULL,
  121376. NULL,
  121377. NULL,
  121378. NULL,
  121379. 0
  121380. };
  121381. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121382. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121383. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121384. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121385. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121386. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121387. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121388. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121389. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121390. };
  121391. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121392. 1, 128,
  121393. _huff_lengthlist_line_2048x27_0sub0,
  121394. 0, 0, 0, 0, 0,
  121395. NULL,
  121396. NULL,
  121397. NULL,
  121398. NULL,
  121399. 0
  121400. };
  121401. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121402. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121403. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121404. };
  121405. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121406. 1, 32,
  121407. _huff_lengthlist_line_2048x27_1sub0,
  121408. 0, 0, 0, 0, 0,
  121409. NULL,
  121410. NULL,
  121411. NULL,
  121412. NULL,
  121413. 0
  121414. };
  121415. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121418. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121419. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121420. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121421. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121422. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121423. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121424. };
  121425. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121426. 1, 128,
  121427. _huff_lengthlist_line_2048x27_1sub1,
  121428. 0, 0, 0, 0, 0,
  121429. NULL,
  121430. NULL,
  121431. NULL,
  121432. NULL,
  121433. 0
  121434. };
  121435. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121436. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121437. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121438. };
  121439. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121440. 1, 32,
  121441. _huff_lengthlist_line_2048x27_2sub0,
  121442. 0, 0, 0, 0, 0,
  121443. NULL,
  121444. NULL,
  121445. NULL,
  121446. NULL,
  121447. 0
  121448. };
  121449. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121452. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121453. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121454. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121455. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121456. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121457. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121458. };
  121459. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121460. 1, 128,
  121461. _huff_lengthlist_line_2048x27_2sub1,
  121462. 0, 0, 0, 0, 0,
  121463. NULL,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. 0
  121468. };
  121469. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121470. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121471. 5, 5,
  121472. };
  121473. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121474. 1, 18,
  121475. _huff_lengthlist_line_2048x27_3sub1,
  121476. 0, 0, 0, 0, 0,
  121477. NULL,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. 0
  121482. };
  121483. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121485. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121486. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121487. 10,12,
  121488. };
  121489. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121490. 1, 50,
  121491. _huff_lengthlist_line_2048x27_3sub2,
  121492. 0, 0, 0, 0, 0,
  121493. NULL,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. 0
  121498. };
  121499. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  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, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121504. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121505. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121506. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121507. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121508. };
  121509. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121510. 1, 128,
  121511. _huff_lengthlist_line_2048x27_3sub3,
  121512. 0, 0, 0, 0, 0,
  121513. NULL,
  121514. NULL,
  121515. NULL,
  121516. NULL,
  121517. 0
  121518. };
  121519. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121520. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121521. 4, 5,
  121522. };
  121523. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121524. 1, 18,
  121525. _huff_lengthlist_line_2048x27_4sub1,
  121526. 0, 0, 0, 0, 0,
  121527. NULL,
  121528. NULL,
  121529. NULL,
  121530. NULL,
  121531. 0
  121532. };
  121533. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121535. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121536. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121537. 10,10,
  121538. };
  121539. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121540. 1, 50,
  121541. _huff_lengthlist_line_2048x27_4sub2,
  121542. 0, 0, 0, 0, 0,
  121543. NULL,
  121544. NULL,
  121545. NULL,
  121546. NULL,
  121547. 0
  121548. };
  121549. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121553. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121554. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121555. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121556. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121557. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121558. };
  121559. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121560. 1, 128,
  121561. _huff_lengthlist_line_2048x27_4sub3,
  121562. 0, 0, 0, 0, 0,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. NULL,
  121567. 0
  121568. };
  121569. static long _huff_lengthlist_line_256x4low_class0[] = {
  121570. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121571. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121572. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121573. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121574. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121575. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121576. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121577. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121578. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121579. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121580. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121581. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121582. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121583. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121584. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121585. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121586. };
  121587. static static_codebook _huff_book_line_256x4low_class0 = {
  121588. 1, 256,
  121589. _huff_lengthlist_line_256x4low_class0,
  121590. 0, 0, 0, 0, 0,
  121591. NULL,
  121592. NULL,
  121593. NULL,
  121594. NULL,
  121595. 0
  121596. };
  121597. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121598. 1, 3, 2, 3,
  121599. };
  121600. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121601. 1, 4,
  121602. _huff_lengthlist_line_256x4low_0sub0,
  121603. 0, 0, 0, 0, 0,
  121604. NULL,
  121605. NULL,
  121606. NULL,
  121607. NULL,
  121608. 0
  121609. };
  121610. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121611. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121612. };
  121613. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121614. 1, 10,
  121615. _huff_lengthlist_line_256x4low_0sub1,
  121616. 0, 0, 0, 0, 0,
  121617. NULL,
  121618. NULL,
  121619. NULL,
  121620. NULL,
  121621. 0
  121622. };
  121623. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121625. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121626. };
  121627. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121628. 1, 25,
  121629. _huff_lengthlist_line_256x4low_0sub2,
  121630. 0, 0, 0, 0, 0,
  121631. NULL,
  121632. NULL,
  121633. NULL,
  121634. NULL,
  121635. 0
  121636. };
  121637. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  121640. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121641. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121642. };
  121643. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121644. 1, 64,
  121645. _huff_lengthlist_line_256x4low_0sub3,
  121646. 0, 0, 0, 0, 0,
  121647. NULL,
  121648. NULL,
  121649. NULL,
  121650. NULL,
  121651. 0
  121652. };
  121653. /*** End of inlined file: floor_books.h ***/
  121654. static static_codebook *_floor_128x4_books[]={
  121655. &_huff_book_line_128x4_class0,
  121656. &_huff_book_line_128x4_0sub0,
  121657. &_huff_book_line_128x4_0sub1,
  121658. &_huff_book_line_128x4_0sub2,
  121659. &_huff_book_line_128x4_0sub3,
  121660. };
  121661. static static_codebook *_floor_256x4_books[]={
  121662. &_huff_book_line_256x4_class0,
  121663. &_huff_book_line_256x4_0sub0,
  121664. &_huff_book_line_256x4_0sub1,
  121665. &_huff_book_line_256x4_0sub2,
  121666. &_huff_book_line_256x4_0sub3,
  121667. };
  121668. static static_codebook *_floor_128x7_books[]={
  121669. &_huff_book_line_128x7_class0,
  121670. &_huff_book_line_128x7_class1,
  121671. &_huff_book_line_128x7_0sub1,
  121672. &_huff_book_line_128x7_0sub2,
  121673. &_huff_book_line_128x7_0sub3,
  121674. &_huff_book_line_128x7_1sub1,
  121675. &_huff_book_line_128x7_1sub2,
  121676. &_huff_book_line_128x7_1sub3,
  121677. };
  121678. static static_codebook *_floor_256x7_books[]={
  121679. &_huff_book_line_256x7_class0,
  121680. &_huff_book_line_256x7_class1,
  121681. &_huff_book_line_256x7_0sub1,
  121682. &_huff_book_line_256x7_0sub2,
  121683. &_huff_book_line_256x7_0sub3,
  121684. &_huff_book_line_256x7_1sub1,
  121685. &_huff_book_line_256x7_1sub2,
  121686. &_huff_book_line_256x7_1sub3,
  121687. };
  121688. static static_codebook *_floor_128x11_books[]={
  121689. &_huff_book_line_128x11_class1,
  121690. &_huff_book_line_128x11_class2,
  121691. &_huff_book_line_128x11_class3,
  121692. &_huff_book_line_128x11_0sub0,
  121693. &_huff_book_line_128x11_1sub0,
  121694. &_huff_book_line_128x11_1sub1,
  121695. &_huff_book_line_128x11_2sub1,
  121696. &_huff_book_line_128x11_2sub2,
  121697. &_huff_book_line_128x11_2sub3,
  121698. &_huff_book_line_128x11_3sub1,
  121699. &_huff_book_line_128x11_3sub2,
  121700. &_huff_book_line_128x11_3sub3,
  121701. };
  121702. static static_codebook *_floor_128x17_books[]={
  121703. &_huff_book_line_128x17_class1,
  121704. &_huff_book_line_128x17_class2,
  121705. &_huff_book_line_128x17_class3,
  121706. &_huff_book_line_128x17_0sub0,
  121707. &_huff_book_line_128x17_1sub0,
  121708. &_huff_book_line_128x17_1sub1,
  121709. &_huff_book_line_128x17_2sub1,
  121710. &_huff_book_line_128x17_2sub2,
  121711. &_huff_book_line_128x17_2sub3,
  121712. &_huff_book_line_128x17_3sub1,
  121713. &_huff_book_line_128x17_3sub2,
  121714. &_huff_book_line_128x17_3sub3,
  121715. };
  121716. static static_codebook *_floor_256x4low_books[]={
  121717. &_huff_book_line_256x4low_class0,
  121718. &_huff_book_line_256x4low_0sub0,
  121719. &_huff_book_line_256x4low_0sub1,
  121720. &_huff_book_line_256x4low_0sub2,
  121721. &_huff_book_line_256x4low_0sub3,
  121722. };
  121723. static static_codebook *_floor_1024x27_books[]={
  121724. &_huff_book_line_1024x27_class1,
  121725. &_huff_book_line_1024x27_class2,
  121726. &_huff_book_line_1024x27_class3,
  121727. &_huff_book_line_1024x27_class4,
  121728. &_huff_book_line_1024x27_0sub0,
  121729. &_huff_book_line_1024x27_1sub0,
  121730. &_huff_book_line_1024x27_1sub1,
  121731. &_huff_book_line_1024x27_2sub0,
  121732. &_huff_book_line_1024x27_2sub1,
  121733. &_huff_book_line_1024x27_3sub1,
  121734. &_huff_book_line_1024x27_3sub2,
  121735. &_huff_book_line_1024x27_3sub3,
  121736. &_huff_book_line_1024x27_4sub1,
  121737. &_huff_book_line_1024x27_4sub2,
  121738. &_huff_book_line_1024x27_4sub3,
  121739. };
  121740. static static_codebook *_floor_2048x27_books[]={
  121741. &_huff_book_line_2048x27_class1,
  121742. &_huff_book_line_2048x27_class2,
  121743. &_huff_book_line_2048x27_class3,
  121744. &_huff_book_line_2048x27_class4,
  121745. &_huff_book_line_2048x27_0sub0,
  121746. &_huff_book_line_2048x27_1sub0,
  121747. &_huff_book_line_2048x27_1sub1,
  121748. &_huff_book_line_2048x27_2sub0,
  121749. &_huff_book_line_2048x27_2sub1,
  121750. &_huff_book_line_2048x27_3sub1,
  121751. &_huff_book_line_2048x27_3sub2,
  121752. &_huff_book_line_2048x27_3sub3,
  121753. &_huff_book_line_2048x27_4sub1,
  121754. &_huff_book_line_2048x27_4sub2,
  121755. &_huff_book_line_2048x27_4sub3,
  121756. };
  121757. static static_codebook *_floor_512x17_books[]={
  121758. &_huff_book_line_512x17_class1,
  121759. &_huff_book_line_512x17_class2,
  121760. &_huff_book_line_512x17_class3,
  121761. &_huff_book_line_512x17_0sub0,
  121762. &_huff_book_line_512x17_1sub0,
  121763. &_huff_book_line_512x17_1sub1,
  121764. &_huff_book_line_512x17_2sub1,
  121765. &_huff_book_line_512x17_2sub2,
  121766. &_huff_book_line_512x17_2sub3,
  121767. &_huff_book_line_512x17_3sub1,
  121768. &_huff_book_line_512x17_3sub2,
  121769. &_huff_book_line_512x17_3sub3,
  121770. };
  121771. static static_codebook **_floor_books[10]={
  121772. _floor_128x4_books,
  121773. _floor_256x4_books,
  121774. _floor_128x7_books,
  121775. _floor_256x7_books,
  121776. _floor_128x11_books,
  121777. _floor_128x17_books,
  121778. _floor_256x4low_books,
  121779. _floor_1024x27_books,
  121780. _floor_2048x27_books,
  121781. _floor_512x17_books,
  121782. };
  121783. static vorbis_info_floor1 _floor[10]={
  121784. /* 128 x 4 */
  121785. {
  121786. 1,{0},{4},{2},{0},
  121787. {{1,2,3,4}},
  121788. 4,{0,128, 33,8,16,70},
  121789. 60,30,500, 1.,18., -1
  121790. },
  121791. /* 256 x 4 */
  121792. {
  121793. 1,{0},{4},{2},{0},
  121794. {{1,2,3,4}},
  121795. 4,{0,256, 66,16,32,140},
  121796. 60,30,500, 1.,18., -1
  121797. },
  121798. /* 128 x 7 */
  121799. {
  121800. 2,{0,1},{3,4},{2,2},{0,1},
  121801. {{-1,2,3,4},{-1,5,6,7}},
  121802. 4,{0,128, 14,4,58, 2,8,28,90},
  121803. 60,30,500, 1.,18., -1
  121804. },
  121805. /* 256 x 7 */
  121806. {
  121807. 2,{0,1},{3,4},{2,2},{0,1},
  121808. {{-1,2,3,4},{-1,5,6,7}},
  121809. 4,{0,256, 28,8,116, 4,16,56,180},
  121810. 60,30,500, 1.,18., -1
  121811. },
  121812. /* 128 x 11 */
  121813. {
  121814. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121815. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121816. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121817. 60,30,500, 1,18., -1
  121818. },
  121819. /* 128 x 17 */
  121820. {
  121821. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121822. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121823. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  121824. 60,30,500, 1,18., -1
  121825. },
  121826. /* 256 x 4 (low bitrate version) */
  121827. {
  121828. 1,{0},{4},{2},{0},
  121829. {{1,2,3,4}},
  121830. 4,{0,256, 66,16,32,140},
  121831. 60,30,500, 1.,18., -1
  121832. },
  121833. /* 1024 x 27 */
  121834. {
  121835. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121836. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121837. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  121838. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  121839. 60,30,500, 3,18., -1 /* lowpass */
  121840. },
  121841. /* 2048 x 27 */
  121842. {
  121843. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121844. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121845. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  121846. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  121847. 60,30,500, 3,18., -1 /* lowpass */
  121848. },
  121849. /* 512 x 17 */
  121850. {
  121851. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121852. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121853. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  121854. 7,23,39, 55,79,110, 156,232,360},
  121855. 60,30,500, 1,18., -1 /* lowpass! */
  121856. },
  121857. };
  121858. /*** End of inlined file: floor_all.h ***/
  121859. /*** Start of inlined file: residue_44.h ***/
  121860. /*** Start of inlined file: res_books_stereo.h ***/
  121861. static long _vq_quantlist__16c0_s_p1_0[] = {
  121862. 1,
  121863. 0,
  121864. 2,
  121865. };
  121866. static long _vq_lengthlist__16c0_s_p1_0[] = {
  121867. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121868. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  121873. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121878. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121913. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  121918. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  121923. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121959. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121964. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121969. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0,
  122278. };
  122279. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122280. -0.5, 0.5,
  122281. };
  122282. static long _vq_quantmap__16c0_s_p1_0[] = {
  122283. 1, 0, 2,
  122284. };
  122285. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122286. _vq_quantthresh__16c0_s_p1_0,
  122287. _vq_quantmap__16c0_s_p1_0,
  122288. 3,
  122289. 3
  122290. };
  122291. static static_codebook _16c0_s_p1_0 = {
  122292. 8, 6561,
  122293. _vq_lengthlist__16c0_s_p1_0,
  122294. 1, -535822336, 1611661312, 2, 0,
  122295. _vq_quantlist__16c0_s_p1_0,
  122296. NULL,
  122297. &_vq_auxt__16c0_s_p1_0,
  122298. NULL,
  122299. 0
  122300. };
  122301. static long _vq_quantlist__16c0_s_p2_0[] = {
  122302. 2,
  122303. 1,
  122304. 3,
  122305. 0,
  122306. 4,
  122307. };
  122308. static long _vq_lengthlist__16c0_s_p2_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,
  122349. };
  122350. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122351. -1.5, -0.5, 0.5, 1.5,
  122352. };
  122353. static long _vq_quantmap__16c0_s_p2_0[] = {
  122354. 3, 1, 0, 2, 4,
  122355. };
  122356. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122357. _vq_quantthresh__16c0_s_p2_0,
  122358. _vq_quantmap__16c0_s_p2_0,
  122359. 5,
  122360. 5
  122361. };
  122362. static static_codebook _16c0_s_p2_0 = {
  122363. 4, 625,
  122364. _vq_lengthlist__16c0_s_p2_0,
  122365. 1, -533725184, 1611661312, 3, 0,
  122366. _vq_quantlist__16c0_s_p2_0,
  122367. NULL,
  122368. &_vq_auxt__16c0_s_p2_0,
  122369. NULL,
  122370. 0
  122371. };
  122372. static long _vq_quantlist__16c0_s_p3_0[] = {
  122373. 2,
  122374. 1,
  122375. 3,
  122376. 0,
  122377. 4,
  122378. };
  122379. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122380. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  122420. };
  122421. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122422. -1.5, -0.5, 0.5, 1.5,
  122423. };
  122424. static long _vq_quantmap__16c0_s_p3_0[] = {
  122425. 3, 1, 0, 2, 4,
  122426. };
  122427. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122428. _vq_quantthresh__16c0_s_p3_0,
  122429. _vq_quantmap__16c0_s_p3_0,
  122430. 5,
  122431. 5
  122432. };
  122433. static static_codebook _16c0_s_p3_0 = {
  122434. 4, 625,
  122435. _vq_lengthlist__16c0_s_p3_0,
  122436. 1, -533725184, 1611661312, 3, 0,
  122437. _vq_quantlist__16c0_s_p3_0,
  122438. NULL,
  122439. &_vq_auxt__16c0_s_p3_0,
  122440. NULL,
  122441. 0
  122442. };
  122443. static long _vq_quantlist__16c0_s_p4_0[] = {
  122444. 4,
  122445. 3,
  122446. 5,
  122447. 2,
  122448. 6,
  122449. 1,
  122450. 7,
  122451. 0,
  122452. 8,
  122453. };
  122454. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122455. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122456. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122457. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122458. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122459. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0,
  122461. };
  122462. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122463. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122464. };
  122465. static long _vq_quantmap__16c0_s_p4_0[] = {
  122466. 7, 5, 3, 1, 0, 2, 4, 6,
  122467. 8,
  122468. };
  122469. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122470. _vq_quantthresh__16c0_s_p4_0,
  122471. _vq_quantmap__16c0_s_p4_0,
  122472. 9,
  122473. 9
  122474. };
  122475. static static_codebook _16c0_s_p4_0 = {
  122476. 2, 81,
  122477. _vq_lengthlist__16c0_s_p4_0,
  122478. 1, -531628032, 1611661312, 4, 0,
  122479. _vq_quantlist__16c0_s_p4_0,
  122480. NULL,
  122481. &_vq_auxt__16c0_s_p4_0,
  122482. NULL,
  122483. 0
  122484. };
  122485. static long _vq_quantlist__16c0_s_p5_0[] = {
  122486. 4,
  122487. 3,
  122488. 5,
  122489. 2,
  122490. 6,
  122491. 1,
  122492. 7,
  122493. 0,
  122494. 8,
  122495. };
  122496. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122497. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122498. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122499. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122500. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122501. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122502. 10,
  122503. };
  122504. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122505. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122506. };
  122507. static long _vq_quantmap__16c0_s_p5_0[] = {
  122508. 7, 5, 3, 1, 0, 2, 4, 6,
  122509. 8,
  122510. };
  122511. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122512. _vq_quantthresh__16c0_s_p5_0,
  122513. _vq_quantmap__16c0_s_p5_0,
  122514. 9,
  122515. 9
  122516. };
  122517. static static_codebook _16c0_s_p5_0 = {
  122518. 2, 81,
  122519. _vq_lengthlist__16c0_s_p5_0,
  122520. 1, -531628032, 1611661312, 4, 0,
  122521. _vq_quantlist__16c0_s_p5_0,
  122522. NULL,
  122523. &_vq_auxt__16c0_s_p5_0,
  122524. NULL,
  122525. 0
  122526. };
  122527. static long _vq_quantlist__16c0_s_p6_0[] = {
  122528. 8,
  122529. 7,
  122530. 9,
  122531. 6,
  122532. 10,
  122533. 5,
  122534. 11,
  122535. 4,
  122536. 12,
  122537. 3,
  122538. 13,
  122539. 2,
  122540. 14,
  122541. 1,
  122542. 15,
  122543. 0,
  122544. 16,
  122545. };
  122546. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122547. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122548. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122549. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122550. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122551. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122552. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122553. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122554. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122555. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122556. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122557. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122558. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122559. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122560. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122561. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122562. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122563. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122565. 14,
  122566. };
  122567. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122568. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122569. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122570. };
  122571. static long _vq_quantmap__16c0_s_p6_0[] = {
  122572. 15, 13, 11, 9, 7, 5, 3, 1,
  122573. 0, 2, 4, 6, 8, 10, 12, 14,
  122574. 16,
  122575. };
  122576. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122577. _vq_quantthresh__16c0_s_p6_0,
  122578. _vq_quantmap__16c0_s_p6_0,
  122579. 17,
  122580. 17
  122581. };
  122582. static static_codebook _16c0_s_p6_0 = {
  122583. 2, 289,
  122584. _vq_lengthlist__16c0_s_p6_0,
  122585. 1, -529530880, 1611661312, 5, 0,
  122586. _vq_quantlist__16c0_s_p6_0,
  122587. NULL,
  122588. &_vq_auxt__16c0_s_p6_0,
  122589. NULL,
  122590. 0
  122591. };
  122592. static long _vq_quantlist__16c0_s_p7_0[] = {
  122593. 1,
  122594. 0,
  122595. 2,
  122596. };
  122597. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122598. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122599. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122600. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122601. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122602. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122603. 13,
  122604. };
  122605. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122606. -5.5, 5.5,
  122607. };
  122608. static long _vq_quantmap__16c0_s_p7_0[] = {
  122609. 1, 0, 2,
  122610. };
  122611. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122612. _vq_quantthresh__16c0_s_p7_0,
  122613. _vq_quantmap__16c0_s_p7_0,
  122614. 3,
  122615. 3
  122616. };
  122617. static static_codebook _16c0_s_p7_0 = {
  122618. 4, 81,
  122619. _vq_lengthlist__16c0_s_p7_0,
  122620. 1, -529137664, 1618345984, 2, 0,
  122621. _vq_quantlist__16c0_s_p7_0,
  122622. NULL,
  122623. &_vq_auxt__16c0_s_p7_0,
  122624. NULL,
  122625. 0
  122626. };
  122627. static long _vq_quantlist__16c0_s_p7_1[] = {
  122628. 5,
  122629. 4,
  122630. 6,
  122631. 3,
  122632. 7,
  122633. 2,
  122634. 8,
  122635. 1,
  122636. 9,
  122637. 0,
  122638. 10,
  122639. };
  122640. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122641. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122642. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122643. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122644. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122645. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122646. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122647. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122648. 11,11,11, 9, 9, 9, 9,10,10,
  122649. };
  122650. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122651. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122652. 3.5, 4.5,
  122653. };
  122654. static long _vq_quantmap__16c0_s_p7_1[] = {
  122655. 9, 7, 5, 3, 1, 0, 2, 4,
  122656. 6, 8, 10,
  122657. };
  122658. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122659. _vq_quantthresh__16c0_s_p7_1,
  122660. _vq_quantmap__16c0_s_p7_1,
  122661. 11,
  122662. 11
  122663. };
  122664. static static_codebook _16c0_s_p7_1 = {
  122665. 2, 121,
  122666. _vq_lengthlist__16c0_s_p7_1,
  122667. 1, -531365888, 1611661312, 4, 0,
  122668. _vq_quantlist__16c0_s_p7_1,
  122669. NULL,
  122670. &_vq_auxt__16c0_s_p7_1,
  122671. NULL,
  122672. 0
  122673. };
  122674. static long _vq_quantlist__16c0_s_p8_0[] = {
  122675. 6,
  122676. 5,
  122677. 7,
  122678. 4,
  122679. 8,
  122680. 3,
  122681. 9,
  122682. 2,
  122683. 10,
  122684. 1,
  122685. 11,
  122686. 0,
  122687. 12,
  122688. };
  122689. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122690. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122691. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122692. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122693. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122694. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122695. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122696. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122697. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122698. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122699. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122700. 0,12,13,13,12,13,14,14,14,
  122701. };
  122702. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122703. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122704. 12.5, 17.5, 22.5, 27.5,
  122705. };
  122706. static long _vq_quantmap__16c0_s_p8_0[] = {
  122707. 11, 9, 7, 5, 3, 1, 0, 2,
  122708. 4, 6, 8, 10, 12,
  122709. };
  122710. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122711. _vq_quantthresh__16c0_s_p8_0,
  122712. _vq_quantmap__16c0_s_p8_0,
  122713. 13,
  122714. 13
  122715. };
  122716. static static_codebook _16c0_s_p8_0 = {
  122717. 2, 169,
  122718. _vq_lengthlist__16c0_s_p8_0,
  122719. 1, -526516224, 1616117760, 4, 0,
  122720. _vq_quantlist__16c0_s_p8_0,
  122721. NULL,
  122722. &_vq_auxt__16c0_s_p8_0,
  122723. NULL,
  122724. 0
  122725. };
  122726. static long _vq_quantlist__16c0_s_p8_1[] = {
  122727. 2,
  122728. 1,
  122729. 3,
  122730. 0,
  122731. 4,
  122732. };
  122733. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122734. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122735. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122736. };
  122737. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122738. -1.5, -0.5, 0.5, 1.5,
  122739. };
  122740. static long _vq_quantmap__16c0_s_p8_1[] = {
  122741. 3, 1, 0, 2, 4,
  122742. };
  122743. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122744. _vq_quantthresh__16c0_s_p8_1,
  122745. _vq_quantmap__16c0_s_p8_1,
  122746. 5,
  122747. 5
  122748. };
  122749. static static_codebook _16c0_s_p8_1 = {
  122750. 2, 25,
  122751. _vq_lengthlist__16c0_s_p8_1,
  122752. 1, -533725184, 1611661312, 3, 0,
  122753. _vq_quantlist__16c0_s_p8_1,
  122754. NULL,
  122755. &_vq_auxt__16c0_s_p8_1,
  122756. NULL,
  122757. 0
  122758. };
  122759. static long _vq_quantlist__16c0_s_p9_0[] = {
  122760. 1,
  122761. 0,
  122762. 2,
  122763. };
  122764. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122765. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122766. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122767. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122768. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122769. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122770. 7,
  122771. };
  122772. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122773. -157.5, 157.5,
  122774. };
  122775. static long _vq_quantmap__16c0_s_p9_0[] = {
  122776. 1, 0, 2,
  122777. };
  122778. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122779. _vq_quantthresh__16c0_s_p9_0,
  122780. _vq_quantmap__16c0_s_p9_0,
  122781. 3,
  122782. 3
  122783. };
  122784. static static_codebook _16c0_s_p9_0 = {
  122785. 4, 81,
  122786. _vq_lengthlist__16c0_s_p9_0,
  122787. 1, -518803456, 1628680192, 2, 0,
  122788. _vq_quantlist__16c0_s_p9_0,
  122789. NULL,
  122790. &_vq_auxt__16c0_s_p9_0,
  122791. NULL,
  122792. 0
  122793. };
  122794. static long _vq_quantlist__16c0_s_p9_1[] = {
  122795. 7,
  122796. 6,
  122797. 8,
  122798. 5,
  122799. 9,
  122800. 4,
  122801. 10,
  122802. 3,
  122803. 11,
  122804. 2,
  122805. 12,
  122806. 1,
  122807. 13,
  122808. 0,
  122809. 14,
  122810. };
  122811. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122812. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122813. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122814. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122815. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122816. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122820. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122821. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122823. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122824. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122826. 10,
  122827. };
  122828. static float _vq_quantthresh__16c0_s_p9_1[] = {
  122829. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122830. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122831. };
  122832. static long _vq_quantmap__16c0_s_p9_1[] = {
  122833. 13, 11, 9, 7, 5, 3, 1, 0,
  122834. 2, 4, 6, 8, 10, 12, 14,
  122835. };
  122836. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  122837. _vq_quantthresh__16c0_s_p9_1,
  122838. _vq_quantmap__16c0_s_p9_1,
  122839. 15,
  122840. 15
  122841. };
  122842. static static_codebook _16c0_s_p9_1 = {
  122843. 2, 225,
  122844. _vq_lengthlist__16c0_s_p9_1,
  122845. 1, -520986624, 1620377600, 4, 0,
  122846. _vq_quantlist__16c0_s_p9_1,
  122847. NULL,
  122848. &_vq_auxt__16c0_s_p9_1,
  122849. NULL,
  122850. 0
  122851. };
  122852. static long _vq_quantlist__16c0_s_p9_2[] = {
  122853. 10,
  122854. 9,
  122855. 11,
  122856. 8,
  122857. 12,
  122858. 7,
  122859. 13,
  122860. 6,
  122861. 14,
  122862. 5,
  122863. 15,
  122864. 4,
  122865. 16,
  122866. 3,
  122867. 17,
  122868. 2,
  122869. 18,
  122870. 1,
  122871. 19,
  122872. 0,
  122873. 20,
  122874. };
  122875. static long _vq_lengthlist__16c0_s_p9_2[] = {
  122876. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  122877. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  122878. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  122879. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  122880. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  122881. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  122882. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  122883. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  122884. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  122885. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  122886. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  122887. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  122888. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  122889. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  122890. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  122891. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  122892. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  122893. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  122894. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  122895. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  122896. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  122897. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  122898. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  122899. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  122900. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  122901. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  122902. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  122903. 10,11,10,10,11, 9,10,10,10,
  122904. };
  122905. static float _vq_quantthresh__16c0_s_p9_2[] = {
  122906. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122907. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122908. 6.5, 7.5, 8.5, 9.5,
  122909. };
  122910. static long _vq_quantmap__16c0_s_p9_2[] = {
  122911. 19, 17, 15, 13, 11, 9, 7, 5,
  122912. 3, 1, 0, 2, 4, 6, 8, 10,
  122913. 12, 14, 16, 18, 20,
  122914. };
  122915. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  122916. _vq_quantthresh__16c0_s_p9_2,
  122917. _vq_quantmap__16c0_s_p9_2,
  122918. 21,
  122919. 21
  122920. };
  122921. static static_codebook _16c0_s_p9_2 = {
  122922. 2, 441,
  122923. _vq_lengthlist__16c0_s_p9_2,
  122924. 1, -529268736, 1611661312, 5, 0,
  122925. _vq_quantlist__16c0_s_p9_2,
  122926. NULL,
  122927. &_vq_auxt__16c0_s_p9_2,
  122928. NULL,
  122929. 0
  122930. };
  122931. static long _huff_lengthlist__16c0_s_single[] = {
  122932. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  122933. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  122934. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  122935. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  122936. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  122937. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  122938. 16,16,18,18,
  122939. };
  122940. static static_codebook _huff_book__16c0_s_single = {
  122941. 2, 100,
  122942. _huff_lengthlist__16c0_s_single,
  122943. 0, 0, 0, 0, 0,
  122944. NULL,
  122945. NULL,
  122946. NULL,
  122947. NULL,
  122948. 0
  122949. };
  122950. static long _huff_lengthlist__16c1_s_long[] = {
  122951. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  122952. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  122953. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  122954. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  122955. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  122956. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  122957. 12,11,11,13,
  122958. };
  122959. static static_codebook _huff_book__16c1_s_long = {
  122960. 2, 100,
  122961. _huff_lengthlist__16c1_s_long,
  122962. 0, 0, 0, 0, 0,
  122963. NULL,
  122964. NULL,
  122965. NULL,
  122966. NULL,
  122967. 0
  122968. };
  122969. static long _vq_quantlist__16c1_s_p1_0[] = {
  122970. 1,
  122971. 0,
  122972. 2,
  122973. };
  122974. static long _vq_lengthlist__16c1_s_p1_0[] = {
  122975. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122976. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122981. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122986. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123021. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123026. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123031. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123067. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123072. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123077. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0,
  123386. };
  123387. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123388. -0.5, 0.5,
  123389. };
  123390. static long _vq_quantmap__16c1_s_p1_0[] = {
  123391. 1, 0, 2,
  123392. };
  123393. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123394. _vq_quantthresh__16c1_s_p1_0,
  123395. _vq_quantmap__16c1_s_p1_0,
  123396. 3,
  123397. 3
  123398. };
  123399. static static_codebook _16c1_s_p1_0 = {
  123400. 8, 6561,
  123401. _vq_lengthlist__16c1_s_p1_0,
  123402. 1, -535822336, 1611661312, 2, 0,
  123403. _vq_quantlist__16c1_s_p1_0,
  123404. NULL,
  123405. &_vq_auxt__16c1_s_p1_0,
  123406. NULL,
  123407. 0
  123408. };
  123409. static long _vq_quantlist__16c1_s_p2_0[] = {
  123410. 2,
  123411. 1,
  123412. 3,
  123413. 0,
  123414. 4,
  123415. };
  123416. static long _vq_lengthlist__16c1_s_p2_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,
  123457. };
  123458. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123459. -1.5, -0.5, 0.5, 1.5,
  123460. };
  123461. static long _vq_quantmap__16c1_s_p2_0[] = {
  123462. 3, 1, 0, 2, 4,
  123463. };
  123464. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123465. _vq_quantthresh__16c1_s_p2_0,
  123466. _vq_quantmap__16c1_s_p2_0,
  123467. 5,
  123468. 5
  123469. };
  123470. static static_codebook _16c1_s_p2_0 = {
  123471. 4, 625,
  123472. _vq_lengthlist__16c1_s_p2_0,
  123473. 1, -533725184, 1611661312, 3, 0,
  123474. _vq_quantlist__16c1_s_p2_0,
  123475. NULL,
  123476. &_vq_auxt__16c1_s_p2_0,
  123477. NULL,
  123478. 0
  123479. };
  123480. static long _vq_quantlist__16c1_s_p3_0[] = {
  123481. 2,
  123482. 1,
  123483. 3,
  123484. 0,
  123485. 4,
  123486. };
  123487. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123488. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  123528. };
  123529. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123530. -1.5, -0.5, 0.5, 1.5,
  123531. };
  123532. static long _vq_quantmap__16c1_s_p3_0[] = {
  123533. 3, 1, 0, 2, 4,
  123534. };
  123535. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123536. _vq_quantthresh__16c1_s_p3_0,
  123537. _vq_quantmap__16c1_s_p3_0,
  123538. 5,
  123539. 5
  123540. };
  123541. static static_codebook _16c1_s_p3_0 = {
  123542. 4, 625,
  123543. _vq_lengthlist__16c1_s_p3_0,
  123544. 1, -533725184, 1611661312, 3, 0,
  123545. _vq_quantlist__16c1_s_p3_0,
  123546. NULL,
  123547. &_vq_auxt__16c1_s_p3_0,
  123548. NULL,
  123549. 0
  123550. };
  123551. static long _vq_quantlist__16c1_s_p4_0[] = {
  123552. 4,
  123553. 3,
  123554. 5,
  123555. 2,
  123556. 6,
  123557. 1,
  123558. 7,
  123559. 0,
  123560. 8,
  123561. };
  123562. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123563. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123564. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123565. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123566. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123567. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0,
  123569. };
  123570. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123571. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123572. };
  123573. static long _vq_quantmap__16c1_s_p4_0[] = {
  123574. 7, 5, 3, 1, 0, 2, 4, 6,
  123575. 8,
  123576. };
  123577. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123578. _vq_quantthresh__16c1_s_p4_0,
  123579. _vq_quantmap__16c1_s_p4_0,
  123580. 9,
  123581. 9
  123582. };
  123583. static static_codebook _16c1_s_p4_0 = {
  123584. 2, 81,
  123585. _vq_lengthlist__16c1_s_p4_0,
  123586. 1, -531628032, 1611661312, 4, 0,
  123587. _vq_quantlist__16c1_s_p4_0,
  123588. NULL,
  123589. &_vq_auxt__16c1_s_p4_0,
  123590. NULL,
  123591. 0
  123592. };
  123593. static long _vq_quantlist__16c1_s_p5_0[] = {
  123594. 4,
  123595. 3,
  123596. 5,
  123597. 2,
  123598. 6,
  123599. 1,
  123600. 7,
  123601. 0,
  123602. 8,
  123603. };
  123604. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123605. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123606. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123607. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123608. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123609. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123610. 10,
  123611. };
  123612. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123613. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123614. };
  123615. static long _vq_quantmap__16c1_s_p5_0[] = {
  123616. 7, 5, 3, 1, 0, 2, 4, 6,
  123617. 8,
  123618. };
  123619. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123620. _vq_quantthresh__16c1_s_p5_0,
  123621. _vq_quantmap__16c1_s_p5_0,
  123622. 9,
  123623. 9
  123624. };
  123625. static static_codebook _16c1_s_p5_0 = {
  123626. 2, 81,
  123627. _vq_lengthlist__16c1_s_p5_0,
  123628. 1, -531628032, 1611661312, 4, 0,
  123629. _vq_quantlist__16c1_s_p5_0,
  123630. NULL,
  123631. &_vq_auxt__16c1_s_p5_0,
  123632. NULL,
  123633. 0
  123634. };
  123635. static long _vq_quantlist__16c1_s_p6_0[] = {
  123636. 8,
  123637. 7,
  123638. 9,
  123639. 6,
  123640. 10,
  123641. 5,
  123642. 11,
  123643. 4,
  123644. 12,
  123645. 3,
  123646. 13,
  123647. 2,
  123648. 14,
  123649. 1,
  123650. 15,
  123651. 0,
  123652. 16,
  123653. };
  123654. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123655. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123656. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123657. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123658. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123659. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123660. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123661. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123662. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123663. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123664. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123665. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123666. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123667. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123668. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123669. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123670. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123671. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123673. 14,
  123674. };
  123675. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123676. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123677. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123678. };
  123679. static long _vq_quantmap__16c1_s_p6_0[] = {
  123680. 15, 13, 11, 9, 7, 5, 3, 1,
  123681. 0, 2, 4, 6, 8, 10, 12, 14,
  123682. 16,
  123683. };
  123684. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123685. _vq_quantthresh__16c1_s_p6_0,
  123686. _vq_quantmap__16c1_s_p6_0,
  123687. 17,
  123688. 17
  123689. };
  123690. static static_codebook _16c1_s_p6_0 = {
  123691. 2, 289,
  123692. _vq_lengthlist__16c1_s_p6_0,
  123693. 1, -529530880, 1611661312, 5, 0,
  123694. _vq_quantlist__16c1_s_p6_0,
  123695. NULL,
  123696. &_vq_auxt__16c1_s_p6_0,
  123697. NULL,
  123698. 0
  123699. };
  123700. static long _vq_quantlist__16c1_s_p7_0[] = {
  123701. 1,
  123702. 0,
  123703. 2,
  123704. };
  123705. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123706. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123707. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123708. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123709. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123710. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123711. 11,
  123712. };
  123713. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123714. -5.5, 5.5,
  123715. };
  123716. static long _vq_quantmap__16c1_s_p7_0[] = {
  123717. 1, 0, 2,
  123718. };
  123719. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123720. _vq_quantthresh__16c1_s_p7_0,
  123721. _vq_quantmap__16c1_s_p7_0,
  123722. 3,
  123723. 3
  123724. };
  123725. static static_codebook _16c1_s_p7_0 = {
  123726. 4, 81,
  123727. _vq_lengthlist__16c1_s_p7_0,
  123728. 1, -529137664, 1618345984, 2, 0,
  123729. _vq_quantlist__16c1_s_p7_0,
  123730. NULL,
  123731. &_vq_auxt__16c1_s_p7_0,
  123732. NULL,
  123733. 0
  123734. };
  123735. static long _vq_quantlist__16c1_s_p7_1[] = {
  123736. 5,
  123737. 4,
  123738. 6,
  123739. 3,
  123740. 7,
  123741. 2,
  123742. 8,
  123743. 1,
  123744. 9,
  123745. 0,
  123746. 10,
  123747. };
  123748. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123749. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123750. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123751. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123752. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123753. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123754. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123755. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123756. 10,10,10, 8, 8, 8, 8, 9, 9,
  123757. };
  123758. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123759. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123760. 3.5, 4.5,
  123761. };
  123762. static long _vq_quantmap__16c1_s_p7_1[] = {
  123763. 9, 7, 5, 3, 1, 0, 2, 4,
  123764. 6, 8, 10,
  123765. };
  123766. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123767. _vq_quantthresh__16c1_s_p7_1,
  123768. _vq_quantmap__16c1_s_p7_1,
  123769. 11,
  123770. 11
  123771. };
  123772. static static_codebook _16c1_s_p7_1 = {
  123773. 2, 121,
  123774. _vq_lengthlist__16c1_s_p7_1,
  123775. 1, -531365888, 1611661312, 4, 0,
  123776. _vq_quantlist__16c1_s_p7_1,
  123777. NULL,
  123778. &_vq_auxt__16c1_s_p7_1,
  123779. NULL,
  123780. 0
  123781. };
  123782. static long _vq_quantlist__16c1_s_p8_0[] = {
  123783. 6,
  123784. 5,
  123785. 7,
  123786. 4,
  123787. 8,
  123788. 3,
  123789. 9,
  123790. 2,
  123791. 10,
  123792. 1,
  123793. 11,
  123794. 0,
  123795. 12,
  123796. };
  123797. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123798. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123799. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123800. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123801. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123802. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123803. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123804. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123805. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123806. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123807. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123808. 0,12,12,12,12,13,13,14,15,
  123809. };
  123810. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123811. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123812. 12.5, 17.5, 22.5, 27.5,
  123813. };
  123814. static long _vq_quantmap__16c1_s_p8_0[] = {
  123815. 11, 9, 7, 5, 3, 1, 0, 2,
  123816. 4, 6, 8, 10, 12,
  123817. };
  123818. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123819. _vq_quantthresh__16c1_s_p8_0,
  123820. _vq_quantmap__16c1_s_p8_0,
  123821. 13,
  123822. 13
  123823. };
  123824. static static_codebook _16c1_s_p8_0 = {
  123825. 2, 169,
  123826. _vq_lengthlist__16c1_s_p8_0,
  123827. 1, -526516224, 1616117760, 4, 0,
  123828. _vq_quantlist__16c1_s_p8_0,
  123829. NULL,
  123830. &_vq_auxt__16c1_s_p8_0,
  123831. NULL,
  123832. 0
  123833. };
  123834. static long _vq_quantlist__16c1_s_p8_1[] = {
  123835. 2,
  123836. 1,
  123837. 3,
  123838. 0,
  123839. 4,
  123840. };
  123841. static long _vq_lengthlist__16c1_s_p8_1[] = {
  123842. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123843. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123844. };
  123845. static float _vq_quantthresh__16c1_s_p8_1[] = {
  123846. -1.5, -0.5, 0.5, 1.5,
  123847. };
  123848. static long _vq_quantmap__16c1_s_p8_1[] = {
  123849. 3, 1, 0, 2, 4,
  123850. };
  123851. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  123852. _vq_quantthresh__16c1_s_p8_1,
  123853. _vq_quantmap__16c1_s_p8_1,
  123854. 5,
  123855. 5
  123856. };
  123857. static static_codebook _16c1_s_p8_1 = {
  123858. 2, 25,
  123859. _vq_lengthlist__16c1_s_p8_1,
  123860. 1, -533725184, 1611661312, 3, 0,
  123861. _vq_quantlist__16c1_s_p8_1,
  123862. NULL,
  123863. &_vq_auxt__16c1_s_p8_1,
  123864. NULL,
  123865. 0
  123866. };
  123867. static long _vq_quantlist__16c1_s_p9_0[] = {
  123868. 6,
  123869. 5,
  123870. 7,
  123871. 4,
  123872. 8,
  123873. 3,
  123874. 9,
  123875. 2,
  123876. 10,
  123877. 1,
  123878. 11,
  123879. 0,
  123880. 12,
  123881. };
  123882. static long _vq_lengthlist__16c1_s_p9_0[] = {
  123883. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123884. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123885. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123886. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123887. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123888. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123889. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123890. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123891. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123892. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123893. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123894. };
  123895. static float _vq_quantthresh__16c1_s_p9_0[] = {
  123896. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123897. 787.5, 1102.5, 1417.5, 1732.5,
  123898. };
  123899. static long _vq_quantmap__16c1_s_p9_0[] = {
  123900. 11, 9, 7, 5, 3, 1, 0, 2,
  123901. 4, 6, 8, 10, 12,
  123902. };
  123903. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  123904. _vq_quantthresh__16c1_s_p9_0,
  123905. _vq_quantmap__16c1_s_p9_0,
  123906. 13,
  123907. 13
  123908. };
  123909. static static_codebook _16c1_s_p9_0 = {
  123910. 2, 169,
  123911. _vq_lengthlist__16c1_s_p9_0,
  123912. 1, -513964032, 1628680192, 4, 0,
  123913. _vq_quantlist__16c1_s_p9_0,
  123914. NULL,
  123915. &_vq_auxt__16c1_s_p9_0,
  123916. NULL,
  123917. 0
  123918. };
  123919. static long _vq_quantlist__16c1_s_p9_1[] = {
  123920. 7,
  123921. 6,
  123922. 8,
  123923. 5,
  123924. 9,
  123925. 4,
  123926. 10,
  123927. 3,
  123928. 11,
  123929. 2,
  123930. 12,
  123931. 1,
  123932. 13,
  123933. 0,
  123934. 14,
  123935. };
  123936. static long _vq_lengthlist__16c1_s_p9_1[] = {
  123937. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  123938. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  123939. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  123940. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  123941. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  123942. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  123943. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  123944. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123945. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123946. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123947. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123948. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123949. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  123950. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123951. 13,
  123952. };
  123953. static float _vq_quantthresh__16c1_s_p9_1[] = {
  123954. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123955. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123956. };
  123957. static long _vq_quantmap__16c1_s_p9_1[] = {
  123958. 13, 11, 9, 7, 5, 3, 1, 0,
  123959. 2, 4, 6, 8, 10, 12, 14,
  123960. };
  123961. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  123962. _vq_quantthresh__16c1_s_p9_1,
  123963. _vq_quantmap__16c1_s_p9_1,
  123964. 15,
  123965. 15
  123966. };
  123967. static static_codebook _16c1_s_p9_1 = {
  123968. 2, 225,
  123969. _vq_lengthlist__16c1_s_p9_1,
  123970. 1, -520986624, 1620377600, 4, 0,
  123971. _vq_quantlist__16c1_s_p9_1,
  123972. NULL,
  123973. &_vq_auxt__16c1_s_p9_1,
  123974. NULL,
  123975. 0
  123976. };
  123977. static long _vq_quantlist__16c1_s_p9_2[] = {
  123978. 10,
  123979. 9,
  123980. 11,
  123981. 8,
  123982. 12,
  123983. 7,
  123984. 13,
  123985. 6,
  123986. 14,
  123987. 5,
  123988. 15,
  123989. 4,
  123990. 16,
  123991. 3,
  123992. 17,
  123993. 2,
  123994. 18,
  123995. 1,
  123996. 19,
  123997. 0,
  123998. 20,
  123999. };
  124000. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124001. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124002. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124003. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124004. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124005. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124006. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124007. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124008. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124009. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124010. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124011. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124012. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124013. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124014. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124015. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124016. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124017. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124018. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124019. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124020. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124021. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124022. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124023. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124024. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124025. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124026. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124027. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124028. 11,11,11,11,12,11,11,12,11,
  124029. };
  124030. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124031. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124032. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124033. 6.5, 7.5, 8.5, 9.5,
  124034. };
  124035. static long _vq_quantmap__16c1_s_p9_2[] = {
  124036. 19, 17, 15, 13, 11, 9, 7, 5,
  124037. 3, 1, 0, 2, 4, 6, 8, 10,
  124038. 12, 14, 16, 18, 20,
  124039. };
  124040. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124041. _vq_quantthresh__16c1_s_p9_2,
  124042. _vq_quantmap__16c1_s_p9_2,
  124043. 21,
  124044. 21
  124045. };
  124046. static static_codebook _16c1_s_p9_2 = {
  124047. 2, 441,
  124048. _vq_lengthlist__16c1_s_p9_2,
  124049. 1, -529268736, 1611661312, 5, 0,
  124050. _vq_quantlist__16c1_s_p9_2,
  124051. NULL,
  124052. &_vq_auxt__16c1_s_p9_2,
  124053. NULL,
  124054. 0
  124055. };
  124056. static long _huff_lengthlist__16c1_s_short[] = {
  124057. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124058. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124059. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124060. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124061. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124062. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124063. 9, 9,10,13,
  124064. };
  124065. static static_codebook _huff_book__16c1_s_short = {
  124066. 2, 100,
  124067. _huff_lengthlist__16c1_s_short,
  124068. 0, 0, 0, 0, 0,
  124069. NULL,
  124070. NULL,
  124071. NULL,
  124072. NULL,
  124073. 0
  124074. };
  124075. static long _huff_lengthlist__16c2_s_long[] = {
  124076. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124077. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124078. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124079. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124080. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124081. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124082. 14,14,16,18,
  124083. };
  124084. static static_codebook _huff_book__16c2_s_long = {
  124085. 2, 100,
  124086. _huff_lengthlist__16c2_s_long,
  124087. 0, 0, 0, 0, 0,
  124088. NULL,
  124089. NULL,
  124090. NULL,
  124091. NULL,
  124092. 0
  124093. };
  124094. static long _vq_quantlist__16c2_s_p1_0[] = {
  124095. 1,
  124096. 0,
  124097. 2,
  124098. };
  124099. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124100. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124101. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0,
  124106. };
  124107. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124108. -0.5, 0.5,
  124109. };
  124110. static long _vq_quantmap__16c2_s_p1_0[] = {
  124111. 1, 0, 2,
  124112. };
  124113. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124114. _vq_quantthresh__16c2_s_p1_0,
  124115. _vq_quantmap__16c2_s_p1_0,
  124116. 3,
  124117. 3
  124118. };
  124119. static static_codebook _16c2_s_p1_0 = {
  124120. 4, 81,
  124121. _vq_lengthlist__16c2_s_p1_0,
  124122. 1, -535822336, 1611661312, 2, 0,
  124123. _vq_quantlist__16c2_s_p1_0,
  124124. NULL,
  124125. &_vq_auxt__16c2_s_p1_0,
  124126. NULL,
  124127. 0
  124128. };
  124129. static long _vq_quantlist__16c2_s_p2_0[] = {
  124130. 2,
  124131. 1,
  124132. 3,
  124133. 0,
  124134. 4,
  124135. };
  124136. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124137. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124138. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124139. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124140. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124141. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124142. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124143. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124144. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124150. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124151. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124152. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124158. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124159. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124160. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124166. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124167. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124168. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124173. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124174. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124175. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124176. 13,
  124177. };
  124178. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124179. -1.5, -0.5, 0.5, 1.5,
  124180. };
  124181. static long _vq_quantmap__16c2_s_p2_0[] = {
  124182. 3, 1, 0, 2, 4,
  124183. };
  124184. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124185. _vq_quantthresh__16c2_s_p2_0,
  124186. _vq_quantmap__16c2_s_p2_0,
  124187. 5,
  124188. 5
  124189. };
  124190. static static_codebook _16c2_s_p2_0 = {
  124191. 4, 625,
  124192. _vq_lengthlist__16c2_s_p2_0,
  124193. 1, -533725184, 1611661312, 3, 0,
  124194. _vq_quantlist__16c2_s_p2_0,
  124195. NULL,
  124196. &_vq_auxt__16c2_s_p2_0,
  124197. NULL,
  124198. 0
  124199. };
  124200. static long _vq_quantlist__16c2_s_p3_0[] = {
  124201. 4,
  124202. 3,
  124203. 5,
  124204. 2,
  124205. 6,
  124206. 1,
  124207. 7,
  124208. 0,
  124209. 8,
  124210. };
  124211. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124212. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124213. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124214. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124215. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0,
  124218. };
  124219. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124220. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124221. };
  124222. static long _vq_quantmap__16c2_s_p3_0[] = {
  124223. 7, 5, 3, 1, 0, 2, 4, 6,
  124224. 8,
  124225. };
  124226. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124227. _vq_quantthresh__16c2_s_p3_0,
  124228. _vq_quantmap__16c2_s_p3_0,
  124229. 9,
  124230. 9
  124231. };
  124232. static static_codebook _16c2_s_p3_0 = {
  124233. 2, 81,
  124234. _vq_lengthlist__16c2_s_p3_0,
  124235. 1, -531628032, 1611661312, 4, 0,
  124236. _vq_quantlist__16c2_s_p3_0,
  124237. NULL,
  124238. &_vq_auxt__16c2_s_p3_0,
  124239. NULL,
  124240. 0
  124241. };
  124242. static long _vq_quantlist__16c2_s_p4_0[] = {
  124243. 8,
  124244. 7,
  124245. 9,
  124246. 6,
  124247. 10,
  124248. 5,
  124249. 11,
  124250. 4,
  124251. 12,
  124252. 3,
  124253. 13,
  124254. 2,
  124255. 14,
  124256. 1,
  124257. 15,
  124258. 0,
  124259. 16,
  124260. };
  124261. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124262. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124263. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124264. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124265. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124266. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124267. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124268. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124269. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124270. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124271. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0,
  124281. };
  124282. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124283. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124284. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124285. };
  124286. static long _vq_quantmap__16c2_s_p4_0[] = {
  124287. 15, 13, 11, 9, 7, 5, 3, 1,
  124288. 0, 2, 4, 6, 8, 10, 12, 14,
  124289. 16,
  124290. };
  124291. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124292. _vq_quantthresh__16c2_s_p4_0,
  124293. _vq_quantmap__16c2_s_p4_0,
  124294. 17,
  124295. 17
  124296. };
  124297. static static_codebook _16c2_s_p4_0 = {
  124298. 2, 289,
  124299. _vq_lengthlist__16c2_s_p4_0,
  124300. 1, -529530880, 1611661312, 5, 0,
  124301. _vq_quantlist__16c2_s_p4_0,
  124302. NULL,
  124303. &_vq_auxt__16c2_s_p4_0,
  124304. NULL,
  124305. 0
  124306. };
  124307. static long _vq_quantlist__16c2_s_p5_0[] = {
  124308. 1,
  124309. 0,
  124310. 2,
  124311. };
  124312. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124313. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124314. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124315. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124316. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124317. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124318. 12,
  124319. };
  124320. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124321. -5.5, 5.5,
  124322. };
  124323. static long _vq_quantmap__16c2_s_p5_0[] = {
  124324. 1, 0, 2,
  124325. };
  124326. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124327. _vq_quantthresh__16c2_s_p5_0,
  124328. _vq_quantmap__16c2_s_p5_0,
  124329. 3,
  124330. 3
  124331. };
  124332. static static_codebook _16c2_s_p5_0 = {
  124333. 4, 81,
  124334. _vq_lengthlist__16c2_s_p5_0,
  124335. 1, -529137664, 1618345984, 2, 0,
  124336. _vq_quantlist__16c2_s_p5_0,
  124337. NULL,
  124338. &_vq_auxt__16c2_s_p5_0,
  124339. NULL,
  124340. 0
  124341. };
  124342. static long _vq_quantlist__16c2_s_p5_1[] = {
  124343. 5,
  124344. 4,
  124345. 6,
  124346. 3,
  124347. 7,
  124348. 2,
  124349. 8,
  124350. 1,
  124351. 9,
  124352. 0,
  124353. 10,
  124354. };
  124355. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124356. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124357. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124358. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124359. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124360. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124361. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124362. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124363. 11,11,11, 7, 7, 8, 8, 8, 8,
  124364. };
  124365. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124366. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124367. 3.5, 4.5,
  124368. };
  124369. static long _vq_quantmap__16c2_s_p5_1[] = {
  124370. 9, 7, 5, 3, 1, 0, 2, 4,
  124371. 6, 8, 10,
  124372. };
  124373. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124374. _vq_quantthresh__16c2_s_p5_1,
  124375. _vq_quantmap__16c2_s_p5_1,
  124376. 11,
  124377. 11
  124378. };
  124379. static static_codebook _16c2_s_p5_1 = {
  124380. 2, 121,
  124381. _vq_lengthlist__16c2_s_p5_1,
  124382. 1, -531365888, 1611661312, 4, 0,
  124383. _vq_quantlist__16c2_s_p5_1,
  124384. NULL,
  124385. &_vq_auxt__16c2_s_p5_1,
  124386. NULL,
  124387. 0
  124388. };
  124389. static long _vq_quantlist__16c2_s_p6_0[] = {
  124390. 6,
  124391. 5,
  124392. 7,
  124393. 4,
  124394. 8,
  124395. 3,
  124396. 9,
  124397. 2,
  124398. 10,
  124399. 1,
  124400. 11,
  124401. 0,
  124402. 12,
  124403. };
  124404. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124405. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124406. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124407. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124408. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124409. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124410. 12, 8, 8,10,10,11,11,12,12,13,13, 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,
  124416. };
  124417. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124418. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124419. 12.5, 17.5, 22.5, 27.5,
  124420. };
  124421. static long _vq_quantmap__16c2_s_p6_0[] = {
  124422. 11, 9, 7, 5, 3, 1, 0, 2,
  124423. 4, 6, 8, 10, 12,
  124424. };
  124425. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124426. _vq_quantthresh__16c2_s_p6_0,
  124427. _vq_quantmap__16c2_s_p6_0,
  124428. 13,
  124429. 13
  124430. };
  124431. static static_codebook _16c2_s_p6_0 = {
  124432. 2, 169,
  124433. _vq_lengthlist__16c2_s_p6_0,
  124434. 1, -526516224, 1616117760, 4, 0,
  124435. _vq_quantlist__16c2_s_p6_0,
  124436. NULL,
  124437. &_vq_auxt__16c2_s_p6_0,
  124438. NULL,
  124439. 0
  124440. };
  124441. static long _vq_quantlist__16c2_s_p6_1[] = {
  124442. 2,
  124443. 1,
  124444. 3,
  124445. 0,
  124446. 4,
  124447. };
  124448. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124449. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124450. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124451. };
  124452. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124453. -1.5, -0.5, 0.5, 1.5,
  124454. };
  124455. static long _vq_quantmap__16c2_s_p6_1[] = {
  124456. 3, 1, 0, 2, 4,
  124457. };
  124458. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124459. _vq_quantthresh__16c2_s_p6_1,
  124460. _vq_quantmap__16c2_s_p6_1,
  124461. 5,
  124462. 5
  124463. };
  124464. static static_codebook _16c2_s_p6_1 = {
  124465. 2, 25,
  124466. _vq_lengthlist__16c2_s_p6_1,
  124467. 1, -533725184, 1611661312, 3, 0,
  124468. _vq_quantlist__16c2_s_p6_1,
  124469. NULL,
  124470. &_vq_auxt__16c2_s_p6_1,
  124471. NULL,
  124472. 0
  124473. };
  124474. static long _vq_quantlist__16c2_s_p7_0[] = {
  124475. 6,
  124476. 5,
  124477. 7,
  124478. 4,
  124479. 8,
  124480. 3,
  124481. 9,
  124482. 2,
  124483. 10,
  124484. 1,
  124485. 11,
  124486. 0,
  124487. 12,
  124488. };
  124489. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124490. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124491. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124492. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124493. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124494. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124495. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124496. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124497. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124498. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124499. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124500. 18,13,14,13,13,14,13,15,14,
  124501. };
  124502. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124503. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124504. 27.5, 38.5, 49.5, 60.5,
  124505. };
  124506. static long _vq_quantmap__16c2_s_p7_0[] = {
  124507. 11, 9, 7, 5, 3, 1, 0, 2,
  124508. 4, 6, 8, 10, 12,
  124509. };
  124510. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124511. _vq_quantthresh__16c2_s_p7_0,
  124512. _vq_quantmap__16c2_s_p7_0,
  124513. 13,
  124514. 13
  124515. };
  124516. static static_codebook _16c2_s_p7_0 = {
  124517. 2, 169,
  124518. _vq_lengthlist__16c2_s_p7_0,
  124519. 1, -523206656, 1618345984, 4, 0,
  124520. _vq_quantlist__16c2_s_p7_0,
  124521. NULL,
  124522. &_vq_auxt__16c2_s_p7_0,
  124523. NULL,
  124524. 0
  124525. };
  124526. static long _vq_quantlist__16c2_s_p7_1[] = {
  124527. 5,
  124528. 4,
  124529. 6,
  124530. 3,
  124531. 7,
  124532. 2,
  124533. 8,
  124534. 1,
  124535. 9,
  124536. 0,
  124537. 10,
  124538. };
  124539. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124540. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124541. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124542. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124543. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124544. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124545. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124546. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124547. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124548. };
  124549. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124550. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124551. 3.5, 4.5,
  124552. };
  124553. static long _vq_quantmap__16c2_s_p7_1[] = {
  124554. 9, 7, 5, 3, 1, 0, 2, 4,
  124555. 6, 8, 10,
  124556. };
  124557. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124558. _vq_quantthresh__16c2_s_p7_1,
  124559. _vq_quantmap__16c2_s_p7_1,
  124560. 11,
  124561. 11
  124562. };
  124563. static static_codebook _16c2_s_p7_1 = {
  124564. 2, 121,
  124565. _vq_lengthlist__16c2_s_p7_1,
  124566. 1, -531365888, 1611661312, 4, 0,
  124567. _vq_quantlist__16c2_s_p7_1,
  124568. NULL,
  124569. &_vq_auxt__16c2_s_p7_1,
  124570. NULL,
  124571. 0
  124572. };
  124573. static long _vq_quantlist__16c2_s_p8_0[] = {
  124574. 7,
  124575. 6,
  124576. 8,
  124577. 5,
  124578. 9,
  124579. 4,
  124580. 10,
  124581. 3,
  124582. 11,
  124583. 2,
  124584. 12,
  124585. 1,
  124586. 13,
  124587. 0,
  124588. 14,
  124589. };
  124590. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124591. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124592. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124593. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124594. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124595. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124596. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124597. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124598. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124599. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124600. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124601. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124602. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124603. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124604. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124605. 13,
  124606. };
  124607. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124608. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124609. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124610. };
  124611. static long _vq_quantmap__16c2_s_p8_0[] = {
  124612. 13, 11, 9, 7, 5, 3, 1, 0,
  124613. 2, 4, 6, 8, 10, 12, 14,
  124614. };
  124615. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124616. _vq_quantthresh__16c2_s_p8_0,
  124617. _vq_quantmap__16c2_s_p8_0,
  124618. 15,
  124619. 15
  124620. };
  124621. static static_codebook _16c2_s_p8_0 = {
  124622. 2, 225,
  124623. _vq_lengthlist__16c2_s_p8_0,
  124624. 1, -520986624, 1620377600, 4, 0,
  124625. _vq_quantlist__16c2_s_p8_0,
  124626. NULL,
  124627. &_vq_auxt__16c2_s_p8_0,
  124628. NULL,
  124629. 0
  124630. };
  124631. static long _vq_quantlist__16c2_s_p8_1[] = {
  124632. 10,
  124633. 9,
  124634. 11,
  124635. 8,
  124636. 12,
  124637. 7,
  124638. 13,
  124639. 6,
  124640. 14,
  124641. 5,
  124642. 15,
  124643. 4,
  124644. 16,
  124645. 3,
  124646. 17,
  124647. 2,
  124648. 18,
  124649. 1,
  124650. 19,
  124651. 0,
  124652. 20,
  124653. };
  124654. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124655. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124656. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124657. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124658. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124659. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124660. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124661. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124662. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124663. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124664. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124665. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124666. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124667. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124668. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124669. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124670. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124671. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124672. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124673. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124674. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124675. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124676. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124677. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124678. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124679. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124680. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124681. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124682. 10,11,10,10,10,10,10,10,10,
  124683. };
  124684. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124685. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124686. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124687. 6.5, 7.5, 8.5, 9.5,
  124688. };
  124689. static long _vq_quantmap__16c2_s_p8_1[] = {
  124690. 19, 17, 15, 13, 11, 9, 7, 5,
  124691. 3, 1, 0, 2, 4, 6, 8, 10,
  124692. 12, 14, 16, 18, 20,
  124693. };
  124694. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124695. _vq_quantthresh__16c2_s_p8_1,
  124696. _vq_quantmap__16c2_s_p8_1,
  124697. 21,
  124698. 21
  124699. };
  124700. static static_codebook _16c2_s_p8_1 = {
  124701. 2, 441,
  124702. _vq_lengthlist__16c2_s_p8_1,
  124703. 1, -529268736, 1611661312, 5, 0,
  124704. _vq_quantlist__16c2_s_p8_1,
  124705. NULL,
  124706. &_vq_auxt__16c2_s_p8_1,
  124707. NULL,
  124708. 0
  124709. };
  124710. static long _vq_quantlist__16c2_s_p9_0[] = {
  124711. 6,
  124712. 5,
  124713. 7,
  124714. 4,
  124715. 8,
  124716. 3,
  124717. 9,
  124718. 2,
  124719. 10,
  124720. 1,
  124721. 11,
  124722. 0,
  124723. 12,
  124724. };
  124725. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124726. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124727. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124728. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124731. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124732. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124733. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124734. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124735. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124736. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124737. };
  124738. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124739. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124740. 2327.5, 3258.5, 4189.5, 5120.5,
  124741. };
  124742. static long _vq_quantmap__16c2_s_p9_0[] = {
  124743. 11, 9, 7, 5, 3, 1, 0, 2,
  124744. 4, 6, 8, 10, 12,
  124745. };
  124746. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124747. _vq_quantthresh__16c2_s_p9_0,
  124748. _vq_quantmap__16c2_s_p9_0,
  124749. 13,
  124750. 13
  124751. };
  124752. static static_codebook _16c2_s_p9_0 = {
  124753. 2, 169,
  124754. _vq_lengthlist__16c2_s_p9_0,
  124755. 1, -510275072, 1631393792, 4, 0,
  124756. _vq_quantlist__16c2_s_p9_0,
  124757. NULL,
  124758. &_vq_auxt__16c2_s_p9_0,
  124759. NULL,
  124760. 0
  124761. };
  124762. static long _vq_quantlist__16c2_s_p9_1[] = {
  124763. 8,
  124764. 7,
  124765. 9,
  124766. 6,
  124767. 10,
  124768. 5,
  124769. 11,
  124770. 4,
  124771. 12,
  124772. 3,
  124773. 13,
  124774. 2,
  124775. 14,
  124776. 1,
  124777. 15,
  124778. 0,
  124779. 16,
  124780. };
  124781. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124782. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124783. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124784. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124785. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124786. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124787. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124788. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124789. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124790. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124793. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124795. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124796. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124797. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124798. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124800. 10,
  124801. };
  124802. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124803. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124804. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124805. };
  124806. static long _vq_quantmap__16c2_s_p9_1[] = {
  124807. 15, 13, 11, 9, 7, 5, 3, 1,
  124808. 0, 2, 4, 6, 8, 10, 12, 14,
  124809. 16,
  124810. };
  124811. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124812. _vq_quantthresh__16c2_s_p9_1,
  124813. _vq_quantmap__16c2_s_p9_1,
  124814. 17,
  124815. 17
  124816. };
  124817. static static_codebook _16c2_s_p9_1 = {
  124818. 2, 289,
  124819. _vq_lengthlist__16c2_s_p9_1,
  124820. 1, -518488064, 1622704128, 5, 0,
  124821. _vq_quantlist__16c2_s_p9_1,
  124822. NULL,
  124823. &_vq_auxt__16c2_s_p9_1,
  124824. NULL,
  124825. 0
  124826. };
  124827. static long _vq_quantlist__16c2_s_p9_2[] = {
  124828. 13,
  124829. 12,
  124830. 14,
  124831. 11,
  124832. 15,
  124833. 10,
  124834. 16,
  124835. 9,
  124836. 17,
  124837. 8,
  124838. 18,
  124839. 7,
  124840. 19,
  124841. 6,
  124842. 20,
  124843. 5,
  124844. 21,
  124845. 4,
  124846. 22,
  124847. 3,
  124848. 23,
  124849. 2,
  124850. 24,
  124851. 1,
  124852. 25,
  124853. 0,
  124854. 26,
  124855. };
  124856. static long _vq_lengthlist__16c2_s_p9_2[] = {
  124857. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  124858. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  124859. };
  124860. static float _vq_quantthresh__16c2_s_p9_2[] = {
  124861. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  124862. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124863. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  124864. 11.5, 12.5,
  124865. };
  124866. static long _vq_quantmap__16c2_s_p9_2[] = {
  124867. 25, 23, 21, 19, 17, 15, 13, 11,
  124868. 9, 7, 5, 3, 1, 0, 2, 4,
  124869. 6, 8, 10, 12, 14, 16, 18, 20,
  124870. 22, 24, 26,
  124871. };
  124872. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  124873. _vq_quantthresh__16c2_s_p9_2,
  124874. _vq_quantmap__16c2_s_p9_2,
  124875. 27,
  124876. 27
  124877. };
  124878. static static_codebook _16c2_s_p9_2 = {
  124879. 1, 27,
  124880. _vq_lengthlist__16c2_s_p9_2,
  124881. 1, -528875520, 1611661312, 5, 0,
  124882. _vq_quantlist__16c2_s_p9_2,
  124883. NULL,
  124884. &_vq_auxt__16c2_s_p9_2,
  124885. NULL,
  124886. 0
  124887. };
  124888. static long _huff_lengthlist__16c2_s_short[] = {
  124889. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  124890. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  124891. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  124892. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  124893. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  124894. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  124895. 15,12,14,14,
  124896. };
  124897. static static_codebook _huff_book__16c2_s_short = {
  124898. 2, 100,
  124899. _huff_lengthlist__16c2_s_short,
  124900. 0, 0, 0, 0, 0,
  124901. NULL,
  124902. NULL,
  124903. NULL,
  124904. NULL,
  124905. 0
  124906. };
  124907. static long _vq_quantlist__8c0_s_p1_0[] = {
  124908. 1,
  124909. 0,
  124910. 2,
  124911. };
  124912. static long _vq_lengthlist__8c0_s_p1_0[] = {
  124913. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124914. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  124919. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124924. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  124959. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  124964. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  124969. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125005. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125010. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125015. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0,
  125324. };
  125325. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125326. -0.5, 0.5,
  125327. };
  125328. static long _vq_quantmap__8c0_s_p1_0[] = {
  125329. 1, 0, 2,
  125330. };
  125331. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125332. _vq_quantthresh__8c0_s_p1_0,
  125333. _vq_quantmap__8c0_s_p1_0,
  125334. 3,
  125335. 3
  125336. };
  125337. static static_codebook _8c0_s_p1_0 = {
  125338. 8, 6561,
  125339. _vq_lengthlist__8c0_s_p1_0,
  125340. 1, -535822336, 1611661312, 2, 0,
  125341. _vq_quantlist__8c0_s_p1_0,
  125342. NULL,
  125343. &_vq_auxt__8c0_s_p1_0,
  125344. NULL,
  125345. 0
  125346. };
  125347. static long _vq_quantlist__8c0_s_p2_0[] = {
  125348. 2,
  125349. 1,
  125350. 3,
  125351. 0,
  125352. 4,
  125353. };
  125354. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0,
  125395. };
  125396. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125397. -1.5, -0.5, 0.5, 1.5,
  125398. };
  125399. static long _vq_quantmap__8c0_s_p2_0[] = {
  125400. 3, 1, 0, 2, 4,
  125401. };
  125402. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125403. _vq_quantthresh__8c0_s_p2_0,
  125404. _vq_quantmap__8c0_s_p2_0,
  125405. 5,
  125406. 5
  125407. };
  125408. static static_codebook _8c0_s_p2_0 = {
  125409. 4, 625,
  125410. _vq_lengthlist__8c0_s_p2_0,
  125411. 1, -533725184, 1611661312, 3, 0,
  125412. _vq_quantlist__8c0_s_p2_0,
  125413. NULL,
  125414. &_vq_auxt__8c0_s_p2_0,
  125415. NULL,
  125416. 0
  125417. };
  125418. static long _vq_quantlist__8c0_s_p3_0[] = {
  125419. 2,
  125420. 1,
  125421. 3,
  125422. 0,
  125423. 4,
  125424. };
  125425. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125426. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0,
  125466. };
  125467. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125468. -1.5, -0.5, 0.5, 1.5,
  125469. };
  125470. static long _vq_quantmap__8c0_s_p3_0[] = {
  125471. 3, 1, 0, 2, 4,
  125472. };
  125473. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125474. _vq_quantthresh__8c0_s_p3_0,
  125475. _vq_quantmap__8c0_s_p3_0,
  125476. 5,
  125477. 5
  125478. };
  125479. static static_codebook _8c0_s_p3_0 = {
  125480. 4, 625,
  125481. _vq_lengthlist__8c0_s_p3_0,
  125482. 1, -533725184, 1611661312, 3, 0,
  125483. _vq_quantlist__8c0_s_p3_0,
  125484. NULL,
  125485. &_vq_auxt__8c0_s_p3_0,
  125486. NULL,
  125487. 0
  125488. };
  125489. static long _vq_quantlist__8c0_s_p4_0[] = {
  125490. 4,
  125491. 3,
  125492. 5,
  125493. 2,
  125494. 6,
  125495. 1,
  125496. 7,
  125497. 0,
  125498. 8,
  125499. };
  125500. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125501. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125502. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125503. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125504. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125505. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0,
  125507. };
  125508. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125509. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125510. };
  125511. static long _vq_quantmap__8c0_s_p4_0[] = {
  125512. 7, 5, 3, 1, 0, 2, 4, 6,
  125513. 8,
  125514. };
  125515. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125516. _vq_quantthresh__8c0_s_p4_0,
  125517. _vq_quantmap__8c0_s_p4_0,
  125518. 9,
  125519. 9
  125520. };
  125521. static static_codebook _8c0_s_p4_0 = {
  125522. 2, 81,
  125523. _vq_lengthlist__8c0_s_p4_0,
  125524. 1, -531628032, 1611661312, 4, 0,
  125525. _vq_quantlist__8c0_s_p4_0,
  125526. NULL,
  125527. &_vq_auxt__8c0_s_p4_0,
  125528. NULL,
  125529. 0
  125530. };
  125531. static long _vq_quantlist__8c0_s_p5_0[] = {
  125532. 4,
  125533. 3,
  125534. 5,
  125535. 2,
  125536. 6,
  125537. 1,
  125538. 7,
  125539. 0,
  125540. 8,
  125541. };
  125542. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125543. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125544. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125545. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125546. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125547. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125548. 10,
  125549. };
  125550. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125551. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125552. };
  125553. static long _vq_quantmap__8c0_s_p5_0[] = {
  125554. 7, 5, 3, 1, 0, 2, 4, 6,
  125555. 8,
  125556. };
  125557. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125558. _vq_quantthresh__8c0_s_p5_0,
  125559. _vq_quantmap__8c0_s_p5_0,
  125560. 9,
  125561. 9
  125562. };
  125563. static static_codebook _8c0_s_p5_0 = {
  125564. 2, 81,
  125565. _vq_lengthlist__8c0_s_p5_0,
  125566. 1, -531628032, 1611661312, 4, 0,
  125567. _vq_quantlist__8c0_s_p5_0,
  125568. NULL,
  125569. &_vq_auxt__8c0_s_p5_0,
  125570. NULL,
  125571. 0
  125572. };
  125573. static long _vq_quantlist__8c0_s_p6_0[] = {
  125574. 8,
  125575. 7,
  125576. 9,
  125577. 6,
  125578. 10,
  125579. 5,
  125580. 11,
  125581. 4,
  125582. 12,
  125583. 3,
  125584. 13,
  125585. 2,
  125586. 14,
  125587. 1,
  125588. 15,
  125589. 0,
  125590. 16,
  125591. };
  125592. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125593. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125594. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125595. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125596. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125597. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125598. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125599. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125600. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125601. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125602. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125603. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125604. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125605. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125606. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125607. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125608. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125609. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125611. 14,
  125612. };
  125613. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125614. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125615. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125616. };
  125617. static long _vq_quantmap__8c0_s_p6_0[] = {
  125618. 15, 13, 11, 9, 7, 5, 3, 1,
  125619. 0, 2, 4, 6, 8, 10, 12, 14,
  125620. 16,
  125621. };
  125622. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125623. _vq_quantthresh__8c0_s_p6_0,
  125624. _vq_quantmap__8c0_s_p6_0,
  125625. 17,
  125626. 17
  125627. };
  125628. static static_codebook _8c0_s_p6_0 = {
  125629. 2, 289,
  125630. _vq_lengthlist__8c0_s_p6_0,
  125631. 1, -529530880, 1611661312, 5, 0,
  125632. _vq_quantlist__8c0_s_p6_0,
  125633. NULL,
  125634. &_vq_auxt__8c0_s_p6_0,
  125635. NULL,
  125636. 0
  125637. };
  125638. static long _vq_quantlist__8c0_s_p7_0[] = {
  125639. 1,
  125640. 0,
  125641. 2,
  125642. };
  125643. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125644. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125645. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125646. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125647. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125648. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125649. 10,
  125650. };
  125651. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125652. -5.5, 5.5,
  125653. };
  125654. static long _vq_quantmap__8c0_s_p7_0[] = {
  125655. 1, 0, 2,
  125656. };
  125657. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125658. _vq_quantthresh__8c0_s_p7_0,
  125659. _vq_quantmap__8c0_s_p7_0,
  125660. 3,
  125661. 3
  125662. };
  125663. static static_codebook _8c0_s_p7_0 = {
  125664. 4, 81,
  125665. _vq_lengthlist__8c0_s_p7_0,
  125666. 1, -529137664, 1618345984, 2, 0,
  125667. _vq_quantlist__8c0_s_p7_0,
  125668. NULL,
  125669. &_vq_auxt__8c0_s_p7_0,
  125670. NULL,
  125671. 0
  125672. };
  125673. static long _vq_quantlist__8c0_s_p7_1[] = {
  125674. 5,
  125675. 4,
  125676. 6,
  125677. 3,
  125678. 7,
  125679. 2,
  125680. 8,
  125681. 1,
  125682. 9,
  125683. 0,
  125684. 10,
  125685. };
  125686. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125687. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125688. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125689. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125690. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125691. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125692. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125693. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125694. 10,10,10, 9, 9, 9,10,10,10,
  125695. };
  125696. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125697. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125698. 3.5, 4.5,
  125699. };
  125700. static long _vq_quantmap__8c0_s_p7_1[] = {
  125701. 9, 7, 5, 3, 1, 0, 2, 4,
  125702. 6, 8, 10,
  125703. };
  125704. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125705. _vq_quantthresh__8c0_s_p7_1,
  125706. _vq_quantmap__8c0_s_p7_1,
  125707. 11,
  125708. 11
  125709. };
  125710. static static_codebook _8c0_s_p7_1 = {
  125711. 2, 121,
  125712. _vq_lengthlist__8c0_s_p7_1,
  125713. 1, -531365888, 1611661312, 4, 0,
  125714. _vq_quantlist__8c0_s_p7_1,
  125715. NULL,
  125716. &_vq_auxt__8c0_s_p7_1,
  125717. NULL,
  125718. 0
  125719. };
  125720. static long _vq_quantlist__8c0_s_p8_0[] = {
  125721. 6,
  125722. 5,
  125723. 7,
  125724. 4,
  125725. 8,
  125726. 3,
  125727. 9,
  125728. 2,
  125729. 10,
  125730. 1,
  125731. 11,
  125732. 0,
  125733. 12,
  125734. };
  125735. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125736. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125737. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125738. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125739. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125740. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125741. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125742. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125743. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125744. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125745. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125746. 0, 0,13,13,11,13,13,11,12,
  125747. };
  125748. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125749. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125750. 12.5, 17.5, 22.5, 27.5,
  125751. };
  125752. static long _vq_quantmap__8c0_s_p8_0[] = {
  125753. 11, 9, 7, 5, 3, 1, 0, 2,
  125754. 4, 6, 8, 10, 12,
  125755. };
  125756. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125757. _vq_quantthresh__8c0_s_p8_0,
  125758. _vq_quantmap__8c0_s_p8_0,
  125759. 13,
  125760. 13
  125761. };
  125762. static static_codebook _8c0_s_p8_0 = {
  125763. 2, 169,
  125764. _vq_lengthlist__8c0_s_p8_0,
  125765. 1, -526516224, 1616117760, 4, 0,
  125766. _vq_quantlist__8c0_s_p8_0,
  125767. NULL,
  125768. &_vq_auxt__8c0_s_p8_0,
  125769. NULL,
  125770. 0
  125771. };
  125772. static long _vq_quantlist__8c0_s_p8_1[] = {
  125773. 2,
  125774. 1,
  125775. 3,
  125776. 0,
  125777. 4,
  125778. };
  125779. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125780. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125781. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125782. };
  125783. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125784. -1.5, -0.5, 0.5, 1.5,
  125785. };
  125786. static long _vq_quantmap__8c0_s_p8_1[] = {
  125787. 3, 1, 0, 2, 4,
  125788. };
  125789. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125790. _vq_quantthresh__8c0_s_p8_1,
  125791. _vq_quantmap__8c0_s_p8_1,
  125792. 5,
  125793. 5
  125794. };
  125795. static static_codebook _8c0_s_p8_1 = {
  125796. 2, 25,
  125797. _vq_lengthlist__8c0_s_p8_1,
  125798. 1, -533725184, 1611661312, 3, 0,
  125799. _vq_quantlist__8c0_s_p8_1,
  125800. NULL,
  125801. &_vq_auxt__8c0_s_p8_1,
  125802. NULL,
  125803. 0
  125804. };
  125805. static long _vq_quantlist__8c0_s_p9_0[] = {
  125806. 1,
  125807. 0,
  125808. 2,
  125809. };
  125810. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125811. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125812. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125813. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125814. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125815. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125816. 7,
  125817. };
  125818. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125819. -157.5, 157.5,
  125820. };
  125821. static long _vq_quantmap__8c0_s_p9_0[] = {
  125822. 1, 0, 2,
  125823. };
  125824. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  125825. _vq_quantthresh__8c0_s_p9_0,
  125826. _vq_quantmap__8c0_s_p9_0,
  125827. 3,
  125828. 3
  125829. };
  125830. static static_codebook _8c0_s_p9_0 = {
  125831. 4, 81,
  125832. _vq_lengthlist__8c0_s_p9_0,
  125833. 1, -518803456, 1628680192, 2, 0,
  125834. _vq_quantlist__8c0_s_p9_0,
  125835. NULL,
  125836. &_vq_auxt__8c0_s_p9_0,
  125837. NULL,
  125838. 0
  125839. };
  125840. static long _vq_quantlist__8c0_s_p9_1[] = {
  125841. 7,
  125842. 6,
  125843. 8,
  125844. 5,
  125845. 9,
  125846. 4,
  125847. 10,
  125848. 3,
  125849. 11,
  125850. 2,
  125851. 12,
  125852. 1,
  125853. 13,
  125854. 0,
  125855. 14,
  125856. };
  125857. static long _vq_lengthlist__8c0_s_p9_1[] = {
  125858. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  125859. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  125860. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  125861. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  125862. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125863. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125872. 11,
  125873. };
  125874. static float _vq_quantthresh__8c0_s_p9_1[] = {
  125875. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125876. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125877. };
  125878. static long _vq_quantmap__8c0_s_p9_1[] = {
  125879. 13, 11, 9, 7, 5, 3, 1, 0,
  125880. 2, 4, 6, 8, 10, 12, 14,
  125881. };
  125882. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  125883. _vq_quantthresh__8c0_s_p9_1,
  125884. _vq_quantmap__8c0_s_p9_1,
  125885. 15,
  125886. 15
  125887. };
  125888. static static_codebook _8c0_s_p9_1 = {
  125889. 2, 225,
  125890. _vq_lengthlist__8c0_s_p9_1,
  125891. 1, -520986624, 1620377600, 4, 0,
  125892. _vq_quantlist__8c0_s_p9_1,
  125893. NULL,
  125894. &_vq_auxt__8c0_s_p9_1,
  125895. NULL,
  125896. 0
  125897. };
  125898. static long _vq_quantlist__8c0_s_p9_2[] = {
  125899. 10,
  125900. 9,
  125901. 11,
  125902. 8,
  125903. 12,
  125904. 7,
  125905. 13,
  125906. 6,
  125907. 14,
  125908. 5,
  125909. 15,
  125910. 4,
  125911. 16,
  125912. 3,
  125913. 17,
  125914. 2,
  125915. 18,
  125916. 1,
  125917. 19,
  125918. 0,
  125919. 20,
  125920. };
  125921. static long _vq_lengthlist__8c0_s_p9_2[] = {
  125922. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  125923. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  125924. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  125925. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  125926. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  125927. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  125928. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  125929. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  125930. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  125931. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  125932. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  125933. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  125934. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  125935. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  125936. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  125937. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  125938. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  125939. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  125940. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  125941. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  125942. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  125943. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  125944. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  125945. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  125946. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  125947. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  125948. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  125949. 10,11, 9,11,10, 9,10, 9,10,
  125950. };
  125951. static float _vq_quantthresh__8c0_s_p9_2[] = {
  125952. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125953. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125954. 6.5, 7.5, 8.5, 9.5,
  125955. };
  125956. static long _vq_quantmap__8c0_s_p9_2[] = {
  125957. 19, 17, 15, 13, 11, 9, 7, 5,
  125958. 3, 1, 0, 2, 4, 6, 8, 10,
  125959. 12, 14, 16, 18, 20,
  125960. };
  125961. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  125962. _vq_quantthresh__8c0_s_p9_2,
  125963. _vq_quantmap__8c0_s_p9_2,
  125964. 21,
  125965. 21
  125966. };
  125967. static static_codebook _8c0_s_p9_2 = {
  125968. 2, 441,
  125969. _vq_lengthlist__8c0_s_p9_2,
  125970. 1, -529268736, 1611661312, 5, 0,
  125971. _vq_quantlist__8c0_s_p9_2,
  125972. NULL,
  125973. &_vq_auxt__8c0_s_p9_2,
  125974. NULL,
  125975. 0
  125976. };
  125977. static long _huff_lengthlist__8c0_s_single[] = {
  125978. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  125979. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  125980. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  125981. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  125982. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  125983. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  125984. 17,16,17,17,
  125985. };
  125986. static static_codebook _huff_book__8c0_s_single = {
  125987. 2, 100,
  125988. _huff_lengthlist__8c0_s_single,
  125989. 0, 0, 0, 0, 0,
  125990. NULL,
  125991. NULL,
  125992. NULL,
  125993. NULL,
  125994. 0
  125995. };
  125996. static long _vq_quantlist__8c1_s_p1_0[] = {
  125997. 1,
  125998. 0,
  125999. 2,
  126000. };
  126001. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126002. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126003. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126008. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126013. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126048. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126053. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126058. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126094. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126099. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126104. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0,
  126413. };
  126414. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126415. -0.5, 0.5,
  126416. };
  126417. static long _vq_quantmap__8c1_s_p1_0[] = {
  126418. 1, 0, 2,
  126419. };
  126420. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126421. _vq_quantthresh__8c1_s_p1_0,
  126422. _vq_quantmap__8c1_s_p1_0,
  126423. 3,
  126424. 3
  126425. };
  126426. static static_codebook _8c1_s_p1_0 = {
  126427. 8, 6561,
  126428. _vq_lengthlist__8c1_s_p1_0,
  126429. 1, -535822336, 1611661312, 2, 0,
  126430. _vq_quantlist__8c1_s_p1_0,
  126431. NULL,
  126432. &_vq_auxt__8c1_s_p1_0,
  126433. NULL,
  126434. 0
  126435. };
  126436. static long _vq_quantlist__8c1_s_p2_0[] = {
  126437. 2,
  126438. 1,
  126439. 3,
  126440. 0,
  126441. 4,
  126442. };
  126443. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0,
  126484. };
  126485. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126486. -1.5, -0.5, 0.5, 1.5,
  126487. };
  126488. static long _vq_quantmap__8c1_s_p2_0[] = {
  126489. 3, 1, 0, 2, 4,
  126490. };
  126491. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126492. _vq_quantthresh__8c1_s_p2_0,
  126493. _vq_quantmap__8c1_s_p2_0,
  126494. 5,
  126495. 5
  126496. };
  126497. static static_codebook _8c1_s_p2_0 = {
  126498. 4, 625,
  126499. _vq_lengthlist__8c1_s_p2_0,
  126500. 1, -533725184, 1611661312, 3, 0,
  126501. _vq_quantlist__8c1_s_p2_0,
  126502. NULL,
  126503. &_vq_auxt__8c1_s_p2_0,
  126504. NULL,
  126505. 0
  126506. };
  126507. static long _vq_quantlist__8c1_s_p3_0[] = {
  126508. 2,
  126509. 1,
  126510. 3,
  126511. 0,
  126512. 4,
  126513. };
  126514. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126515. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0,
  126555. };
  126556. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126557. -1.5, -0.5, 0.5, 1.5,
  126558. };
  126559. static long _vq_quantmap__8c1_s_p3_0[] = {
  126560. 3, 1, 0, 2, 4,
  126561. };
  126562. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126563. _vq_quantthresh__8c1_s_p3_0,
  126564. _vq_quantmap__8c1_s_p3_0,
  126565. 5,
  126566. 5
  126567. };
  126568. static static_codebook _8c1_s_p3_0 = {
  126569. 4, 625,
  126570. _vq_lengthlist__8c1_s_p3_0,
  126571. 1, -533725184, 1611661312, 3, 0,
  126572. _vq_quantlist__8c1_s_p3_0,
  126573. NULL,
  126574. &_vq_auxt__8c1_s_p3_0,
  126575. NULL,
  126576. 0
  126577. };
  126578. static long _vq_quantlist__8c1_s_p4_0[] = {
  126579. 4,
  126580. 3,
  126581. 5,
  126582. 2,
  126583. 6,
  126584. 1,
  126585. 7,
  126586. 0,
  126587. 8,
  126588. };
  126589. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126590. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126591. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126592. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126593. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126594. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0,
  126596. };
  126597. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126598. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126599. };
  126600. static long _vq_quantmap__8c1_s_p4_0[] = {
  126601. 7, 5, 3, 1, 0, 2, 4, 6,
  126602. 8,
  126603. };
  126604. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126605. _vq_quantthresh__8c1_s_p4_0,
  126606. _vq_quantmap__8c1_s_p4_0,
  126607. 9,
  126608. 9
  126609. };
  126610. static static_codebook _8c1_s_p4_0 = {
  126611. 2, 81,
  126612. _vq_lengthlist__8c1_s_p4_0,
  126613. 1, -531628032, 1611661312, 4, 0,
  126614. _vq_quantlist__8c1_s_p4_0,
  126615. NULL,
  126616. &_vq_auxt__8c1_s_p4_0,
  126617. NULL,
  126618. 0
  126619. };
  126620. static long _vq_quantlist__8c1_s_p5_0[] = {
  126621. 4,
  126622. 3,
  126623. 5,
  126624. 2,
  126625. 6,
  126626. 1,
  126627. 7,
  126628. 0,
  126629. 8,
  126630. };
  126631. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126632. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126633. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126634. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126635. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126636. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126637. 10,
  126638. };
  126639. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126640. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126641. };
  126642. static long _vq_quantmap__8c1_s_p5_0[] = {
  126643. 7, 5, 3, 1, 0, 2, 4, 6,
  126644. 8,
  126645. };
  126646. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126647. _vq_quantthresh__8c1_s_p5_0,
  126648. _vq_quantmap__8c1_s_p5_0,
  126649. 9,
  126650. 9
  126651. };
  126652. static static_codebook _8c1_s_p5_0 = {
  126653. 2, 81,
  126654. _vq_lengthlist__8c1_s_p5_0,
  126655. 1, -531628032, 1611661312, 4, 0,
  126656. _vq_quantlist__8c1_s_p5_0,
  126657. NULL,
  126658. &_vq_auxt__8c1_s_p5_0,
  126659. NULL,
  126660. 0
  126661. };
  126662. static long _vq_quantlist__8c1_s_p6_0[] = {
  126663. 8,
  126664. 7,
  126665. 9,
  126666. 6,
  126667. 10,
  126668. 5,
  126669. 11,
  126670. 4,
  126671. 12,
  126672. 3,
  126673. 13,
  126674. 2,
  126675. 14,
  126676. 1,
  126677. 15,
  126678. 0,
  126679. 16,
  126680. };
  126681. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126682. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126683. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126684. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126685. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126686. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126687. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126688. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126689. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126690. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126691. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126692. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126693. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126694. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126695. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126696. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126697. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126698. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126700. 14,
  126701. };
  126702. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126703. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126704. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126705. };
  126706. static long _vq_quantmap__8c1_s_p6_0[] = {
  126707. 15, 13, 11, 9, 7, 5, 3, 1,
  126708. 0, 2, 4, 6, 8, 10, 12, 14,
  126709. 16,
  126710. };
  126711. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126712. _vq_quantthresh__8c1_s_p6_0,
  126713. _vq_quantmap__8c1_s_p6_0,
  126714. 17,
  126715. 17
  126716. };
  126717. static static_codebook _8c1_s_p6_0 = {
  126718. 2, 289,
  126719. _vq_lengthlist__8c1_s_p6_0,
  126720. 1, -529530880, 1611661312, 5, 0,
  126721. _vq_quantlist__8c1_s_p6_0,
  126722. NULL,
  126723. &_vq_auxt__8c1_s_p6_0,
  126724. NULL,
  126725. 0
  126726. };
  126727. static long _vq_quantlist__8c1_s_p7_0[] = {
  126728. 1,
  126729. 0,
  126730. 2,
  126731. };
  126732. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126733. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126734. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126735. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126736. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126737. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126738. 9,
  126739. };
  126740. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126741. -5.5, 5.5,
  126742. };
  126743. static long _vq_quantmap__8c1_s_p7_0[] = {
  126744. 1, 0, 2,
  126745. };
  126746. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126747. _vq_quantthresh__8c1_s_p7_0,
  126748. _vq_quantmap__8c1_s_p7_0,
  126749. 3,
  126750. 3
  126751. };
  126752. static static_codebook _8c1_s_p7_0 = {
  126753. 4, 81,
  126754. _vq_lengthlist__8c1_s_p7_0,
  126755. 1, -529137664, 1618345984, 2, 0,
  126756. _vq_quantlist__8c1_s_p7_0,
  126757. NULL,
  126758. &_vq_auxt__8c1_s_p7_0,
  126759. NULL,
  126760. 0
  126761. };
  126762. static long _vq_quantlist__8c1_s_p7_1[] = {
  126763. 5,
  126764. 4,
  126765. 6,
  126766. 3,
  126767. 7,
  126768. 2,
  126769. 8,
  126770. 1,
  126771. 9,
  126772. 0,
  126773. 10,
  126774. };
  126775. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126776. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126777. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126778. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126779. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126780. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126781. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126782. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126783. 10,10,10, 8, 8, 8, 8, 8, 8,
  126784. };
  126785. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126786. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126787. 3.5, 4.5,
  126788. };
  126789. static long _vq_quantmap__8c1_s_p7_1[] = {
  126790. 9, 7, 5, 3, 1, 0, 2, 4,
  126791. 6, 8, 10,
  126792. };
  126793. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126794. _vq_quantthresh__8c1_s_p7_1,
  126795. _vq_quantmap__8c1_s_p7_1,
  126796. 11,
  126797. 11
  126798. };
  126799. static static_codebook _8c1_s_p7_1 = {
  126800. 2, 121,
  126801. _vq_lengthlist__8c1_s_p7_1,
  126802. 1, -531365888, 1611661312, 4, 0,
  126803. _vq_quantlist__8c1_s_p7_1,
  126804. NULL,
  126805. &_vq_auxt__8c1_s_p7_1,
  126806. NULL,
  126807. 0
  126808. };
  126809. static long _vq_quantlist__8c1_s_p8_0[] = {
  126810. 6,
  126811. 5,
  126812. 7,
  126813. 4,
  126814. 8,
  126815. 3,
  126816. 9,
  126817. 2,
  126818. 10,
  126819. 1,
  126820. 11,
  126821. 0,
  126822. 12,
  126823. };
  126824. static long _vq_lengthlist__8c1_s_p8_0[] = {
  126825. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  126826. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126827. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126828. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126829. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  126830. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  126831. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  126832. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  126833. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  126834. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  126835. 0,12,12,11,10,12,11,13,12,
  126836. };
  126837. static float _vq_quantthresh__8c1_s_p8_0[] = {
  126838. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126839. 12.5, 17.5, 22.5, 27.5,
  126840. };
  126841. static long _vq_quantmap__8c1_s_p8_0[] = {
  126842. 11, 9, 7, 5, 3, 1, 0, 2,
  126843. 4, 6, 8, 10, 12,
  126844. };
  126845. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  126846. _vq_quantthresh__8c1_s_p8_0,
  126847. _vq_quantmap__8c1_s_p8_0,
  126848. 13,
  126849. 13
  126850. };
  126851. static static_codebook _8c1_s_p8_0 = {
  126852. 2, 169,
  126853. _vq_lengthlist__8c1_s_p8_0,
  126854. 1, -526516224, 1616117760, 4, 0,
  126855. _vq_quantlist__8c1_s_p8_0,
  126856. NULL,
  126857. &_vq_auxt__8c1_s_p8_0,
  126858. NULL,
  126859. 0
  126860. };
  126861. static long _vq_quantlist__8c1_s_p8_1[] = {
  126862. 2,
  126863. 1,
  126864. 3,
  126865. 0,
  126866. 4,
  126867. };
  126868. static long _vq_lengthlist__8c1_s_p8_1[] = {
  126869. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  126870. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  126871. };
  126872. static float _vq_quantthresh__8c1_s_p8_1[] = {
  126873. -1.5, -0.5, 0.5, 1.5,
  126874. };
  126875. static long _vq_quantmap__8c1_s_p8_1[] = {
  126876. 3, 1, 0, 2, 4,
  126877. };
  126878. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  126879. _vq_quantthresh__8c1_s_p8_1,
  126880. _vq_quantmap__8c1_s_p8_1,
  126881. 5,
  126882. 5
  126883. };
  126884. static static_codebook _8c1_s_p8_1 = {
  126885. 2, 25,
  126886. _vq_lengthlist__8c1_s_p8_1,
  126887. 1, -533725184, 1611661312, 3, 0,
  126888. _vq_quantlist__8c1_s_p8_1,
  126889. NULL,
  126890. &_vq_auxt__8c1_s_p8_1,
  126891. NULL,
  126892. 0
  126893. };
  126894. static long _vq_quantlist__8c1_s_p9_0[] = {
  126895. 6,
  126896. 5,
  126897. 7,
  126898. 4,
  126899. 8,
  126900. 3,
  126901. 9,
  126902. 2,
  126903. 10,
  126904. 1,
  126905. 11,
  126906. 0,
  126907. 12,
  126908. };
  126909. static long _vq_lengthlist__8c1_s_p9_0[] = {
  126910. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  126911. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  126912. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126913. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126915. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126916. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126917. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126918. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126919. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126920. 10,10,10,10,10, 9, 9, 9, 9,
  126921. };
  126922. static float _vq_quantthresh__8c1_s_p9_0[] = {
  126923. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126924. 787.5, 1102.5, 1417.5, 1732.5,
  126925. };
  126926. static long _vq_quantmap__8c1_s_p9_0[] = {
  126927. 11, 9, 7, 5, 3, 1, 0, 2,
  126928. 4, 6, 8, 10, 12,
  126929. };
  126930. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  126931. _vq_quantthresh__8c1_s_p9_0,
  126932. _vq_quantmap__8c1_s_p9_0,
  126933. 13,
  126934. 13
  126935. };
  126936. static static_codebook _8c1_s_p9_0 = {
  126937. 2, 169,
  126938. _vq_lengthlist__8c1_s_p9_0,
  126939. 1, -513964032, 1628680192, 4, 0,
  126940. _vq_quantlist__8c1_s_p9_0,
  126941. NULL,
  126942. &_vq_auxt__8c1_s_p9_0,
  126943. NULL,
  126944. 0
  126945. };
  126946. static long _vq_quantlist__8c1_s_p9_1[] = {
  126947. 7,
  126948. 6,
  126949. 8,
  126950. 5,
  126951. 9,
  126952. 4,
  126953. 10,
  126954. 3,
  126955. 11,
  126956. 2,
  126957. 12,
  126958. 1,
  126959. 13,
  126960. 0,
  126961. 14,
  126962. };
  126963. static long _vq_lengthlist__8c1_s_p9_1[] = {
  126964. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  126965. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  126966. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  126967. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  126968. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  126969. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  126970. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  126971. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  126972. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  126973. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  126974. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  126975. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  126976. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  126977. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  126978. 15,
  126979. };
  126980. static float _vq_quantthresh__8c1_s_p9_1[] = {
  126981. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126982. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126983. };
  126984. static long _vq_quantmap__8c1_s_p9_1[] = {
  126985. 13, 11, 9, 7, 5, 3, 1, 0,
  126986. 2, 4, 6, 8, 10, 12, 14,
  126987. };
  126988. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  126989. _vq_quantthresh__8c1_s_p9_1,
  126990. _vq_quantmap__8c1_s_p9_1,
  126991. 15,
  126992. 15
  126993. };
  126994. static static_codebook _8c1_s_p9_1 = {
  126995. 2, 225,
  126996. _vq_lengthlist__8c1_s_p9_1,
  126997. 1, -520986624, 1620377600, 4, 0,
  126998. _vq_quantlist__8c1_s_p9_1,
  126999. NULL,
  127000. &_vq_auxt__8c1_s_p9_1,
  127001. NULL,
  127002. 0
  127003. };
  127004. static long _vq_quantlist__8c1_s_p9_2[] = {
  127005. 10,
  127006. 9,
  127007. 11,
  127008. 8,
  127009. 12,
  127010. 7,
  127011. 13,
  127012. 6,
  127013. 14,
  127014. 5,
  127015. 15,
  127016. 4,
  127017. 16,
  127018. 3,
  127019. 17,
  127020. 2,
  127021. 18,
  127022. 1,
  127023. 19,
  127024. 0,
  127025. 20,
  127026. };
  127027. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127028. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127029. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127030. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127031. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127032. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127033. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127034. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127035. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127036. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127037. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127038. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127039. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127040. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127041. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127042. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127043. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127044. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127045. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127046. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127047. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127048. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127049. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127050. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127051. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127052. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127053. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127054. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127055. 10,10,10,10,10,10,10,10,10,
  127056. };
  127057. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127058. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127059. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127060. 6.5, 7.5, 8.5, 9.5,
  127061. };
  127062. static long _vq_quantmap__8c1_s_p9_2[] = {
  127063. 19, 17, 15, 13, 11, 9, 7, 5,
  127064. 3, 1, 0, 2, 4, 6, 8, 10,
  127065. 12, 14, 16, 18, 20,
  127066. };
  127067. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127068. _vq_quantthresh__8c1_s_p9_2,
  127069. _vq_quantmap__8c1_s_p9_2,
  127070. 21,
  127071. 21
  127072. };
  127073. static static_codebook _8c1_s_p9_2 = {
  127074. 2, 441,
  127075. _vq_lengthlist__8c1_s_p9_2,
  127076. 1, -529268736, 1611661312, 5, 0,
  127077. _vq_quantlist__8c1_s_p9_2,
  127078. NULL,
  127079. &_vq_auxt__8c1_s_p9_2,
  127080. NULL,
  127081. 0
  127082. };
  127083. static long _huff_lengthlist__8c1_s_single[] = {
  127084. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127085. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127086. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127087. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127088. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127089. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127090. 9, 7, 7, 8,
  127091. };
  127092. static static_codebook _huff_book__8c1_s_single = {
  127093. 2, 100,
  127094. _huff_lengthlist__8c1_s_single,
  127095. 0, 0, 0, 0, 0,
  127096. NULL,
  127097. NULL,
  127098. NULL,
  127099. NULL,
  127100. 0
  127101. };
  127102. static long _huff_lengthlist__44c2_s_long[] = {
  127103. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127104. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127105. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127106. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127107. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127108. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127109. 10, 8, 8, 9,
  127110. };
  127111. static static_codebook _huff_book__44c2_s_long = {
  127112. 2, 100,
  127113. _huff_lengthlist__44c2_s_long,
  127114. 0, 0, 0, 0, 0,
  127115. NULL,
  127116. NULL,
  127117. NULL,
  127118. NULL,
  127119. 0
  127120. };
  127121. static long _vq_quantlist__44c2_s_p1_0[] = {
  127122. 1,
  127123. 0,
  127124. 2,
  127125. };
  127126. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127127. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127128. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127133. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127138. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127173. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127178. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127183. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127219. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127224. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127229. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0,
  127538. };
  127539. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127540. -0.5, 0.5,
  127541. };
  127542. static long _vq_quantmap__44c2_s_p1_0[] = {
  127543. 1, 0, 2,
  127544. };
  127545. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127546. _vq_quantthresh__44c2_s_p1_0,
  127547. _vq_quantmap__44c2_s_p1_0,
  127548. 3,
  127549. 3
  127550. };
  127551. static static_codebook _44c2_s_p1_0 = {
  127552. 8, 6561,
  127553. _vq_lengthlist__44c2_s_p1_0,
  127554. 1, -535822336, 1611661312, 2, 0,
  127555. _vq_quantlist__44c2_s_p1_0,
  127556. NULL,
  127557. &_vq_auxt__44c2_s_p1_0,
  127558. NULL,
  127559. 0
  127560. };
  127561. static long _vq_quantlist__44c2_s_p2_0[] = {
  127562. 2,
  127563. 1,
  127564. 3,
  127565. 0,
  127566. 4,
  127567. };
  127568. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127569. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127570. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127571. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127572. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127573. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127579. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127580. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127581. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127587. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127588. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127595. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127596. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0,
  127609. };
  127610. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127611. -1.5, -0.5, 0.5, 1.5,
  127612. };
  127613. static long _vq_quantmap__44c2_s_p2_0[] = {
  127614. 3, 1, 0, 2, 4,
  127615. };
  127616. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127617. _vq_quantthresh__44c2_s_p2_0,
  127618. _vq_quantmap__44c2_s_p2_0,
  127619. 5,
  127620. 5
  127621. };
  127622. static static_codebook _44c2_s_p2_0 = {
  127623. 4, 625,
  127624. _vq_lengthlist__44c2_s_p2_0,
  127625. 1, -533725184, 1611661312, 3, 0,
  127626. _vq_quantlist__44c2_s_p2_0,
  127627. NULL,
  127628. &_vq_auxt__44c2_s_p2_0,
  127629. NULL,
  127630. 0
  127631. };
  127632. static long _vq_quantlist__44c2_s_p3_0[] = {
  127633. 2,
  127634. 1,
  127635. 3,
  127636. 0,
  127637. 4,
  127638. };
  127639. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127640. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0,
  127680. };
  127681. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127682. -1.5, -0.5, 0.5, 1.5,
  127683. };
  127684. static long _vq_quantmap__44c2_s_p3_0[] = {
  127685. 3, 1, 0, 2, 4,
  127686. };
  127687. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127688. _vq_quantthresh__44c2_s_p3_0,
  127689. _vq_quantmap__44c2_s_p3_0,
  127690. 5,
  127691. 5
  127692. };
  127693. static static_codebook _44c2_s_p3_0 = {
  127694. 4, 625,
  127695. _vq_lengthlist__44c2_s_p3_0,
  127696. 1, -533725184, 1611661312, 3, 0,
  127697. _vq_quantlist__44c2_s_p3_0,
  127698. NULL,
  127699. &_vq_auxt__44c2_s_p3_0,
  127700. NULL,
  127701. 0
  127702. };
  127703. static long _vq_quantlist__44c2_s_p4_0[] = {
  127704. 4,
  127705. 3,
  127706. 5,
  127707. 2,
  127708. 6,
  127709. 1,
  127710. 7,
  127711. 0,
  127712. 8,
  127713. };
  127714. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127715. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127716. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127717. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127718. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127719. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0,
  127721. };
  127722. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127723. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127724. };
  127725. static long _vq_quantmap__44c2_s_p4_0[] = {
  127726. 7, 5, 3, 1, 0, 2, 4, 6,
  127727. 8,
  127728. };
  127729. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127730. _vq_quantthresh__44c2_s_p4_0,
  127731. _vq_quantmap__44c2_s_p4_0,
  127732. 9,
  127733. 9
  127734. };
  127735. static static_codebook _44c2_s_p4_0 = {
  127736. 2, 81,
  127737. _vq_lengthlist__44c2_s_p4_0,
  127738. 1, -531628032, 1611661312, 4, 0,
  127739. _vq_quantlist__44c2_s_p4_0,
  127740. NULL,
  127741. &_vq_auxt__44c2_s_p4_0,
  127742. NULL,
  127743. 0
  127744. };
  127745. static long _vq_quantlist__44c2_s_p5_0[] = {
  127746. 4,
  127747. 3,
  127748. 5,
  127749. 2,
  127750. 6,
  127751. 1,
  127752. 7,
  127753. 0,
  127754. 8,
  127755. };
  127756. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127757. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127758. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127759. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127760. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127761. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127762. 11,
  127763. };
  127764. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127765. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127766. };
  127767. static long _vq_quantmap__44c2_s_p5_0[] = {
  127768. 7, 5, 3, 1, 0, 2, 4, 6,
  127769. 8,
  127770. };
  127771. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127772. _vq_quantthresh__44c2_s_p5_0,
  127773. _vq_quantmap__44c2_s_p5_0,
  127774. 9,
  127775. 9
  127776. };
  127777. static static_codebook _44c2_s_p5_0 = {
  127778. 2, 81,
  127779. _vq_lengthlist__44c2_s_p5_0,
  127780. 1, -531628032, 1611661312, 4, 0,
  127781. _vq_quantlist__44c2_s_p5_0,
  127782. NULL,
  127783. &_vq_auxt__44c2_s_p5_0,
  127784. NULL,
  127785. 0
  127786. };
  127787. static long _vq_quantlist__44c2_s_p6_0[] = {
  127788. 8,
  127789. 7,
  127790. 9,
  127791. 6,
  127792. 10,
  127793. 5,
  127794. 11,
  127795. 4,
  127796. 12,
  127797. 3,
  127798. 13,
  127799. 2,
  127800. 14,
  127801. 1,
  127802. 15,
  127803. 0,
  127804. 16,
  127805. };
  127806. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127807. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127808. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127809. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127810. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127811. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127812. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127813. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127814. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127815. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127816. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127817. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127818. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127819. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127820. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127821. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127822. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  127823. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127825. 14,
  127826. };
  127827. static float _vq_quantthresh__44c2_s_p6_0[] = {
  127828. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127829. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127830. };
  127831. static long _vq_quantmap__44c2_s_p6_0[] = {
  127832. 15, 13, 11, 9, 7, 5, 3, 1,
  127833. 0, 2, 4, 6, 8, 10, 12, 14,
  127834. 16,
  127835. };
  127836. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  127837. _vq_quantthresh__44c2_s_p6_0,
  127838. _vq_quantmap__44c2_s_p6_0,
  127839. 17,
  127840. 17
  127841. };
  127842. static static_codebook _44c2_s_p6_0 = {
  127843. 2, 289,
  127844. _vq_lengthlist__44c2_s_p6_0,
  127845. 1, -529530880, 1611661312, 5, 0,
  127846. _vq_quantlist__44c2_s_p6_0,
  127847. NULL,
  127848. &_vq_auxt__44c2_s_p6_0,
  127849. NULL,
  127850. 0
  127851. };
  127852. static long _vq_quantlist__44c2_s_p7_0[] = {
  127853. 1,
  127854. 0,
  127855. 2,
  127856. };
  127857. static long _vq_lengthlist__44c2_s_p7_0[] = {
  127858. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127859. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  127860. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127861. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  127862. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  127863. 11,
  127864. };
  127865. static float _vq_quantthresh__44c2_s_p7_0[] = {
  127866. -5.5, 5.5,
  127867. };
  127868. static long _vq_quantmap__44c2_s_p7_0[] = {
  127869. 1, 0, 2,
  127870. };
  127871. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  127872. _vq_quantthresh__44c2_s_p7_0,
  127873. _vq_quantmap__44c2_s_p7_0,
  127874. 3,
  127875. 3
  127876. };
  127877. static static_codebook _44c2_s_p7_0 = {
  127878. 4, 81,
  127879. _vq_lengthlist__44c2_s_p7_0,
  127880. 1, -529137664, 1618345984, 2, 0,
  127881. _vq_quantlist__44c2_s_p7_0,
  127882. NULL,
  127883. &_vq_auxt__44c2_s_p7_0,
  127884. NULL,
  127885. 0
  127886. };
  127887. static long _vq_quantlist__44c2_s_p7_1[] = {
  127888. 5,
  127889. 4,
  127890. 6,
  127891. 3,
  127892. 7,
  127893. 2,
  127894. 8,
  127895. 1,
  127896. 9,
  127897. 0,
  127898. 10,
  127899. };
  127900. static long _vq_lengthlist__44c2_s_p7_1[] = {
  127901. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  127902. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  127903. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127904. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127905. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127906. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127907. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127908. 10,10,10, 8, 8, 8, 8, 8, 8,
  127909. };
  127910. static float _vq_quantthresh__44c2_s_p7_1[] = {
  127911. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127912. 3.5, 4.5,
  127913. };
  127914. static long _vq_quantmap__44c2_s_p7_1[] = {
  127915. 9, 7, 5, 3, 1, 0, 2, 4,
  127916. 6, 8, 10,
  127917. };
  127918. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  127919. _vq_quantthresh__44c2_s_p7_1,
  127920. _vq_quantmap__44c2_s_p7_1,
  127921. 11,
  127922. 11
  127923. };
  127924. static static_codebook _44c2_s_p7_1 = {
  127925. 2, 121,
  127926. _vq_lengthlist__44c2_s_p7_1,
  127927. 1, -531365888, 1611661312, 4, 0,
  127928. _vq_quantlist__44c2_s_p7_1,
  127929. NULL,
  127930. &_vq_auxt__44c2_s_p7_1,
  127931. NULL,
  127932. 0
  127933. };
  127934. static long _vq_quantlist__44c2_s_p8_0[] = {
  127935. 6,
  127936. 5,
  127937. 7,
  127938. 4,
  127939. 8,
  127940. 3,
  127941. 9,
  127942. 2,
  127943. 10,
  127944. 1,
  127945. 11,
  127946. 0,
  127947. 12,
  127948. };
  127949. static long _vq_lengthlist__44c2_s_p8_0[] = {
  127950. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  127951. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  127952. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127953. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127954. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  127955. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  127956. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  127957. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  127958. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  127959. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  127960. 0,12,12,12,12,13,12,14,14,
  127961. };
  127962. static float _vq_quantthresh__44c2_s_p8_0[] = {
  127963. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127964. 12.5, 17.5, 22.5, 27.5,
  127965. };
  127966. static long _vq_quantmap__44c2_s_p8_0[] = {
  127967. 11, 9, 7, 5, 3, 1, 0, 2,
  127968. 4, 6, 8, 10, 12,
  127969. };
  127970. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  127971. _vq_quantthresh__44c2_s_p8_0,
  127972. _vq_quantmap__44c2_s_p8_0,
  127973. 13,
  127974. 13
  127975. };
  127976. static static_codebook _44c2_s_p8_0 = {
  127977. 2, 169,
  127978. _vq_lengthlist__44c2_s_p8_0,
  127979. 1, -526516224, 1616117760, 4, 0,
  127980. _vq_quantlist__44c2_s_p8_0,
  127981. NULL,
  127982. &_vq_auxt__44c2_s_p8_0,
  127983. NULL,
  127984. 0
  127985. };
  127986. static long _vq_quantlist__44c2_s_p8_1[] = {
  127987. 2,
  127988. 1,
  127989. 3,
  127990. 0,
  127991. 4,
  127992. };
  127993. static long _vq_lengthlist__44c2_s_p8_1[] = {
  127994. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  127995. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127996. };
  127997. static float _vq_quantthresh__44c2_s_p8_1[] = {
  127998. -1.5, -0.5, 0.5, 1.5,
  127999. };
  128000. static long _vq_quantmap__44c2_s_p8_1[] = {
  128001. 3, 1, 0, 2, 4,
  128002. };
  128003. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128004. _vq_quantthresh__44c2_s_p8_1,
  128005. _vq_quantmap__44c2_s_p8_1,
  128006. 5,
  128007. 5
  128008. };
  128009. static static_codebook _44c2_s_p8_1 = {
  128010. 2, 25,
  128011. _vq_lengthlist__44c2_s_p8_1,
  128012. 1, -533725184, 1611661312, 3, 0,
  128013. _vq_quantlist__44c2_s_p8_1,
  128014. NULL,
  128015. &_vq_auxt__44c2_s_p8_1,
  128016. NULL,
  128017. 0
  128018. };
  128019. static long _vq_quantlist__44c2_s_p9_0[] = {
  128020. 6,
  128021. 5,
  128022. 7,
  128023. 4,
  128024. 8,
  128025. 3,
  128026. 9,
  128027. 2,
  128028. 10,
  128029. 1,
  128030. 11,
  128031. 0,
  128032. 12,
  128033. };
  128034. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128035. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128036. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128038. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128045. 11,11,11,11,11,11,11,11,11,
  128046. };
  128047. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128048. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128049. 552.5, 773.5, 994.5, 1215.5,
  128050. };
  128051. static long _vq_quantmap__44c2_s_p9_0[] = {
  128052. 11, 9, 7, 5, 3, 1, 0, 2,
  128053. 4, 6, 8, 10, 12,
  128054. };
  128055. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128056. _vq_quantthresh__44c2_s_p9_0,
  128057. _vq_quantmap__44c2_s_p9_0,
  128058. 13,
  128059. 13
  128060. };
  128061. static static_codebook _44c2_s_p9_0 = {
  128062. 2, 169,
  128063. _vq_lengthlist__44c2_s_p9_0,
  128064. 1, -514541568, 1627103232, 4, 0,
  128065. _vq_quantlist__44c2_s_p9_0,
  128066. NULL,
  128067. &_vq_auxt__44c2_s_p9_0,
  128068. NULL,
  128069. 0
  128070. };
  128071. static long _vq_quantlist__44c2_s_p9_1[] = {
  128072. 6,
  128073. 5,
  128074. 7,
  128075. 4,
  128076. 8,
  128077. 3,
  128078. 9,
  128079. 2,
  128080. 10,
  128081. 1,
  128082. 11,
  128083. 0,
  128084. 12,
  128085. };
  128086. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128087. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128088. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128089. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128090. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128091. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128092. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128093. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128094. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128095. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128096. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128097. 17,13,12,12,10,13,11,14,14,
  128098. };
  128099. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128100. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128101. 42.5, 59.5, 76.5, 93.5,
  128102. };
  128103. static long _vq_quantmap__44c2_s_p9_1[] = {
  128104. 11, 9, 7, 5, 3, 1, 0, 2,
  128105. 4, 6, 8, 10, 12,
  128106. };
  128107. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128108. _vq_quantthresh__44c2_s_p9_1,
  128109. _vq_quantmap__44c2_s_p9_1,
  128110. 13,
  128111. 13
  128112. };
  128113. static static_codebook _44c2_s_p9_1 = {
  128114. 2, 169,
  128115. _vq_lengthlist__44c2_s_p9_1,
  128116. 1, -522616832, 1620115456, 4, 0,
  128117. _vq_quantlist__44c2_s_p9_1,
  128118. NULL,
  128119. &_vq_auxt__44c2_s_p9_1,
  128120. NULL,
  128121. 0
  128122. };
  128123. static long _vq_quantlist__44c2_s_p9_2[] = {
  128124. 8,
  128125. 7,
  128126. 9,
  128127. 6,
  128128. 10,
  128129. 5,
  128130. 11,
  128131. 4,
  128132. 12,
  128133. 3,
  128134. 13,
  128135. 2,
  128136. 14,
  128137. 1,
  128138. 15,
  128139. 0,
  128140. 16,
  128141. };
  128142. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128143. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128144. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128145. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128146. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128147. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128148. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128149. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128150. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128151. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128152. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128153. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128154. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128155. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128156. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128157. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128158. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128159. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128160. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128161. 10,
  128162. };
  128163. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128164. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128165. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128166. };
  128167. static long _vq_quantmap__44c2_s_p9_2[] = {
  128168. 15, 13, 11, 9, 7, 5, 3, 1,
  128169. 0, 2, 4, 6, 8, 10, 12, 14,
  128170. 16,
  128171. };
  128172. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128173. _vq_quantthresh__44c2_s_p9_2,
  128174. _vq_quantmap__44c2_s_p9_2,
  128175. 17,
  128176. 17
  128177. };
  128178. static static_codebook _44c2_s_p9_2 = {
  128179. 2, 289,
  128180. _vq_lengthlist__44c2_s_p9_2,
  128181. 1, -529530880, 1611661312, 5, 0,
  128182. _vq_quantlist__44c2_s_p9_2,
  128183. NULL,
  128184. &_vq_auxt__44c2_s_p9_2,
  128185. NULL,
  128186. 0
  128187. };
  128188. static long _huff_lengthlist__44c2_s_short[] = {
  128189. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128190. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128191. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128192. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128193. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128194. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128195. 6, 8, 9,12,
  128196. };
  128197. static static_codebook _huff_book__44c2_s_short = {
  128198. 2, 100,
  128199. _huff_lengthlist__44c2_s_short,
  128200. 0, 0, 0, 0, 0,
  128201. NULL,
  128202. NULL,
  128203. NULL,
  128204. NULL,
  128205. 0
  128206. };
  128207. static long _huff_lengthlist__44c3_s_long[] = {
  128208. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128209. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128210. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128211. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128212. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128213. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128214. 9, 8, 8, 8,
  128215. };
  128216. static static_codebook _huff_book__44c3_s_long = {
  128217. 2, 100,
  128218. _huff_lengthlist__44c3_s_long,
  128219. 0, 0, 0, 0, 0,
  128220. NULL,
  128221. NULL,
  128222. NULL,
  128223. NULL,
  128224. 0
  128225. };
  128226. static long _vq_quantlist__44c3_s_p1_0[] = {
  128227. 1,
  128228. 0,
  128229. 2,
  128230. };
  128231. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128232. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128233. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128238. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128243. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128278. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128283. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128288. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128324. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128329. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128334. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0,
  128643. };
  128644. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128645. -0.5, 0.5,
  128646. };
  128647. static long _vq_quantmap__44c3_s_p1_0[] = {
  128648. 1, 0, 2,
  128649. };
  128650. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128651. _vq_quantthresh__44c3_s_p1_0,
  128652. _vq_quantmap__44c3_s_p1_0,
  128653. 3,
  128654. 3
  128655. };
  128656. static static_codebook _44c3_s_p1_0 = {
  128657. 8, 6561,
  128658. _vq_lengthlist__44c3_s_p1_0,
  128659. 1, -535822336, 1611661312, 2, 0,
  128660. _vq_quantlist__44c3_s_p1_0,
  128661. NULL,
  128662. &_vq_auxt__44c3_s_p1_0,
  128663. NULL,
  128664. 0
  128665. };
  128666. static long _vq_quantlist__44c3_s_p2_0[] = {
  128667. 2,
  128668. 1,
  128669. 3,
  128670. 0,
  128671. 4,
  128672. };
  128673. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128674. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128675. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128676. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128677. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128678. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128684. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128685. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128686. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128692. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128693. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128700. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128701. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0,
  128714. };
  128715. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128716. -1.5, -0.5, 0.5, 1.5,
  128717. };
  128718. static long _vq_quantmap__44c3_s_p2_0[] = {
  128719. 3, 1, 0, 2, 4,
  128720. };
  128721. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128722. _vq_quantthresh__44c3_s_p2_0,
  128723. _vq_quantmap__44c3_s_p2_0,
  128724. 5,
  128725. 5
  128726. };
  128727. static static_codebook _44c3_s_p2_0 = {
  128728. 4, 625,
  128729. _vq_lengthlist__44c3_s_p2_0,
  128730. 1, -533725184, 1611661312, 3, 0,
  128731. _vq_quantlist__44c3_s_p2_0,
  128732. NULL,
  128733. &_vq_auxt__44c3_s_p2_0,
  128734. NULL,
  128735. 0
  128736. };
  128737. static long _vq_quantlist__44c3_s_p3_0[] = {
  128738. 2,
  128739. 1,
  128740. 3,
  128741. 0,
  128742. 4,
  128743. };
  128744. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128745. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0,
  128785. };
  128786. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128787. -1.5, -0.5, 0.5, 1.5,
  128788. };
  128789. static long _vq_quantmap__44c3_s_p3_0[] = {
  128790. 3, 1, 0, 2, 4,
  128791. };
  128792. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128793. _vq_quantthresh__44c3_s_p3_0,
  128794. _vq_quantmap__44c3_s_p3_0,
  128795. 5,
  128796. 5
  128797. };
  128798. static static_codebook _44c3_s_p3_0 = {
  128799. 4, 625,
  128800. _vq_lengthlist__44c3_s_p3_0,
  128801. 1, -533725184, 1611661312, 3, 0,
  128802. _vq_quantlist__44c3_s_p3_0,
  128803. NULL,
  128804. &_vq_auxt__44c3_s_p3_0,
  128805. NULL,
  128806. 0
  128807. };
  128808. static long _vq_quantlist__44c3_s_p4_0[] = {
  128809. 4,
  128810. 3,
  128811. 5,
  128812. 2,
  128813. 6,
  128814. 1,
  128815. 7,
  128816. 0,
  128817. 8,
  128818. };
  128819. static long _vq_lengthlist__44c3_s_p4_0[] = {
  128820. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128821. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128822. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128823. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  128824. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0,
  128826. };
  128827. static float _vq_quantthresh__44c3_s_p4_0[] = {
  128828. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128829. };
  128830. static long _vq_quantmap__44c3_s_p4_0[] = {
  128831. 7, 5, 3, 1, 0, 2, 4, 6,
  128832. 8,
  128833. };
  128834. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  128835. _vq_quantthresh__44c3_s_p4_0,
  128836. _vq_quantmap__44c3_s_p4_0,
  128837. 9,
  128838. 9
  128839. };
  128840. static static_codebook _44c3_s_p4_0 = {
  128841. 2, 81,
  128842. _vq_lengthlist__44c3_s_p4_0,
  128843. 1, -531628032, 1611661312, 4, 0,
  128844. _vq_quantlist__44c3_s_p4_0,
  128845. NULL,
  128846. &_vq_auxt__44c3_s_p4_0,
  128847. NULL,
  128848. 0
  128849. };
  128850. static long _vq_quantlist__44c3_s_p5_0[] = {
  128851. 4,
  128852. 3,
  128853. 5,
  128854. 2,
  128855. 6,
  128856. 1,
  128857. 7,
  128858. 0,
  128859. 8,
  128860. };
  128861. static long _vq_lengthlist__44c3_s_p5_0[] = {
  128862. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  128863. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  128864. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  128865. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  128866. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  128867. 11,
  128868. };
  128869. static float _vq_quantthresh__44c3_s_p5_0[] = {
  128870. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128871. };
  128872. static long _vq_quantmap__44c3_s_p5_0[] = {
  128873. 7, 5, 3, 1, 0, 2, 4, 6,
  128874. 8,
  128875. };
  128876. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  128877. _vq_quantthresh__44c3_s_p5_0,
  128878. _vq_quantmap__44c3_s_p5_0,
  128879. 9,
  128880. 9
  128881. };
  128882. static static_codebook _44c3_s_p5_0 = {
  128883. 2, 81,
  128884. _vq_lengthlist__44c3_s_p5_0,
  128885. 1, -531628032, 1611661312, 4, 0,
  128886. _vq_quantlist__44c3_s_p5_0,
  128887. NULL,
  128888. &_vq_auxt__44c3_s_p5_0,
  128889. NULL,
  128890. 0
  128891. };
  128892. static long _vq_quantlist__44c3_s_p6_0[] = {
  128893. 8,
  128894. 7,
  128895. 9,
  128896. 6,
  128897. 10,
  128898. 5,
  128899. 11,
  128900. 4,
  128901. 12,
  128902. 3,
  128903. 13,
  128904. 2,
  128905. 14,
  128906. 1,
  128907. 15,
  128908. 0,
  128909. 16,
  128910. };
  128911. static long _vq_lengthlist__44c3_s_p6_0[] = {
  128912. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128913. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128914. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  128915. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128916. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128917. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128918. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  128919. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128920. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128921. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  128922. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  128923. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  128924. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  128925. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  128926. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  128927. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128928. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128930. 13,
  128931. };
  128932. static float _vq_quantthresh__44c3_s_p6_0[] = {
  128933. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128934. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128935. };
  128936. static long _vq_quantmap__44c3_s_p6_0[] = {
  128937. 15, 13, 11, 9, 7, 5, 3, 1,
  128938. 0, 2, 4, 6, 8, 10, 12, 14,
  128939. 16,
  128940. };
  128941. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  128942. _vq_quantthresh__44c3_s_p6_0,
  128943. _vq_quantmap__44c3_s_p6_0,
  128944. 17,
  128945. 17
  128946. };
  128947. static static_codebook _44c3_s_p6_0 = {
  128948. 2, 289,
  128949. _vq_lengthlist__44c3_s_p6_0,
  128950. 1, -529530880, 1611661312, 5, 0,
  128951. _vq_quantlist__44c3_s_p6_0,
  128952. NULL,
  128953. &_vq_auxt__44c3_s_p6_0,
  128954. NULL,
  128955. 0
  128956. };
  128957. static long _vq_quantlist__44c3_s_p7_0[] = {
  128958. 1,
  128959. 0,
  128960. 2,
  128961. };
  128962. static long _vq_lengthlist__44c3_s_p7_0[] = {
  128963. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128964. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128965. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128966. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  128967. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128968. 10,
  128969. };
  128970. static float _vq_quantthresh__44c3_s_p7_0[] = {
  128971. -5.5, 5.5,
  128972. };
  128973. static long _vq_quantmap__44c3_s_p7_0[] = {
  128974. 1, 0, 2,
  128975. };
  128976. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  128977. _vq_quantthresh__44c3_s_p7_0,
  128978. _vq_quantmap__44c3_s_p7_0,
  128979. 3,
  128980. 3
  128981. };
  128982. static static_codebook _44c3_s_p7_0 = {
  128983. 4, 81,
  128984. _vq_lengthlist__44c3_s_p7_0,
  128985. 1, -529137664, 1618345984, 2, 0,
  128986. _vq_quantlist__44c3_s_p7_0,
  128987. NULL,
  128988. &_vq_auxt__44c3_s_p7_0,
  128989. NULL,
  128990. 0
  128991. };
  128992. static long _vq_quantlist__44c3_s_p7_1[] = {
  128993. 5,
  128994. 4,
  128995. 6,
  128996. 3,
  128997. 7,
  128998. 2,
  128999. 8,
  129000. 1,
  129001. 9,
  129002. 0,
  129003. 10,
  129004. };
  129005. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129006. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129007. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129008. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129009. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129010. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129011. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129012. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129013. 10,10,10, 8, 8, 8, 8, 8, 8,
  129014. };
  129015. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129016. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129017. 3.5, 4.5,
  129018. };
  129019. static long _vq_quantmap__44c3_s_p7_1[] = {
  129020. 9, 7, 5, 3, 1, 0, 2, 4,
  129021. 6, 8, 10,
  129022. };
  129023. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129024. _vq_quantthresh__44c3_s_p7_1,
  129025. _vq_quantmap__44c3_s_p7_1,
  129026. 11,
  129027. 11
  129028. };
  129029. static static_codebook _44c3_s_p7_1 = {
  129030. 2, 121,
  129031. _vq_lengthlist__44c3_s_p7_1,
  129032. 1, -531365888, 1611661312, 4, 0,
  129033. _vq_quantlist__44c3_s_p7_1,
  129034. NULL,
  129035. &_vq_auxt__44c3_s_p7_1,
  129036. NULL,
  129037. 0
  129038. };
  129039. static long _vq_quantlist__44c3_s_p8_0[] = {
  129040. 6,
  129041. 5,
  129042. 7,
  129043. 4,
  129044. 8,
  129045. 3,
  129046. 9,
  129047. 2,
  129048. 10,
  129049. 1,
  129050. 11,
  129051. 0,
  129052. 12,
  129053. };
  129054. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129055. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129056. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129057. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129058. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129059. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129060. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129061. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129062. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129063. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129064. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129065. 0,13,13,12,12,13,12,14,13,
  129066. };
  129067. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129068. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129069. 12.5, 17.5, 22.5, 27.5,
  129070. };
  129071. static long _vq_quantmap__44c3_s_p8_0[] = {
  129072. 11, 9, 7, 5, 3, 1, 0, 2,
  129073. 4, 6, 8, 10, 12,
  129074. };
  129075. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129076. _vq_quantthresh__44c3_s_p8_0,
  129077. _vq_quantmap__44c3_s_p8_0,
  129078. 13,
  129079. 13
  129080. };
  129081. static static_codebook _44c3_s_p8_0 = {
  129082. 2, 169,
  129083. _vq_lengthlist__44c3_s_p8_0,
  129084. 1, -526516224, 1616117760, 4, 0,
  129085. _vq_quantlist__44c3_s_p8_0,
  129086. NULL,
  129087. &_vq_auxt__44c3_s_p8_0,
  129088. NULL,
  129089. 0
  129090. };
  129091. static long _vq_quantlist__44c3_s_p8_1[] = {
  129092. 2,
  129093. 1,
  129094. 3,
  129095. 0,
  129096. 4,
  129097. };
  129098. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129099. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129100. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129101. };
  129102. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129103. -1.5, -0.5, 0.5, 1.5,
  129104. };
  129105. static long _vq_quantmap__44c3_s_p8_1[] = {
  129106. 3, 1, 0, 2, 4,
  129107. };
  129108. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129109. _vq_quantthresh__44c3_s_p8_1,
  129110. _vq_quantmap__44c3_s_p8_1,
  129111. 5,
  129112. 5
  129113. };
  129114. static static_codebook _44c3_s_p8_1 = {
  129115. 2, 25,
  129116. _vq_lengthlist__44c3_s_p8_1,
  129117. 1, -533725184, 1611661312, 3, 0,
  129118. _vq_quantlist__44c3_s_p8_1,
  129119. NULL,
  129120. &_vq_auxt__44c3_s_p8_1,
  129121. NULL,
  129122. 0
  129123. };
  129124. static long _vq_quantlist__44c3_s_p9_0[] = {
  129125. 6,
  129126. 5,
  129127. 7,
  129128. 4,
  129129. 8,
  129130. 3,
  129131. 9,
  129132. 2,
  129133. 10,
  129134. 1,
  129135. 11,
  129136. 0,
  129137. 12,
  129138. };
  129139. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129140. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129141. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129142. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129143. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129144. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129145. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129146. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129147. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129148. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129150. 11,11,11,11,11,11,11,11,11,
  129151. };
  129152. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129153. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129154. 637.5, 892.5, 1147.5, 1402.5,
  129155. };
  129156. static long _vq_quantmap__44c3_s_p9_0[] = {
  129157. 11, 9, 7, 5, 3, 1, 0, 2,
  129158. 4, 6, 8, 10, 12,
  129159. };
  129160. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129161. _vq_quantthresh__44c3_s_p9_0,
  129162. _vq_quantmap__44c3_s_p9_0,
  129163. 13,
  129164. 13
  129165. };
  129166. static static_codebook _44c3_s_p9_0 = {
  129167. 2, 169,
  129168. _vq_lengthlist__44c3_s_p9_0,
  129169. 1, -514332672, 1627381760, 4, 0,
  129170. _vq_quantlist__44c3_s_p9_0,
  129171. NULL,
  129172. &_vq_auxt__44c3_s_p9_0,
  129173. NULL,
  129174. 0
  129175. };
  129176. static long _vq_quantlist__44c3_s_p9_1[] = {
  129177. 7,
  129178. 6,
  129179. 8,
  129180. 5,
  129181. 9,
  129182. 4,
  129183. 10,
  129184. 3,
  129185. 11,
  129186. 2,
  129187. 12,
  129188. 1,
  129189. 13,
  129190. 0,
  129191. 14,
  129192. };
  129193. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129194. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129195. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129196. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129197. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129198. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129199. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129200. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129201. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129202. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129203. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129204. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129205. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129206. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129207. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129208. 15,
  129209. };
  129210. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129211. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129212. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129213. };
  129214. static long _vq_quantmap__44c3_s_p9_1[] = {
  129215. 13, 11, 9, 7, 5, 3, 1, 0,
  129216. 2, 4, 6, 8, 10, 12, 14,
  129217. };
  129218. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129219. _vq_quantthresh__44c3_s_p9_1,
  129220. _vq_quantmap__44c3_s_p9_1,
  129221. 15,
  129222. 15
  129223. };
  129224. static static_codebook _44c3_s_p9_1 = {
  129225. 2, 225,
  129226. _vq_lengthlist__44c3_s_p9_1,
  129227. 1, -522338304, 1620115456, 4, 0,
  129228. _vq_quantlist__44c3_s_p9_1,
  129229. NULL,
  129230. &_vq_auxt__44c3_s_p9_1,
  129231. NULL,
  129232. 0
  129233. };
  129234. static long _vq_quantlist__44c3_s_p9_2[] = {
  129235. 8,
  129236. 7,
  129237. 9,
  129238. 6,
  129239. 10,
  129240. 5,
  129241. 11,
  129242. 4,
  129243. 12,
  129244. 3,
  129245. 13,
  129246. 2,
  129247. 14,
  129248. 1,
  129249. 15,
  129250. 0,
  129251. 16,
  129252. };
  129253. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129254. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129255. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129256. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129257. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129258. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129259. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129260. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129261. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129262. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129263. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129264. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129265. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129266. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129267. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129268. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129269. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129270. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129271. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129272. 10,
  129273. };
  129274. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129275. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129276. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129277. };
  129278. static long _vq_quantmap__44c3_s_p9_2[] = {
  129279. 15, 13, 11, 9, 7, 5, 3, 1,
  129280. 0, 2, 4, 6, 8, 10, 12, 14,
  129281. 16,
  129282. };
  129283. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129284. _vq_quantthresh__44c3_s_p9_2,
  129285. _vq_quantmap__44c3_s_p9_2,
  129286. 17,
  129287. 17
  129288. };
  129289. static static_codebook _44c3_s_p9_2 = {
  129290. 2, 289,
  129291. _vq_lengthlist__44c3_s_p9_2,
  129292. 1, -529530880, 1611661312, 5, 0,
  129293. _vq_quantlist__44c3_s_p9_2,
  129294. NULL,
  129295. &_vq_auxt__44c3_s_p9_2,
  129296. NULL,
  129297. 0
  129298. };
  129299. static long _huff_lengthlist__44c3_s_short[] = {
  129300. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129301. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129302. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129303. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129304. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129305. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129306. 6, 8, 9,11,
  129307. };
  129308. static static_codebook _huff_book__44c3_s_short = {
  129309. 2, 100,
  129310. _huff_lengthlist__44c3_s_short,
  129311. 0, 0, 0, 0, 0,
  129312. NULL,
  129313. NULL,
  129314. NULL,
  129315. NULL,
  129316. 0
  129317. };
  129318. static long _huff_lengthlist__44c4_s_long[] = {
  129319. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129320. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129321. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129322. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129323. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129324. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129325. 9, 8, 7, 7,
  129326. };
  129327. static static_codebook _huff_book__44c4_s_long = {
  129328. 2, 100,
  129329. _huff_lengthlist__44c4_s_long,
  129330. 0, 0, 0, 0, 0,
  129331. NULL,
  129332. NULL,
  129333. NULL,
  129334. NULL,
  129335. 0
  129336. };
  129337. static long _vq_quantlist__44c4_s_p1_0[] = {
  129338. 1,
  129339. 0,
  129340. 2,
  129341. };
  129342. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129343. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129344. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129349. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129354. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129389. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129394. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129399. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129435. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129440. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129445. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0,
  129754. };
  129755. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129756. -0.5, 0.5,
  129757. };
  129758. static long _vq_quantmap__44c4_s_p1_0[] = {
  129759. 1, 0, 2,
  129760. };
  129761. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129762. _vq_quantthresh__44c4_s_p1_0,
  129763. _vq_quantmap__44c4_s_p1_0,
  129764. 3,
  129765. 3
  129766. };
  129767. static static_codebook _44c4_s_p1_0 = {
  129768. 8, 6561,
  129769. _vq_lengthlist__44c4_s_p1_0,
  129770. 1, -535822336, 1611661312, 2, 0,
  129771. _vq_quantlist__44c4_s_p1_0,
  129772. NULL,
  129773. &_vq_auxt__44c4_s_p1_0,
  129774. NULL,
  129775. 0
  129776. };
  129777. static long _vq_quantlist__44c4_s_p2_0[] = {
  129778. 2,
  129779. 1,
  129780. 3,
  129781. 0,
  129782. 4,
  129783. };
  129784. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129785. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129786. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129787. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129788. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129789. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129795. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129796. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129797. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129803. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129804. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129811. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129812. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0,
  129825. };
  129826. static float _vq_quantthresh__44c4_s_p2_0[] = {
  129827. -1.5, -0.5, 0.5, 1.5,
  129828. };
  129829. static long _vq_quantmap__44c4_s_p2_0[] = {
  129830. 3, 1, 0, 2, 4,
  129831. };
  129832. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  129833. _vq_quantthresh__44c4_s_p2_0,
  129834. _vq_quantmap__44c4_s_p2_0,
  129835. 5,
  129836. 5
  129837. };
  129838. static static_codebook _44c4_s_p2_0 = {
  129839. 4, 625,
  129840. _vq_lengthlist__44c4_s_p2_0,
  129841. 1, -533725184, 1611661312, 3, 0,
  129842. _vq_quantlist__44c4_s_p2_0,
  129843. NULL,
  129844. &_vq_auxt__44c4_s_p2_0,
  129845. NULL,
  129846. 0
  129847. };
  129848. static long _vq_quantlist__44c4_s_p3_0[] = {
  129849. 2,
  129850. 1,
  129851. 3,
  129852. 0,
  129853. 4,
  129854. };
  129855. static long _vq_lengthlist__44c4_s_p3_0[] = {
  129856. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0,
  129896. };
  129897. static float _vq_quantthresh__44c4_s_p3_0[] = {
  129898. -1.5, -0.5, 0.5, 1.5,
  129899. };
  129900. static long _vq_quantmap__44c4_s_p3_0[] = {
  129901. 3, 1, 0, 2, 4,
  129902. };
  129903. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  129904. _vq_quantthresh__44c4_s_p3_0,
  129905. _vq_quantmap__44c4_s_p3_0,
  129906. 5,
  129907. 5
  129908. };
  129909. static static_codebook _44c4_s_p3_0 = {
  129910. 4, 625,
  129911. _vq_lengthlist__44c4_s_p3_0,
  129912. 1, -533725184, 1611661312, 3, 0,
  129913. _vq_quantlist__44c4_s_p3_0,
  129914. NULL,
  129915. &_vq_auxt__44c4_s_p3_0,
  129916. NULL,
  129917. 0
  129918. };
  129919. static long _vq_quantlist__44c4_s_p4_0[] = {
  129920. 4,
  129921. 3,
  129922. 5,
  129923. 2,
  129924. 6,
  129925. 1,
  129926. 7,
  129927. 0,
  129928. 8,
  129929. };
  129930. static long _vq_lengthlist__44c4_s_p4_0[] = {
  129931. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129932. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129933. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129934. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129935. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0,
  129937. };
  129938. static float _vq_quantthresh__44c4_s_p4_0[] = {
  129939. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129940. };
  129941. static long _vq_quantmap__44c4_s_p4_0[] = {
  129942. 7, 5, 3, 1, 0, 2, 4, 6,
  129943. 8,
  129944. };
  129945. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  129946. _vq_quantthresh__44c4_s_p4_0,
  129947. _vq_quantmap__44c4_s_p4_0,
  129948. 9,
  129949. 9
  129950. };
  129951. static static_codebook _44c4_s_p4_0 = {
  129952. 2, 81,
  129953. _vq_lengthlist__44c4_s_p4_0,
  129954. 1, -531628032, 1611661312, 4, 0,
  129955. _vq_quantlist__44c4_s_p4_0,
  129956. NULL,
  129957. &_vq_auxt__44c4_s_p4_0,
  129958. NULL,
  129959. 0
  129960. };
  129961. static long _vq_quantlist__44c4_s_p5_0[] = {
  129962. 4,
  129963. 3,
  129964. 5,
  129965. 2,
  129966. 6,
  129967. 1,
  129968. 7,
  129969. 0,
  129970. 8,
  129971. };
  129972. static long _vq_lengthlist__44c4_s_p5_0[] = {
  129973. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129974. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  129975. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  129976. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  129977. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  129978. 10,
  129979. };
  129980. static float _vq_quantthresh__44c4_s_p5_0[] = {
  129981. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129982. };
  129983. static long _vq_quantmap__44c4_s_p5_0[] = {
  129984. 7, 5, 3, 1, 0, 2, 4, 6,
  129985. 8,
  129986. };
  129987. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  129988. _vq_quantthresh__44c4_s_p5_0,
  129989. _vq_quantmap__44c4_s_p5_0,
  129990. 9,
  129991. 9
  129992. };
  129993. static static_codebook _44c4_s_p5_0 = {
  129994. 2, 81,
  129995. _vq_lengthlist__44c4_s_p5_0,
  129996. 1, -531628032, 1611661312, 4, 0,
  129997. _vq_quantlist__44c4_s_p5_0,
  129998. NULL,
  129999. &_vq_auxt__44c4_s_p5_0,
  130000. NULL,
  130001. 0
  130002. };
  130003. static long _vq_quantlist__44c4_s_p6_0[] = {
  130004. 8,
  130005. 7,
  130006. 9,
  130007. 6,
  130008. 10,
  130009. 5,
  130010. 11,
  130011. 4,
  130012. 12,
  130013. 3,
  130014. 13,
  130015. 2,
  130016. 14,
  130017. 1,
  130018. 15,
  130019. 0,
  130020. 16,
  130021. };
  130022. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130023. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130024. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130025. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130026. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130027. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130028. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130029. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130030. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130031. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130032. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130033. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130034. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130035. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130036. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130037. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130038. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130039. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130041. 13,
  130042. };
  130043. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130044. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130045. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130046. };
  130047. static long _vq_quantmap__44c4_s_p6_0[] = {
  130048. 15, 13, 11, 9, 7, 5, 3, 1,
  130049. 0, 2, 4, 6, 8, 10, 12, 14,
  130050. 16,
  130051. };
  130052. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130053. _vq_quantthresh__44c4_s_p6_0,
  130054. _vq_quantmap__44c4_s_p6_0,
  130055. 17,
  130056. 17
  130057. };
  130058. static static_codebook _44c4_s_p6_0 = {
  130059. 2, 289,
  130060. _vq_lengthlist__44c4_s_p6_0,
  130061. 1, -529530880, 1611661312, 5, 0,
  130062. _vq_quantlist__44c4_s_p6_0,
  130063. NULL,
  130064. &_vq_auxt__44c4_s_p6_0,
  130065. NULL,
  130066. 0
  130067. };
  130068. static long _vq_quantlist__44c4_s_p7_0[] = {
  130069. 1,
  130070. 0,
  130071. 2,
  130072. };
  130073. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130074. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130075. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130076. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130077. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130078. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130079. 10,
  130080. };
  130081. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130082. -5.5, 5.5,
  130083. };
  130084. static long _vq_quantmap__44c4_s_p7_0[] = {
  130085. 1, 0, 2,
  130086. };
  130087. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130088. _vq_quantthresh__44c4_s_p7_0,
  130089. _vq_quantmap__44c4_s_p7_0,
  130090. 3,
  130091. 3
  130092. };
  130093. static static_codebook _44c4_s_p7_0 = {
  130094. 4, 81,
  130095. _vq_lengthlist__44c4_s_p7_0,
  130096. 1, -529137664, 1618345984, 2, 0,
  130097. _vq_quantlist__44c4_s_p7_0,
  130098. NULL,
  130099. &_vq_auxt__44c4_s_p7_0,
  130100. NULL,
  130101. 0
  130102. };
  130103. static long _vq_quantlist__44c4_s_p7_1[] = {
  130104. 5,
  130105. 4,
  130106. 6,
  130107. 3,
  130108. 7,
  130109. 2,
  130110. 8,
  130111. 1,
  130112. 9,
  130113. 0,
  130114. 10,
  130115. };
  130116. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130117. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130118. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130119. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130120. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130121. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130122. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130123. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130124. 10,10,10, 8, 8, 8, 8, 9, 9,
  130125. };
  130126. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130127. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130128. 3.5, 4.5,
  130129. };
  130130. static long _vq_quantmap__44c4_s_p7_1[] = {
  130131. 9, 7, 5, 3, 1, 0, 2, 4,
  130132. 6, 8, 10,
  130133. };
  130134. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130135. _vq_quantthresh__44c4_s_p7_1,
  130136. _vq_quantmap__44c4_s_p7_1,
  130137. 11,
  130138. 11
  130139. };
  130140. static static_codebook _44c4_s_p7_1 = {
  130141. 2, 121,
  130142. _vq_lengthlist__44c4_s_p7_1,
  130143. 1, -531365888, 1611661312, 4, 0,
  130144. _vq_quantlist__44c4_s_p7_1,
  130145. NULL,
  130146. &_vq_auxt__44c4_s_p7_1,
  130147. NULL,
  130148. 0
  130149. };
  130150. static long _vq_quantlist__44c4_s_p8_0[] = {
  130151. 6,
  130152. 5,
  130153. 7,
  130154. 4,
  130155. 8,
  130156. 3,
  130157. 9,
  130158. 2,
  130159. 10,
  130160. 1,
  130161. 11,
  130162. 0,
  130163. 12,
  130164. };
  130165. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130166. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130167. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130168. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130169. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130170. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130171. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130172. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130173. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130174. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130175. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130176. 0,13,12,12,12,12,12,13,13,
  130177. };
  130178. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130179. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130180. 12.5, 17.5, 22.5, 27.5,
  130181. };
  130182. static long _vq_quantmap__44c4_s_p8_0[] = {
  130183. 11, 9, 7, 5, 3, 1, 0, 2,
  130184. 4, 6, 8, 10, 12,
  130185. };
  130186. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130187. _vq_quantthresh__44c4_s_p8_0,
  130188. _vq_quantmap__44c4_s_p8_0,
  130189. 13,
  130190. 13
  130191. };
  130192. static static_codebook _44c4_s_p8_0 = {
  130193. 2, 169,
  130194. _vq_lengthlist__44c4_s_p8_0,
  130195. 1, -526516224, 1616117760, 4, 0,
  130196. _vq_quantlist__44c4_s_p8_0,
  130197. NULL,
  130198. &_vq_auxt__44c4_s_p8_0,
  130199. NULL,
  130200. 0
  130201. };
  130202. static long _vq_quantlist__44c4_s_p8_1[] = {
  130203. 2,
  130204. 1,
  130205. 3,
  130206. 0,
  130207. 4,
  130208. };
  130209. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130210. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130211. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130212. };
  130213. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130214. -1.5, -0.5, 0.5, 1.5,
  130215. };
  130216. static long _vq_quantmap__44c4_s_p8_1[] = {
  130217. 3, 1, 0, 2, 4,
  130218. };
  130219. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130220. _vq_quantthresh__44c4_s_p8_1,
  130221. _vq_quantmap__44c4_s_p8_1,
  130222. 5,
  130223. 5
  130224. };
  130225. static static_codebook _44c4_s_p8_1 = {
  130226. 2, 25,
  130227. _vq_lengthlist__44c4_s_p8_1,
  130228. 1, -533725184, 1611661312, 3, 0,
  130229. _vq_quantlist__44c4_s_p8_1,
  130230. NULL,
  130231. &_vq_auxt__44c4_s_p8_1,
  130232. NULL,
  130233. 0
  130234. };
  130235. static long _vq_quantlist__44c4_s_p9_0[] = {
  130236. 6,
  130237. 5,
  130238. 7,
  130239. 4,
  130240. 8,
  130241. 3,
  130242. 9,
  130243. 2,
  130244. 10,
  130245. 1,
  130246. 11,
  130247. 0,
  130248. 12,
  130249. };
  130250. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130251. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130252. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130253. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130254. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130255. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130256. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130257. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130258. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130259. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130260. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130261. 12,12,12,12,12,12,12,12,12,
  130262. };
  130263. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130264. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130265. 787.5, 1102.5, 1417.5, 1732.5,
  130266. };
  130267. static long _vq_quantmap__44c4_s_p9_0[] = {
  130268. 11, 9, 7, 5, 3, 1, 0, 2,
  130269. 4, 6, 8, 10, 12,
  130270. };
  130271. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130272. _vq_quantthresh__44c4_s_p9_0,
  130273. _vq_quantmap__44c4_s_p9_0,
  130274. 13,
  130275. 13
  130276. };
  130277. static static_codebook _44c4_s_p9_0 = {
  130278. 2, 169,
  130279. _vq_lengthlist__44c4_s_p9_0,
  130280. 1, -513964032, 1628680192, 4, 0,
  130281. _vq_quantlist__44c4_s_p9_0,
  130282. NULL,
  130283. &_vq_auxt__44c4_s_p9_0,
  130284. NULL,
  130285. 0
  130286. };
  130287. static long _vq_quantlist__44c4_s_p9_1[] = {
  130288. 7,
  130289. 6,
  130290. 8,
  130291. 5,
  130292. 9,
  130293. 4,
  130294. 10,
  130295. 3,
  130296. 11,
  130297. 2,
  130298. 12,
  130299. 1,
  130300. 13,
  130301. 0,
  130302. 14,
  130303. };
  130304. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130305. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130306. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130307. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130308. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130309. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130310. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130311. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130312. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130313. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130314. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130315. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130316. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130317. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130318. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130319. 15,
  130320. };
  130321. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130322. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130323. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130324. };
  130325. static long _vq_quantmap__44c4_s_p9_1[] = {
  130326. 13, 11, 9, 7, 5, 3, 1, 0,
  130327. 2, 4, 6, 8, 10, 12, 14,
  130328. };
  130329. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130330. _vq_quantthresh__44c4_s_p9_1,
  130331. _vq_quantmap__44c4_s_p9_1,
  130332. 15,
  130333. 15
  130334. };
  130335. static static_codebook _44c4_s_p9_1 = {
  130336. 2, 225,
  130337. _vq_lengthlist__44c4_s_p9_1,
  130338. 1, -520986624, 1620377600, 4, 0,
  130339. _vq_quantlist__44c4_s_p9_1,
  130340. NULL,
  130341. &_vq_auxt__44c4_s_p9_1,
  130342. NULL,
  130343. 0
  130344. };
  130345. static long _vq_quantlist__44c4_s_p9_2[] = {
  130346. 10,
  130347. 9,
  130348. 11,
  130349. 8,
  130350. 12,
  130351. 7,
  130352. 13,
  130353. 6,
  130354. 14,
  130355. 5,
  130356. 15,
  130357. 4,
  130358. 16,
  130359. 3,
  130360. 17,
  130361. 2,
  130362. 18,
  130363. 1,
  130364. 19,
  130365. 0,
  130366. 20,
  130367. };
  130368. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130369. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130370. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130371. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130372. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130373. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130374. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130375. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130376. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130377. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130378. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130379. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130380. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130381. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130382. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130383. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130384. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130385. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130386. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130387. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130388. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130389. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130390. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130391. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130392. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130393. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130394. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130395. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130396. 10,10,10,10,10,10,10,10,10,
  130397. };
  130398. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130399. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130400. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130401. 6.5, 7.5, 8.5, 9.5,
  130402. };
  130403. static long _vq_quantmap__44c4_s_p9_2[] = {
  130404. 19, 17, 15, 13, 11, 9, 7, 5,
  130405. 3, 1, 0, 2, 4, 6, 8, 10,
  130406. 12, 14, 16, 18, 20,
  130407. };
  130408. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130409. _vq_quantthresh__44c4_s_p9_2,
  130410. _vq_quantmap__44c4_s_p9_2,
  130411. 21,
  130412. 21
  130413. };
  130414. static static_codebook _44c4_s_p9_2 = {
  130415. 2, 441,
  130416. _vq_lengthlist__44c4_s_p9_2,
  130417. 1, -529268736, 1611661312, 5, 0,
  130418. _vq_quantlist__44c4_s_p9_2,
  130419. NULL,
  130420. &_vq_auxt__44c4_s_p9_2,
  130421. NULL,
  130422. 0
  130423. };
  130424. static long _huff_lengthlist__44c4_s_short[] = {
  130425. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130426. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130427. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130428. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130429. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130430. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130431. 7, 9,12,17,
  130432. };
  130433. static static_codebook _huff_book__44c4_s_short = {
  130434. 2, 100,
  130435. _huff_lengthlist__44c4_s_short,
  130436. 0, 0, 0, 0, 0,
  130437. NULL,
  130438. NULL,
  130439. NULL,
  130440. NULL,
  130441. 0
  130442. };
  130443. static long _huff_lengthlist__44c5_s_long[] = {
  130444. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130445. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130446. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130447. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130448. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130449. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130450. 9, 8, 7, 7,
  130451. };
  130452. static static_codebook _huff_book__44c5_s_long = {
  130453. 2, 100,
  130454. _huff_lengthlist__44c5_s_long,
  130455. 0, 0, 0, 0, 0,
  130456. NULL,
  130457. NULL,
  130458. NULL,
  130459. NULL,
  130460. 0
  130461. };
  130462. static long _vq_quantlist__44c5_s_p1_0[] = {
  130463. 1,
  130464. 0,
  130465. 2,
  130466. };
  130467. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130468. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130469. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130474. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130479. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130514. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130519. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130524. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130560. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130565. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130570. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 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, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0,
  130879. };
  130880. static float _vq_quantthresh__44c5_s_p1_0[] = {
  130881. -0.5, 0.5,
  130882. };
  130883. static long _vq_quantmap__44c5_s_p1_0[] = {
  130884. 1, 0, 2,
  130885. };
  130886. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  130887. _vq_quantthresh__44c5_s_p1_0,
  130888. _vq_quantmap__44c5_s_p1_0,
  130889. 3,
  130890. 3
  130891. };
  130892. static static_codebook _44c5_s_p1_0 = {
  130893. 8, 6561,
  130894. _vq_lengthlist__44c5_s_p1_0,
  130895. 1, -535822336, 1611661312, 2, 0,
  130896. _vq_quantlist__44c5_s_p1_0,
  130897. NULL,
  130898. &_vq_auxt__44c5_s_p1_0,
  130899. NULL,
  130900. 0
  130901. };
  130902. static long _vq_quantlist__44c5_s_p2_0[] = {
  130903. 2,
  130904. 1,
  130905. 3,
  130906. 0,
  130907. 4,
  130908. };
  130909. static long _vq_lengthlist__44c5_s_p2_0[] = {
  130910. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130911. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  130912. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130913. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  130914. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  130920. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  130921. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  130922. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  130928. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  130929. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  130936. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  130937. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0,
  130950. };
  130951. static float _vq_quantthresh__44c5_s_p2_0[] = {
  130952. -1.5, -0.5, 0.5, 1.5,
  130953. };
  130954. static long _vq_quantmap__44c5_s_p2_0[] = {
  130955. 3, 1, 0, 2, 4,
  130956. };
  130957. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  130958. _vq_quantthresh__44c5_s_p2_0,
  130959. _vq_quantmap__44c5_s_p2_0,
  130960. 5,
  130961. 5
  130962. };
  130963. static static_codebook _44c5_s_p2_0 = {
  130964. 4, 625,
  130965. _vq_lengthlist__44c5_s_p2_0,
  130966. 1, -533725184, 1611661312, 3, 0,
  130967. _vq_quantlist__44c5_s_p2_0,
  130968. NULL,
  130969. &_vq_auxt__44c5_s_p2_0,
  130970. NULL,
  130971. 0
  130972. };
  130973. static long _vq_quantlist__44c5_s_p3_0[] = {
  130974. 2,
  130975. 1,
  130976. 3,
  130977. 0,
  130978. 4,
  130979. };
  130980. static long _vq_lengthlist__44c5_s_p3_0[] = {
  130981. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0,
  131021. };
  131022. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131023. -1.5, -0.5, 0.5, 1.5,
  131024. };
  131025. static long _vq_quantmap__44c5_s_p3_0[] = {
  131026. 3, 1, 0, 2, 4,
  131027. };
  131028. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131029. _vq_quantthresh__44c5_s_p3_0,
  131030. _vq_quantmap__44c5_s_p3_0,
  131031. 5,
  131032. 5
  131033. };
  131034. static static_codebook _44c5_s_p3_0 = {
  131035. 4, 625,
  131036. _vq_lengthlist__44c5_s_p3_0,
  131037. 1, -533725184, 1611661312, 3, 0,
  131038. _vq_quantlist__44c5_s_p3_0,
  131039. NULL,
  131040. &_vq_auxt__44c5_s_p3_0,
  131041. NULL,
  131042. 0
  131043. };
  131044. static long _vq_quantlist__44c5_s_p4_0[] = {
  131045. 4,
  131046. 3,
  131047. 5,
  131048. 2,
  131049. 6,
  131050. 1,
  131051. 7,
  131052. 0,
  131053. 8,
  131054. };
  131055. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131056. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131057. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131058. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131059. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131060. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0,
  131062. };
  131063. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131064. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131065. };
  131066. static long _vq_quantmap__44c5_s_p4_0[] = {
  131067. 7, 5, 3, 1, 0, 2, 4, 6,
  131068. 8,
  131069. };
  131070. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131071. _vq_quantthresh__44c5_s_p4_0,
  131072. _vq_quantmap__44c5_s_p4_0,
  131073. 9,
  131074. 9
  131075. };
  131076. static static_codebook _44c5_s_p4_0 = {
  131077. 2, 81,
  131078. _vq_lengthlist__44c5_s_p4_0,
  131079. 1, -531628032, 1611661312, 4, 0,
  131080. _vq_quantlist__44c5_s_p4_0,
  131081. NULL,
  131082. &_vq_auxt__44c5_s_p4_0,
  131083. NULL,
  131084. 0
  131085. };
  131086. static long _vq_quantlist__44c5_s_p5_0[] = {
  131087. 4,
  131088. 3,
  131089. 5,
  131090. 2,
  131091. 6,
  131092. 1,
  131093. 7,
  131094. 0,
  131095. 8,
  131096. };
  131097. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131098. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131099. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131100. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131101. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131102. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131103. 10,
  131104. };
  131105. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131106. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131107. };
  131108. static long _vq_quantmap__44c5_s_p5_0[] = {
  131109. 7, 5, 3, 1, 0, 2, 4, 6,
  131110. 8,
  131111. };
  131112. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131113. _vq_quantthresh__44c5_s_p5_0,
  131114. _vq_quantmap__44c5_s_p5_0,
  131115. 9,
  131116. 9
  131117. };
  131118. static static_codebook _44c5_s_p5_0 = {
  131119. 2, 81,
  131120. _vq_lengthlist__44c5_s_p5_0,
  131121. 1, -531628032, 1611661312, 4, 0,
  131122. _vq_quantlist__44c5_s_p5_0,
  131123. NULL,
  131124. &_vq_auxt__44c5_s_p5_0,
  131125. NULL,
  131126. 0
  131127. };
  131128. static long _vq_quantlist__44c5_s_p6_0[] = {
  131129. 8,
  131130. 7,
  131131. 9,
  131132. 6,
  131133. 10,
  131134. 5,
  131135. 11,
  131136. 4,
  131137. 12,
  131138. 3,
  131139. 13,
  131140. 2,
  131141. 14,
  131142. 1,
  131143. 15,
  131144. 0,
  131145. 16,
  131146. };
  131147. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131148. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131149. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131150. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131151. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131152. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131153. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131154. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131155. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131156. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131157. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131158. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131159. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131160. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131161. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131162. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131163. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131164. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131166. 13,
  131167. };
  131168. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131169. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131170. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131171. };
  131172. static long _vq_quantmap__44c5_s_p6_0[] = {
  131173. 15, 13, 11, 9, 7, 5, 3, 1,
  131174. 0, 2, 4, 6, 8, 10, 12, 14,
  131175. 16,
  131176. };
  131177. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131178. _vq_quantthresh__44c5_s_p6_0,
  131179. _vq_quantmap__44c5_s_p6_0,
  131180. 17,
  131181. 17
  131182. };
  131183. static static_codebook _44c5_s_p6_0 = {
  131184. 2, 289,
  131185. _vq_lengthlist__44c5_s_p6_0,
  131186. 1, -529530880, 1611661312, 5, 0,
  131187. _vq_quantlist__44c5_s_p6_0,
  131188. NULL,
  131189. &_vq_auxt__44c5_s_p6_0,
  131190. NULL,
  131191. 0
  131192. };
  131193. static long _vq_quantlist__44c5_s_p7_0[] = {
  131194. 1,
  131195. 0,
  131196. 2,
  131197. };
  131198. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131199. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131200. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131201. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131202. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131203. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131204. 10,
  131205. };
  131206. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131207. -5.5, 5.5,
  131208. };
  131209. static long _vq_quantmap__44c5_s_p7_0[] = {
  131210. 1, 0, 2,
  131211. };
  131212. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131213. _vq_quantthresh__44c5_s_p7_0,
  131214. _vq_quantmap__44c5_s_p7_0,
  131215. 3,
  131216. 3
  131217. };
  131218. static static_codebook _44c5_s_p7_0 = {
  131219. 4, 81,
  131220. _vq_lengthlist__44c5_s_p7_0,
  131221. 1, -529137664, 1618345984, 2, 0,
  131222. _vq_quantlist__44c5_s_p7_0,
  131223. NULL,
  131224. &_vq_auxt__44c5_s_p7_0,
  131225. NULL,
  131226. 0
  131227. };
  131228. static long _vq_quantlist__44c5_s_p7_1[] = {
  131229. 5,
  131230. 4,
  131231. 6,
  131232. 3,
  131233. 7,
  131234. 2,
  131235. 8,
  131236. 1,
  131237. 9,
  131238. 0,
  131239. 10,
  131240. };
  131241. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131242. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131243. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131244. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131245. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131246. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131247. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131248. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131249. 10,10,10, 8, 8, 8, 8, 8, 8,
  131250. };
  131251. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131252. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131253. 3.5, 4.5,
  131254. };
  131255. static long _vq_quantmap__44c5_s_p7_1[] = {
  131256. 9, 7, 5, 3, 1, 0, 2, 4,
  131257. 6, 8, 10,
  131258. };
  131259. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131260. _vq_quantthresh__44c5_s_p7_1,
  131261. _vq_quantmap__44c5_s_p7_1,
  131262. 11,
  131263. 11
  131264. };
  131265. static static_codebook _44c5_s_p7_1 = {
  131266. 2, 121,
  131267. _vq_lengthlist__44c5_s_p7_1,
  131268. 1, -531365888, 1611661312, 4, 0,
  131269. _vq_quantlist__44c5_s_p7_1,
  131270. NULL,
  131271. &_vq_auxt__44c5_s_p7_1,
  131272. NULL,
  131273. 0
  131274. };
  131275. static long _vq_quantlist__44c5_s_p8_0[] = {
  131276. 6,
  131277. 5,
  131278. 7,
  131279. 4,
  131280. 8,
  131281. 3,
  131282. 9,
  131283. 2,
  131284. 10,
  131285. 1,
  131286. 11,
  131287. 0,
  131288. 12,
  131289. };
  131290. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131291. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131292. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131293. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131294. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131295. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131296. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131297. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131298. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131299. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131300. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131301. 0,12,12,12,12,12,12,13,13,
  131302. };
  131303. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131304. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131305. 12.5, 17.5, 22.5, 27.5,
  131306. };
  131307. static long _vq_quantmap__44c5_s_p8_0[] = {
  131308. 11, 9, 7, 5, 3, 1, 0, 2,
  131309. 4, 6, 8, 10, 12,
  131310. };
  131311. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131312. _vq_quantthresh__44c5_s_p8_0,
  131313. _vq_quantmap__44c5_s_p8_0,
  131314. 13,
  131315. 13
  131316. };
  131317. static static_codebook _44c5_s_p8_0 = {
  131318. 2, 169,
  131319. _vq_lengthlist__44c5_s_p8_0,
  131320. 1, -526516224, 1616117760, 4, 0,
  131321. _vq_quantlist__44c5_s_p8_0,
  131322. NULL,
  131323. &_vq_auxt__44c5_s_p8_0,
  131324. NULL,
  131325. 0
  131326. };
  131327. static long _vq_quantlist__44c5_s_p8_1[] = {
  131328. 2,
  131329. 1,
  131330. 3,
  131331. 0,
  131332. 4,
  131333. };
  131334. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131335. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131336. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131337. };
  131338. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131339. -1.5, -0.5, 0.5, 1.5,
  131340. };
  131341. static long _vq_quantmap__44c5_s_p8_1[] = {
  131342. 3, 1, 0, 2, 4,
  131343. };
  131344. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131345. _vq_quantthresh__44c5_s_p8_1,
  131346. _vq_quantmap__44c5_s_p8_1,
  131347. 5,
  131348. 5
  131349. };
  131350. static static_codebook _44c5_s_p8_1 = {
  131351. 2, 25,
  131352. _vq_lengthlist__44c5_s_p8_1,
  131353. 1, -533725184, 1611661312, 3, 0,
  131354. _vq_quantlist__44c5_s_p8_1,
  131355. NULL,
  131356. &_vq_auxt__44c5_s_p8_1,
  131357. NULL,
  131358. 0
  131359. };
  131360. static long _vq_quantlist__44c5_s_p9_0[] = {
  131361. 7,
  131362. 6,
  131363. 8,
  131364. 5,
  131365. 9,
  131366. 4,
  131367. 10,
  131368. 3,
  131369. 11,
  131370. 2,
  131371. 12,
  131372. 1,
  131373. 13,
  131374. 0,
  131375. 14,
  131376. };
  131377. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131378. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131379. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131380. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131381. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131382. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131383. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131384. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131385. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131386. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131387. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131388. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131389. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131390. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131391. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131392. 12,
  131393. };
  131394. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131395. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131396. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131397. };
  131398. static long _vq_quantmap__44c5_s_p9_0[] = {
  131399. 13, 11, 9, 7, 5, 3, 1, 0,
  131400. 2, 4, 6, 8, 10, 12, 14,
  131401. };
  131402. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131403. _vq_quantthresh__44c5_s_p9_0,
  131404. _vq_quantmap__44c5_s_p9_0,
  131405. 15,
  131406. 15
  131407. };
  131408. static static_codebook _44c5_s_p9_0 = {
  131409. 2, 225,
  131410. _vq_lengthlist__44c5_s_p9_0,
  131411. 1, -512522752, 1628852224, 4, 0,
  131412. _vq_quantlist__44c5_s_p9_0,
  131413. NULL,
  131414. &_vq_auxt__44c5_s_p9_0,
  131415. NULL,
  131416. 0
  131417. };
  131418. static long _vq_quantlist__44c5_s_p9_1[] = {
  131419. 8,
  131420. 7,
  131421. 9,
  131422. 6,
  131423. 10,
  131424. 5,
  131425. 11,
  131426. 4,
  131427. 12,
  131428. 3,
  131429. 13,
  131430. 2,
  131431. 14,
  131432. 1,
  131433. 15,
  131434. 0,
  131435. 16,
  131436. };
  131437. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131438. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131439. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131440. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131441. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131442. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131443. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131444. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131445. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131446. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131447. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131448. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131449. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131450. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131451. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131452. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131453. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131454. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131455. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131456. 15,
  131457. };
  131458. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131459. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131460. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131461. };
  131462. static long _vq_quantmap__44c5_s_p9_1[] = {
  131463. 15, 13, 11, 9, 7, 5, 3, 1,
  131464. 0, 2, 4, 6, 8, 10, 12, 14,
  131465. 16,
  131466. };
  131467. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131468. _vq_quantthresh__44c5_s_p9_1,
  131469. _vq_quantmap__44c5_s_p9_1,
  131470. 17,
  131471. 17
  131472. };
  131473. static static_codebook _44c5_s_p9_1 = {
  131474. 2, 289,
  131475. _vq_lengthlist__44c5_s_p9_1,
  131476. 1, -520814592, 1620377600, 5, 0,
  131477. _vq_quantlist__44c5_s_p9_1,
  131478. NULL,
  131479. &_vq_auxt__44c5_s_p9_1,
  131480. NULL,
  131481. 0
  131482. };
  131483. static long _vq_quantlist__44c5_s_p9_2[] = {
  131484. 10,
  131485. 9,
  131486. 11,
  131487. 8,
  131488. 12,
  131489. 7,
  131490. 13,
  131491. 6,
  131492. 14,
  131493. 5,
  131494. 15,
  131495. 4,
  131496. 16,
  131497. 3,
  131498. 17,
  131499. 2,
  131500. 18,
  131501. 1,
  131502. 19,
  131503. 0,
  131504. 20,
  131505. };
  131506. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131507. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131508. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131509. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131510. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131511. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131512. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131513. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131514. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131515. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131516. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131517. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131518. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131519. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131520. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131521. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131522. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131523. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131524. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131525. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131526. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131527. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131528. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131529. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131530. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131531. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131532. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131533. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131534. 10,10,10,10,10,10,10,10,10,
  131535. };
  131536. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131537. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131538. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131539. 6.5, 7.5, 8.5, 9.5,
  131540. };
  131541. static long _vq_quantmap__44c5_s_p9_2[] = {
  131542. 19, 17, 15, 13, 11, 9, 7, 5,
  131543. 3, 1, 0, 2, 4, 6, 8, 10,
  131544. 12, 14, 16, 18, 20,
  131545. };
  131546. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131547. _vq_quantthresh__44c5_s_p9_2,
  131548. _vq_quantmap__44c5_s_p9_2,
  131549. 21,
  131550. 21
  131551. };
  131552. static static_codebook _44c5_s_p9_2 = {
  131553. 2, 441,
  131554. _vq_lengthlist__44c5_s_p9_2,
  131555. 1, -529268736, 1611661312, 5, 0,
  131556. _vq_quantlist__44c5_s_p9_2,
  131557. NULL,
  131558. &_vq_auxt__44c5_s_p9_2,
  131559. NULL,
  131560. 0
  131561. };
  131562. static long _huff_lengthlist__44c5_s_short[] = {
  131563. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131564. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131565. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131566. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131567. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131568. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131569. 6, 8,11,16,
  131570. };
  131571. static static_codebook _huff_book__44c5_s_short = {
  131572. 2, 100,
  131573. _huff_lengthlist__44c5_s_short,
  131574. 0, 0, 0, 0, 0,
  131575. NULL,
  131576. NULL,
  131577. NULL,
  131578. NULL,
  131579. 0
  131580. };
  131581. static long _huff_lengthlist__44c6_s_long[] = {
  131582. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131583. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131584. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131585. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131586. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131587. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131588. 11,10,10,12,
  131589. };
  131590. static static_codebook _huff_book__44c6_s_long = {
  131591. 2, 100,
  131592. _huff_lengthlist__44c6_s_long,
  131593. 0, 0, 0, 0, 0,
  131594. NULL,
  131595. NULL,
  131596. NULL,
  131597. NULL,
  131598. 0
  131599. };
  131600. static long _vq_quantlist__44c6_s_p1_0[] = {
  131601. 1,
  131602. 0,
  131603. 2,
  131604. };
  131605. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131606. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131607. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131609. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131610. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131611. 8,
  131612. };
  131613. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131614. -0.5, 0.5,
  131615. };
  131616. static long _vq_quantmap__44c6_s_p1_0[] = {
  131617. 1, 0, 2,
  131618. };
  131619. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131620. _vq_quantthresh__44c6_s_p1_0,
  131621. _vq_quantmap__44c6_s_p1_0,
  131622. 3,
  131623. 3
  131624. };
  131625. static static_codebook _44c6_s_p1_0 = {
  131626. 4, 81,
  131627. _vq_lengthlist__44c6_s_p1_0,
  131628. 1, -535822336, 1611661312, 2, 0,
  131629. _vq_quantlist__44c6_s_p1_0,
  131630. NULL,
  131631. &_vq_auxt__44c6_s_p1_0,
  131632. NULL,
  131633. 0
  131634. };
  131635. static long _vq_quantlist__44c6_s_p2_0[] = {
  131636. 2,
  131637. 1,
  131638. 3,
  131639. 0,
  131640. 4,
  131641. };
  131642. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131643. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131644. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131645. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131646. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131647. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131648. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131649. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131650. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131653. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131654. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131655. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131656. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131657. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131658. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131661. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131662. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131663. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131664. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131665. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131666. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131669. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131670. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131671. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131672. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131673. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131674. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131679. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131680. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131681. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131682. 13,
  131683. };
  131684. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131685. -1.5, -0.5, 0.5, 1.5,
  131686. };
  131687. static long _vq_quantmap__44c6_s_p2_0[] = {
  131688. 3, 1, 0, 2, 4,
  131689. };
  131690. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131691. _vq_quantthresh__44c6_s_p2_0,
  131692. _vq_quantmap__44c6_s_p2_0,
  131693. 5,
  131694. 5
  131695. };
  131696. static static_codebook _44c6_s_p2_0 = {
  131697. 4, 625,
  131698. _vq_lengthlist__44c6_s_p2_0,
  131699. 1, -533725184, 1611661312, 3, 0,
  131700. _vq_quantlist__44c6_s_p2_0,
  131701. NULL,
  131702. &_vq_auxt__44c6_s_p2_0,
  131703. NULL,
  131704. 0
  131705. };
  131706. static long _vq_quantlist__44c6_s_p3_0[] = {
  131707. 4,
  131708. 3,
  131709. 5,
  131710. 2,
  131711. 6,
  131712. 1,
  131713. 7,
  131714. 0,
  131715. 8,
  131716. };
  131717. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131718. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131719. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131720. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131721. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0,
  131724. };
  131725. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131726. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131727. };
  131728. static long _vq_quantmap__44c6_s_p3_0[] = {
  131729. 7, 5, 3, 1, 0, 2, 4, 6,
  131730. 8,
  131731. };
  131732. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131733. _vq_quantthresh__44c6_s_p3_0,
  131734. _vq_quantmap__44c6_s_p3_0,
  131735. 9,
  131736. 9
  131737. };
  131738. static static_codebook _44c6_s_p3_0 = {
  131739. 2, 81,
  131740. _vq_lengthlist__44c6_s_p3_0,
  131741. 1, -531628032, 1611661312, 4, 0,
  131742. _vq_quantlist__44c6_s_p3_0,
  131743. NULL,
  131744. &_vq_auxt__44c6_s_p3_0,
  131745. NULL,
  131746. 0
  131747. };
  131748. static long _vq_quantlist__44c6_s_p4_0[] = {
  131749. 8,
  131750. 7,
  131751. 9,
  131752. 6,
  131753. 10,
  131754. 5,
  131755. 11,
  131756. 4,
  131757. 12,
  131758. 3,
  131759. 13,
  131760. 2,
  131761. 14,
  131762. 1,
  131763. 15,
  131764. 0,
  131765. 16,
  131766. };
  131767. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131768. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131769. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131770. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131771. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131772. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131773. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131774. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131775. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131776. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131777. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0,
  131787. };
  131788. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131789. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131790. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131791. };
  131792. static long _vq_quantmap__44c6_s_p4_0[] = {
  131793. 15, 13, 11, 9, 7, 5, 3, 1,
  131794. 0, 2, 4, 6, 8, 10, 12, 14,
  131795. 16,
  131796. };
  131797. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131798. _vq_quantthresh__44c6_s_p4_0,
  131799. _vq_quantmap__44c6_s_p4_0,
  131800. 17,
  131801. 17
  131802. };
  131803. static static_codebook _44c6_s_p4_0 = {
  131804. 2, 289,
  131805. _vq_lengthlist__44c6_s_p4_0,
  131806. 1, -529530880, 1611661312, 5, 0,
  131807. _vq_quantlist__44c6_s_p4_0,
  131808. NULL,
  131809. &_vq_auxt__44c6_s_p4_0,
  131810. NULL,
  131811. 0
  131812. };
  131813. static long _vq_quantlist__44c6_s_p5_0[] = {
  131814. 1,
  131815. 0,
  131816. 2,
  131817. };
  131818. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131819. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  131820. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  131821. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  131822. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  131823. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  131824. 12,
  131825. };
  131826. static float _vq_quantthresh__44c6_s_p5_0[] = {
  131827. -5.5, 5.5,
  131828. };
  131829. static long _vq_quantmap__44c6_s_p5_0[] = {
  131830. 1, 0, 2,
  131831. };
  131832. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  131833. _vq_quantthresh__44c6_s_p5_0,
  131834. _vq_quantmap__44c6_s_p5_0,
  131835. 3,
  131836. 3
  131837. };
  131838. static static_codebook _44c6_s_p5_0 = {
  131839. 4, 81,
  131840. _vq_lengthlist__44c6_s_p5_0,
  131841. 1, -529137664, 1618345984, 2, 0,
  131842. _vq_quantlist__44c6_s_p5_0,
  131843. NULL,
  131844. &_vq_auxt__44c6_s_p5_0,
  131845. NULL,
  131846. 0
  131847. };
  131848. static long _vq_quantlist__44c6_s_p5_1[] = {
  131849. 5,
  131850. 4,
  131851. 6,
  131852. 3,
  131853. 7,
  131854. 2,
  131855. 8,
  131856. 1,
  131857. 9,
  131858. 0,
  131859. 10,
  131860. };
  131861. static long _vq_lengthlist__44c6_s_p5_1[] = {
  131862. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  131863. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  131864. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  131865. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  131866. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  131867. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  131868. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  131869. 11,10,10, 7, 7, 8, 8, 8, 8,
  131870. };
  131871. static float _vq_quantthresh__44c6_s_p5_1[] = {
  131872. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131873. 3.5, 4.5,
  131874. };
  131875. static long _vq_quantmap__44c6_s_p5_1[] = {
  131876. 9, 7, 5, 3, 1, 0, 2, 4,
  131877. 6, 8, 10,
  131878. };
  131879. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  131880. _vq_quantthresh__44c6_s_p5_1,
  131881. _vq_quantmap__44c6_s_p5_1,
  131882. 11,
  131883. 11
  131884. };
  131885. static static_codebook _44c6_s_p5_1 = {
  131886. 2, 121,
  131887. _vq_lengthlist__44c6_s_p5_1,
  131888. 1, -531365888, 1611661312, 4, 0,
  131889. _vq_quantlist__44c6_s_p5_1,
  131890. NULL,
  131891. &_vq_auxt__44c6_s_p5_1,
  131892. NULL,
  131893. 0
  131894. };
  131895. static long _vq_quantlist__44c6_s_p6_0[] = {
  131896. 6,
  131897. 5,
  131898. 7,
  131899. 4,
  131900. 8,
  131901. 3,
  131902. 9,
  131903. 2,
  131904. 10,
  131905. 1,
  131906. 11,
  131907. 0,
  131908. 12,
  131909. };
  131910. static long _vq_lengthlist__44c6_s_p6_0[] = {
  131911. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  131912. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  131913. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  131914. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131915. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  131916. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131921. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131922. };
  131923. static float _vq_quantthresh__44c6_s_p6_0[] = {
  131924. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131925. 12.5, 17.5, 22.5, 27.5,
  131926. };
  131927. static long _vq_quantmap__44c6_s_p6_0[] = {
  131928. 11, 9, 7, 5, 3, 1, 0, 2,
  131929. 4, 6, 8, 10, 12,
  131930. };
  131931. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  131932. _vq_quantthresh__44c6_s_p6_0,
  131933. _vq_quantmap__44c6_s_p6_0,
  131934. 13,
  131935. 13
  131936. };
  131937. static static_codebook _44c6_s_p6_0 = {
  131938. 2, 169,
  131939. _vq_lengthlist__44c6_s_p6_0,
  131940. 1, -526516224, 1616117760, 4, 0,
  131941. _vq_quantlist__44c6_s_p6_0,
  131942. NULL,
  131943. &_vq_auxt__44c6_s_p6_0,
  131944. NULL,
  131945. 0
  131946. };
  131947. static long _vq_quantlist__44c6_s_p6_1[] = {
  131948. 2,
  131949. 1,
  131950. 3,
  131951. 0,
  131952. 4,
  131953. };
  131954. static long _vq_lengthlist__44c6_s_p6_1[] = {
  131955. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131956. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131957. };
  131958. static float _vq_quantthresh__44c6_s_p6_1[] = {
  131959. -1.5, -0.5, 0.5, 1.5,
  131960. };
  131961. static long _vq_quantmap__44c6_s_p6_1[] = {
  131962. 3, 1, 0, 2, 4,
  131963. };
  131964. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  131965. _vq_quantthresh__44c6_s_p6_1,
  131966. _vq_quantmap__44c6_s_p6_1,
  131967. 5,
  131968. 5
  131969. };
  131970. static static_codebook _44c6_s_p6_1 = {
  131971. 2, 25,
  131972. _vq_lengthlist__44c6_s_p6_1,
  131973. 1, -533725184, 1611661312, 3, 0,
  131974. _vq_quantlist__44c6_s_p6_1,
  131975. NULL,
  131976. &_vq_auxt__44c6_s_p6_1,
  131977. NULL,
  131978. 0
  131979. };
  131980. static long _vq_quantlist__44c6_s_p7_0[] = {
  131981. 6,
  131982. 5,
  131983. 7,
  131984. 4,
  131985. 8,
  131986. 3,
  131987. 9,
  131988. 2,
  131989. 10,
  131990. 1,
  131991. 11,
  131992. 0,
  131993. 12,
  131994. };
  131995. static long _vq_lengthlist__44c6_s_p7_0[] = {
  131996. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  131997. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  131998. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  131999. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132000. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132001. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132002. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132003. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132004. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132005. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132006. 20,13,13,13,13,13,13,14,14,
  132007. };
  132008. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132009. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132010. 27.5, 38.5, 49.5, 60.5,
  132011. };
  132012. static long _vq_quantmap__44c6_s_p7_0[] = {
  132013. 11, 9, 7, 5, 3, 1, 0, 2,
  132014. 4, 6, 8, 10, 12,
  132015. };
  132016. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132017. _vq_quantthresh__44c6_s_p7_0,
  132018. _vq_quantmap__44c6_s_p7_0,
  132019. 13,
  132020. 13
  132021. };
  132022. static static_codebook _44c6_s_p7_0 = {
  132023. 2, 169,
  132024. _vq_lengthlist__44c6_s_p7_0,
  132025. 1, -523206656, 1618345984, 4, 0,
  132026. _vq_quantlist__44c6_s_p7_0,
  132027. NULL,
  132028. &_vq_auxt__44c6_s_p7_0,
  132029. NULL,
  132030. 0
  132031. };
  132032. static long _vq_quantlist__44c6_s_p7_1[] = {
  132033. 5,
  132034. 4,
  132035. 6,
  132036. 3,
  132037. 7,
  132038. 2,
  132039. 8,
  132040. 1,
  132041. 9,
  132042. 0,
  132043. 10,
  132044. };
  132045. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132046. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132047. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132048. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132049. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132050. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132051. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132052. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132053. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132054. };
  132055. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132056. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132057. 3.5, 4.5,
  132058. };
  132059. static long _vq_quantmap__44c6_s_p7_1[] = {
  132060. 9, 7, 5, 3, 1, 0, 2, 4,
  132061. 6, 8, 10,
  132062. };
  132063. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132064. _vq_quantthresh__44c6_s_p7_1,
  132065. _vq_quantmap__44c6_s_p7_1,
  132066. 11,
  132067. 11
  132068. };
  132069. static static_codebook _44c6_s_p7_1 = {
  132070. 2, 121,
  132071. _vq_lengthlist__44c6_s_p7_1,
  132072. 1, -531365888, 1611661312, 4, 0,
  132073. _vq_quantlist__44c6_s_p7_1,
  132074. NULL,
  132075. &_vq_auxt__44c6_s_p7_1,
  132076. NULL,
  132077. 0
  132078. };
  132079. static long _vq_quantlist__44c6_s_p8_0[] = {
  132080. 7,
  132081. 6,
  132082. 8,
  132083. 5,
  132084. 9,
  132085. 4,
  132086. 10,
  132087. 3,
  132088. 11,
  132089. 2,
  132090. 12,
  132091. 1,
  132092. 13,
  132093. 0,
  132094. 14,
  132095. };
  132096. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132097. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132098. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132099. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132100. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132101. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132102. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132103. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132104. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132105. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132106. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132107. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132108. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132109. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132110. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132111. 14,
  132112. };
  132113. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132114. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132115. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132116. };
  132117. static long _vq_quantmap__44c6_s_p8_0[] = {
  132118. 13, 11, 9, 7, 5, 3, 1, 0,
  132119. 2, 4, 6, 8, 10, 12, 14,
  132120. };
  132121. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132122. _vq_quantthresh__44c6_s_p8_0,
  132123. _vq_quantmap__44c6_s_p8_0,
  132124. 15,
  132125. 15
  132126. };
  132127. static static_codebook _44c6_s_p8_0 = {
  132128. 2, 225,
  132129. _vq_lengthlist__44c6_s_p8_0,
  132130. 1, -520986624, 1620377600, 4, 0,
  132131. _vq_quantlist__44c6_s_p8_0,
  132132. NULL,
  132133. &_vq_auxt__44c6_s_p8_0,
  132134. NULL,
  132135. 0
  132136. };
  132137. static long _vq_quantlist__44c6_s_p8_1[] = {
  132138. 10,
  132139. 9,
  132140. 11,
  132141. 8,
  132142. 12,
  132143. 7,
  132144. 13,
  132145. 6,
  132146. 14,
  132147. 5,
  132148. 15,
  132149. 4,
  132150. 16,
  132151. 3,
  132152. 17,
  132153. 2,
  132154. 18,
  132155. 1,
  132156. 19,
  132157. 0,
  132158. 20,
  132159. };
  132160. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132161. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132162. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132164. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132165. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132166. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132167. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132168. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132169. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132170. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132171. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132172. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132173. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132174. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132175. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132176. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132177. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132178. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132179. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132180. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132181. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132182. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132183. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132184. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132185. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132186. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132187. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132188. 10,10,10,10,10,10,10,10,10,
  132189. };
  132190. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132191. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132192. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132193. 6.5, 7.5, 8.5, 9.5,
  132194. };
  132195. static long _vq_quantmap__44c6_s_p8_1[] = {
  132196. 19, 17, 15, 13, 11, 9, 7, 5,
  132197. 3, 1, 0, 2, 4, 6, 8, 10,
  132198. 12, 14, 16, 18, 20,
  132199. };
  132200. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132201. _vq_quantthresh__44c6_s_p8_1,
  132202. _vq_quantmap__44c6_s_p8_1,
  132203. 21,
  132204. 21
  132205. };
  132206. static static_codebook _44c6_s_p8_1 = {
  132207. 2, 441,
  132208. _vq_lengthlist__44c6_s_p8_1,
  132209. 1, -529268736, 1611661312, 5, 0,
  132210. _vq_quantlist__44c6_s_p8_1,
  132211. NULL,
  132212. &_vq_auxt__44c6_s_p8_1,
  132213. NULL,
  132214. 0
  132215. };
  132216. static long _vq_quantlist__44c6_s_p9_0[] = {
  132217. 6,
  132218. 5,
  132219. 7,
  132220. 4,
  132221. 8,
  132222. 3,
  132223. 9,
  132224. 2,
  132225. 10,
  132226. 1,
  132227. 11,
  132228. 0,
  132229. 12,
  132230. };
  132231. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132232. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132233. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132235. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132236. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132240. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132242. 10,10,10,10,10,10,10,10,10,
  132243. };
  132244. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132245. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132246. 1592.5, 2229.5, 2866.5, 3503.5,
  132247. };
  132248. static long _vq_quantmap__44c6_s_p9_0[] = {
  132249. 11, 9, 7, 5, 3, 1, 0, 2,
  132250. 4, 6, 8, 10, 12,
  132251. };
  132252. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132253. _vq_quantthresh__44c6_s_p9_0,
  132254. _vq_quantmap__44c6_s_p9_0,
  132255. 13,
  132256. 13
  132257. };
  132258. static static_codebook _44c6_s_p9_0 = {
  132259. 2, 169,
  132260. _vq_lengthlist__44c6_s_p9_0,
  132261. 1, -511845376, 1630791680, 4, 0,
  132262. _vq_quantlist__44c6_s_p9_0,
  132263. NULL,
  132264. &_vq_auxt__44c6_s_p9_0,
  132265. NULL,
  132266. 0
  132267. };
  132268. static long _vq_quantlist__44c6_s_p9_1[] = {
  132269. 6,
  132270. 5,
  132271. 7,
  132272. 4,
  132273. 8,
  132274. 3,
  132275. 9,
  132276. 2,
  132277. 10,
  132278. 1,
  132279. 11,
  132280. 0,
  132281. 12,
  132282. };
  132283. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132284. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132285. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132286. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132287. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132288. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132289. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132290. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132291. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132292. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132293. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132294. 15,12,10,11,11,13,11,12,13,
  132295. };
  132296. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132297. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132298. 122.5, 171.5, 220.5, 269.5,
  132299. };
  132300. static long _vq_quantmap__44c6_s_p9_1[] = {
  132301. 11, 9, 7, 5, 3, 1, 0, 2,
  132302. 4, 6, 8, 10, 12,
  132303. };
  132304. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132305. _vq_quantthresh__44c6_s_p9_1,
  132306. _vq_quantmap__44c6_s_p9_1,
  132307. 13,
  132308. 13
  132309. };
  132310. static static_codebook _44c6_s_p9_1 = {
  132311. 2, 169,
  132312. _vq_lengthlist__44c6_s_p9_1,
  132313. 1, -518889472, 1622704128, 4, 0,
  132314. _vq_quantlist__44c6_s_p9_1,
  132315. NULL,
  132316. &_vq_auxt__44c6_s_p9_1,
  132317. NULL,
  132318. 0
  132319. };
  132320. static long _vq_quantlist__44c6_s_p9_2[] = {
  132321. 24,
  132322. 23,
  132323. 25,
  132324. 22,
  132325. 26,
  132326. 21,
  132327. 27,
  132328. 20,
  132329. 28,
  132330. 19,
  132331. 29,
  132332. 18,
  132333. 30,
  132334. 17,
  132335. 31,
  132336. 16,
  132337. 32,
  132338. 15,
  132339. 33,
  132340. 14,
  132341. 34,
  132342. 13,
  132343. 35,
  132344. 12,
  132345. 36,
  132346. 11,
  132347. 37,
  132348. 10,
  132349. 38,
  132350. 9,
  132351. 39,
  132352. 8,
  132353. 40,
  132354. 7,
  132355. 41,
  132356. 6,
  132357. 42,
  132358. 5,
  132359. 43,
  132360. 4,
  132361. 44,
  132362. 3,
  132363. 45,
  132364. 2,
  132365. 46,
  132366. 1,
  132367. 47,
  132368. 0,
  132369. 48,
  132370. };
  132371. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132372. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132373. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132374. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132375. 7,
  132376. };
  132377. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132378. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132379. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132380. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132381. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132382. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132383. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132384. };
  132385. static long _vq_quantmap__44c6_s_p9_2[] = {
  132386. 47, 45, 43, 41, 39, 37, 35, 33,
  132387. 31, 29, 27, 25, 23, 21, 19, 17,
  132388. 15, 13, 11, 9, 7, 5, 3, 1,
  132389. 0, 2, 4, 6, 8, 10, 12, 14,
  132390. 16, 18, 20, 22, 24, 26, 28, 30,
  132391. 32, 34, 36, 38, 40, 42, 44, 46,
  132392. 48,
  132393. };
  132394. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132395. _vq_quantthresh__44c6_s_p9_2,
  132396. _vq_quantmap__44c6_s_p9_2,
  132397. 49,
  132398. 49
  132399. };
  132400. static static_codebook _44c6_s_p9_2 = {
  132401. 1, 49,
  132402. _vq_lengthlist__44c6_s_p9_2,
  132403. 1, -526909440, 1611661312, 6, 0,
  132404. _vq_quantlist__44c6_s_p9_2,
  132405. NULL,
  132406. &_vq_auxt__44c6_s_p9_2,
  132407. NULL,
  132408. 0
  132409. };
  132410. static long _huff_lengthlist__44c6_s_short[] = {
  132411. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132412. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132413. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132414. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132415. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132416. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132417. 9,10,17,18,
  132418. };
  132419. static static_codebook _huff_book__44c6_s_short = {
  132420. 2, 100,
  132421. _huff_lengthlist__44c6_s_short,
  132422. 0, 0, 0, 0, 0,
  132423. NULL,
  132424. NULL,
  132425. NULL,
  132426. NULL,
  132427. 0
  132428. };
  132429. static long _huff_lengthlist__44c7_s_long[] = {
  132430. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132431. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132432. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132433. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132434. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132435. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132436. 11,10,10,12,
  132437. };
  132438. static static_codebook _huff_book__44c7_s_long = {
  132439. 2, 100,
  132440. _huff_lengthlist__44c7_s_long,
  132441. 0, 0, 0, 0, 0,
  132442. NULL,
  132443. NULL,
  132444. NULL,
  132445. NULL,
  132446. 0
  132447. };
  132448. static long _vq_quantlist__44c7_s_p1_0[] = {
  132449. 1,
  132450. 0,
  132451. 2,
  132452. };
  132453. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132454. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132455. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132456. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132457. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132458. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132459. 8,
  132460. };
  132461. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132462. -0.5, 0.5,
  132463. };
  132464. static long _vq_quantmap__44c7_s_p1_0[] = {
  132465. 1, 0, 2,
  132466. };
  132467. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132468. _vq_quantthresh__44c7_s_p1_0,
  132469. _vq_quantmap__44c7_s_p1_0,
  132470. 3,
  132471. 3
  132472. };
  132473. static static_codebook _44c7_s_p1_0 = {
  132474. 4, 81,
  132475. _vq_lengthlist__44c7_s_p1_0,
  132476. 1, -535822336, 1611661312, 2, 0,
  132477. _vq_quantlist__44c7_s_p1_0,
  132478. NULL,
  132479. &_vq_auxt__44c7_s_p1_0,
  132480. NULL,
  132481. 0
  132482. };
  132483. static long _vq_quantlist__44c7_s_p2_0[] = {
  132484. 2,
  132485. 1,
  132486. 3,
  132487. 0,
  132488. 4,
  132489. };
  132490. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132491. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132492. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132493. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132494. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132495. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132496. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132497. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132498. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132501. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132502. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132503. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132504. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132505. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132506. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132509. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132510. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132511. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132512. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132513. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132514. 13,13, 0, 0, 0,12,13, 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. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132517. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132518. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132519. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132520. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132521. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132522. 0, 0,13,13, 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, 9,
  132527. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132528. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132529. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132530. 13,
  132531. };
  132532. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132533. -1.5, -0.5, 0.5, 1.5,
  132534. };
  132535. static long _vq_quantmap__44c7_s_p2_0[] = {
  132536. 3, 1, 0, 2, 4,
  132537. };
  132538. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132539. _vq_quantthresh__44c7_s_p2_0,
  132540. _vq_quantmap__44c7_s_p2_0,
  132541. 5,
  132542. 5
  132543. };
  132544. static static_codebook _44c7_s_p2_0 = {
  132545. 4, 625,
  132546. _vq_lengthlist__44c7_s_p2_0,
  132547. 1, -533725184, 1611661312, 3, 0,
  132548. _vq_quantlist__44c7_s_p2_0,
  132549. NULL,
  132550. &_vq_auxt__44c7_s_p2_0,
  132551. NULL,
  132552. 0
  132553. };
  132554. static long _vq_quantlist__44c7_s_p3_0[] = {
  132555. 4,
  132556. 3,
  132557. 5,
  132558. 2,
  132559. 6,
  132560. 1,
  132561. 7,
  132562. 0,
  132563. 8,
  132564. };
  132565. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132566. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132567. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132568. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132569. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132571. 0,
  132572. };
  132573. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132574. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132575. };
  132576. static long _vq_quantmap__44c7_s_p3_0[] = {
  132577. 7, 5, 3, 1, 0, 2, 4, 6,
  132578. 8,
  132579. };
  132580. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132581. _vq_quantthresh__44c7_s_p3_0,
  132582. _vq_quantmap__44c7_s_p3_0,
  132583. 9,
  132584. 9
  132585. };
  132586. static static_codebook _44c7_s_p3_0 = {
  132587. 2, 81,
  132588. _vq_lengthlist__44c7_s_p3_0,
  132589. 1, -531628032, 1611661312, 4, 0,
  132590. _vq_quantlist__44c7_s_p3_0,
  132591. NULL,
  132592. &_vq_auxt__44c7_s_p3_0,
  132593. NULL,
  132594. 0
  132595. };
  132596. static long _vq_quantlist__44c7_s_p4_0[] = {
  132597. 8,
  132598. 7,
  132599. 9,
  132600. 6,
  132601. 10,
  132602. 5,
  132603. 11,
  132604. 4,
  132605. 12,
  132606. 3,
  132607. 13,
  132608. 2,
  132609. 14,
  132610. 1,
  132611. 15,
  132612. 0,
  132613. 16,
  132614. };
  132615. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132616. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132617. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132618. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132619. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132620. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132621. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132622. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132623. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132624. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132625. 9,10,10,11,11,12,12,13,13, 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,
  132635. };
  132636. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132637. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132638. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132639. };
  132640. static long _vq_quantmap__44c7_s_p4_0[] = {
  132641. 15, 13, 11, 9, 7, 5, 3, 1,
  132642. 0, 2, 4, 6, 8, 10, 12, 14,
  132643. 16,
  132644. };
  132645. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132646. _vq_quantthresh__44c7_s_p4_0,
  132647. _vq_quantmap__44c7_s_p4_0,
  132648. 17,
  132649. 17
  132650. };
  132651. static static_codebook _44c7_s_p4_0 = {
  132652. 2, 289,
  132653. _vq_lengthlist__44c7_s_p4_0,
  132654. 1, -529530880, 1611661312, 5, 0,
  132655. _vq_quantlist__44c7_s_p4_0,
  132656. NULL,
  132657. &_vq_auxt__44c7_s_p4_0,
  132658. NULL,
  132659. 0
  132660. };
  132661. static long _vq_quantlist__44c7_s_p5_0[] = {
  132662. 1,
  132663. 0,
  132664. 2,
  132665. };
  132666. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132667. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132668. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132669. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132670. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132671. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132672. 12,
  132673. };
  132674. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132675. -5.5, 5.5,
  132676. };
  132677. static long _vq_quantmap__44c7_s_p5_0[] = {
  132678. 1, 0, 2,
  132679. };
  132680. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132681. _vq_quantthresh__44c7_s_p5_0,
  132682. _vq_quantmap__44c7_s_p5_0,
  132683. 3,
  132684. 3
  132685. };
  132686. static static_codebook _44c7_s_p5_0 = {
  132687. 4, 81,
  132688. _vq_lengthlist__44c7_s_p5_0,
  132689. 1, -529137664, 1618345984, 2, 0,
  132690. _vq_quantlist__44c7_s_p5_0,
  132691. NULL,
  132692. &_vq_auxt__44c7_s_p5_0,
  132693. NULL,
  132694. 0
  132695. };
  132696. static long _vq_quantlist__44c7_s_p5_1[] = {
  132697. 5,
  132698. 4,
  132699. 6,
  132700. 3,
  132701. 7,
  132702. 2,
  132703. 8,
  132704. 1,
  132705. 9,
  132706. 0,
  132707. 10,
  132708. };
  132709. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132710. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132711. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132712. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132713. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132714. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132715. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132716. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132717. 11,11,11, 7, 7, 8, 8, 8, 8,
  132718. };
  132719. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132720. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132721. 3.5, 4.5,
  132722. };
  132723. static long _vq_quantmap__44c7_s_p5_1[] = {
  132724. 9, 7, 5, 3, 1, 0, 2, 4,
  132725. 6, 8, 10,
  132726. };
  132727. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132728. _vq_quantthresh__44c7_s_p5_1,
  132729. _vq_quantmap__44c7_s_p5_1,
  132730. 11,
  132731. 11
  132732. };
  132733. static static_codebook _44c7_s_p5_1 = {
  132734. 2, 121,
  132735. _vq_lengthlist__44c7_s_p5_1,
  132736. 1, -531365888, 1611661312, 4, 0,
  132737. _vq_quantlist__44c7_s_p5_1,
  132738. NULL,
  132739. &_vq_auxt__44c7_s_p5_1,
  132740. NULL,
  132741. 0
  132742. };
  132743. static long _vq_quantlist__44c7_s_p6_0[] = {
  132744. 6,
  132745. 5,
  132746. 7,
  132747. 4,
  132748. 8,
  132749. 3,
  132750. 9,
  132751. 2,
  132752. 10,
  132753. 1,
  132754. 11,
  132755. 0,
  132756. 12,
  132757. };
  132758. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132759. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132760. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132761. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132762. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132763. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132764. 12, 9, 9,10,10,11,11,11,11,12,12, 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,
  132770. };
  132771. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132772. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132773. 12.5, 17.5, 22.5, 27.5,
  132774. };
  132775. static long _vq_quantmap__44c7_s_p6_0[] = {
  132776. 11, 9, 7, 5, 3, 1, 0, 2,
  132777. 4, 6, 8, 10, 12,
  132778. };
  132779. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132780. _vq_quantthresh__44c7_s_p6_0,
  132781. _vq_quantmap__44c7_s_p6_0,
  132782. 13,
  132783. 13
  132784. };
  132785. static static_codebook _44c7_s_p6_0 = {
  132786. 2, 169,
  132787. _vq_lengthlist__44c7_s_p6_0,
  132788. 1, -526516224, 1616117760, 4, 0,
  132789. _vq_quantlist__44c7_s_p6_0,
  132790. NULL,
  132791. &_vq_auxt__44c7_s_p6_0,
  132792. NULL,
  132793. 0
  132794. };
  132795. static long _vq_quantlist__44c7_s_p6_1[] = {
  132796. 2,
  132797. 1,
  132798. 3,
  132799. 0,
  132800. 4,
  132801. };
  132802. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132803. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132804. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132805. };
  132806. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132807. -1.5, -0.5, 0.5, 1.5,
  132808. };
  132809. static long _vq_quantmap__44c7_s_p6_1[] = {
  132810. 3, 1, 0, 2, 4,
  132811. };
  132812. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132813. _vq_quantthresh__44c7_s_p6_1,
  132814. _vq_quantmap__44c7_s_p6_1,
  132815. 5,
  132816. 5
  132817. };
  132818. static static_codebook _44c7_s_p6_1 = {
  132819. 2, 25,
  132820. _vq_lengthlist__44c7_s_p6_1,
  132821. 1, -533725184, 1611661312, 3, 0,
  132822. _vq_quantlist__44c7_s_p6_1,
  132823. NULL,
  132824. &_vq_auxt__44c7_s_p6_1,
  132825. NULL,
  132826. 0
  132827. };
  132828. static long _vq_quantlist__44c7_s_p7_0[] = {
  132829. 6,
  132830. 5,
  132831. 7,
  132832. 4,
  132833. 8,
  132834. 3,
  132835. 9,
  132836. 2,
  132837. 10,
  132838. 1,
  132839. 11,
  132840. 0,
  132841. 12,
  132842. };
  132843. static long _vq_lengthlist__44c7_s_p7_0[] = {
  132844. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  132845. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  132846. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  132847. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  132848. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  132849. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  132850. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  132851. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  132852. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  132853. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  132854. 19,13,13,13,13,14,14,15,15,
  132855. };
  132856. static float _vq_quantthresh__44c7_s_p7_0[] = {
  132857. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132858. 27.5, 38.5, 49.5, 60.5,
  132859. };
  132860. static long _vq_quantmap__44c7_s_p7_0[] = {
  132861. 11, 9, 7, 5, 3, 1, 0, 2,
  132862. 4, 6, 8, 10, 12,
  132863. };
  132864. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  132865. _vq_quantthresh__44c7_s_p7_0,
  132866. _vq_quantmap__44c7_s_p7_0,
  132867. 13,
  132868. 13
  132869. };
  132870. static static_codebook _44c7_s_p7_0 = {
  132871. 2, 169,
  132872. _vq_lengthlist__44c7_s_p7_0,
  132873. 1, -523206656, 1618345984, 4, 0,
  132874. _vq_quantlist__44c7_s_p7_0,
  132875. NULL,
  132876. &_vq_auxt__44c7_s_p7_0,
  132877. NULL,
  132878. 0
  132879. };
  132880. static long _vq_quantlist__44c7_s_p7_1[] = {
  132881. 5,
  132882. 4,
  132883. 6,
  132884. 3,
  132885. 7,
  132886. 2,
  132887. 8,
  132888. 1,
  132889. 9,
  132890. 0,
  132891. 10,
  132892. };
  132893. static long _vq_lengthlist__44c7_s_p7_1[] = {
  132894. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  132895. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  132896. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  132897. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132898. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132899. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132900. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132901. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132902. };
  132903. static float _vq_quantthresh__44c7_s_p7_1[] = {
  132904. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132905. 3.5, 4.5,
  132906. };
  132907. static long _vq_quantmap__44c7_s_p7_1[] = {
  132908. 9, 7, 5, 3, 1, 0, 2, 4,
  132909. 6, 8, 10,
  132910. };
  132911. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  132912. _vq_quantthresh__44c7_s_p7_1,
  132913. _vq_quantmap__44c7_s_p7_1,
  132914. 11,
  132915. 11
  132916. };
  132917. static static_codebook _44c7_s_p7_1 = {
  132918. 2, 121,
  132919. _vq_lengthlist__44c7_s_p7_1,
  132920. 1, -531365888, 1611661312, 4, 0,
  132921. _vq_quantlist__44c7_s_p7_1,
  132922. NULL,
  132923. &_vq_auxt__44c7_s_p7_1,
  132924. NULL,
  132925. 0
  132926. };
  132927. static long _vq_quantlist__44c7_s_p8_0[] = {
  132928. 7,
  132929. 6,
  132930. 8,
  132931. 5,
  132932. 9,
  132933. 4,
  132934. 10,
  132935. 3,
  132936. 11,
  132937. 2,
  132938. 12,
  132939. 1,
  132940. 13,
  132941. 0,
  132942. 14,
  132943. };
  132944. static long _vq_lengthlist__44c7_s_p8_0[] = {
  132945. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  132946. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  132947. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  132948. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  132949. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  132950. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  132951. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  132952. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  132953. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  132954. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  132955. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  132956. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  132957. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  132958. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  132959. 14,
  132960. };
  132961. static float _vq_quantthresh__44c7_s_p8_0[] = {
  132962. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132963. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132964. };
  132965. static long _vq_quantmap__44c7_s_p8_0[] = {
  132966. 13, 11, 9, 7, 5, 3, 1, 0,
  132967. 2, 4, 6, 8, 10, 12, 14,
  132968. };
  132969. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  132970. _vq_quantthresh__44c7_s_p8_0,
  132971. _vq_quantmap__44c7_s_p8_0,
  132972. 15,
  132973. 15
  132974. };
  132975. static static_codebook _44c7_s_p8_0 = {
  132976. 2, 225,
  132977. _vq_lengthlist__44c7_s_p8_0,
  132978. 1, -520986624, 1620377600, 4, 0,
  132979. _vq_quantlist__44c7_s_p8_0,
  132980. NULL,
  132981. &_vq_auxt__44c7_s_p8_0,
  132982. NULL,
  132983. 0
  132984. };
  132985. static long _vq_quantlist__44c7_s_p8_1[] = {
  132986. 10,
  132987. 9,
  132988. 11,
  132989. 8,
  132990. 12,
  132991. 7,
  132992. 13,
  132993. 6,
  132994. 14,
  132995. 5,
  132996. 15,
  132997. 4,
  132998. 16,
  132999. 3,
  133000. 17,
  133001. 2,
  133002. 18,
  133003. 1,
  133004. 19,
  133005. 0,
  133006. 20,
  133007. };
  133008. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133009. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133010. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133011. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133012. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133013. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133014. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133015. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133016. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133017. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133018. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133019. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133020. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133021. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133022. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133023. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133024. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133025. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133026. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133027. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133028. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133029. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133030. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133031. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133032. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133033. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133034. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133035. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133036. 10,10,10,10,10,10,10,10,10,
  133037. };
  133038. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133039. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133040. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133041. 6.5, 7.5, 8.5, 9.5,
  133042. };
  133043. static long _vq_quantmap__44c7_s_p8_1[] = {
  133044. 19, 17, 15, 13, 11, 9, 7, 5,
  133045. 3, 1, 0, 2, 4, 6, 8, 10,
  133046. 12, 14, 16, 18, 20,
  133047. };
  133048. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133049. _vq_quantthresh__44c7_s_p8_1,
  133050. _vq_quantmap__44c7_s_p8_1,
  133051. 21,
  133052. 21
  133053. };
  133054. static static_codebook _44c7_s_p8_1 = {
  133055. 2, 441,
  133056. _vq_lengthlist__44c7_s_p8_1,
  133057. 1, -529268736, 1611661312, 5, 0,
  133058. _vq_quantlist__44c7_s_p8_1,
  133059. NULL,
  133060. &_vq_auxt__44c7_s_p8_1,
  133061. NULL,
  133062. 0
  133063. };
  133064. static long _vq_quantlist__44c7_s_p9_0[] = {
  133065. 6,
  133066. 5,
  133067. 7,
  133068. 4,
  133069. 8,
  133070. 3,
  133071. 9,
  133072. 2,
  133073. 10,
  133074. 1,
  133075. 11,
  133076. 0,
  133077. 12,
  133078. };
  133079. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133080. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133081. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133090. 11,11,11,11,11,11,11,11,11,
  133091. };
  133092. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133093. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133094. 1592.5, 2229.5, 2866.5, 3503.5,
  133095. };
  133096. static long _vq_quantmap__44c7_s_p9_0[] = {
  133097. 11, 9, 7, 5, 3, 1, 0, 2,
  133098. 4, 6, 8, 10, 12,
  133099. };
  133100. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133101. _vq_quantthresh__44c7_s_p9_0,
  133102. _vq_quantmap__44c7_s_p9_0,
  133103. 13,
  133104. 13
  133105. };
  133106. static static_codebook _44c7_s_p9_0 = {
  133107. 2, 169,
  133108. _vq_lengthlist__44c7_s_p9_0,
  133109. 1, -511845376, 1630791680, 4, 0,
  133110. _vq_quantlist__44c7_s_p9_0,
  133111. NULL,
  133112. &_vq_auxt__44c7_s_p9_0,
  133113. NULL,
  133114. 0
  133115. };
  133116. static long _vq_quantlist__44c7_s_p9_1[] = {
  133117. 6,
  133118. 5,
  133119. 7,
  133120. 4,
  133121. 8,
  133122. 3,
  133123. 9,
  133124. 2,
  133125. 10,
  133126. 1,
  133127. 11,
  133128. 0,
  133129. 12,
  133130. };
  133131. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133132. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133133. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133134. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133135. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133136. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133137. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133138. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133139. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133140. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133141. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133142. 15,11,11,10,10,12,12,12,12,
  133143. };
  133144. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133145. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133146. 122.5, 171.5, 220.5, 269.5,
  133147. };
  133148. static long _vq_quantmap__44c7_s_p9_1[] = {
  133149. 11, 9, 7, 5, 3, 1, 0, 2,
  133150. 4, 6, 8, 10, 12,
  133151. };
  133152. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133153. _vq_quantthresh__44c7_s_p9_1,
  133154. _vq_quantmap__44c7_s_p9_1,
  133155. 13,
  133156. 13
  133157. };
  133158. static static_codebook _44c7_s_p9_1 = {
  133159. 2, 169,
  133160. _vq_lengthlist__44c7_s_p9_1,
  133161. 1, -518889472, 1622704128, 4, 0,
  133162. _vq_quantlist__44c7_s_p9_1,
  133163. NULL,
  133164. &_vq_auxt__44c7_s_p9_1,
  133165. NULL,
  133166. 0
  133167. };
  133168. static long _vq_quantlist__44c7_s_p9_2[] = {
  133169. 24,
  133170. 23,
  133171. 25,
  133172. 22,
  133173. 26,
  133174. 21,
  133175. 27,
  133176. 20,
  133177. 28,
  133178. 19,
  133179. 29,
  133180. 18,
  133181. 30,
  133182. 17,
  133183. 31,
  133184. 16,
  133185. 32,
  133186. 15,
  133187. 33,
  133188. 14,
  133189. 34,
  133190. 13,
  133191. 35,
  133192. 12,
  133193. 36,
  133194. 11,
  133195. 37,
  133196. 10,
  133197. 38,
  133198. 9,
  133199. 39,
  133200. 8,
  133201. 40,
  133202. 7,
  133203. 41,
  133204. 6,
  133205. 42,
  133206. 5,
  133207. 43,
  133208. 4,
  133209. 44,
  133210. 3,
  133211. 45,
  133212. 2,
  133213. 46,
  133214. 1,
  133215. 47,
  133216. 0,
  133217. 48,
  133218. };
  133219. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133220. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133221. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133222. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133223. 7,
  133224. };
  133225. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133226. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133227. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133228. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133229. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133230. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133231. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133232. };
  133233. static long _vq_quantmap__44c7_s_p9_2[] = {
  133234. 47, 45, 43, 41, 39, 37, 35, 33,
  133235. 31, 29, 27, 25, 23, 21, 19, 17,
  133236. 15, 13, 11, 9, 7, 5, 3, 1,
  133237. 0, 2, 4, 6, 8, 10, 12, 14,
  133238. 16, 18, 20, 22, 24, 26, 28, 30,
  133239. 32, 34, 36, 38, 40, 42, 44, 46,
  133240. 48,
  133241. };
  133242. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133243. _vq_quantthresh__44c7_s_p9_2,
  133244. _vq_quantmap__44c7_s_p9_2,
  133245. 49,
  133246. 49
  133247. };
  133248. static static_codebook _44c7_s_p9_2 = {
  133249. 1, 49,
  133250. _vq_lengthlist__44c7_s_p9_2,
  133251. 1, -526909440, 1611661312, 6, 0,
  133252. _vq_quantlist__44c7_s_p9_2,
  133253. NULL,
  133254. &_vq_auxt__44c7_s_p9_2,
  133255. NULL,
  133256. 0
  133257. };
  133258. static long _huff_lengthlist__44c7_s_short[] = {
  133259. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133260. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133261. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133262. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133263. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133264. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133265. 10, 9,11,14,
  133266. };
  133267. static static_codebook _huff_book__44c7_s_short = {
  133268. 2, 100,
  133269. _huff_lengthlist__44c7_s_short,
  133270. 0, 0, 0, 0, 0,
  133271. NULL,
  133272. NULL,
  133273. NULL,
  133274. NULL,
  133275. 0
  133276. };
  133277. static long _huff_lengthlist__44c8_s_long[] = {
  133278. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133279. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133280. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133281. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133282. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133283. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133284. 11, 9, 9,10,
  133285. };
  133286. static static_codebook _huff_book__44c8_s_long = {
  133287. 2, 100,
  133288. _huff_lengthlist__44c8_s_long,
  133289. 0, 0, 0, 0, 0,
  133290. NULL,
  133291. NULL,
  133292. NULL,
  133293. NULL,
  133294. 0
  133295. };
  133296. static long _vq_quantlist__44c8_s_p1_0[] = {
  133297. 1,
  133298. 0,
  133299. 2,
  133300. };
  133301. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133302. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133303. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133304. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133305. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133306. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133307. 8,
  133308. };
  133309. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133310. -0.5, 0.5,
  133311. };
  133312. static long _vq_quantmap__44c8_s_p1_0[] = {
  133313. 1, 0, 2,
  133314. };
  133315. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133316. _vq_quantthresh__44c8_s_p1_0,
  133317. _vq_quantmap__44c8_s_p1_0,
  133318. 3,
  133319. 3
  133320. };
  133321. static static_codebook _44c8_s_p1_0 = {
  133322. 4, 81,
  133323. _vq_lengthlist__44c8_s_p1_0,
  133324. 1, -535822336, 1611661312, 2, 0,
  133325. _vq_quantlist__44c8_s_p1_0,
  133326. NULL,
  133327. &_vq_auxt__44c8_s_p1_0,
  133328. NULL,
  133329. 0
  133330. };
  133331. static long _vq_quantlist__44c8_s_p2_0[] = {
  133332. 2,
  133333. 1,
  133334. 3,
  133335. 0,
  133336. 4,
  133337. };
  133338. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133339. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133340. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133341. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133342. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133343. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133344. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133345. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133346. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133349. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133350. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133351. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133352. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133353. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133354. 0,12,12,13,13, 0, 0, 0,12,13, 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, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133357. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133358. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133359. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133360. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133361. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133362. 13,13, 0, 0, 0,12,13, 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. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133365. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133366. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133367. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133368. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133369. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133370. 0, 0,13,13, 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, 9,
  133375. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133376. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133377. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133378. 13,
  133379. };
  133380. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133381. -1.5, -0.5, 0.5, 1.5,
  133382. };
  133383. static long _vq_quantmap__44c8_s_p2_0[] = {
  133384. 3, 1, 0, 2, 4,
  133385. };
  133386. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133387. _vq_quantthresh__44c8_s_p2_0,
  133388. _vq_quantmap__44c8_s_p2_0,
  133389. 5,
  133390. 5
  133391. };
  133392. static static_codebook _44c8_s_p2_0 = {
  133393. 4, 625,
  133394. _vq_lengthlist__44c8_s_p2_0,
  133395. 1, -533725184, 1611661312, 3, 0,
  133396. _vq_quantlist__44c8_s_p2_0,
  133397. NULL,
  133398. &_vq_auxt__44c8_s_p2_0,
  133399. NULL,
  133400. 0
  133401. };
  133402. static long _vq_quantlist__44c8_s_p3_0[] = {
  133403. 4,
  133404. 3,
  133405. 5,
  133406. 2,
  133407. 6,
  133408. 1,
  133409. 7,
  133410. 0,
  133411. 8,
  133412. };
  133413. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133414. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133415. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133416. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133417. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0,
  133420. };
  133421. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133422. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133423. };
  133424. static long _vq_quantmap__44c8_s_p3_0[] = {
  133425. 7, 5, 3, 1, 0, 2, 4, 6,
  133426. 8,
  133427. };
  133428. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133429. _vq_quantthresh__44c8_s_p3_0,
  133430. _vq_quantmap__44c8_s_p3_0,
  133431. 9,
  133432. 9
  133433. };
  133434. static static_codebook _44c8_s_p3_0 = {
  133435. 2, 81,
  133436. _vq_lengthlist__44c8_s_p3_0,
  133437. 1, -531628032, 1611661312, 4, 0,
  133438. _vq_quantlist__44c8_s_p3_0,
  133439. NULL,
  133440. &_vq_auxt__44c8_s_p3_0,
  133441. NULL,
  133442. 0
  133443. };
  133444. static long _vq_quantlist__44c8_s_p4_0[] = {
  133445. 8,
  133446. 7,
  133447. 9,
  133448. 6,
  133449. 10,
  133450. 5,
  133451. 11,
  133452. 4,
  133453. 12,
  133454. 3,
  133455. 13,
  133456. 2,
  133457. 14,
  133458. 1,
  133459. 15,
  133460. 0,
  133461. 16,
  133462. };
  133463. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133464. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133465. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133466. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133467. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133468. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133469. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133470. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133471. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133472. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133473. 9,10,10,11,11,12,12,13,13, 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,
  133483. };
  133484. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133485. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133486. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133487. };
  133488. static long _vq_quantmap__44c8_s_p4_0[] = {
  133489. 15, 13, 11, 9, 7, 5, 3, 1,
  133490. 0, 2, 4, 6, 8, 10, 12, 14,
  133491. 16,
  133492. };
  133493. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133494. _vq_quantthresh__44c8_s_p4_0,
  133495. _vq_quantmap__44c8_s_p4_0,
  133496. 17,
  133497. 17
  133498. };
  133499. static static_codebook _44c8_s_p4_0 = {
  133500. 2, 289,
  133501. _vq_lengthlist__44c8_s_p4_0,
  133502. 1, -529530880, 1611661312, 5, 0,
  133503. _vq_quantlist__44c8_s_p4_0,
  133504. NULL,
  133505. &_vq_auxt__44c8_s_p4_0,
  133506. NULL,
  133507. 0
  133508. };
  133509. static long _vq_quantlist__44c8_s_p5_0[] = {
  133510. 1,
  133511. 0,
  133512. 2,
  133513. };
  133514. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133515. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133516. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133517. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133518. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133519. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133520. 12,
  133521. };
  133522. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133523. -5.5, 5.5,
  133524. };
  133525. static long _vq_quantmap__44c8_s_p5_0[] = {
  133526. 1, 0, 2,
  133527. };
  133528. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133529. _vq_quantthresh__44c8_s_p5_0,
  133530. _vq_quantmap__44c8_s_p5_0,
  133531. 3,
  133532. 3
  133533. };
  133534. static static_codebook _44c8_s_p5_0 = {
  133535. 4, 81,
  133536. _vq_lengthlist__44c8_s_p5_0,
  133537. 1, -529137664, 1618345984, 2, 0,
  133538. _vq_quantlist__44c8_s_p5_0,
  133539. NULL,
  133540. &_vq_auxt__44c8_s_p5_0,
  133541. NULL,
  133542. 0
  133543. };
  133544. static long _vq_quantlist__44c8_s_p5_1[] = {
  133545. 5,
  133546. 4,
  133547. 6,
  133548. 3,
  133549. 7,
  133550. 2,
  133551. 8,
  133552. 1,
  133553. 9,
  133554. 0,
  133555. 10,
  133556. };
  133557. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133558. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133559. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133560. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133561. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133562. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133563. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133564. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133565. 11,11,11, 7, 7, 7, 7, 8, 8,
  133566. };
  133567. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133568. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133569. 3.5, 4.5,
  133570. };
  133571. static long _vq_quantmap__44c8_s_p5_1[] = {
  133572. 9, 7, 5, 3, 1, 0, 2, 4,
  133573. 6, 8, 10,
  133574. };
  133575. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133576. _vq_quantthresh__44c8_s_p5_1,
  133577. _vq_quantmap__44c8_s_p5_1,
  133578. 11,
  133579. 11
  133580. };
  133581. static static_codebook _44c8_s_p5_1 = {
  133582. 2, 121,
  133583. _vq_lengthlist__44c8_s_p5_1,
  133584. 1, -531365888, 1611661312, 4, 0,
  133585. _vq_quantlist__44c8_s_p5_1,
  133586. NULL,
  133587. &_vq_auxt__44c8_s_p5_1,
  133588. NULL,
  133589. 0
  133590. };
  133591. static long _vq_quantlist__44c8_s_p6_0[] = {
  133592. 6,
  133593. 5,
  133594. 7,
  133595. 4,
  133596. 8,
  133597. 3,
  133598. 9,
  133599. 2,
  133600. 10,
  133601. 1,
  133602. 11,
  133603. 0,
  133604. 12,
  133605. };
  133606. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133607. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133608. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133609. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133610. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133611. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133612. 12, 9, 9,10,10,11,11,12,12,12,12, 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,
  133618. };
  133619. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133620. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133621. 12.5, 17.5, 22.5, 27.5,
  133622. };
  133623. static long _vq_quantmap__44c8_s_p6_0[] = {
  133624. 11, 9, 7, 5, 3, 1, 0, 2,
  133625. 4, 6, 8, 10, 12,
  133626. };
  133627. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133628. _vq_quantthresh__44c8_s_p6_0,
  133629. _vq_quantmap__44c8_s_p6_0,
  133630. 13,
  133631. 13
  133632. };
  133633. static static_codebook _44c8_s_p6_0 = {
  133634. 2, 169,
  133635. _vq_lengthlist__44c8_s_p6_0,
  133636. 1, -526516224, 1616117760, 4, 0,
  133637. _vq_quantlist__44c8_s_p6_0,
  133638. NULL,
  133639. &_vq_auxt__44c8_s_p6_0,
  133640. NULL,
  133641. 0
  133642. };
  133643. static long _vq_quantlist__44c8_s_p6_1[] = {
  133644. 2,
  133645. 1,
  133646. 3,
  133647. 0,
  133648. 4,
  133649. };
  133650. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133651. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133652. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133653. };
  133654. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133655. -1.5, -0.5, 0.5, 1.5,
  133656. };
  133657. static long _vq_quantmap__44c8_s_p6_1[] = {
  133658. 3, 1, 0, 2, 4,
  133659. };
  133660. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133661. _vq_quantthresh__44c8_s_p6_1,
  133662. _vq_quantmap__44c8_s_p6_1,
  133663. 5,
  133664. 5
  133665. };
  133666. static static_codebook _44c8_s_p6_1 = {
  133667. 2, 25,
  133668. _vq_lengthlist__44c8_s_p6_1,
  133669. 1, -533725184, 1611661312, 3, 0,
  133670. _vq_quantlist__44c8_s_p6_1,
  133671. NULL,
  133672. &_vq_auxt__44c8_s_p6_1,
  133673. NULL,
  133674. 0
  133675. };
  133676. static long _vq_quantlist__44c8_s_p7_0[] = {
  133677. 6,
  133678. 5,
  133679. 7,
  133680. 4,
  133681. 8,
  133682. 3,
  133683. 9,
  133684. 2,
  133685. 10,
  133686. 1,
  133687. 11,
  133688. 0,
  133689. 12,
  133690. };
  133691. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133692. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133693. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133694. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133695. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133696. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133697. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133698. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133699. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133700. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133701. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133702. 20,13,13,13,13,14,13,15,15,
  133703. };
  133704. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133705. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133706. 27.5, 38.5, 49.5, 60.5,
  133707. };
  133708. static long _vq_quantmap__44c8_s_p7_0[] = {
  133709. 11, 9, 7, 5, 3, 1, 0, 2,
  133710. 4, 6, 8, 10, 12,
  133711. };
  133712. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133713. _vq_quantthresh__44c8_s_p7_0,
  133714. _vq_quantmap__44c8_s_p7_0,
  133715. 13,
  133716. 13
  133717. };
  133718. static static_codebook _44c8_s_p7_0 = {
  133719. 2, 169,
  133720. _vq_lengthlist__44c8_s_p7_0,
  133721. 1, -523206656, 1618345984, 4, 0,
  133722. _vq_quantlist__44c8_s_p7_0,
  133723. NULL,
  133724. &_vq_auxt__44c8_s_p7_0,
  133725. NULL,
  133726. 0
  133727. };
  133728. static long _vq_quantlist__44c8_s_p7_1[] = {
  133729. 5,
  133730. 4,
  133731. 6,
  133732. 3,
  133733. 7,
  133734. 2,
  133735. 8,
  133736. 1,
  133737. 9,
  133738. 0,
  133739. 10,
  133740. };
  133741. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133742. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133743. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133744. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133745. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133746. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133747. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133748. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133749. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133750. };
  133751. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133752. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133753. 3.5, 4.5,
  133754. };
  133755. static long _vq_quantmap__44c8_s_p7_1[] = {
  133756. 9, 7, 5, 3, 1, 0, 2, 4,
  133757. 6, 8, 10,
  133758. };
  133759. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133760. _vq_quantthresh__44c8_s_p7_1,
  133761. _vq_quantmap__44c8_s_p7_1,
  133762. 11,
  133763. 11
  133764. };
  133765. static static_codebook _44c8_s_p7_1 = {
  133766. 2, 121,
  133767. _vq_lengthlist__44c8_s_p7_1,
  133768. 1, -531365888, 1611661312, 4, 0,
  133769. _vq_quantlist__44c8_s_p7_1,
  133770. NULL,
  133771. &_vq_auxt__44c8_s_p7_1,
  133772. NULL,
  133773. 0
  133774. };
  133775. static long _vq_quantlist__44c8_s_p8_0[] = {
  133776. 7,
  133777. 6,
  133778. 8,
  133779. 5,
  133780. 9,
  133781. 4,
  133782. 10,
  133783. 3,
  133784. 11,
  133785. 2,
  133786. 12,
  133787. 1,
  133788. 13,
  133789. 0,
  133790. 14,
  133791. };
  133792. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133793. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133794. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133795. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133796. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133797. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133798. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133799. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133800. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133801. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133802. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133803. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133804. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133805. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133806. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133807. 15,
  133808. };
  133809. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133810. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133811. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133812. };
  133813. static long _vq_quantmap__44c8_s_p8_0[] = {
  133814. 13, 11, 9, 7, 5, 3, 1, 0,
  133815. 2, 4, 6, 8, 10, 12, 14,
  133816. };
  133817. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133818. _vq_quantthresh__44c8_s_p8_0,
  133819. _vq_quantmap__44c8_s_p8_0,
  133820. 15,
  133821. 15
  133822. };
  133823. static static_codebook _44c8_s_p8_0 = {
  133824. 2, 225,
  133825. _vq_lengthlist__44c8_s_p8_0,
  133826. 1, -520986624, 1620377600, 4, 0,
  133827. _vq_quantlist__44c8_s_p8_0,
  133828. NULL,
  133829. &_vq_auxt__44c8_s_p8_0,
  133830. NULL,
  133831. 0
  133832. };
  133833. static long _vq_quantlist__44c8_s_p8_1[] = {
  133834. 10,
  133835. 9,
  133836. 11,
  133837. 8,
  133838. 12,
  133839. 7,
  133840. 13,
  133841. 6,
  133842. 14,
  133843. 5,
  133844. 15,
  133845. 4,
  133846. 16,
  133847. 3,
  133848. 17,
  133849. 2,
  133850. 18,
  133851. 1,
  133852. 19,
  133853. 0,
  133854. 20,
  133855. };
  133856. static long _vq_lengthlist__44c8_s_p8_1[] = {
  133857. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133858. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133859. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133860. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133861. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133862. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133863. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133864. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133865. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133866. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133867. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  133868. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133869. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  133870. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133871. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  133872. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  133873. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  133874. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  133875. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  133876. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  133877. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  133878. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  133879. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133880. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  133881. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  133882. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  133883. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133884. 10, 9, 9,10,10, 9,10, 9, 9,
  133885. };
  133886. static float _vq_quantthresh__44c8_s_p8_1[] = {
  133887. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133888. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133889. 6.5, 7.5, 8.5, 9.5,
  133890. };
  133891. static long _vq_quantmap__44c8_s_p8_1[] = {
  133892. 19, 17, 15, 13, 11, 9, 7, 5,
  133893. 3, 1, 0, 2, 4, 6, 8, 10,
  133894. 12, 14, 16, 18, 20,
  133895. };
  133896. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  133897. _vq_quantthresh__44c8_s_p8_1,
  133898. _vq_quantmap__44c8_s_p8_1,
  133899. 21,
  133900. 21
  133901. };
  133902. static static_codebook _44c8_s_p8_1 = {
  133903. 2, 441,
  133904. _vq_lengthlist__44c8_s_p8_1,
  133905. 1, -529268736, 1611661312, 5, 0,
  133906. _vq_quantlist__44c8_s_p8_1,
  133907. NULL,
  133908. &_vq_auxt__44c8_s_p8_1,
  133909. NULL,
  133910. 0
  133911. };
  133912. static long _vq_quantlist__44c8_s_p9_0[] = {
  133913. 8,
  133914. 7,
  133915. 9,
  133916. 6,
  133917. 10,
  133918. 5,
  133919. 11,
  133920. 4,
  133921. 12,
  133922. 3,
  133923. 13,
  133924. 2,
  133925. 14,
  133926. 1,
  133927. 15,
  133928. 0,
  133929. 16,
  133930. };
  133931. static long _vq_lengthlist__44c8_s_p9_0[] = {
  133932. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133933. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  133934. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  133935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133944. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133945. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133946. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133950. 10,
  133951. };
  133952. static float _vq_quantthresh__44c8_s_p9_0[] = {
  133953. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  133954. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  133955. };
  133956. static long _vq_quantmap__44c8_s_p9_0[] = {
  133957. 15, 13, 11, 9, 7, 5, 3, 1,
  133958. 0, 2, 4, 6, 8, 10, 12, 14,
  133959. 16,
  133960. };
  133961. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  133962. _vq_quantthresh__44c8_s_p9_0,
  133963. _vq_quantmap__44c8_s_p9_0,
  133964. 17,
  133965. 17
  133966. };
  133967. static static_codebook _44c8_s_p9_0 = {
  133968. 2, 289,
  133969. _vq_lengthlist__44c8_s_p9_0,
  133970. 1, -509798400, 1631393792, 5, 0,
  133971. _vq_quantlist__44c8_s_p9_0,
  133972. NULL,
  133973. &_vq_auxt__44c8_s_p9_0,
  133974. NULL,
  133975. 0
  133976. };
  133977. static long _vq_quantlist__44c8_s_p9_1[] = {
  133978. 9,
  133979. 8,
  133980. 10,
  133981. 7,
  133982. 11,
  133983. 6,
  133984. 12,
  133985. 5,
  133986. 13,
  133987. 4,
  133988. 14,
  133989. 3,
  133990. 15,
  133991. 2,
  133992. 16,
  133993. 1,
  133994. 17,
  133995. 0,
  133996. 18,
  133997. };
  133998. static long _vq_lengthlist__44c8_s_p9_1[] = {
  133999. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134000. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134001. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134002. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134003. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134004. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134005. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134006. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134007. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134008. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134009. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134010. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134011. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134012. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134013. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134014. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134015. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134016. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134017. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134018. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134019. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134020. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134021. 14,13,13,14,14,15,14,15,14,
  134022. };
  134023. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134024. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134025. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134026. 367.5, 416.5,
  134027. };
  134028. static long _vq_quantmap__44c8_s_p9_1[] = {
  134029. 17, 15, 13, 11, 9, 7, 5, 3,
  134030. 1, 0, 2, 4, 6, 8, 10, 12,
  134031. 14, 16, 18,
  134032. };
  134033. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134034. _vq_quantthresh__44c8_s_p9_1,
  134035. _vq_quantmap__44c8_s_p9_1,
  134036. 19,
  134037. 19
  134038. };
  134039. static static_codebook _44c8_s_p9_1 = {
  134040. 2, 361,
  134041. _vq_lengthlist__44c8_s_p9_1,
  134042. 1, -518287360, 1622704128, 5, 0,
  134043. _vq_quantlist__44c8_s_p9_1,
  134044. NULL,
  134045. &_vq_auxt__44c8_s_p9_1,
  134046. NULL,
  134047. 0
  134048. };
  134049. static long _vq_quantlist__44c8_s_p9_2[] = {
  134050. 24,
  134051. 23,
  134052. 25,
  134053. 22,
  134054. 26,
  134055. 21,
  134056. 27,
  134057. 20,
  134058. 28,
  134059. 19,
  134060. 29,
  134061. 18,
  134062. 30,
  134063. 17,
  134064. 31,
  134065. 16,
  134066. 32,
  134067. 15,
  134068. 33,
  134069. 14,
  134070. 34,
  134071. 13,
  134072. 35,
  134073. 12,
  134074. 36,
  134075. 11,
  134076. 37,
  134077. 10,
  134078. 38,
  134079. 9,
  134080. 39,
  134081. 8,
  134082. 40,
  134083. 7,
  134084. 41,
  134085. 6,
  134086. 42,
  134087. 5,
  134088. 43,
  134089. 4,
  134090. 44,
  134091. 3,
  134092. 45,
  134093. 2,
  134094. 46,
  134095. 1,
  134096. 47,
  134097. 0,
  134098. 48,
  134099. };
  134100. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134101. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134102. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134103. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134104. 7,
  134105. };
  134106. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134107. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134108. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134109. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134110. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134111. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134112. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134113. };
  134114. static long _vq_quantmap__44c8_s_p9_2[] = {
  134115. 47, 45, 43, 41, 39, 37, 35, 33,
  134116. 31, 29, 27, 25, 23, 21, 19, 17,
  134117. 15, 13, 11, 9, 7, 5, 3, 1,
  134118. 0, 2, 4, 6, 8, 10, 12, 14,
  134119. 16, 18, 20, 22, 24, 26, 28, 30,
  134120. 32, 34, 36, 38, 40, 42, 44, 46,
  134121. 48,
  134122. };
  134123. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134124. _vq_quantthresh__44c8_s_p9_2,
  134125. _vq_quantmap__44c8_s_p9_2,
  134126. 49,
  134127. 49
  134128. };
  134129. static static_codebook _44c8_s_p9_2 = {
  134130. 1, 49,
  134131. _vq_lengthlist__44c8_s_p9_2,
  134132. 1, -526909440, 1611661312, 6, 0,
  134133. _vq_quantlist__44c8_s_p9_2,
  134134. NULL,
  134135. &_vq_auxt__44c8_s_p9_2,
  134136. NULL,
  134137. 0
  134138. };
  134139. static long _huff_lengthlist__44c8_s_short[] = {
  134140. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134141. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134142. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134143. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134144. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134145. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134146. 10, 9,11,14,
  134147. };
  134148. static static_codebook _huff_book__44c8_s_short = {
  134149. 2, 100,
  134150. _huff_lengthlist__44c8_s_short,
  134151. 0, 0, 0, 0, 0,
  134152. NULL,
  134153. NULL,
  134154. NULL,
  134155. NULL,
  134156. 0
  134157. };
  134158. static long _huff_lengthlist__44c9_s_long[] = {
  134159. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134160. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134161. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134162. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134163. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134164. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134165. 10, 9, 8, 9,
  134166. };
  134167. static static_codebook _huff_book__44c9_s_long = {
  134168. 2, 100,
  134169. _huff_lengthlist__44c9_s_long,
  134170. 0, 0, 0, 0, 0,
  134171. NULL,
  134172. NULL,
  134173. NULL,
  134174. NULL,
  134175. 0
  134176. };
  134177. static long _vq_quantlist__44c9_s_p1_0[] = {
  134178. 1,
  134179. 0,
  134180. 2,
  134181. };
  134182. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134183. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134184. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134185. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134186. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134187. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134188. 7,
  134189. };
  134190. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134191. -0.5, 0.5,
  134192. };
  134193. static long _vq_quantmap__44c9_s_p1_0[] = {
  134194. 1, 0, 2,
  134195. };
  134196. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134197. _vq_quantthresh__44c9_s_p1_0,
  134198. _vq_quantmap__44c9_s_p1_0,
  134199. 3,
  134200. 3
  134201. };
  134202. static static_codebook _44c9_s_p1_0 = {
  134203. 4, 81,
  134204. _vq_lengthlist__44c9_s_p1_0,
  134205. 1, -535822336, 1611661312, 2, 0,
  134206. _vq_quantlist__44c9_s_p1_0,
  134207. NULL,
  134208. &_vq_auxt__44c9_s_p1_0,
  134209. NULL,
  134210. 0
  134211. };
  134212. static long _vq_quantlist__44c9_s_p2_0[] = {
  134213. 2,
  134214. 1,
  134215. 3,
  134216. 0,
  134217. 4,
  134218. };
  134219. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134220. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134221. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134222. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134223. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134224. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134225. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134226. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134227. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134230. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134231. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134232. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134233. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134234. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134235. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134238. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134239. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134240. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134241. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134242. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134243. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134246. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134247. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134248. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134249. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134250. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134251. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134256. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134257. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134258. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134259. 12,
  134260. };
  134261. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134262. -1.5, -0.5, 0.5, 1.5,
  134263. };
  134264. static long _vq_quantmap__44c9_s_p2_0[] = {
  134265. 3, 1, 0, 2, 4,
  134266. };
  134267. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134268. _vq_quantthresh__44c9_s_p2_0,
  134269. _vq_quantmap__44c9_s_p2_0,
  134270. 5,
  134271. 5
  134272. };
  134273. static static_codebook _44c9_s_p2_0 = {
  134274. 4, 625,
  134275. _vq_lengthlist__44c9_s_p2_0,
  134276. 1, -533725184, 1611661312, 3, 0,
  134277. _vq_quantlist__44c9_s_p2_0,
  134278. NULL,
  134279. &_vq_auxt__44c9_s_p2_0,
  134280. NULL,
  134281. 0
  134282. };
  134283. static long _vq_quantlist__44c9_s_p3_0[] = {
  134284. 4,
  134285. 3,
  134286. 5,
  134287. 2,
  134288. 6,
  134289. 1,
  134290. 7,
  134291. 0,
  134292. 8,
  134293. };
  134294. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134295. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134296. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134297. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134298. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134300. 0,
  134301. };
  134302. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134303. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134304. };
  134305. static long _vq_quantmap__44c9_s_p3_0[] = {
  134306. 7, 5, 3, 1, 0, 2, 4, 6,
  134307. 8,
  134308. };
  134309. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134310. _vq_quantthresh__44c9_s_p3_0,
  134311. _vq_quantmap__44c9_s_p3_0,
  134312. 9,
  134313. 9
  134314. };
  134315. static static_codebook _44c9_s_p3_0 = {
  134316. 2, 81,
  134317. _vq_lengthlist__44c9_s_p3_0,
  134318. 1, -531628032, 1611661312, 4, 0,
  134319. _vq_quantlist__44c9_s_p3_0,
  134320. NULL,
  134321. &_vq_auxt__44c9_s_p3_0,
  134322. NULL,
  134323. 0
  134324. };
  134325. static long _vq_quantlist__44c9_s_p4_0[] = {
  134326. 8,
  134327. 7,
  134328. 9,
  134329. 6,
  134330. 10,
  134331. 5,
  134332. 11,
  134333. 4,
  134334. 12,
  134335. 3,
  134336. 13,
  134337. 2,
  134338. 14,
  134339. 1,
  134340. 15,
  134341. 0,
  134342. 16,
  134343. };
  134344. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134345. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134346. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134347. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134348. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134349. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134350. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134351. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134352. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134353. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134354. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0,
  134364. };
  134365. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134366. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134367. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134368. };
  134369. static long _vq_quantmap__44c9_s_p4_0[] = {
  134370. 15, 13, 11, 9, 7, 5, 3, 1,
  134371. 0, 2, 4, 6, 8, 10, 12, 14,
  134372. 16,
  134373. };
  134374. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134375. _vq_quantthresh__44c9_s_p4_0,
  134376. _vq_quantmap__44c9_s_p4_0,
  134377. 17,
  134378. 17
  134379. };
  134380. static static_codebook _44c9_s_p4_0 = {
  134381. 2, 289,
  134382. _vq_lengthlist__44c9_s_p4_0,
  134383. 1, -529530880, 1611661312, 5, 0,
  134384. _vq_quantlist__44c9_s_p4_0,
  134385. NULL,
  134386. &_vq_auxt__44c9_s_p4_0,
  134387. NULL,
  134388. 0
  134389. };
  134390. static long _vq_quantlist__44c9_s_p5_0[] = {
  134391. 1,
  134392. 0,
  134393. 2,
  134394. };
  134395. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134396. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134397. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134398. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134399. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134400. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134401. 12,
  134402. };
  134403. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134404. -5.5, 5.5,
  134405. };
  134406. static long _vq_quantmap__44c9_s_p5_0[] = {
  134407. 1, 0, 2,
  134408. };
  134409. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134410. _vq_quantthresh__44c9_s_p5_0,
  134411. _vq_quantmap__44c9_s_p5_0,
  134412. 3,
  134413. 3
  134414. };
  134415. static static_codebook _44c9_s_p5_0 = {
  134416. 4, 81,
  134417. _vq_lengthlist__44c9_s_p5_0,
  134418. 1, -529137664, 1618345984, 2, 0,
  134419. _vq_quantlist__44c9_s_p5_0,
  134420. NULL,
  134421. &_vq_auxt__44c9_s_p5_0,
  134422. NULL,
  134423. 0
  134424. };
  134425. static long _vq_quantlist__44c9_s_p5_1[] = {
  134426. 5,
  134427. 4,
  134428. 6,
  134429. 3,
  134430. 7,
  134431. 2,
  134432. 8,
  134433. 1,
  134434. 9,
  134435. 0,
  134436. 10,
  134437. };
  134438. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134439. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134440. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134441. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134442. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134443. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134444. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134445. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134446. 11,11,11, 7, 7, 7, 7, 7, 7,
  134447. };
  134448. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134449. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134450. 3.5, 4.5,
  134451. };
  134452. static long _vq_quantmap__44c9_s_p5_1[] = {
  134453. 9, 7, 5, 3, 1, 0, 2, 4,
  134454. 6, 8, 10,
  134455. };
  134456. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134457. _vq_quantthresh__44c9_s_p5_1,
  134458. _vq_quantmap__44c9_s_p5_1,
  134459. 11,
  134460. 11
  134461. };
  134462. static static_codebook _44c9_s_p5_1 = {
  134463. 2, 121,
  134464. _vq_lengthlist__44c9_s_p5_1,
  134465. 1, -531365888, 1611661312, 4, 0,
  134466. _vq_quantlist__44c9_s_p5_1,
  134467. NULL,
  134468. &_vq_auxt__44c9_s_p5_1,
  134469. NULL,
  134470. 0
  134471. };
  134472. static long _vq_quantlist__44c9_s_p6_0[] = {
  134473. 6,
  134474. 5,
  134475. 7,
  134476. 4,
  134477. 8,
  134478. 3,
  134479. 9,
  134480. 2,
  134481. 10,
  134482. 1,
  134483. 11,
  134484. 0,
  134485. 12,
  134486. };
  134487. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134488. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134489. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134490. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134491. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134492. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134493. 11, 8, 8, 9, 9,10,10,11,11,12,12, 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,
  134499. };
  134500. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134501. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134502. 12.5, 17.5, 22.5, 27.5,
  134503. };
  134504. static long _vq_quantmap__44c9_s_p6_0[] = {
  134505. 11, 9, 7, 5, 3, 1, 0, 2,
  134506. 4, 6, 8, 10, 12,
  134507. };
  134508. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134509. _vq_quantthresh__44c9_s_p6_0,
  134510. _vq_quantmap__44c9_s_p6_0,
  134511. 13,
  134512. 13
  134513. };
  134514. static static_codebook _44c9_s_p6_0 = {
  134515. 2, 169,
  134516. _vq_lengthlist__44c9_s_p6_0,
  134517. 1, -526516224, 1616117760, 4, 0,
  134518. _vq_quantlist__44c9_s_p6_0,
  134519. NULL,
  134520. &_vq_auxt__44c9_s_p6_0,
  134521. NULL,
  134522. 0
  134523. };
  134524. static long _vq_quantlist__44c9_s_p6_1[] = {
  134525. 2,
  134526. 1,
  134527. 3,
  134528. 0,
  134529. 4,
  134530. };
  134531. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134532. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134533. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134534. };
  134535. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134536. -1.5, -0.5, 0.5, 1.5,
  134537. };
  134538. static long _vq_quantmap__44c9_s_p6_1[] = {
  134539. 3, 1, 0, 2, 4,
  134540. };
  134541. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134542. _vq_quantthresh__44c9_s_p6_1,
  134543. _vq_quantmap__44c9_s_p6_1,
  134544. 5,
  134545. 5
  134546. };
  134547. static static_codebook _44c9_s_p6_1 = {
  134548. 2, 25,
  134549. _vq_lengthlist__44c9_s_p6_1,
  134550. 1, -533725184, 1611661312, 3, 0,
  134551. _vq_quantlist__44c9_s_p6_1,
  134552. NULL,
  134553. &_vq_auxt__44c9_s_p6_1,
  134554. NULL,
  134555. 0
  134556. };
  134557. static long _vq_quantlist__44c9_s_p7_0[] = {
  134558. 6,
  134559. 5,
  134560. 7,
  134561. 4,
  134562. 8,
  134563. 3,
  134564. 9,
  134565. 2,
  134566. 10,
  134567. 1,
  134568. 11,
  134569. 0,
  134570. 12,
  134571. };
  134572. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134573. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134574. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134575. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134576. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134577. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134578. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134579. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134580. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134581. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134582. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134583. 19,12,12,12,12,13,13,14,14,
  134584. };
  134585. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134586. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134587. 27.5, 38.5, 49.5, 60.5,
  134588. };
  134589. static long _vq_quantmap__44c9_s_p7_0[] = {
  134590. 11, 9, 7, 5, 3, 1, 0, 2,
  134591. 4, 6, 8, 10, 12,
  134592. };
  134593. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134594. _vq_quantthresh__44c9_s_p7_0,
  134595. _vq_quantmap__44c9_s_p7_0,
  134596. 13,
  134597. 13
  134598. };
  134599. static static_codebook _44c9_s_p7_0 = {
  134600. 2, 169,
  134601. _vq_lengthlist__44c9_s_p7_0,
  134602. 1, -523206656, 1618345984, 4, 0,
  134603. _vq_quantlist__44c9_s_p7_0,
  134604. NULL,
  134605. &_vq_auxt__44c9_s_p7_0,
  134606. NULL,
  134607. 0
  134608. };
  134609. static long _vq_quantlist__44c9_s_p7_1[] = {
  134610. 5,
  134611. 4,
  134612. 6,
  134613. 3,
  134614. 7,
  134615. 2,
  134616. 8,
  134617. 1,
  134618. 9,
  134619. 0,
  134620. 10,
  134621. };
  134622. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134623. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134624. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134625. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134626. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134627. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134628. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134629. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134630. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134631. };
  134632. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134633. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134634. 3.5, 4.5,
  134635. };
  134636. static long _vq_quantmap__44c9_s_p7_1[] = {
  134637. 9, 7, 5, 3, 1, 0, 2, 4,
  134638. 6, 8, 10,
  134639. };
  134640. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134641. _vq_quantthresh__44c9_s_p7_1,
  134642. _vq_quantmap__44c9_s_p7_1,
  134643. 11,
  134644. 11
  134645. };
  134646. static static_codebook _44c9_s_p7_1 = {
  134647. 2, 121,
  134648. _vq_lengthlist__44c9_s_p7_1,
  134649. 1, -531365888, 1611661312, 4, 0,
  134650. _vq_quantlist__44c9_s_p7_1,
  134651. NULL,
  134652. &_vq_auxt__44c9_s_p7_1,
  134653. NULL,
  134654. 0
  134655. };
  134656. static long _vq_quantlist__44c9_s_p8_0[] = {
  134657. 7,
  134658. 6,
  134659. 8,
  134660. 5,
  134661. 9,
  134662. 4,
  134663. 10,
  134664. 3,
  134665. 11,
  134666. 2,
  134667. 12,
  134668. 1,
  134669. 13,
  134670. 0,
  134671. 14,
  134672. };
  134673. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134674. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134675. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134676. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134677. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134678. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134679. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134680. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134681. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134682. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134683. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134684. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134685. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134686. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134687. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134688. 14,
  134689. };
  134690. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134691. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134692. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134693. };
  134694. static long _vq_quantmap__44c9_s_p8_0[] = {
  134695. 13, 11, 9, 7, 5, 3, 1, 0,
  134696. 2, 4, 6, 8, 10, 12, 14,
  134697. };
  134698. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134699. _vq_quantthresh__44c9_s_p8_0,
  134700. _vq_quantmap__44c9_s_p8_0,
  134701. 15,
  134702. 15
  134703. };
  134704. static static_codebook _44c9_s_p8_0 = {
  134705. 2, 225,
  134706. _vq_lengthlist__44c9_s_p8_0,
  134707. 1, -520986624, 1620377600, 4, 0,
  134708. _vq_quantlist__44c9_s_p8_0,
  134709. NULL,
  134710. &_vq_auxt__44c9_s_p8_0,
  134711. NULL,
  134712. 0
  134713. };
  134714. static long _vq_quantlist__44c9_s_p8_1[] = {
  134715. 10,
  134716. 9,
  134717. 11,
  134718. 8,
  134719. 12,
  134720. 7,
  134721. 13,
  134722. 6,
  134723. 14,
  134724. 5,
  134725. 15,
  134726. 4,
  134727. 16,
  134728. 3,
  134729. 17,
  134730. 2,
  134731. 18,
  134732. 1,
  134733. 19,
  134734. 0,
  134735. 20,
  134736. };
  134737. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134738. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134739. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134740. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134741. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134742. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134743. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134744. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134745. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134746. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134747. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134748. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134749. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134750. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134751. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134752. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134753. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134754. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134755. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134756. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134757. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134758. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134759. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134760. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134761. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134762. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134763. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134764. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134765. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134766. };
  134767. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134768. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134769. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134770. 6.5, 7.5, 8.5, 9.5,
  134771. };
  134772. static long _vq_quantmap__44c9_s_p8_1[] = {
  134773. 19, 17, 15, 13, 11, 9, 7, 5,
  134774. 3, 1, 0, 2, 4, 6, 8, 10,
  134775. 12, 14, 16, 18, 20,
  134776. };
  134777. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134778. _vq_quantthresh__44c9_s_p8_1,
  134779. _vq_quantmap__44c9_s_p8_1,
  134780. 21,
  134781. 21
  134782. };
  134783. static static_codebook _44c9_s_p8_1 = {
  134784. 2, 441,
  134785. _vq_lengthlist__44c9_s_p8_1,
  134786. 1, -529268736, 1611661312, 5, 0,
  134787. _vq_quantlist__44c9_s_p8_1,
  134788. NULL,
  134789. &_vq_auxt__44c9_s_p8_1,
  134790. NULL,
  134791. 0
  134792. };
  134793. static long _vq_quantlist__44c9_s_p9_0[] = {
  134794. 9,
  134795. 8,
  134796. 10,
  134797. 7,
  134798. 11,
  134799. 6,
  134800. 12,
  134801. 5,
  134802. 13,
  134803. 4,
  134804. 14,
  134805. 3,
  134806. 15,
  134807. 2,
  134808. 16,
  134809. 1,
  134810. 17,
  134811. 0,
  134812. 18,
  134813. };
  134814. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134815. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134816. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134817. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134818. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  134819. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134820. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134821. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134822. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134823. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134824. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134825. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134826. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134827. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134828. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134829. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134830. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134831. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  134832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134837. 11,11,11,11,11,11,11,11,11,
  134838. };
  134839. static float _vq_quantthresh__44c9_s_p9_0[] = {
  134840. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  134841. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  134842. 6982.5, 7913.5,
  134843. };
  134844. static long _vq_quantmap__44c9_s_p9_0[] = {
  134845. 17, 15, 13, 11, 9, 7, 5, 3,
  134846. 1, 0, 2, 4, 6, 8, 10, 12,
  134847. 14, 16, 18,
  134848. };
  134849. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  134850. _vq_quantthresh__44c9_s_p9_0,
  134851. _vq_quantmap__44c9_s_p9_0,
  134852. 19,
  134853. 19
  134854. };
  134855. static static_codebook _44c9_s_p9_0 = {
  134856. 2, 361,
  134857. _vq_lengthlist__44c9_s_p9_0,
  134858. 1, -508535424, 1631393792, 5, 0,
  134859. _vq_quantlist__44c9_s_p9_0,
  134860. NULL,
  134861. &_vq_auxt__44c9_s_p9_0,
  134862. NULL,
  134863. 0
  134864. };
  134865. static long _vq_quantlist__44c9_s_p9_1[] = {
  134866. 9,
  134867. 8,
  134868. 10,
  134869. 7,
  134870. 11,
  134871. 6,
  134872. 12,
  134873. 5,
  134874. 13,
  134875. 4,
  134876. 14,
  134877. 3,
  134878. 15,
  134879. 2,
  134880. 16,
  134881. 1,
  134882. 17,
  134883. 0,
  134884. 18,
  134885. };
  134886. static long _vq_lengthlist__44c9_s_p9_1[] = {
  134887. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  134888. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  134889. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  134890. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  134891. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  134892. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  134893. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  134894. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  134895. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  134896. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  134897. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  134898. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  134899. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  134900. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  134901. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  134902. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  134903. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  134904. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  134905. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  134906. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  134907. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  134908. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  134909. 13,13,13,14,13,14,15,15,15,
  134910. };
  134911. static float _vq_quantthresh__44c9_s_p9_1[] = {
  134912. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134913. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134914. 367.5, 416.5,
  134915. };
  134916. static long _vq_quantmap__44c9_s_p9_1[] = {
  134917. 17, 15, 13, 11, 9, 7, 5, 3,
  134918. 1, 0, 2, 4, 6, 8, 10, 12,
  134919. 14, 16, 18,
  134920. };
  134921. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  134922. _vq_quantthresh__44c9_s_p9_1,
  134923. _vq_quantmap__44c9_s_p9_1,
  134924. 19,
  134925. 19
  134926. };
  134927. static static_codebook _44c9_s_p9_1 = {
  134928. 2, 361,
  134929. _vq_lengthlist__44c9_s_p9_1,
  134930. 1, -518287360, 1622704128, 5, 0,
  134931. _vq_quantlist__44c9_s_p9_1,
  134932. NULL,
  134933. &_vq_auxt__44c9_s_p9_1,
  134934. NULL,
  134935. 0
  134936. };
  134937. static long _vq_quantlist__44c9_s_p9_2[] = {
  134938. 24,
  134939. 23,
  134940. 25,
  134941. 22,
  134942. 26,
  134943. 21,
  134944. 27,
  134945. 20,
  134946. 28,
  134947. 19,
  134948. 29,
  134949. 18,
  134950. 30,
  134951. 17,
  134952. 31,
  134953. 16,
  134954. 32,
  134955. 15,
  134956. 33,
  134957. 14,
  134958. 34,
  134959. 13,
  134960. 35,
  134961. 12,
  134962. 36,
  134963. 11,
  134964. 37,
  134965. 10,
  134966. 38,
  134967. 9,
  134968. 39,
  134969. 8,
  134970. 40,
  134971. 7,
  134972. 41,
  134973. 6,
  134974. 42,
  134975. 5,
  134976. 43,
  134977. 4,
  134978. 44,
  134979. 3,
  134980. 45,
  134981. 2,
  134982. 46,
  134983. 1,
  134984. 47,
  134985. 0,
  134986. 48,
  134987. };
  134988. static long _vq_lengthlist__44c9_s_p9_2[] = {
  134989. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134990. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134991. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134992. 7,
  134993. };
  134994. static float _vq_quantthresh__44c9_s_p9_2[] = {
  134995. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134996. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134997. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134998. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134999. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135000. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135001. };
  135002. static long _vq_quantmap__44c9_s_p9_2[] = {
  135003. 47, 45, 43, 41, 39, 37, 35, 33,
  135004. 31, 29, 27, 25, 23, 21, 19, 17,
  135005. 15, 13, 11, 9, 7, 5, 3, 1,
  135006. 0, 2, 4, 6, 8, 10, 12, 14,
  135007. 16, 18, 20, 22, 24, 26, 28, 30,
  135008. 32, 34, 36, 38, 40, 42, 44, 46,
  135009. 48,
  135010. };
  135011. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135012. _vq_quantthresh__44c9_s_p9_2,
  135013. _vq_quantmap__44c9_s_p9_2,
  135014. 49,
  135015. 49
  135016. };
  135017. static static_codebook _44c9_s_p9_2 = {
  135018. 1, 49,
  135019. _vq_lengthlist__44c9_s_p9_2,
  135020. 1, -526909440, 1611661312, 6, 0,
  135021. _vq_quantlist__44c9_s_p9_2,
  135022. NULL,
  135023. &_vq_auxt__44c9_s_p9_2,
  135024. NULL,
  135025. 0
  135026. };
  135027. static long _huff_lengthlist__44c9_s_short[] = {
  135028. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135029. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135030. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135031. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135032. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135033. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135034. 9, 8,10,13,
  135035. };
  135036. static static_codebook _huff_book__44c9_s_short = {
  135037. 2, 100,
  135038. _huff_lengthlist__44c9_s_short,
  135039. 0, 0, 0, 0, 0,
  135040. NULL,
  135041. NULL,
  135042. NULL,
  135043. NULL,
  135044. 0
  135045. };
  135046. static long _huff_lengthlist__44c0_s_long[] = {
  135047. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135048. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135049. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135050. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135051. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135052. 12,
  135053. };
  135054. static static_codebook _huff_book__44c0_s_long = {
  135055. 2, 81,
  135056. _huff_lengthlist__44c0_s_long,
  135057. 0, 0, 0, 0, 0,
  135058. NULL,
  135059. NULL,
  135060. NULL,
  135061. NULL,
  135062. 0
  135063. };
  135064. static long _vq_quantlist__44c0_s_p1_0[] = {
  135065. 1,
  135066. 0,
  135067. 2,
  135068. };
  135069. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135070. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135071. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135076. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135081. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135116. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135121. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135126. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135162. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135167. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135172. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0,
  135481. };
  135482. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135483. -0.5, 0.5,
  135484. };
  135485. static long _vq_quantmap__44c0_s_p1_0[] = {
  135486. 1, 0, 2,
  135487. };
  135488. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135489. _vq_quantthresh__44c0_s_p1_0,
  135490. _vq_quantmap__44c0_s_p1_0,
  135491. 3,
  135492. 3
  135493. };
  135494. static static_codebook _44c0_s_p1_0 = {
  135495. 8, 6561,
  135496. _vq_lengthlist__44c0_s_p1_0,
  135497. 1, -535822336, 1611661312, 2, 0,
  135498. _vq_quantlist__44c0_s_p1_0,
  135499. NULL,
  135500. &_vq_auxt__44c0_s_p1_0,
  135501. NULL,
  135502. 0
  135503. };
  135504. static long _vq_quantlist__44c0_s_p2_0[] = {
  135505. 2,
  135506. 1,
  135507. 3,
  135508. 0,
  135509. 4,
  135510. };
  135511. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135512. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  135552. };
  135553. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135554. -1.5, -0.5, 0.5, 1.5,
  135555. };
  135556. static long _vq_quantmap__44c0_s_p2_0[] = {
  135557. 3, 1, 0, 2, 4,
  135558. };
  135559. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135560. _vq_quantthresh__44c0_s_p2_0,
  135561. _vq_quantmap__44c0_s_p2_0,
  135562. 5,
  135563. 5
  135564. };
  135565. static static_codebook _44c0_s_p2_0 = {
  135566. 4, 625,
  135567. _vq_lengthlist__44c0_s_p2_0,
  135568. 1, -533725184, 1611661312, 3, 0,
  135569. _vq_quantlist__44c0_s_p2_0,
  135570. NULL,
  135571. &_vq_auxt__44c0_s_p2_0,
  135572. NULL,
  135573. 0
  135574. };
  135575. static long _vq_quantlist__44c0_s_p3_0[] = {
  135576. 4,
  135577. 3,
  135578. 5,
  135579. 2,
  135580. 6,
  135581. 1,
  135582. 7,
  135583. 0,
  135584. 8,
  135585. };
  135586. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135587. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135588. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135589. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135590. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135591. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0,
  135593. };
  135594. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135595. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135596. };
  135597. static long _vq_quantmap__44c0_s_p3_0[] = {
  135598. 7, 5, 3, 1, 0, 2, 4, 6,
  135599. 8,
  135600. };
  135601. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135602. _vq_quantthresh__44c0_s_p3_0,
  135603. _vq_quantmap__44c0_s_p3_0,
  135604. 9,
  135605. 9
  135606. };
  135607. static static_codebook _44c0_s_p3_0 = {
  135608. 2, 81,
  135609. _vq_lengthlist__44c0_s_p3_0,
  135610. 1, -531628032, 1611661312, 4, 0,
  135611. _vq_quantlist__44c0_s_p3_0,
  135612. NULL,
  135613. &_vq_auxt__44c0_s_p3_0,
  135614. NULL,
  135615. 0
  135616. };
  135617. static long _vq_quantlist__44c0_s_p4_0[] = {
  135618. 4,
  135619. 3,
  135620. 5,
  135621. 2,
  135622. 6,
  135623. 1,
  135624. 7,
  135625. 0,
  135626. 8,
  135627. };
  135628. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135629. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135630. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135631. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135632. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135633. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135634. 10,
  135635. };
  135636. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135637. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135638. };
  135639. static long _vq_quantmap__44c0_s_p4_0[] = {
  135640. 7, 5, 3, 1, 0, 2, 4, 6,
  135641. 8,
  135642. };
  135643. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135644. _vq_quantthresh__44c0_s_p4_0,
  135645. _vq_quantmap__44c0_s_p4_0,
  135646. 9,
  135647. 9
  135648. };
  135649. static static_codebook _44c0_s_p4_0 = {
  135650. 2, 81,
  135651. _vq_lengthlist__44c0_s_p4_0,
  135652. 1, -531628032, 1611661312, 4, 0,
  135653. _vq_quantlist__44c0_s_p4_0,
  135654. NULL,
  135655. &_vq_auxt__44c0_s_p4_0,
  135656. NULL,
  135657. 0
  135658. };
  135659. static long _vq_quantlist__44c0_s_p5_0[] = {
  135660. 8,
  135661. 7,
  135662. 9,
  135663. 6,
  135664. 10,
  135665. 5,
  135666. 11,
  135667. 4,
  135668. 12,
  135669. 3,
  135670. 13,
  135671. 2,
  135672. 14,
  135673. 1,
  135674. 15,
  135675. 0,
  135676. 16,
  135677. };
  135678. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135679. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135680. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135681. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135682. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135683. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135684. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135685. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135686. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135687. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135688. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135689. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135690. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135691. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135692. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135693. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135694. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135695. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135697. 14,
  135698. };
  135699. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135700. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135701. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135702. };
  135703. static long _vq_quantmap__44c0_s_p5_0[] = {
  135704. 15, 13, 11, 9, 7, 5, 3, 1,
  135705. 0, 2, 4, 6, 8, 10, 12, 14,
  135706. 16,
  135707. };
  135708. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135709. _vq_quantthresh__44c0_s_p5_0,
  135710. _vq_quantmap__44c0_s_p5_0,
  135711. 17,
  135712. 17
  135713. };
  135714. static static_codebook _44c0_s_p5_0 = {
  135715. 2, 289,
  135716. _vq_lengthlist__44c0_s_p5_0,
  135717. 1, -529530880, 1611661312, 5, 0,
  135718. _vq_quantlist__44c0_s_p5_0,
  135719. NULL,
  135720. &_vq_auxt__44c0_s_p5_0,
  135721. NULL,
  135722. 0
  135723. };
  135724. static long _vq_quantlist__44c0_s_p6_0[] = {
  135725. 1,
  135726. 0,
  135727. 2,
  135728. };
  135729. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135730. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135731. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135732. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135733. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135734. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135735. 10,
  135736. };
  135737. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135738. -5.5, 5.5,
  135739. };
  135740. static long _vq_quantmap__44c0_s_p6_0[] = {
  135741. 1, 0, 2,
  135742. };
  135743. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135744. _vq_quantthresh__44c0_s_p6_0,
  135745. _vq_quantmap__44c0_s_p6_0,
  135746. 3,
  135747. 3
  135748. };
  135749. static static_codebook _44c0_s_p6_0 = {
  135750. 4, 81,
  135751. _vq_lengthlist__44c0_s_p6_0,
  135752. 1, -529137664, 1618345984, 2, 0,
  135753. _vq_quantlist__44c0_s_p6_0,
  135754. NULL,
  135755. &_vq_auxt__44c0_s_p6_0,
  135756. NULL,
  135757. 0
  135758. };
  135759. static long _vq_quantlist__44c0_s_p6_1[] = {
  135760. 5,
  135761. 4,
  135762. 6,
  135763. 3,
  135764. 7,
  135765. 2,
  135766. 8,
  135767. 1,
  135768. 9,
  135769. 0,
  135770. 10,
  135771. };
  135772. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135773. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135774. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135775. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135776. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135777. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135778. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135779. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135780. 10,10,10, 8, 8, 8, 8, 8, 8,
  135781. };
  135782. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135783. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135784. 3.5, 4.5,
  135785. };
  135786. static long _vq_quantmap__44c0_s_p6_1[] = {
  135787. 9, 7, 5, 3, 1, 0, 2, 4,
  135788. 6, 8, 10,
  135789. };
  135790. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135791. _vq_quantthresh__44c0_s_p6_1,
  135792. _vq_quantmap__44c0_s_p6_1,
  135793. 11,
  135794. 11
  135795. };
  135796. static static_codebook _44c0_s_p6_1 = {
  135797. 2, 121,
  135798. _vq_lengthlist__44c0_s_p6_1,
  135799. 1, -531365888, 1611661312, 4, 0,
  135800. _vq_quantlist__44c0_s_p6_1,
  135801. NULL,
  135802. &_vq_auxt__44c0_s_p6_1,
  135803. NULL,
  135804. 0
  135805. };
  135806. static long _vq_quantlist__44c0_s_p7_0[] = {
  135807. 6,
  135808. 5,
  135809. 7,
  135810. 4,
  135811. 8,
  135812. 3,
  135813. 9,
  135814. 2,
  135815. 10,
  135816. 1,
  135817. 11,
  135818. 0,
  135819. 12,
  135820. };
  135821. static long _vq_lengthlist__44c0_s_p7_0[] = {
  135822. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135823. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135824. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135825. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135826. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135827. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135828. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  135829. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135830. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135831. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  135832. 0,12,12,11,11,12,12,13,13,
  135833. };
  135834. static float _vq_quantthresh__44c0_s_p7_0[] = {
  135835. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135836. 12.5, 17.5, 22.5, 27.5,
  135837. };
  135838. static long _vq_quantmap__44c0_s_p7_0[] = {
  135839. 11, 9, 7, 5, 3, 1, 0, 2,
  135840. 4, 6, 8, 10, 12,
  135841. };
  135842. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  135843. _vq_quantthresh__44c0_s_p7_0,
  135844. _vq_quantmap__44c0_s_p7_0,
  135845. 13,
  135846. 13
  135847. };
  135848. static static_codebook _44c0_s_p7_0 = {
  135849. 2, 169,
  135850. _vq_lengthlist__44c0_s_p7_0,
  135851. 1, -526516224, 1616117760, 4, 0,
  135852. _vq_quantlist__44c0_s_p7_0,
  135853. NULL,
  135854. &_vq_auxt__44c0_s_p7_0,
  135855. NULL,
  135856. 0
  135857. };
  135858. static long _vq_quantlist__44c0_s_p7_1[] = {
  135859. 2,
  135860. 1,
  135861. 3,
  135862. 0,
  135863. 4,
  135864. };
  135865. static long _vq_lengthlist__44c0_s_p7_1[] = {
  135866. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135867. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135868. };
  135869. static float _vq_quantthresh__44c0_s_p7_1[] = {
  135870. -1.5, -0.5, 0.5, 1.5,
  135871. };
  135872. static long _vq_quantmap__44c0_s_p7_1[] = {
  135873. 3, 1, 0, 2, 4,
  135874. };
  135875. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  135876. _vq_quantthresh__44c0_s_p7_1,
  135877. _vq_quantmap__44c0_s_p7_1,
  135878. 5,
  135879. 5
  135880. };
  135881. static static_codebook _44c0_s_p7_1 = {
  135882. 2, 25,
  135883. _vq_lengthlist__44c0_s_p7_1,
  135884. 1, -533725184, 1611661312, 3, 0,
  135885. _vq_quantlist__44c0_s_p7_1,
  135886. NULL,
  135887. &_vq_auxt__44c0_s_p7_1,
  135888. NULL,
  135889. 0
  135890. };
  135891. static long _vq_quantlist__44c0_s_p8_0[] = {
  135892. 2,
  135893. 1,
  135894. 3,
  135895. 0,
  135896. 4,
  135897. };
  135898. static long _vq_lengthlist__44c0_s_p8_0[] = {
  135899. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  135900. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135901. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135902. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135903. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135904. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135906. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  135907. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135908. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135909. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135910. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135911. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  135912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135914. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  135915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135921. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135938. 11,
  135939. };
  135940. static float _vq_quantthresh__44c0_s_p8_0[] = {
  135941. -331.5, -110.5, 110.5, 331.5,
  135942. };
  135943. static long _vq_quantmap__44c0_s_p8_0[] = {
  135944. 3, 1, 0, 2, 4,
  135945. };
  135946. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  135947. _vq_quantthresh__44c0_s_p8_0,
  135948. _vq_quantmap__44c0_s_p8_0,
  135949. 5,
  135950. 5
  135951. };
  135952. static static_codebook _44c0_s_p8_0 = {
  135953. 4, 625,
  135954. _vq_lengthlist__44c0_s_p8_0,
  135955. 1, -518283264, 1627103232, 3, 0,
  135956. _vq_quantlist__44c0_s_p8_0,
  135957. NULL,
  135958. &_vq_auxt__44c0_s_p8_0,
  135959. NULL,
  135960. 0
  135961. };
  135962. static long _vq_quantlist__44c0_s_p8_1[] = {
  135963. 6,
  135964. 5,
  135965. 7,
  135966. 4,
  135967. 8,
  135968. 3,
  135969. 9,
  135970. 2,
  135971. 10,
  135972. 1,
  135973. 11,
  135974. 0,
  135975. 12,
  135976. };
  135977. static long _vq_lengthlist__44c0_s_p8_1[] = {
  135978. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  135979. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  135980. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  135981. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  135982. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  135983. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  135984. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  135985. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  135986. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  135987. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  135988. 16,13,13,12,12,14,14,15,13,
  135989. };
  135990. static float _vq_quantthresh__44c0_s_p8_1[] = {
  135991. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135992. 42.5, 59.5, 76.5, 93.5,
  135993. };
  135994. static long _vq_quantmap__44c0_s_p8_1[] = {
  135995. 11, 9, 7, 5, 3, 1, 0, 2,
  135996. 4, 6, 8, 10, 12,
  135997. };
  135998. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  135999. _vq_quantthresh__44c0_s_p8_1,
  136000. _vq_quantmap__44c0_s_p8_1,
  136001. 13,
  136002. 13
  136003. };
  136004. static static_codebook _44c0_s_p8_1 = {
  136005. 2, 169,
  136006. _vq_lengthlist__44c0_s_p8_1,
  136007. 1, -522616832, 1620115456, 4, 0,
  136008. _vq_quantlist__44c0_s_p8_1,
  136009. NULL,
  136010. &_vq_auxt__44c0_s_p8_1,
  136011. NULL,
  136012. 0
  136013. };
  136014. static long _vq_quantlist__44c0_s_p8_2[] = {
  136015. 8,
  136016. 7,
  136017. 9,
  136018. 6,
  136019. 10,
  136020. 5,
  136021. 11,
  136022. 4,
  136023. 12,
  136024. 3,
  136025. 13,
  136026. 2,
  136027. 14,
  136028. 1,
  136029. 15,
  136030. 0,
  136031. 16,
  136032. };
  136033. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136034. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136035. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136036. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136037. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136038. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136039. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136040. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136041. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136042. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136043. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136044. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136045. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136046. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136047. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136048. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136049. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136050. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136051. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136052. 10,
  136053. };
  136054. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136055. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136056. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136057. };
  136058. static long _vq_quantmap__44c0_s_p8_2[] = {
  136059. 15, 13, 11, 9, 7, 5, 3, 1,
  136060. 0, 2, 4, 6, 8, 10, 12, 14,
  136061. 16,
  136062. };
  136063. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136064. _vq_quantthresh__44c0_s_p8_2,
  136065. _vq_quantmap__44c0_s_p8_2,
  136066. 17,
  136067. 17
  136068. };
  136069. static static_codebook _44c0_s_p8_2 = {
  136070. 2, 289,
  136071. _vq_lengthlist__44c0_s_p8_2,
  136072. 1, -529530880, 1611661312, 5, 0,
  136073. _vq_quantlist__44c0_s_p8_2,
  136074. NULL,
  136075. &_vq_auxt__44c0_s_p8_2,
  136076. NULL,
  136077. 0
  136078. };
  136079. static long _huff_lengthlist__44c0_s_short[] = {
  136080. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136081. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136082. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136083. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136084. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136085. 12,
  136086. };
  136087. static static_codebook _huff_book__44c0_s_short = {
  136088. 2, 81,
  136089. _huff_lengthlist__44c0_s_short,
  136090. 0, 0, 0, 0, 0,
  136091. NULL,
  136092. NULL,
  136093. NULL,
  136094. NULL,
  136095. 0
  136096. };
  136097. static long _huff_lengthlist__44c0_sm_long[] = {
  136098. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136099. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136100. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136101. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136102. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136103. 13,
  136104. };
  136105. static static_codebook _huff_book__44c0_sm_long = {
  136106. 2, 81,
  136107. _huff_lengthlist__44c0_sm_long,
  136108. 0, 0, 0, 0, 0,
  136109. NULL,
  136110. NULL,
  136111. NULL,
  136112. NULL,
  136113. 0
  136114. };
  136115. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136116. 1,
  136117. 0,
  136118. 2,
  136119. };
  136120. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136121. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136122. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136127. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136132. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136167. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136172. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136177. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136213. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136218. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136223. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0,
  136532. };
  136533. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136534. -0.5, 0.5,
  136535. };
  136536. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136537. 1, 0, 2,
  136538. };
  136539. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136540. _vq_quantthresh__44c0_sm_p1_0,
  136541. _vq_quantmap__44c0_sm_p1_0,
  136542. 3,
  136543. 3
  136544. };
  136545. static static_codebook _44c0_sm_p1_0 = {
  136546. 8, 6561,
  136547. _vq_lengthlist__44c0_sm_p1_0,
  136548. 1, -535822336, 1611661312, 2, 0,
  136549. _vq_quantlist__44c0_sm_p1_0,
  136550. NULL,
  136551. &_vq_auxt__44c0_sm_p1_0,
  136552. NULL,
  136553. 0
  136554. };
  136555. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136556. 2,
  136557. 1,
  136558. 3,
  136559. 0,
  136560. 4,
  136561. };
  136562. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136563. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  136603. };
  136604. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136605. -1.5, -0.5, 0.5, 1.5,
  136606. };
  136607. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136608. 3, 1, 0, 2, 4,
  136609. };
  136610. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136611. _vq_quantthresh__44c0_sm_p2_0,
  136612. _vq_quantmap__44c0_sm_p2_0,
  136613. 5,
  136614. 5
  136615. };
  136616. static static_codebook _44c0_sm_p2_0 = {
  136617. 4, 625,
  136618. _vq_lengthlist__44c0_sm_p2_0,
  136619. 1, -533725184, 1611661312, 3, 0,
  136620. _vq_quantlist__44c0_sm_p2_0,
  136621. NULL,
  136622. &_vq_auxt__44c0_sm_p2_0,
  136623. NULL,
  136624. 0
  136625. };
  136626. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136627. 4,
  136628. 3,
  136629. 5,
  136630. 2,
  136631. 6,
  136632. 1,
  136633. 7,
  136634. 0,
  136635. 8,
  136636. };
  136637. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136638. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136639. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136640. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136641. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136642. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0,
  136644. };
  136645. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136646. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136647. };
  136648. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136649. 7, 5, 3, 1, 0, 2, 4, 6,
  136650. 8,
  136651. };
  136652. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136653. _vq_quantthresh__44c0_sm_p3_0,
  136654. _vq_quantmap__44c0_sm_p3_0,
  136655. 9,
  136656. 9
  136657. };
  136658. static static_codebook _44c0_sm_p3_0 = {
  136659. 2, 81,
  136660. _vq_lengthlist__44c0_sm_p3_0,
  136661. 1, -531628032, 1611661312, 4, 0,
  136662. _vq_quantlist__44c0_sm_p3_0,
  136663. NULL,
  136664. &_vq_auxt__44c0_sm_p3_0,
  136665. NULL,
  136666. 0
  136667. };
  136668. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136669. 4,
  136670. 3,
  136671. 5,
  136672. 2,
  136673. 6,
  136674. 1,
  136675. 7,
  136676. 0,
  136677. 8,
  136678. };
  136679. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136680. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136681. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136682. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136683. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136684. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136685. 11,
  136686. };
  136687. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136688. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136689. };
  136690. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136691. 7, 5, 3, 1, 0, 2, 4, 6,
  136692. 8,
  136693. };
  136694. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136695. _vq_quantthresh__44c0_sm_p4_0,
  136696. _vq_quantmap__44c0_sm_p4_0,
  136697. 9,
  136698. 9
  136699. };
  136700. static static_codebook _44c0_sm_p4_0 = {
  136701. 2, 81,
  136702. _vq_lengthlist__44c0_sm_p4_0,
  136703. 1, -531628032, 1611661312, 4, 0,
  136704. _vq_quantlist__44c0_sm_p4_0,
  136705. NULL,
  136706. &_vq_auxt__44c0_sm_p4_0,
  136707. NULL,
  136708. 0
  136709. };
  136710. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136711. 8,
  136712. 7,
  136713. 9,
  136714. 6,
  136715. 10,
  136716. 5,
  136717. 11,
  136718. 4,
  136719. 12,
  136720. 3,
  136721. 13,
  136722. 2,
  136723. 14,
  136724. 1,
  136725. 15,
  136726. 0,
  136727. 16,
  136728. };
  136729. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136730. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136731. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136732. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136733. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136734. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136735. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136736. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136737. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136738. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136739. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136740. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136741. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136742. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136743. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136744. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136745. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136746. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136748. 14,
  136749. };
  136750. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136751. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136752. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136753. };
  136754. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136755. 15, 13, 11, 9, 7, 5, 3, 1,
  136756. 0, 2, 4, 6, 8, 10, 12, 14,
  136757. 16,
  136758. };
  136759. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136760. _vq_quantthresh__44c0_sm_p5_0,
  136761. _vq_quantmap__44c0_sm_p5_0,
  136762. 17,
  136763. 17
  136764. };
  136765. static static_codebook _44c0_sm_p5_0 = {
  136766. 2, 289,
  136767. _vq_lengthlist__44c0_sm_p5_0,
  136768. 1, -529530880, 1611661312, 5, 0,
  136769. _vq_quantlist__44c0_sm_p5_0,
  136770. NULL,
  136771. &_vq_auxt__44c0_sm_p5_0,
  136772. NULL,
  136773. 0
  136774. };
  136775. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136776. 1,
  136777. 0,
  136778. 2,
  136779. };
  136780. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136781. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136782. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136783. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136784. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136785. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136786. 11,
  136787. };
  136788. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136789. -5.5, 5.5,
  136790. };
  136791. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136792. 1, 0, 2,
  136793. };
  136794. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136795. _vq_quantthresh__44c0_sm_p6_0,
  136796. _vq_quantmap__44c0_sm_p6_0,
  136797. 3,
  136798. 3
  136799. };
  136800. static static_codebook _44c0_sm_p6_0 = {
  136801. 4, 81,
  136802. _vq_lengthlist__44c0_sm_p6_0,
  136803. 1, -529137664, 1618345984, 2, 0,
  136804. _vq_quantlist__44c0_sm_p6_0,
  136805. NULL,
  136806. &_vq_auxt__44c0_sm_p6_0,
  136807. NULL,
  136808. 0
  136809. };
  136810. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136811. 5,
  136812. 4,
  136813. 6,
  136814. 3,
  136815. 7,
  136816. 2,
  136817. 8,
  136818. 1,
  136819. 9,
  136820. 0,
  136821. 10,
  136822. };
  136823. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  136824. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  136825. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136826. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136827. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136828. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136829. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136830. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136831. 10,10,10, 8, 8, 8, 8, 8, 8,
  136832. };
  136833. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  136834. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136835. 3.5, 4.5,
  136836. };
  136837. static long _vq_quantmap__44c0_sm_p6_1[] = {
  136838. 9, 7, 5, 3, 1, 0, 2, 4,
  136839. 6, 8, 10,
  136840. };
  136841. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  136842. _vq_quantthresh__44c0_sm_p6_1,
  136843. _vq_quantmap__44c0_sm_p6_1,
  136844. 11,
  136845. 11
  136846. };
  136847. static static_codebook _44c0_sm_p6_1 = {
  136848. 2, 121,
  136849. _vq_lengthlist__44c0_sm_p6_1,
  136850. 1, -531365888, 1611661312, 4, 0,
  136851. _vq_quantlist__44c0_sm_p6_1,
  136852. NULL,
  136853. &_vq_auxt__44c0_sm_p6_1,
  136854. NULL,
  136855. 0
  136856. };
  136857. static long _vq_quantlist__44c0_sm_p7_0[] = {
  136858. 6,
  136859. 5,
  136860. 7,
  136861. 4,
  136862. 8,
  136863. 3,
  136864. 9,
  136865. 2,
  136866. 10,
  136867. 1,
  136868. 11,
  136869. 0,
  136870. 12,
  136871. };
  136872. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  136873. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136874. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  136875. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136876. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136877. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136878. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  136879. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136880. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136881. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136882. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  136883. 0,12,12,11,11,13,12,14,14,
  136884. };
  136885. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  136886. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136887. 12.5, 17.5, 22.5, 27.5,
  136888. };
  136889. static long _vq_quantmap__44c0_sm_p7_0[] = {
  136890. 11, 9, 7, 5, 3, 1, 0, 2,
  136891. 4, 6, 8, 10, 12,
  136892. };
  136893. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  136894. _vq_quantthresh__44c0_sm_p7_0,
  136895. _vq_quantmap__44c0_sm_p7_0,
  136896. 13,
  136897. 13
  136898. };
  136899. static static_codebook _44c0_sm_p7_0 = {
  136900. 2, 169,
  136901. _vq_lengthlist__44c0_sm_p7_0,
  136902. 1, -526516224, 1616117760, 4, 0,
  136903. _vq_quantlist__44c0_sm_p7_0,
  136904. NULL,
  136905. &_vq_auxt__44c0_sm_p7_0,
  136906. NULL,
  136907. 0
  136908. };
  136909. static long _vq_quantlist__44c0_sm_p7_1[] = {
  136910. 2,
  136911. 1,
  136912. 3,
  136913. 0,
  136914. 4,
  136915. };
  136916. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  136917. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136918. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136919. };
  136920. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  136921. -1.5, -0.5, 0.5, 1.5,
  136922. };
  136923. static long _vq_quantmap__44c0_sm_p7_1[] = {
  136924. 3, 1, 0, 2, 4,
  136925. };
  136926. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  136927. _vq_quantthresh__44c0_sm_p7_1,
  136928. _vq_quantmap__44c0_sm_p7_1,
  136929. 5,
  136930. 5
  136931. };
  136932. static static_codebook _44c0_sm_p7_1 = {
  136933. 2, 25,
  136934. _vq_lengthlist__44c0_sm_p7_1,
  136935. 1, -533725184, 1611661312, 3, 0,
  136936. _vq_quantlist__44c0_sm_p7_1,
  136937. NULL,
  136938. &_vq_auxt__44c0_sm_p7_1,
  136939. NULL,
  136940. 0
  136941. };
  136942. static long _vq_quantlist__44c0_sm_p8_0[] = {
  136943. 4,
  136944. 3,
  136945. 5,
  136946. 2,
  136947. 6,
  136948. 1,
  136949. 7,
  136950. 0,
  136951. 8,
  136952. };
  136953. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  136954. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  136955. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  136956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136957. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136958. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136959. 12,
  136960. };
  136961. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  136962. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136963. };
  136964. static long _vq_quantmap__44c0_sm_p8_0[] = {
  136965. 7, 5, 3, 1, 0, 2, 4, 6,
  136966. 8,
  136967. };
  136968. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  136969. _vq_quantthresh__44c0_sm_p8_0,
  136970. _vq_quantmap__44c0_sm_p8_0,
  136971. 9,
  136972. 9
  136973. };
  136974. static static_codebook _44c0_sm_p8_0 = {
  136975. 2, 81,
  136976. _vq_lengthlist__44c0_sm_p8_0,
  136977. 1, -516186112, 1627103232, 4, 0,
  136978. _vq_quantlist__44c0_sm_p8_0,
  136979. NULL,
  136980. &_vq_auxt__44c0_sm_p8_0,
  136981. NULL,
  136982. 0
  136983. };
  136984. static long _vq_quantlist__44c0_sm_p8_1[] = {
  136985. 6,
  136986. 5,
  136987. 7,
  136988. 4,
  136989. 8,
  136990. 3,
  136991. 9,
  136992. 2,
  136993. 10,
  136994. 1,
  136995. 11,
  136996. 0,
  136997. 12,
  136998. };
  136999. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137000. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137001. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137002. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137003. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137004. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137005. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137006. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137007. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137008. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137009. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137010. 20,13,13,12,12,16,13,15,13,
  137011. };
  137012. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137013. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137014. 42.5, 59.5, 76.5, 93.5,
  137015. };
  137016. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137017. 11, 9, 7, 5, 3, 1, 0, 2,
  137018. 4, 6, 8, 10, 12,
  137019. };
  137020. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137021. _vq_quantthresh__44c0_sm_p8_1,
  137022. _vq_quantmap__44c0_sm_p8_1,
  137023. 13,
  137024. 13
  137025. };
  137026. static static_codebook _44c0_sm_p8_1 = {
  137027. 2, 169,
  137028. _vq_lengthlist__44c0_sm_p8_1,
  137029. 1, -522616832, 1620115456, 4, 0,
  137030. _vq_quantlist__44c0_sm_p8_1,
  137031. NULL,
  137032. &_vq_auxt__44c0_sm_p8_1,
  137033. NULL,
  137034. 0
  137035. };
  137036. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137037. 8,
  137038. 7,
  137039. 9,
  137040. 6,
  137041. 10,
  137042. 5,
  137043. 11,
  137044. 4,
  137045. 12,
  137046. 3,
  137047. 13,
  137048. 2,
  137049. 14,
  137050. 1,
  137051. 15,
  137052. 0,
  137053. 16,
  137054. };
  137055. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137056. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137057. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137058. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137059. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137060. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137061. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137062. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137063. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137064. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137065. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137066. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137067. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137068. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137069. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137070. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137071. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137072. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137073. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137074. 9,
  137075. };
  137076. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137077. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137078. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137079. };
  137080. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137081. 15, 13, 11, 9, 7, 5, 3, 1,
  137082. 0, 2, 4, 6, 8, 10, 12, 14,
  137083. 16,
  137084. };
  137085. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137086. _vq_quantthresh__44c0_sm_p8_2,
  137087. _vq_quantmap__44c0_sm_p8_2,
  137088. 17,
  137089. 17
  137090. };
  137091. static static_codebook _44c0_sm_p8_2 = {
  137092. 2, 289,
  137093. _vq_lengthlist__44c0_sm_p8_2,
  137094. 1, -529530880, 1611661312, 5, 0,
  137095. _vq_quantlist__44c0_sm_p8_2,
  137096. NULL,
  137097. &_vq_auxt__44c0_sm_p8_2,
  137098. NULL,
  137099. 0
  137100. };
  137101. static long _huff_lengthlist__44c0_sm_short[] = {
  137102. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137103. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137104. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137105. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137106. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137107. 12,
  137108. };
  137109. static static_codebook _huff_book__44c0_sm_short = {
  137110. 2, 81,
  137111. _huff_lengthlist__44c0_sm_short,
  137112. 0, 0, 0, 0, 0,
  137113. NULL,
  137114. NULL,
  137115. NULL,
  137116. NULL,
  137117. 0
  137118. };
  137119. static long _huff_lengthlist__44c1_s_long[] = {
  137120. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137121. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137122. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137123. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137124. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137125. 11,
  137126. };
  137127. static static_codebook _huff_book__44c1_s_long = {
  137128. 2, 81,
  137129. _huff_lengthlist__44c1_s_long,
  137130. 0, 0, 0, 0, 0,
  137131. NULL,
  137132. NULL,
  137133. NULL,
  137134. NULL,
  137135. 0
  137136. };
  137137. static long _vq_quantlist__44c1_s_p1_0[] = {
  137138. 1,
  137139. 0,
  137140. 2,
  137141. };
  137142. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137143. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137144. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137149. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137154. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137189. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137194. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137199. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137235. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137240. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137245. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0,
  137554. };
  137555. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137556. -0.5, 0.5,
  137557. };
  137558. static long _vq_quantmap__44c1_s_p1_0[] = {
  137559. 1, 0, 2,
  137560. };
  137561. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137562. _vq_quantthresh__44c1_s_p1_0,
  137563. _vq_quantmap__44c1_s_p1_0,
  137564. 3,
  137565. 3
  137566. };
  137567. static static_codebook _44c1_s_p1_0 = {
  137568. 8, 6561,
  137569. _vq_lengthlist__44c1_s_p1_0,
  137570. 1, -535822336, 1611661312, 2, 0,
  137571. _vq_quantlist__44c1_s_p1_0,
  137572. NULL,
  137573. &_vq_auxt__44c1_s_p1_0,
  137574. NULL,
  137575. 0
  137576. };
  137577. static long _vq_quantlist__44c1_s_p2_0[] = {
  137578. 2,
  137579. 1,
  137580. 3,
  137581. 0,
  137582. 4,
  137583. };
  137584. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137585. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  137625. };
  137626. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137627. -1.5, -0.5, 0.5, 1.5,
  137628. };
  137629. static long _vq_quantmap__44c1_s_p2_0[] = {
  137630. 3, 1, 0, 2, 4,
  137631. };
  137632. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137633. _vq_quantthresh__44c1_s_p2_0,
  137634. _vq_quantmap__44c1_s_p2_0,
  137635. 5,
  137636. 5
  137637. };
  137638. static static_codebook _44c1_s_p2_0 = {
  137639. 4, 625,
  137640. _vq_lengthlist__44c1_s_p2_0,
  137641. 1, -533725184, 1611661312, 3, 0,
  137642. _vq_quantlist__44c1_s_p2_0,
  137643. NULL,
  137644. &_vq_auxt__44c1_s_p2_0,
  137645. NULL,
  137646. 0
  137647. };
  137648. static long _vq_quantlist__44c1_s_p3_0[] = {
  137649. 4,
  137650. 3,
  137651. 5,
  137652. 2,
  137653. 6,
  137654. 1,
  137655. 7,
  137656. 0,
  137657. 8,
  137658. };
  137659. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137660. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137661. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137662. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137663. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137664. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0,
  137666. };
  137667. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137668. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137669. };
  137670. static long _vq_quantmap__44c1_s_p3_0[] = {
  137671. 7, 5, 3, 1, 0, 2, 4, 6,
  137672. 8,
  137673. };
  137674. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137675. _vq_quantthresh__44c1_s_p3_0,
  137676. _vq_quantmap__44c1_s_p3_0,
  137677. 9,
  137678. 9
  137679. };
  137680. static static_codebook _44c1_s_p3_0 = {
  137681. 2, 81,
  137682. _vq_lengthlist__44c1_s_p3_0,
  137683. 1, -531628032, 1611661312, 4, 0,
  137684. _vq_quantlist__44c1_s_p3_0,
  137685. NULL,
  137686. &_vq_auxt__44c1_s_p3_0,
  137687. NULL,
  137688. 0
  137689. };
  137690. static long _vq_quantlist__44c1_s_p4_0[] = {
  137691. 4,
  137692. 3,
  137693. 5,
  137694. 2,
  137695. 6,
  137696. 1,
  137697. 7,
  137698. 0,
  137699. 8,
  137700. };
  137701. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137702. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137703. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137704. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137705. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137706. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137707. 11,
  137708. };
  137709. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137710. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137711. };
  137712. static long _vq_quantmap__44c1_s_p4_0[] = {
  137713. 7, 5, 3, 1, 0, 2, 4, 6,
  137714. 8,
  137715. };
  137716. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137717. _vq_quantthresh__44c1_s_p4_0,
  137718. _vq_quantmap__44c1_s_p4_0,
  137719. 9,
  137720. 9
  137721. };
  137722. static static_codebook _44c1_s_p4_0 = {
  137723. 2, 81,
  137724. _vq_lengthlist__44c1_s_p4_0,
  137725. 1, -531628032, 1611661312, 4, 0,
  137726. _vq_quantlist__44c1_s_p4_0,
  137727. NULL,
  137728. &_vq_auxt__44c1_s_p4_0,
  137729. NULL,
  137730. 0
  137731. };
  137732. static long _vq_quantlist__44c1_s_p5_0[] = {
  137733. 8,
  137734. 7,
  137735. 9,
  137736. 6,
  137737. 10,
  137738. 5,
  137739. 11,
  137740. 4,
  137741. 12,
  137742. 3,
  137743. 13,
  137744. 2,
  137745. 14,
  137746. 1,
  137747. 15,
  137748. 0,
  137749. 16,
  137750. };
  137751. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137752. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137753. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137754. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137755. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137756. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137757. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137758. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137759. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137760. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137761. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137762. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137763. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137764. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137765. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137766. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137767. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137768. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137770. 14,
  137771. };
  137772. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137773. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137774. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137775. };
  137776. static long _vq_quantmap__44c1_s_p5_0[] = {
  137777. 15, 13, 11, 9, 7, 5, 3, 1,
  137778. 0, 2, 4, 6, 8, 10, 12, 14,
  137779. 16,
  137780. };
  137781. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137782. _vq_quantthresh__44c1_s_p5_0,
  137783. _vq_quantmap__44c1_s_p5_0,
  137784. 17,
  137785. 17
  137786. };
  137787. static static_codebook _44c1_s_p5_0 = {
  137788. 2, 289,
  137789. _vq_lengthlist__44c1_s_p5_0,
  137790. 1, -529530880, 1611661312, 5, 0,
  137791. _vq_quantlist__44c1_s_p5_0,
  137792. NULL,
  137793. &_vq_auxt__44c1_s_p5_0,
  137794. NULL,
  137795. 0
  137796. };
  137797. static long _vq_quantlist__44c1_s_p6_0[] = {
  137798. 1,
  137799. 0,
  137800. 2,
  137801. };
  137802. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137803. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137804. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137805. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137806. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137807. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137808. 11,
  137809. };
  137810. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137811. -5.5, 5.5,
  137812. };
  137813. static long _vq_quantmap__44c1_s_p6_0[] = {
  137814. 1, 0, 2,
  137815. };
  137816. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137817. _vq_quantthresh__44c1_s_p6_0,
  137818. _vq_quantmap__44c1_s_p6_0,
  137819. 3,
  137820. 3
  137821. };
  137822. static static_codebook _44c1_s_p6_0 = {
  137823. 4, 81,
  137824. _vq_lengthlist__44c1_s_p6_0,
  137825. 1, -529137664, 1618345984, 2, 0,
  137826. _vq_quantlist__44c1_s_p6_0,
  137827. NULL,
  137828. &_vq_auxt__44c1_s_p6_0,
  137829. NULL,
  137830. 0
  137831. };
  137832. static long _vq_quantlist__44c1_s_p6_1[] = {
  137833. 5,
  137834. 4,
  137835. 6,
  137836. 3,
  137837. 7,
  137838. 2,
  137839. 8,
  137840. 1,
  137841. 9,
  137842. 0,
  137843. 10,
  137844. };
  137845. static long _vq_lengthlist__44c1_s_p6_1[] = {
  137846. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  137847. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  137848. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137849. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  137850. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  137851. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137852. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137853. 10,10,10, 8, 8, 8, 8, 8, 8,
  137854. };
  137855. static float _vq_quantthresh__44c1_s_p6_1[] = {
  137856. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137857. 3.5, 4.5,
  137858. };
  137859. static long _vq_quantmap__44c1_s_p6_1[] = {
  137860. 9, 7, 5, 3, 1, 0, 2, 4,
  137861. 6, 8, 10,
  137862. };
  137863. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  137864. _vq_quantthresh__44c1_s_p6_1,
  137865. _vq_quantmap__44c1_s_p6_1,
  137866. 11,
  137867. 11
  137868. };
  137869. static static_codebook _44c1_s_p6_1 = {
  137870. 2, 121,
  137871. _vq_lengthlist__44c1_s_p6_1,
  137872. 1, -531365888, 1611661312, 4, 0,
  137873. _vq_quantlist__44c1_s_p6_1,
  137874. NULL,
  137875. &_vq_auxt__44c1_s_p6_1,
  137876. NULL,
  137877. 0
  137878. };
  137879. static long _vq_quantlist__44c1_s_p7_0[] = {
  137880. 6,
  137881. 5,
  137882. 7,
  137883. 4,
  137884. 8,
  137885. 3,
  137886. 9,
  137887. 2,
  137888. 10,
  137889. 1,
  137890. 11,
  137891. 0,
  137892. 12,
  137893. };
  137894. static long _vq_lengthlist__44c1_s_p7_0[] = {
  137895. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  137896. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  137897. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137898. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137899. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  137900. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  137901. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  137902. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137903. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137904. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  137905. 0,12,11,11,11,13,10,14,13,
  137906. };
  137907. static float _vq_quantthresh__44c1_s_p7_0[] = {
  137908. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137909. 12.5, 17.5, 22.5, 27.5,
  137910. };
  137911. static long _vq_quantmap__44c1_s_p7_0[] = {
  137912. 11, 9, 7, 5, 3, 1, 0, 2,
  137913. 4, 6, 8, 10, 12,
  137914. };
  137915. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  137916. _vq_quantthresh__44c1_s_p7_0,
  137917. _vq_quantmap__44c1_s_p7_0,
  137918. 13,
  137919. 13
  137920. };
  137921. static static_codebook _44c1_s_p7_0 = {
  137922. 2, 169,
  137923. _vq_lengthlist__44c1_s_p7_0,
  137924. 1, -526516224, 1616117760, 4, 0,
  137925. _vq_quantlist__44c1_s_p7_0,
  137926. NULL,
  137927. &_vq_auxt__44c1_s_p7_0,
  137928. NULL,
  137929. 0
  137930. };
  137931. static long _vq_quantlist__44c1_s_p7_1[] = {
  137932. 2,
  137933. 1,
  137934. 3,
  137935. 0,
  137936. 4,
  137937. };
  137938. static long _vq_lengthlist__44c1_s_p7_1[] = {
  137939. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137940. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137941. };
  137942. static float _vq_quantthresh__44c1_s_p7_1[] = {
  137943. -1.5, -0.5, 0.5, 1.5,
  137944. };
  137945. static long _vq_quantmap__44c1_s_p7_1[] = {
  137946. 3, 1, 0, 2, 4,
  137947. };
  137948. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  137949. _vq_quantthresh__44c1_s_p7_1,
  137950. _vq_quantmap__44c1_s_p7_1,
  137951. 5,
  137952. 5
  137953. };
  137954. static static_codebook _44c1_s_p7_1 = {
  137955. 2, 25,
  137956. _vq_lengthlist__44c1_s_p7_1,
  137957. 1, -533725184, 1611661312, 3, 0,
  137958. _vq_quantlist__44c1_s_p7_1,
  137959. NULL,
  137960. &_vq_auxt__44c1_s_p7_1,
  137961. NULL,
  137962. 0
  137963. };
  137964. static long _vq_quantlist__44c1_s_p8_0[] = {
  137965. 6,
  137966. 5,
  137967. 7,
  137968. 4,
  137969. 8,
  137970. 3,
  137971. 9,
  137972. 2,
  137973. 10,
  137974. 1,
  137975. 11,
  137976. 0,
  137977. 12,
  137978. };
  137979. static long _vq_lengthlist__44c1_s_p8_0[] = {
  137980. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  137981. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  137982. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137983. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137984. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137985. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137986. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137987. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137988. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137989. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137990. 10,10,10,10,10,10,10,10,10,
  137991. };
  137992. static float _vq_quantthresh__44c1_s_p8_0[] = {
  137993. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  137994. 552.5, 773.5, 994.5, 1215.5,
  137995. };
  137996. static long _vq_quantmap__44c1_s_p8_0[] = {
  137997. 11, 9, 7, 5, 3, 1, 0, 2,
  137998. 4, 6, 8, 10, 12,
  137999. };
  138000. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138001. _vq_quantthresh__44c1_s_p8_0,
  138002. _vq_quantmap__44c1_s_p8_0,
  138003. 13,
  138004. 13
  138005. };
  138006. static static_codebook _44c1_s_p8_0 = {
  138007. 2, 169,
  138008. _vq_lengthlist__44c1_s_p8_0,
  138009. 1, -514541568, 1627103232, 4, 0,
  138010. _vq_quantlist__44c1_s_p8_0,
  138011. NULL,
  138012. &_vq_auxt__44c1_s_p8_0,
  138013. NULL,
  138014. 0
  138015. };
  138016. static long _vq_quantlist__44c1_s_p8_1[] = {
  138017. 6,
  138018. 5,
  138019. 7,
  138020. 4,
  138021. 8,
  138022. 3,
  138023. 9,
  138024. 2,
  138025. 10,
  138026. 1,
  138027. 11,
  138028. 0,
  138029. 12,
  138030. };
  138031. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138032. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138033. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138034. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138035. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138036. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138037. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138038. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138039. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138040. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138041. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138042. 16,13,12,12,11,14,12,15,13,
  138043. };
  138044. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138045. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138046. 42.5, 59.5, 76.5, 93.5,
  138047. };
  138048. static long _vq_quantmap__44c1_s_p8_1[] = {
  138049. 11, 9, 7, 5, 3, 1, 0, 2,
  138050. 4, 6, 8, 10, 12,
  138051. };
  138052. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138053. _vq_quantthresh__44c1_s_p8_1,
  138054. _vq_quantmap__44c1_s_p8_1,
  138055. 13,
  138056. 13
  138057. };
  138058. static static_codebook _44c1_s_p8_1 = {
  138059. 2, 169,
  138060. _vq_lengthlist__44c1_s_p8_1,
  138061. 1, -522616832, 1620115456, 4, 0,
  138062. _vq_quantlist__44c1_s_p8_1,
  138063. NULL,
  138064. &_vq_auxt__44c1_s_p8_1,
  138065. NULL,
  138066. 0
  138067. };
  138068. static long _vq_quantlist__44c1_s_p8_2[] = {
  138069. 8,
  138070. 7,
  138071. 9,
  138072. 6,
  138073. 10,
  138074. 5,
  138075. 11,
  138076. 4,
  138077. 12,
  138078. 3,
  138079. 13,
  138080. 2,
  138081. 14,
  138082. 1,
  138083. 15,
  138084. 0,
  138085. 16,
  138086. };
  138087. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138088. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138089. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138090. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138091. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138092. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138093. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138094. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138095. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138096. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138097. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138098. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138099. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138100. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138101. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138102. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138103. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138104. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138105. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138106. 9,
  138107. };
  138108. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138109. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138110. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138111. };
  138112. static long _vq_quantmap__44c1_s_p8_2[] = {
  138113. 15, 13, 11, 9, 7, 5, 3, 1,
  138114. 0, 2, 4, 6, 8, 10, 12, 14,
  138115. 16,
  138116. };
  138117. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138118. _vq_quantthresh__44c1_s_p8_2,
  138119. _vq_quantmap__44c1_s_p8_2,
  138120. 17,
  138121. 17
  138122. };
  138123. static static_codebook _44c1_s_p8_2 = {
  138124. 2, 289,
  138125. _vq_lengthlist__44c1_s_p8_2,
  138126. 1, -529530880, 1611661312, 5, 0,
  138127. _vq_quantlist__44c1_s_p8_2,
  138128. NULL,
  138129. &_vq_auxt__44c1_s_p8_2,
  138130. NULL,
  138131. 0
  138132. };
  138133. static long _huff_lengthlist__44c1_s_short[] = {
  138134. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138135. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138136. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138137. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138138. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138139. 11,
  138140. };
  138141. static static_codebook _huff_book__44c1_s_short = {
  138142. 2, 81,
  138143. _huff_lengthlist__44c1_s_short,
  138144. 0, 0, 0, 0, 0,
  138145. NULL,
  138146. NULL,
  138147. NULL,
  138148. NULL,
  138149. 0
  138150. };
  138151. static long _huff_lengthlist__44c1_sm_long[] = {
  138152. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138153. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138154. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138155. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138156. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138157. 11,
  138158. };
  138159. static static_codebook _huff_book__44c1_sm_long = {
  138160. 2, 81,
  138161. _huff_lengthlist__44c1_sm_long,
  138162. 0, 0, 0, 0, 0,
  138163. NULL,
  138164. NULL,
  138165. NULL,
  138166. NULL,
  138167. 0
  138168. };
  138169. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138170. 1,
  138171. 0,
  138172. 2,
  138173. };
  138174. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138175. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138176. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138181. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138186. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138221. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138226. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138231. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138267. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138272. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138277. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0,
  138586. };
  138587. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138588. -0.5, 0.5,
  138589. };
  138590. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138591. 1, 0, 2,
  138592. };
  138593. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138594. _vq_quantthresh__44c1_sm_p1_0,
  138595. _vq_quantmap__44c1_sm_p1_0,
  138596. 3,
  138597. 3
  138598. };
  138599. static static_codebook _44c1_sm_p1_0 = {
  138600. 8, 6561,
  138601. _vq_lengthlist__44c1_sm_p1_0,
  138602. 1, -535822336, 1611661312, 2, 0,
  138603. _vq_quantlist__44c1_sm_p1_0,
  138604. NULL,
  138605. &_vq_auxt__44c1_sm_p1_0,
  138606. NULL,
  138607. 0
  138608. };
  138609. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138610. 2,
  138611. 1,
  138612. 3,
  138613. 0,
  138614. 4,
  138615. };
  138616. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138617. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0,
  138657. };
  138658. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138659. -1.5, -0.5, 0.5, 1.5,
  138660. };
  138661. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138662. 3, 1, 0, 2, 4,
  138663. };
  138664. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138665. _vq_quantthresh__44c1_sm_p2_0,
  138666. _vq_quantmap__44c1_sm_p2_0,
  138667. 5,
  138668. 5
  138669. };
  138670. static static_codebook _44c1_sm_p2_0 = {
  138671. 4, 625,
  138672. _vq_lengthlist__44c1_sm_p2_0,
  138673. 1, -533725184, 1611661312, 3, 0,
  138674. _vq_quantlist__44c1_sm_p2_0,
  138675. NULL,
  138676. &_vq_auxt__44c1_sm_p2_0,
  138677. NULL,
  138678. 0
  138679. };
  138680. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138681. 4,
  138682. 3,
  138683. 5,
  138684. 2,
  138685. 6,
  138686. 1,
  138687. 7,
  138688. 0,
  138689. 8,
  138690. };
  138691. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138692. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138693. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138694. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138695. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138696. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0,
  138698. };
  138699. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138700. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138701. };
  138702. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138703. 7, 5, 3, 1, 0, 2, 4, 6,
  138704. 8,
  138705. };
  138706. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138707. _vq_quantthresh__44c1_sm_p3_0,
  138708. _vq_quantmap__44c1_sm_p3_0,
  138709. 9,
  138710. 9
  138711. };
  138712. static static_codebook _44c1_sm_p3_0 = {
  138713. 2, 81,
  138714. _vq_lengthlist__44c1_sm_p3_0,
  138715. 1, -531628032, 1611661312, 4, 0,
  138716. _vq_quantlist__44c1_sm_p3_0,
  138717. NULL,
  138718. &_vq_auxt__44c1_sm_p3_0,
  138719. NULL,
  138720. 0
  138721. };
  138722. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138723. 4,
  138724. 3,
  138725. 5,
  138726. 2,
  138727. 6,
  138728. 1,
  138729. 7,
  138730. 0,
  138731. 8,
  138732. };
  138733. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138734. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138735. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138736. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138737. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138738. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138739. 11,
  138740. };
  138741. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138742. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138743. };
  138744. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138745. 7, 5, 3, 1, 0, 2, 4, 6,
  138746. 8,
  138747. };
  138748. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138749. _vq_quantthresh__44c1_sm_p4_0,
  138750. _vq_quantmap__44c1_sm_p4_0,
  138751. 9,
  138752. 9
  138753. };
  138754. static static_codebook _44c1_sm_p4_0 = {
  138755. 2, 81,
  138756. _vq_lengthlist__44c1_sm_p4_0,
  138757. 1, -531628032, 1611661312, 4, 0,
  138758. _vq_quantlist__44c1_sm_p4_0,
  138759. NULL,
  138760. &_vq_auxt__44c1_sm_p4_0,
  138761. NULL,
  138762. 0
  138763. };
  138764. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138765. 8,
  138766. 7,
  138767. 9,
  138768. 6,
  138769. 10,
  138770. 5,
  138771. 11,
  138772. 4,
  138773. 12,
  138774. 3,
  138775. 13,
  138776. 2,
  138777. 14,
  138778. 1,
  138779. 15,
  138780. 0,
  138781. 16,
  138782. };
  138783. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138784. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138785. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138786. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138787. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138788. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138789. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138790. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138791. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138792. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138793. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138794. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138795. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138796. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138797. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138798. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138799. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138800. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138802. 14,
  138803. };
  138804. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138805. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138806. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138807. };
  138808. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138809. 15, 13, 11, 9, 7, 5, 3, 1,
  138810. 0, 2, 4, 6, 8, 10, 12, 14,
  138811. 16,
  138812. };
  138813. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138814. _vq_quantthresh__44c1_sm_p5_0,
  138815. _vq_quantmap__44c1_sm_p5_0,
  138816. 17,
  138817. 17
  138818. };
  138819. static static_codebook _44c1_sm_p5_0 = {
  138820. 2, 289,
  138821. _vq_lengthlist__44c1_sm_p5_0,
  138822. 1, -529530880, 1611661312, 5, 0,
  138823. _vq_quantlist__44c1_sm_p5_0,
  138824. NULL,
  138825. &_vq_auxt__44c1_sm_p5_0,
  138826. NULL,
  138827. 0
  138828. };
  138829. static long _vq_quantlist__44c1_sm_p6_0[] = {
  138830. 1,
  138831. 0,
  138832. 2,
  138833. };
  138834. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  138835. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138836. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138837. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  138838. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  138839. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  138840. 11,
  138841. };
  138842. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  138843. -5.5, 5.5,
  138844. };
  138845. static long _vq_quantmap__44c1_sm_p6_0[] = {
  138846. 1, 0, 2,
  138847. };
  138848. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  138849. _vq_quantthresh__44c1_sm_p6_0,
  138850. _vq_quantmap__44c1_sm_p6_0,
  138851. 3,
  138852. 3
  138853. };
  138854. static static_codebook _44c1_sm_p6_0 = {
  138855. 4, 81,
  138856. _vq_lengthlist__44c1_sm_p6_0,
  138857. 1, -529137664, 1618345984, 2, 0,
  138858. _vq_quantlist__44c1_sm_p6_0,
  138859. NULL,
  138860. &_vq_auxt__44c1_sm_p6_0,
  138861. NULL,
  138862. 0
  138863. };
  138864. static long _vq_quantlist__44c1_sm_p6_1[] = {
  138865. 5,
  138866. 4,
  138867. 6,
  138868. 3,
  138869. 7,
  138870. 2,
  138871. 8,
  138872. 1,
  138873. 9,
  138874. 0,
  138875. 10,
  138876. };
  138877. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  138878. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138879. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138880. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138881. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138882. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138883. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  138884. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138885. 10,10,10, 8, 8, 8, 8, 8, 8,
  138886. };
  138887. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  138888. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138889. 3.5, 4.5,
  138890. };
  138891. static long _vq_quantmap__44c1_sm_p6_1[] = {
  138892. 9, 7, 5, 3, 1, 0, 2, 4,
  138893. 6, 8, 10,
  138894. };
  138895. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  138896. _vq_quantthresh__44c1_sm_p6_1,
  138897. _vq_quantmap__44c1_sm_p6_1,
  138898. 11,
  138899. 11
  138900. };
  138901. static static_codebook _44c1_sm_p6_1 = {
  138902. 2, 121,
  138903. _vq_lengthlist__44c1_sm_p6_1,
  138904. 1, -531365888, 1611661312, 4, 0,
  138905. _vq_quantlist__44c1_sm_p6_1,
  138906. NULL,
  138907. &_vq_auxt__44c1_sm_p6_1,
  138908. NULL,
  138909. 0
  138910. };
  138911. static long _vq_quantlist__44c1_sm_p7_0[] = {
  138912. 6,
  138913. 5,
  138914. 7,
  138915. 4,
  138916. 8,
  138917. 3,
  138918. 9,
  138919. 2,
  138920. 10,
  138921. 1,
  138922. 11,
  138923. 0,
  138924. 12,
  138925. };
  138926. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  138927. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  138928. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  138929. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138930. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138931. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  138932. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  138933. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  138934. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138935. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138936. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  138937. 0,12,12,11,11,13,12,14,13,
  138938. };
  138939. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  138940. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138941. 12.5, 17.5, 22.5, 27.5,
  138942. };
  138943. static long _vq_quantmap__44c1_sm_p7_0[] = {
  138944. 11, 9, 7, 5, 3, 1, 0, 2,
  138945. 4, 6, 8, 10, 12,
  138946. };
  138947. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  138948. _vq_quantthresh__44c1_sm_p7_0,
  138949. _vq_quantmap__44c1_sm_p7_0,
  138950. 13,
  138951. 13
  138952. };
  138953. static static_codebook _44c1_sm_p7_0 = {
  138954. 2, 169,
  138955. _vq_lengthlist__44c1_sm_p7_0,
  138956. 1, -526516224, 1616117760, 4, 0,
  138957. _vq_quantlist__44c1_sm_p7_0,
  138958. NULL,
  138959. &_vq_auxt__44c1_sm_p7_0,
  138960. NULL,
  138961. 0
  138962. };
  138963. static long _vq_quantlist__44c1_sm_p7_1[] = {
  138964. 2,
  138965. 1,
  138966. 3,
  138967. 0,
  138968. 4,
  138969. };
  138970. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  138971. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138972. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138973. };
  138974. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  138975. -1.5, -0.5, 0.5, 1.5,
  138976. };
  138977. static long _vq_quantmap__44c1_sm_p7_1[] = {
  138978. 3, 1, 0, 2, 4,
  138979. };
  138980. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  138981. _vq_quantthresh__44c1_sm_p7_1,
  138982. _vq_quantmap__44c1_sm_p7_1,
  138983. 5,
  138984. 5
  138985. };
  138986. static static_codebook _44c1_sm_p7_1 = {
  138987. 2, 25,
  138988. _vq_lengthlist__44c1_sm_p7_1,
  138989. 1, -533725184, 1611661312, 3, 0,
  138990. _vq_quantlist__44c1_sm_p7_1,
  138991. NULL,
  138992. &_vq_auxt__44c1_sm_p7_1,
  138993. NULL,
  138994. 0
  138995. };
  138996. static long _vq_quantlist__44c1_sm_p8_0[] = {
  138997. 6,
  138998. 5,
  138999. 7,
  139000. 4,
  139001. 8,
  139002. 3,
  139003. 9,
  139004. 2,
  139005. 10,
  139006. 1,
  139007. 11,
  139008. 0,
  139009. 12,
  139010. };
  139011. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139012. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139013. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139014. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139015. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139016. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139017. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139018. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139019. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139020. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139021. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139022. 13,13,13,13,13,13,13,13,13,
  139023. };
  139024. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139025. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139026. 552.5, 773.5, 994.5, 1215.5,
  139027. };
  139028. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139029. 11, 9, 7, 5, 3, 1, 0, 2,
  139030. 4, 6, 8, 10, 12,
  139031. };
  139032. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139033. _vq_quantthresh__44c1_sm_p8_0,
  139034. _vq_quantmap__44c1_sm_p8_0,
  139035. 13,
  139036. 13
  139037. };
  139038. static static_codebook _44c1_sm_p8_0 = {
  139039. 2, 169,
  139040. _vq_lengthlist__44c1_sm_p8_0,
  139041. 1, -514541568, 1627103232, 4, 0,
  139042. _vq_quantlist__44c1_sm_p8_0,
  139043. NULL,
  139044. &_vq_auxt__44c1_sm_p8_0,
  139045. NULL,
  139046. 0
  139047. };
  139048. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139049. 6,
  139050. 5,
  139051. 7,
  139052. 4,
  139053. 8,
  139054. 3,
  139055. 9,
  139056. 2,
  139057. 10,
  139058. 1,
  139059. 11,
  139060. 0,
  139061. 12,
  139062. };
  139063. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139064. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139065. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139066. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139067. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139068. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139069. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139070. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139071. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139072. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139073. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139074. 20,13,12,12,12,14,12,14,13,
  139075. };
  139076. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139077. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139078. 42.5, 59.5, 76.5, 93.5,
  139079. };
  139080. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139081. 11, 9, 7, 5, 3, 1, 0, 2,
  139082. 4, 6, 8, 10, 12,
  139083. };
  139084. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139085. _vq_quantthresh__44c1_sm_p8_1,
  139086. _vq_quantmap__44c1_sm_p8_1,
  139087. 13,
  139088. 13
  139089. };
  139090. static static_codebook _44c1_sm_p8_1 = {
  139091. 2, 169,
  139092. _vq_lengthlist__44c1_sm_p8_1,
  139093. 1, -522616832, 1620115456, 4, 0,
  139094. _vq_quantlist__44c1_sm_p8_1,
  139095. NULL,
  139096. &_vq_auxt__44c1_sm_p8_1,
  139097. NULL,
  139098. 0
  139099. };
  139100. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139101. 8,
  139102. 7,
  139103. 9,
  139104. 6,
  139105. 10,
  139106. 5,
  139107. 11,
  139108. 4,
  139109. 12,
  139110. 3,
  139111. 13,
  139112. 2,
  139113. 14,
  139114. 1,
  139115. 15,
  139116. 0,
  139117. 16,
  139118. };
  139119. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139120. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139121. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139122. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139123. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139124. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139125. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139126. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139127. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139128. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139129. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139130. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139131. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139132. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139133. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139134. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139135. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139136. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139137. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139138. 9,
  139139. };
  139140. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139141. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139142. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139143. };
  139144. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139145. 15, 13, 11, 9, 7, 5, 3, 1,
  139146. 0, 2, 4, 6, 8, 10, 12, 14,
  139147. 16,
  139148. };
  139149. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139150. _vq_quantthresh__44c1_sm_p8_2,
  139151. _vq_quantmap__44c1_sm_p8_2,
  139152. 17,
  139153. 17
  139154. };
  139155. static static_codebook _44c1_sm_p8_2 = {
  139156. 2, 289,
  139157. _vq_lengthlist__44c1_sm_p8_2,
  139158. 1, -529530880, 1611661312, 5, 0,
  139159. _vq_quantlist__44c1_sm_p8_2,
  139160. NULL,
  139161. &_vq_auxt__44c1_sm_p8_2,
  139162. NULL,
  139163. 0
  139164. };
  139165. static long _huff_lengthlist__44c1_sm_short[] = {
  139166. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139167. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139168. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139169. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139170. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139171. 11,
  139172. };
  139173. static static_codebook _huff_book__44c1_sm_short = {
  139174. 2, 81,
  139175. _huff_lengthlist__44c1_sm_short,
  139176. 0, 0, 0, 0, 0,
  139177. NULL,
  139178. NULL,
  139179. NULL,
  139180. NULL,
  139181. 0
  139182. };
  139183. static long _huff_lengthlist__44cn1_s_long[] = {
  139184. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139185. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139186. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139187. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139188. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139189. 20,
  139190. };
  139191. static static_codebook _huff_book__44cn1_s_long = {
  139192. 2, 81,
  139193. _huff_lengthlist__44cn1_s_long,
  139194. 0, 0, 0, 0, 0,
  139195. NULL,
  139196. NULL,
  139197. NULL,
  139198. NULL,
  139199. 0
  139200. };
  139201. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139202. 1,
  139203. 0,
  139204. 2,
  139205. };
  139206. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139207. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139208. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139213. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139218. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139253. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139258. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139263. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139299. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139304. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139309. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0,
  139618. };
  139619. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139620. -0.5, 0.5,
  139621. };
  139622. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139623. 1, 0, 2,
  139624. };
  139625. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139626. _vq_quantthresh__44cn1_s_p1_0,
  139627. _vq_quantmap__44cn1_s_p1_0,
  139628. 3,
  139629. 3
  139630. };
  139631. static static_codebook _44cn1_s_p1_0 = {
  139632. 8, 6561,
  139633. _vq_lengthlist__44cn1_s_p1_0,
  139634. 1, -535822336, 1611661312, 2, 0,
  139635. _vq_quantlist__44cn1_s_p1_0,
  139636. NULL,
  139637. &_vq_auxt__44cn1_s_p1_0,
  139638. NULL,
  139639. 0
  139640. };
  139641. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139642. 2,
  139643. 1,
  139644. 3,
  139645. 0,
  139646. 4,
  139647. };
  139648. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139649. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0,
  139689. };
  139690. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139691. -1.5, -0.5, 0.5, 1.5,
  139692. };
  139693. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139694. 3, 1, 0, 2, 4,
  139695. };
  139696. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139697. _vq_quantthresh__44cn1_s_p2_0,
  139698. _vq_quantmap__44cn1_s_p2_0,
  139699. 5,
  139700. 5
  139701. };
  139702. static static_codebook _44cn1_s_p2_0 = {
  139703. 4, 625,
  139704. _vq_lengthlist__44cn1_s_p2_0,
  139705. 1, -533725184, 1611661312, 3, 0,
  139706. _vq_quantlist__44cn1_s_p2_0,
  139707. NULL,
  139708. &_vq_auxt__44cn1_s_p2_0,
  139709. NULL,
  139710. 0
  139711. };
  139712. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139713. 4,
  139714. 3,
  139715. 5,
  139716. 2,
  139717. 6,
  139718. 1,
  139719. 7,
  139720. 0,
  139721. 8,
  139722. };
  139723. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139724. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139725. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139726. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139727. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139728. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0,
  139730. };
  139731. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139732. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139733. };
  139734. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139735. 7, 5, 3, 1, 0, 2, 4, 6,
  139736. 8,
  139737. };
  139738. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139739. _vq_quantthresh__44cn1_s_p3_0,
  139740. _vq_quantmap__44cn1_s_p3_0,
  139741. 9,
  139742. 9
  139743. };
  139744. static static_codebook _44cn1_s_p3_0 = {
  139745. 2, 81,
  139746. _vq_lengthlist__44cn1_s_p3_0,
  139747. 1, -531628032, 1611661312, 4, 0,
  139748. _vq_quantlist__44cn1_s_p3_0,
  139749. NULL,
  139750. &_vq_auxt__44cn1_s_p3_0,
  139751. NULL,
  139752. 0
  139753. };
  139754. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139755. 4,
  139756. 3,
  139757. 5,
  139758. 2,
  139759. 6,
  139760. 1,
  139761. 7,
  139762. 0,
  139763. 8,
  139764. };
  139765. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139766. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139767. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139768. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139769. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139770. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139771. 11,
  139772. };
  139773. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139774. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139775. };
  139776. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139777. 7, 5, 3, 1, 0, 2, 4, 6,
  139778. 8,
  139779. };
  139780. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139781. _vq_quantthresh__44cn1_s_p4_0,
  139782. _vq_quantmap__44cn1_s_p4_0,
  139783. 9,
  139784. 9
  139785. };
  139786. static static_codebook _44cn1_s_p4_0 = {
  139787. 2, 81,
  139788. _vq_lengthlist__44cn1_s_p4_0,
  139789. 1, -531628032, 1611661312, 4, 0,
  139790. _vq_quantlist__44cn1_s_p4_0,
  139791. NULL,
  139792. &_vq_auxt__44cn1_s_p4_0,
  139793. NULL,
  139794. 0
  139795. };
  139796. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139797. 8,
  139798. 7,
  139799. 9,
  139800. 6,
  139801. 10,
  139802. 5,
  139803. 11,
  139804. 4,
  139805. 12,
  139806. 3,
  139807. 13,
  139808. 2,
  139809. 14,
  139810. 1,
  139811. 15,
  139812. 0,
  139813. 16,
  139814. };
  139815. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139816. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139817. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139818. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139819. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139820. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139821. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  139822. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  139823. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  139824. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139825. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  139826. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139827. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139828. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  139829. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139830. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  139831. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  139832. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  139834. 14,
  139835. };
  139836. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  139837. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139838. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139839. };
  139840. static long _vq_quantmap__44cn1_s_p5_0[] = {
  139841. 15, 13, 11, 9, 7, 5, 3, 1,
  139842. 0, 2, 4, 6, 8, 10, 12, 14,
  139843. 16,
  139844. };
  139845. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  139846. _vq_quantthresh__44cn1_s_p5_0,
  139847. _vq_quantmap__44cn1_s_p5_0,
  139848. 17,
  139849. 17
  139850. };
  139851. static static_codebook _44cn1_s_p5_0 = {
  139852. 2, 289,
  139853. _vq_lengthlist__44cn1_s_p5_0,
  139854. 1, -529530880, 1611661312, 5, 0,
  139855. _vq_quantlist__44cn1_s_p5_0,
  139856. NULL,
  139857. &_vq_auxt__44cn1_s_p5_0,
  139858. NULL,
  139859. 0
  139860. };
  139861. static long _vq_quantlist__44cn1_s_p6_0[] = {
  139862. 1,
  139863. 0,
  139864. 2,
  139865. };
  139866. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  139867. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  139868. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  139869. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  139870. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  139871. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  139872. 10,
  139873. };
  139874. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  139875. -5.5, 5.5,
  139876. };
  139877. static long _vq_quantmap__44cn1_s_p6_0[] = {
  139878. 1, 0, 2,
  139879. };
  139880. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  139881. _vq_quantthresh__44cn1_s_p6_0,
  139882. _vq_quantmap__44cn1_s_p6_0,
  139883. 3,
  139884. 3
  139885. };
  139886. static static_codebook _44cn1_s_p6_0 = {
  139887. 4, 81,
  139888. _vq_lengthlist__44cn1_s_p6_0,
  139889. 1, -529137664, 1618345984, 2, 0,
  139890. _vq_quantlist__44cn1_s_p6_0,
  139891. NULL,
  139892. &_vq_auxt__44cn1_s_p6_0,
  139893. NULL,
  139894. 0
  139895. };
  139896. static long _vq_quantlist__44cn1_s_p6_1[] = {
  139897. 5,
  139898. 4,
  139899. 6,
  139900. 3,
  139901. 7,
  139902. 2,
  139903. 8,
  139904. 1,
  139905. 9,
  139906. 0,
  139907. 10,
  139908. };
  139909. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  139910. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  139911. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  139912. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139913. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  139914. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  139915. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  139916. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  139917. 10,10,10, 9, 9, 9, 9, 9, 9,
  139918. };
  139919. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  139920. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139921. 3.5, 4.5,
  139922. };
  139923. static long _vq_quantmap__44cn1_s_p6_1[] = {
  139924. 9, 7, 5, 3, 1, 0, 2, 4,
  139925. 6, 8, 10,
  139926. };
  139927. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  139928. _vq_quantthresh__44cn1_s_p6_1,
  139929. _vq_quantmap__44cn1_s_p6_1,
  139930. 11,
  139931. 11
  139932. };
  139933. static static_codebook _44cn1_s_p6_1 = {
  139934. 2, 121,
  139935. _vq_lengthlist__44cn1_s_p6_1,
  139936. 1, -531365888, 1611661312, 4, 0,
  139937. _vq_quantlist__44cn1_s_p6_1,
  139938. NULL,
  139939. &_vq_auxt__44cn1_s_p6_1,
  139940. NULL,
  139941. 0
  139942. };
  139943. static long _vq_quantlist__44cn1_s_p7_0[] = {
  139944. 6,
  139945. 5,
  139946. 7,
  139947. 4,
  139948. 8,
  139949. 3,
  139950. 9,
  139951. 2,
  139952. 10,
  139953. 1,
  139954. 11,
  139955. 0,
  139956. 12,
  139957. };
  139958. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  139959. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  139960. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  139961. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139962. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139963. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  139964. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  139965. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  139966. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  139967. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  139968. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  139969. 0,13,13,12,12,13,13,13,14,
  139970. };
  139971. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  139972. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139973. 12.5, 17.5, 22.5, 27.5,
  139974. };
  139975. static long _vq_quantmap__44cn1_s_p7_0[] = {
  139976. 11, 9, 7, 5, 3, 1, 0, 2,
  139977. 4, 6, 8, 10, 12,
  139978. };
  139979. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  139980. _vq_quantthresh__44cn1_s_p7_0,
  139981. _vq_quantmap__44cn1_s_p7_0,
  139982. 13,
  139983. 13
  139984. };
  139985. static static_codebook _44cn1_s_p7_0 = {
  139986. 2, 169,
  139987. _vq_lengthlist__44cn1_s_p7_0,
  139988. 1, -526516224, 1616117760, 4, 0,
  139989. _vq_quantlist__44cn1_s_p7_0,
  139990. NULL,
  139991. &_vq_auxt__44cn1_s_p7_0,
  139992. NULL,
  139993. 0
  139994. };
  139995. static long _vq_quantlist__44cn1_s_p7_1[] = {
  139996. 2,
  139997. 1,
  139998. 3,
  139999. 0,
  140000. 4,
  140001. };
  140002. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140003. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140004. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140005. };
  140006. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140007. -1.5, -0.5, 0.5, 1.5,
  140008. };
  140009. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140010. 3, 1, 0, 2, 4,
  140011. };
  140012. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140013. _vq_quantthresh__44cn1_s_p7_1,
  140014. _vq_quantmap__44cn1_s_p7_1,
  140015. 5,
  140016. 5
  140017. };
  140018. static static_codebook _44cn1_s_p7_1 = {
  140019. 2, 25,
  140020. _vq_lengthlist__44cn1_s_p7_1,
  140021. 1, -533725184, 1611661312, 3, 0,
  140022. _vq_quantlist__44cn1_s_p7_1,
  140023. NULL,
  140024. &_vq_auxt__44cn1_s_p7_1,
  140025. NULL,
  140026. 0
  140027. };
  140028. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140029. 2,
  140030. 1,
  140031. 3,
  140032. 0,
  140033. 4,
  140034. };
  140035. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140036. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140037. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140039. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140043. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140045. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140051. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140058. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140065. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140066. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140068. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140069. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140070. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140071. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140072. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140073. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140074. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140075. 12,
  140076. };
  140077. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140078. -331.5, -110.5, 110.5, 331.5,
  140079. };
  140080. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140081. 3, 1, 0, 2, 4,
  140082. };
  140083. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140084. _vq_quantthresh__44cn1_s_p8_0,
  140085. _vq_quantmap__44cn1_s_p8_0,
  140086. 5,
  140087. 5
  140088. };
  140089. static static_codebook _44cn1_s_p8_0 = {
  140090. 4, 625,
  140091. _vq_lengthlist__44cn1_s_p8_0,
  140092. 1, -518283264, 1627103232, 3, 0,
  140093. _vq_quantlist__44cn1_s_p8_0,
  140094. NULL,
  140095. &_vq_auxt__44cn1_s_p8_0,
  140096. NULL,
  140097. 0
  140098. };
  140099. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140100. 6,
  140101. 5,
  140102. 7,
  140103. 4,
  140104. 8,
  140105. 3,
  140106. 9,
  140107. 2,
  140108. 10,
  140109. 1,
  140110. 11,
  140111. 0,
  140112. 12,
  140113. };
  140114. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140115. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140116. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140117. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140118. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140119. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140120. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140121. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140122. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140123. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140124. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140125. 15,12,12,11,11,14,12,13,14,
  140126. };
  140127. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140128. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140129. 42.5, 59.5, 76.5, 93.5,
  140130. };
  140131. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140132. 11, 9, 7, 5, 3, 1, 0, 2,
  140133. 4, 6, 8, 10, 12,
  140134. };
  140135. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140136. _vq_quantthresh__44cn1_s_p8_1,
  140137. _vq_quantmap__44cn1_s_p8_1,
  140138. 13,
  140139. 13
  140140. };
  140141. static static_codebook _44cn1_s_p8_1 = {
  140142. 2, 169,
  140143. _vq_lengthlist__44cn1_s_p8_1,
  140144. 1, -522616832, 1620115456, 4, 0,
  140145. _vq_quantlist__44cn1_s_p8_1,
  140146. NULL,
  140147. &_vq_auxt__44cn1_s_p8_1,
  140148. NULL,
  140149. 0
  140150. };
  140151. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140152. 8,
  140153. 7,
  140154. 9,
  140155. 6,
  140156. 10,
  140157. 5,
  140158. 11,
  140159. 4,
  140160. 12,
  140161. 3,
  140162. 13,
  140163. 2,
  140164. 14,
  140165. 1,
  140166. 15,
  140167. 0,
  140168. 16,
  140169. };
  140170. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140171. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140172. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140173. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140174. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140175. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140176. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140177. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140178. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140179. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140180. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140181. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140182. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140183. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140184. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140185. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140186. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140187. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140188. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140189. 9,
  140190. };
  140191. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140192. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140193. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140194. };
  140195. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140196. 15, 13, 11, 9, 7, 5, 3, 1,
  140197. 0, 2, 4, 6, 8, 10, 12, 14,
  140198. 16,
  140199. };
  140200. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140201. _vq_quantthresh__44cn1_s_p8_2,
  140202. _vq_quantmap__44cn1_s_p8_2,
  140203. 17,
  140204. 17
  140205. };
  140206. static static_codebook _44cn1_s_p8_2 = {
  140207. 2, 289,
  140208. _vq_lengthlist__44cn1_s_p8_2,
  140209. 1, -529530880, 1611661312, 5, 0,
  140210. _vq_quantlist__44cn1_s_p8_2,
  140211. NULL,
  140212. &_vq_auxt__44cn1_s_p8_2,
  140213. NULL,
  140214. 0
  140215. };
  140216. static long _huff_lengthlist__44cn1_s_short[] = {
  140217. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140218. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140219. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140220. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140221. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140222. 10,
  140223. };
  140224. static static_codebook _huff_book__44cn1_s_short = {
  140225. 2, 81,
  140226. _huff_lengthlist__44cn1_s_short,
  140227. 0, 0, 0, 0, 0,
  140228. NULL,
  140229. NULL,
  140230. NULL,
  140231. NULL,
  140232. 0
  140233. };
  140234. static long _huff_lengthlist__44cn1_sm_long[] = {
  140235. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140236. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140237. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140238. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140239. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140240. 17,
  140241. };
  140242. static static_codebook _huff_book__44cn1_sm_long = {
  140243. 2, 81,
  140244. _huff_lengthlist__44cn1_sm_long,
  140245. 0, 0, 0, 0, 0,
  140246. NULL,
  140247. NULL,
  140248. NULL,
  140249. NULL,
  140250. 0
  140251. };
  140252. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140253. 1,
  140254. 0,
  140255. 2,
  140256. };
  140257. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140258. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140259. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140264. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140269. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140304. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140309. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140314. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140350. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140355. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140360. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0,
  140669. };
  140670. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140671. -0.5, 0.5,
  140672. };
  140673. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140674. 1, 0, 2,
  140675. };
  140676. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140677. _vq_quantthresh__44cn1_sm_p1_0,
  140678. _vq_quantmap__44cn1_sm_p1_0,
  140679. 3,
  140680. 3
  140681. };
  140682. static static_codebook _44cn1_sm_p1_0 = {
  140683. 8, 6561,
  140684. _vq_lengthlist__44cn1_sm_p1_0,
  140685. 1, -535822336, 1611661312, 2, 0,
  140686. _vq_quantlist__44cn1_sm_p1_0,
  140687. NULL,
  140688. &_vq_auxt__44cn1_sm_p1_0,
  140689. NULL,
  140690. 0
  140691. };
  140692. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140693. 2,
  140694. 1,
  140695. 3,
  140696. 0,
  140697. 4,
  140698. };
  140699. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140700. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0,
  140740. };
  140741. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140742. -1.5, -0.5, 0.5, 1.5,
  140743. };
  140744. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140745. 3, 1, 0, 2, 4,
  140746. };
  140747. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140748. _vq_quantthresh__44cn1_sm_p2_0,
  140749. _vq_quantmap__44cn1_sm_p2_0,
  140750. 5,
  140751. 5
  140752. };
  140753. static static_codebook _44cn1_sm_p2_0 = {
  140754. 4, 625,
  140755. _vq_lengthlist__44cn1_sm_p2_0,
  140756. 1, -533725184, 1611661312, 3, 0,
  140757. _vq_quantlist__44cn1_sm_p2_0,
  140758. NULL,
  140759. &_vq_auxt__44cn1_sm_p2_0,
  140760. NULL,
  140761. 0
  140762. };
  140763. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140764. 4,
  140765. 3,
  140766. 5,
  140767. 2,
  140768. 6,
  140769. 1,
  140770. 7,
  140771. 0,
  140772. 8,
  140773. };
  140774. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140775. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140776. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140777. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140778. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140779. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0,
  140781. };
  140782. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140783. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140784. };
  140785. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140786. 7, 5, 3, 1, 0, 2, 4, 6,
  140787. 8,
  140788. };
  140789. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140790. _vq_quantthresh__44cn1_sm_p3_0,
  140791. _vq_quantmap__44cn1_sm_p3_0,
  140792. 9,
  140793. 9
  140794. };
  140795. static static_codebook _44cn1_sm_p3_0 = {
  140796. 2, 81,
  140797. _vq_lengthlist__44cn1_sm_p3_0,
  140798. 1, -531628032, 1611661312, 4, 0,
  140799. _vq_quantlist__44cn1_sm_p3_0,
  140800. NULL,
  140801. &_vq_auxt__44cn1_sm_p3_0,
  140802. NULL,
  140803. 0
  140804. };
  140805. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140806. 4,
  140807. 3,
  140808. 5,
  140809. 2,
  140810. 6,
  140811. 1,
  140812. 7,
  140813. 0,
  140814. 8,
  140815. };
  140816. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140817. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140818. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140819. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140820. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140821. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140822. 11,
  140823. };
  140824. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  140825. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140826. };
  140827. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  140828. 7, 5, 3, 1, 0, 2, 4, 6,
  140829. 8,
  140830. };
  140831. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  140832. _vq_quantthresh__44cn1_sm_p4_0,
  140833. _vq_quantmap__44cn1_sm_p4_0,
  140834. 9,
  140835. 9
  140836. };
  140837. static static_codebook _44cn1_sm_p4_0 = {
  140838. 2, 81,
  140839. _vq_lengthlist__44cn1_sm_p4_0,
  140840. 1, -531628032, 1611661312, 4, 0,
  140841. _vq_quantlist__44cn1_sm_p4_0,
  140842. NULL,
  140843. &_vq_auxt__44cn1_sm_p4_0,
  140844. NULL,
  140845. 0
  140846. };
  140847. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  140848. 8,
  140849. 7,
  140850. 9,
  140851. 6,
  140852. 10,
  140853. 5,
  140854. 11,
  140855. 4,
  140856. 12,
  140857. 3,
  140858. 13,
  140859. 2,
  140860. 14,
  140861. 1,
  140862. 15,
  140863. 0,
  140864. 16,
  140865. };
  140866. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  140867. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  140868. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140869. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140870. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140871. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  140872. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  140873. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  140874. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  140875. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  140876. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  140877. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  140878. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  140879. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  140880. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  140881. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  140882. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  140883. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  140885. 14,
  140886. };
  140887. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  140888. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140889. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140890. };
  140891. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  140892. 15, 13, 11, 9, 7, 5, 3, 1,
  140893. 0, 2, 4, 6, 8, 10, 12, 14,
  140894. 16,
  140895. };
  140896. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  140897. _vq_quantthresh__44cn1_sm_p5_0,
  140898. _vq_quantmap__44cn1_sm_p5_0,
  140899. 17,
  140900. 17
  140901. };
  140902. static static_codebook _44cn1_sm_p5_0 = {
  140903. 2, 289,
  140904. _vq_lengthlist__44cn1_sm_p5_0,
  140905. 1, -529530880, 1611661312, 5, 0,
  140906. _vq_quantlist__44cn1_sm_p5_0,
  140907. NULL,
  140908. &_vq_auxt__44cn1_sm_p5_0,
  140909. NULL,
  140910. 0
  140911. };
  140912. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  140913. 1,
  140914. 0,
  140915. 2,
  140916. };
  140917. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  140918. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  140919. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  140920. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  140921. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  140922. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  140923. 10,
  140924. };
  140925. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  140926. -5.5, 5.5,
  140927. };
  140928. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  140929. 1, 0, 2,
  140930. };
  140931. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  140932. _vq_quantthresh__44cn1_sm_p6_0,
  140933. _vq_quantmap__44cn1_sm_p6_0,
  140934. 3,
  140935. 3
  140936. };
  140937. static static_codebook _44cn1_sm_p6_0 = {
  140938. 4, 81,
  140939. _vq_lengthlist__44cn1_sm_p6_0,
  140940. 1, -529137664, 1618345984, 2, 0,
  140941. _vq_quantlist__44cn1_sm_p6_0,
  140942. NULL,
  140943. &_vq_auxt__44cn1_sm_p6_0,
  140944. NULL,
  140945. 0
  140946. };
  140947. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  140948. 5,
  140949. 4,
  140950. 6,
  140951. 3,
  140952. 7,
  140953. 2,
  140954. 8,
  140955. 1,
  140956. 9,
  140957. 0,
  140958. 10,
  140959. };
  140960. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  140961. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  140962. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  140963. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140964. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  140965. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  140966. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  140967. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  140968. 10,10,10, 8, 9, 8, 8, 9, 8,
  140969. };
  140970. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  140971. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140972. 3.5, 4.5,
  140973. };
  140974. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  140975. 9, 7, 5, 3, 1, 0, 2, 4,
  140976. 6, 8, 10,
  140977. };
  140978. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  140979. _vq_quantthresh__44cn1_sm_p6_1,
  140980. _vq_quantmap__44cn1_sm_p6_1,
  140981. 11,
  140982. 11
  140983. };
  140984. static static_codebook _44cn1_sm_p6_1 = {
  140985. 2, 121,
  140986. _vq_lengthlist__44cn1_sm_p6_1,
  140987. 1, -531365888, 1611661312, 4, 0,
  140988. _vq_quantlist__44cn1_sm_p6_1,
  140989. NULL,
  140990. &_vq_auxt__44cn1_sm_p6_1,
  140991. NULL,
  140992. 0
  140993. };
  140994. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  140995. 6,
  140996. 5,
  140997. 7,
  140998. 4,
  140999. 8,
  141000. 3,
  141001. 9,
  141002. 2,
  141003. 10,
  141004. 1,
  141005. 11,
  141006. 0,
  141007. 12,
  141008. };
  141009. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141010. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141011. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141012. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141013. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141014. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141015. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141016. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141017. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141018. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141019. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141020. 0,13,12,12,12,13,13,13,14,
  141021. };
  141022. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141023. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141024. 12.5, 17.5, 22.5, 27.5,
  141025. };
  141026. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141027. 11, 9, 7, 5, 3, 1, 0, 2,
  141028. 4, 6, 8, 10, 12,
  141029. };
  141030. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141031. _vq_quantthresh__44cn1_sm_p7_0,
  141032. _vq_quantmap__44cn1_sm_p7_0,
  141033. 13,
  141034. 13
  141035. };
  141036. static static_codebook _44cn1_sm_p7_0 = {
  141037. 2, 169,
  141038. _vq_lengthlist__44cn1_sm_p7_0,
  141039. 1, -526516224, 1616117760, 4, 0,
  141040. _vq_quantlist__44cn1_sm_p7_0,
  141041. NULL,
  141042. &_vq_auxt__44cn1_sm_p7_0,
  141043. NULL,
  141044. 0
  141045. };
  141046. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141047. 2,
  141048. 1,
  141049. 3,
  141050. 0,
  141051. 4,
  141052. };
  141053. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141054. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141055. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141056. };
  141057. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141058. -1.5, -0.5, 0.5, 1.5,
  141059. };
  141060. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141061. 3, 1, 0, 2, 4,
  141062. };
  141063. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141064. _vq_quantthresh__44cn1_sm_p7_1,
  141065. _vq_quantmap__44cn1_sm_p7_1,
  141066. 5,
  141067. 5
  141068. };
  141069. static static_codebook _44cn1_sm_p7_1 = {
  141070. 2, 25,
  141071. _vq_lengthlist__44cn1_sm_p7_1,
  141072. 1, -533725184, 1611661312, 3, 0,
  141073. _vq_quantlist__44cn1_sm_p7_1,
  141074. NULL,
  141075. &_vq_auxt__44cn1_sm_p7_1,
  141076. NULL,
  141077. 0
  141078. };
  141079. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141080. 4,
  141081. 3,
  141082. 5,
  141083. 2,
  141084. 6,
  141085. 1,
  141086. 7,
  141087. 0,
  141088. 8,
  141089. };
  141090. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141091. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141092. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141093. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141094. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141095. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141096. 14,
  141097. };
  141098. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141099. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141100. };
  141101. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141102. 7, 5, 3, 1, 0, 2, 4, 6,
  141103. 8,
  141104. };
  141105. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141106. _vq_quantthresh__44cn1_sm_p8_0,
  141107. _vq_quantmap__44cn1_sm_p8_0,
  141108. 9,
  141109. 9
  141110. };
  141111. static static_codebook _44cn1_sm_p8_0 = {
  141112. 2, 81,
  141113. _vq_lengthlist__44cn1_sm_p8_0,
  141114. 1, -516186112, 1627103232, 4, 0,
  141115. _vq_quantlist__44cn1_sm_p8_0,
  141116. NULL,
  141117. &_vq_auxt__44cn1_sm_p8_0,
  141118. NULL,
  141119. 0
  141120. };
  141121. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141122. 6,
  141123. 5,
  141124. 7,
  141125. 4,
  141126. 8,
  141127. 3,
  141128. 9,
  141129. 2,
  141130. 10,
  141131. 1,
  141132. 11,
  141133. 0,
  141134. 12,
  141135. };
  141136. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141137. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141138. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141139. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141140. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141141. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141142. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141143. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141144. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141145. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141146. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141147. 17,12,12,11,10,13,11,13,13,
  141148. };
  141149. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141150. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141151. 42.5, 59.5, 76.5, 93.5,
  141152. };
  141153. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141154. 11, 9, 7, 5, 3, 1, 0, 2,
  141155. 4, 6, 8, 10, 12,
  141156. };
  141157. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141158. _vq_quantthresh__44cn1_sm_p8_1,
  141159. _vq_quantmap__44cn1_sm_p8_1,
  141160. 13,
  141161. 13
  141162. };
  141163. static static_codebook _44cn1_sm_p8_1 = {
  141164. 2, 169,
  141165. _vq_lengthlist__44cn1_sm_p8_1,
  141166. 1, -522616832, 1620115456, 4, 0,
  141167. _vq_quantlist__44cn1_sm_p8_1,
  141168. NULL,
  141169. &_vq_auxt__44cn1_sm_p8_1,
  141170. NULL,
  141171. 0
  141172. };
  141173. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141174. 8,
  141175. 7,
  141176. 9,
  141177. 6,
  141178. 10,
  141179. 5,
  141180. 11,
  141181. 4,
  141182. 12,
  141183. 3,
  141184. 13,
  141185. 2,
  141186. 14,
  141187. 1,
  141188. 15,
  141189. 0,
  141190. 16,
  141191. };
  141192. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141193. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141194. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141195. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141196. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141197. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141198. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141199. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141200. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141201. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141202. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141203. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141204. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141205. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141206. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141207. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141208. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141209. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141210. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141211. 9,
  141212. };
  141213. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141214. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141215. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141216. };
  141217. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141218. 15, 13, 11, 9, 7, 5, 3, 1,
  141219. 0, 2, 4, 6, 8, 10, 12, 14,
  141220. 16,
  141221. };
  141222. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141223. _vq_quantthresh__44cn1_sm_p8_2,
  141224. _vq_quantmap__44cn1_sm_p8_2,
  141225. 17,
  141226. 17
  141227. };
  141228. static static_codebook _44cn1_sm_p8_2 = {
  141229. 2, 289,
  141230. _vq_lengthlist__44cn1_sm_p8_2,
  141231. 1, -529530880, 1611661312, 5, 0,
  141232. _vq_quantlist__44cn1_sm_p8_2,
  141233. NULL,
  141234. &_vq_auxt__44cn1_sm_p8_2,
  141235. NULL,
  141236. 0
  141237. };
  141238. static long _huff_lengthlist__44cn1_sm_short[] = {
  141239. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141240. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141241. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141242. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141243. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141244. 9,
  141245. };
  141246. static static_codebook _huff_book__44cn1_sm_short = {
  141247. 2, 81,
  141248. _huff_lengthlist__44cn1_sm_short,
  141249. 0, 0, 0, 0, 0,
  141250. NULL,
  141251. NULL,
  141252. NULL,
  141253. NULL,
  141254. 0
  141255. };
  141256. /*** End of inlined file: res_books_stereo.h ***/
  141257. /***** residue backends *********************************************/
  141258. static vorbis_info_residue0 _residue_44_low={
  141259. 0,-1, -1, 9,-1,
  141260. /* 0 1 2 3 4 5 6 7 */
  141261. {0},
  141262. {-1},
  141263. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141264. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141265. };
  141266. static vorbis_info_residue0 _residue_44_mid={
  141267. 0,-1, -1, 10,-1,
  141268. /* 0 1 2 3 4 5 6 7 8 */
  141269. {0},
  141270. {-1},
  141271. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141272. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141273. };
  141274. static vorbis_info_residue0 _residue_44_high={
  141275. 0,-1, -1, 10,-1,
  141276. /* 0 1 2 3 4 5 6 7 8 */
  141277. {0},
  141278. {-1},
  141279. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141280. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141281. };
  141282. static static_bookblock _resbook_44s_n1={
  141283. {
  141284. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141285. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141286. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141287. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141288. }
  141289. };
  141290. static static_bookblock _resbook_44sm_n1={
  141291. {
  141292. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141293. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141294. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141295. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141296. }
  141297. };
  141298. static static_bookblock _resbook_44s_0={
  141299. {
  141300. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141301. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141302. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141303. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141304. }
  141305. };
  141306. static static_bookblock _resbook_44sm_0={
  141307. {
  141308. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141309. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141310. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141311. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141312. }
  141313. };
  141314. static static_bookblock _resbook_44s_1={
  141315. {
  141316. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141317. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141318. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141319. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141320. }
  141321. };
  141322. static static_bookblock _resbook_44sm_1={
  141323. {
  141324. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141325. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141326. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141327. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141328. }
  141329. };
  141330. static static_bookblock _resbook_44s_2={
  141331. {
  141332. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141333. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141334. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141335. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141336. }
  141337. };
  141338. static static_bookblock _resbook_44s_3={
  141339. {
  141340. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141341. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141342. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141343. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141344. }
  141345. };
  141346. static static_bookblock _resbook_44s_4={
  141347. {
  141348. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141349. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141350. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141351. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141352. }
  141353. };
  141354. static static_bookblock _resbook_44s_5={
  141355. {
  141356. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141357. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141358. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141359. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141360. }
  141361. };
  141362. static static_bookblock _resbook_44s_6={
  141363. {
  141364. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141365. {0,0,&_44c6_s_p4_0},
  141366. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141367. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141368. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141369. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141370. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141371. }
  141372. };
  141373. static static_bookblock _resbook_44s_7={
  141374. {
  141375. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141376. {0,0,&_44c7_s_p4_0},
  141377. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141378. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141379. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141380. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141381. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141382. }
  141383. };
  141384. static static_bookblock _resbook_44s_8={
  141385. {
  141386. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141387. {0,0,&_44c8_s_p4_0},
  141388. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141389. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141390. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141391. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141392. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141393. }
  141394. };
  141395. static static_bookblock _resbook_44s_9={
  141396. {
  141397. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141398. {0,0,&_44c9_s_p4_0},
  141399. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141400. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141401. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141402. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141403. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141404. }
  141405. };
  141406. static vorbis_residue_template _res_44s_n1[]={
  141407. {2,0, &_residue_44_low,
  141408. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141409. &_resbook_44s_n1,&_resbook_44sm_n1},
  141410. {2,0, &_residue_44_low,
  141411. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141412. &_resbook_44s_n1,&_resbook_44sm_n1}
  141413. };
  141414. static vorbis_residue_template _res_44s_0[]={
  141415. {2,0, &_residue_44_low,
  141416. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141417. &_resbook_44s_0,&_resbook_44sm_0},
  141418. {2,0, &_residue_44_low,
  141419. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141420. &_resbook_44s_0,&_resbook_44sm_0}
  141421. };
  141422. static vorbis_residue_template _res_44s_1[]={
  141423. {2,0, &_residue_44_low,
  141424. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141425. &_resbook_44s_1,&_resbook_44sm_1},
  141426. {2,0, &_residue_44_low,
  141427. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141428. &_resbook_44s_1,&_resbook_44sm_1}
  141429. };
  141430. static vorbis_residue_template _res_44s_2[]={
  141431. {2,0, &_residue_44_mid,
  141432. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141433. &_resbook_44s_2,&_resbook_44s_2},
  141434. {2,0, &_residue_44_mid,
  141435. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141436. &_resbook_44s_2,&_resbook_44s_2}
  141437. };
  141438. static vorbis_residue_template _res_44s_3[]={
  141439. {2,0, &_residue_44_mid,
  141440. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141441. &_resbook_44s_3,&_resbook_44s_3},
  141442. {2,0, &_residue_44_mid,
  141443. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141444. &_resbook_44s_3,&_resbook_44s_3}
  141445. };
  141446. static vorbis_residue_template _res_44s_4[]={
  141447. {2,0, &_residue_44_mid,
  141448. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141449. &_resbook_44s_4,&_resbook_44s_4},
  141450. {2,0, &_residue_44_mid,
  141451. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141452. &_resbook_44s_4,&_resbook_44s_4}
  141453. };
  141454. static vorbis_residue_template _res_44s_5[]={
  141455. {2,0, &_residue_44_mid,
  141456. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141457. &_resbook_44s_5,&_resbook_44s_5},
  141458. {2,0, &_residue_44_mid,
  141459. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141460. &_resbook_44s_5,&_resbook_44s_5}
  141461. };
  141462. static vorbis_residue_template _res_44s_6[]={
  141463. {2,0, &_residue_44_high,
  141464. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141465. &_resbook_44s_6,&_resbook_44s_6},
  141466. {2,0, &_residue_44_high,
  141467. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141468. &_resbook_44s_6,&_resbook_44s_6}
  141469. };
  141470. static vorbis_residue_template _res_44s_7[]={
  141471. {2,0, &_residue_44_high,
  141472. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141473. &_resbook_44s_7,&_resbook_44s_7},
  141474. {2,0, &_residue_44_high,
  141475. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141476. &_resbook_44s_7,&_resbook_44s_7}
  141477. };
  141478. static vorbis_residue_template _res_44s_8[]={
  141479. {2,0, &_residue_44_high,
  141480. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141481. &_resbook_44s_8,&_resbook_44s_8},
  141482. {2,0, &_residue_44_high,
  141483. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141484. &_resbook_44s_8,&_resbook_44s_8}
  141485. };
  141486. static vorbis_residue_template _res_44s_9[]={
  141487. {2,0, &_residue_44_high,
  141488. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141489. &_resbook_44s_9,&_resbook_44s_9},
  141490. {2,0, &_residue_44_high,
  141491. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141492. &_resbook_44s_9,&_resbook_44s_9}
  141493. };
  141494. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141495. { _map_nominal, _res_44s_n1 }, /* -1 */
  141496. { _map_nominal, _res_44s_0 }, /* 0 */
  141497. { _map_nominal, _res_44s_1 }, /* 1 */
  141498. { _map_nominal, _res_44s_2 }, /* 2 */
  141499. { _map_nominal, _res_44s_3 }, /* 3 */
  141500. { _map_nominal, _res_44s_4 }, /* 4 */
  141501. { _map_nominal, _res_44s_5 }, /* 5 */
  141502. { _map_nominal, _res_44s_6 }, /* 6 */
  141503. { _map_nominal, _res_44s_7 }, /* 7 */
  141504. { _map_nominal, _res_44s_8 }, /* 8 */
  141505. { _map_nominal, _res_44s_9 }, /* 9 */
  141506. };
  141507. /*** End of inlined file: residue_44.h ***/
  141508. /*** Start of inlined file: psych_44.h ***/
  141509. /* preecho trigger settings *****************************************/
  141510. static vorbis_info_psy_global _psy_global_44[5]={
  141511. {8, /* lines per eighth octave */
  141512. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141513. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141514. -6.f,
  141515. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141516. },
  141517. {8, /* lines per eighth octave */
  141518. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141519. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141520. -6.f,
  141521. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141522. },
  141523. {8, /* lines per eighth octave */
  141524. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141525. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141526. -6.f,
  141527. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141528. },
  141529. {8, /* lines per eighth octave */
  141530. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141531. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141532. -6.f,
  141533. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141534. },
  141535. {8, /* lines per eighth octave */
  141536. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141537. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141538. -6.f,
  141539. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141540. },
  141541. };
  141542. /* noise compander lookups * low, mid, high quality ****************/
  141543. static compandblock _psy_compand_44[6]={
  141544. /* sub-mode Z short */
  141545. {{
  141546. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141547. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141548. 16,17,18,19,20,21,22, 23, /* 23dB */
  141549. 24,25,26,27,28,29,30, 31, /* 31dB */
  141550. 32,33,34,35,36,37,38, 39, /* 39dB */
  141551. }},
  141552. /* mode_Z nominal short */
  141553. {{
  141554. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141555. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141556. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141557. 15,16,17,17,17,18,18, 19, /* 31dB */
  141558. 19,19,20,21,22,23,24, 25, /* 39dB */
  141559. }},
  141560. /* mode A short */
  141561. {{
  141562. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141563. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141564. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141565. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141566. 11,12,13,14,15,16,17, 18, /* 39dB */
  141567. }},
  141568. /* sub-mode Z long */
  141569. {{
  141570. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141571. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141572. 16,17,18,19,20,21,22, 23, /* 23dB */
  141573. 24,25,26,27,28,29,30, 31, /* 31dB */
  141574. 32,33,34,35,36,37,38, 39, /* 39dB */
  141575. }},
  141576. /* mode_Z nominal long */
  141577. {{
  141578. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141579. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141580. 13,14,14,14,15,15,15, 15, /* 23dB */
  141581. 16,16,17,17,17,18,18, 19, /* 31dB */
  141582. 19,19,20,21,22,23,24, 25, /* 39dB */
  141583. }},
  141584. /* mode A long */
  141585. {{
  141586. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141587. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141588. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141589. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141590. 11,12,13,14,15,16,17, 18, /* 39dB */
  141591. }}
  141592. };
  141593. /* tonal masking curve level adjustments *************************/
  141594. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141595. /* 63 125 250 500 1 2 4 8 16 */
  141596. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141597. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141598. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141599. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141600. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141601. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141602. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141603. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141604. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141605. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141606. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141607. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141608. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141609. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141610. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141611. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141612. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141613. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141614. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141615. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141616. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141617. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141618. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141619. };
  141620. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141621. /* 63 125 250 500 1 2 4 8 16 */
  141622. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141623. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141624. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141625. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141626. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141627. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141628. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141629. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141630. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141631. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141632. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141633. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141634. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141635. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141636. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141637. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141638. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141639. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141640. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141641. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141642. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141643. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141644. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141645. };
  141646. /* noise bias (transition block) */
  141647. static noise3 _psy_noisebias_trans[12]={
  141648. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141649. /* -1 */
  141650. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141651. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141652. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141653. /* 0
  141654. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141655. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141656. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141657. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141658. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141659. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141660. /* 1
  141661. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141662. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141663. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141664. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141665. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141666. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141667. /* 2
  141668. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141669. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141670. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141671. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141672. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141673. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141674. /* 3
  141675. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141676. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141677. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141678. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141679. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141680. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141681. /* 4
  141682. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141683. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141684. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141685. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141686. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141687. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141688. /* 5
  141689. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141690. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141691. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141692. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141693. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141694. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141695. /* 6
  141696. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141697. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141698. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141699. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141700. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141701. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141702. /* 7
  141703. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141704. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141705. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141706. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141707. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141708. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141709. /* 8
  141710. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141711. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141712. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141713. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141714. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141715. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141716. /* 9
  141717. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141718. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141719. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141720. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141721. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141722. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141723. /* 10 */
  141724. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141725. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141726. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141727. };
  141728. /* noise bias (long block) */
  141729. static noise3 _psy_noisebias_long[12]={
  141730. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141731. /* -1 */
  141732. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141733. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141734. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141735. /* 0 */
  141736. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141737. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141738. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141739. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141740. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141741. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141742. /* 1 */
  141743. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141744. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141745. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141746. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141747. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141748. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141749. /* 2 */
  141750. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141751. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141752. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141753. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141754. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141755. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141756. /* 3 */
  141757. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141758. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141759. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141760. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141761. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141762. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141763. /* 4 */
  141764. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141765. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141766. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141767. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141768. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141769. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141770. /* 5 */
  141771. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141772. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141773. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141774. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141775. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141776. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141777. /* 6 */
  141778. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141779. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141780. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141781. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141782. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141783. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141784. /* 7 */
  141785. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141786. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141787. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141788. /* 8 */
  141789. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141790. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141791. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141792. /* 9 */
  141793. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141794. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141795. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141796. /* 10 */
  141797. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141798. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141799. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141800. };
  141801. /* noise bias (impulse block) */
  141802. static noise3 _psy_noisebias_impulse[12]={
  141803. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141804. /* -1 */
  141805. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141806. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141807. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141808. /* 0 */
  141809. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141810. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  141811. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141812. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141813. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141814. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141815. /* 1 */
  141816. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141817. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141818. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141819. /* 2 */
  141820. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141821. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141822. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141823. /* 3 */
  141824. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141825. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141826. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141827. /* 4 */
  141828. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141829. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141830. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141831. /* 5 */
  141832. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141833. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  141834. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  141835. /* 6
  141836. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141837. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  141838. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  141839. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141840. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  141841. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  141842. /* 7 */
  141843. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141844. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  141845. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  141846. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141847. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  141848. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141849. /* 8 */
  141850. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141851. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  141852. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141853. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141854. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  141855. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141856. /* 9 */
  141857. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141858. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  141859. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141860. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141861. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  141862. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141863. /* 10 */
  141864. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  141865. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  141866. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141867. };
  141868. /* noise bias (padding block) */
  141869. static noise3 _psy_noisebias_padding[12]={
  141870. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141871. /* -1 */
  141872. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141873. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141874. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141875. /* 0 */
  141876. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141877. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  141878. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  141879. /* 1 */
  141880. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141881. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141882. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  141883. /* 2 */
  141884. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141885. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141886. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  141887. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141888. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141889. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141890. /* 3 */
  141891. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141892. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141893. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141894. /* 4 */
  141895. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141896. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  141897. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141898. /* 5 */
  141899. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141900. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  141901. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  141902. /* 6 */
  141903. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141904. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  141905. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  141906. /* 7 */
  141907. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141908. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  141909. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  141910. /* 8 */
  141911. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  141912. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  141913. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  141914. /* 9 */
  141915. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  141916. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  141917. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  141918. /* 10 */
  141919. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  141920. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  141921. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141922. };
  141923. static noiseguard _psy_noiseguards_44[4]={
  141924. {3,3,15},
  141925. {3,3,15},
  141926. {10,10,100},
  141927. {10,10,100},
  141928. };
  141929. static int _psy_tone_suppress[12]={
  141930. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  141931. };
  141932. static int _psy_tone_0dB[12]={
  141933. 90,90,95,95,95,95,105,105,105,105,105,105,
  141934. };
  141935. static int _psy_noise_suppress[12]={
  141936. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  141937. };
  141938. static vorbis_info_psy _psy_info_template={
  141939. /* blockflag */
  141940. -1,
  141941. /* ath_adjatt, ath_maxatt */
  141942. -140.,-140.,
  141943. /* tonemask att boost/decay,suppr,curves */
  141944. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  141945. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  141946. 1, -0.f, .5f, .5f, 0,0,0,
  141947. /* noiseoffset*3, noisecompand, max_curve_dB */
  141948. {{-1},{-1},{-1}},{-1},105.f,
  141949. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  141950. 0,0,-1,-1,0.,
  141951. };
  141952. /* ath ****************/
  141953. static int _psy_ath_floater[12]={
  141954. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  141955. };
  141956. static int _psy_ath_abs[12]={
  141957. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  141958. };
  141959. /* stereo setup. These don't map directly to quality level, there's
  141960. an additional indirection as several of the below may be used in a
  141961. single bitmanaged stream
  141962. ****************/
  141963. /* various stereo possibilities */
  141964. /* stereo mode by base quality level */
  141965. static adj_stereo _psy_stereo_modes_44[12]={
  141966. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  141967. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141968. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141969. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  141970. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141971. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  141972. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141973. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141974. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  141975. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141976. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  141977. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141978. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141979. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141980. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  141981. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  141982. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141983. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141984. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141985. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  141986. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  141987. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  141988. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141989. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141990. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  141991. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141992. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141993. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141994. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  141995. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  141996. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141997. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  141998. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141999. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142000. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142001. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142002. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142003. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142004. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142005. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142006. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142007. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142008. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142009. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142010. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142011. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142012. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142013. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142014. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142015. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142016. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142017. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142018. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142019. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142020. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142021. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142022. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142023. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142024. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142025. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142026. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142027. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142028. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142029. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142030. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142031. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142032. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142033. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142034. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142035. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142036. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142037. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142038. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142039. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142040. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142041. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142042. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142043. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142044. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142045. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142046. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142047. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142048. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142049. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142050. };
  142051. /* tone master attenuation by base quality mode and bitrate tweak */
  142052. static att3 _psy_tone_masteratt_44[12]={
  142053. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142054. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142055. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142056. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142057. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142058. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142059. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142060. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142061. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142062. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142063. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142064. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142065. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142066. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142067. };
  142068. /* lowpass by mode **************/
  142069. static double _psy_lowpass_44[12]={
  142070. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142071. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142072. };
  142073. /* noise normalization **********/
  142074. static int _noise_start_short_44[11]={
  142075. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142076. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142077. };
  142078. static int _noise_start_long_44[11]={
  142079. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142080. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142081. };
  142082. static int _noise_part_short_44[11]={
  142083. 8,8,8,8,8,8,8,8,8,8,8
  142084. };
  142085. static int _noise_part_long_44[11]={
  142086. 32,32,32,32,32,32,32,32,32,32,32
  142087. };
  142088. static double _noise_thresh_44[11]={
  142089. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142090. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142091. };
  142092. static double _noise_thresh_5only[2]={
  142093. .5,.5,
  142094. };
  142095. /*** End of inlined file: psych_44.h ***/
  142096. static double rate_mapping_44_stereo[12]={
  142097. 22500.,32000.,40000.,48000.,56000.,64000.,
  142098. 80000.,96000.,112000.,128000.,160000.,250001.
  142099. };
  142100. static double quality_mapping_44[12]={
  142101. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142102. };
  142103. static int blocksize_short_44[11]={
  142104. 512,256,256,256,256,256,256,256,256,256,256
  142105. };
  142106. static int blocksize_long_44[11]={
  142107. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142108. };
  142109. static double _psy_compand_short_mapping[12]={
  142110. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142111. };
  142112. static double _psy_compand_long_mapping[12]={
  142113. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142114. };
  142115. static double _global_mapping_44[12]={
  142116. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142117. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142118. };
  142119. static int _floor_short_mapping_44[11]={
  142120. 1,0,0,2,2,4,5,5,5,5,5
  142121. };
  142122. static int _floor_long_mapping_44[11]={
  142123. 8,7,7,7,7,7,7,7,7,7,7
  142124. };
  142125. ve_setup_data_template ve_setup_44_stereo={
  142126. 11,
  142127. rate_mapping_44_stereo,
  142128. quality_mapping_44,
  142129. 2,
  142130. 40000,
  142131. 50000,
  142132. blocksize_short_44,
  142133. blocksize_long_44,
  142134. _psy_tone_masteratt_44,
  142135. _psy_tone_0dB,
  142136. _psy_tone_suppress,
  142137. _vp_tonemask_adj_otherblock,
  142138. _vp_tonemask_adj_longblock,
  142139. _vp_tonemask_adj_otherblock,
  142140. _psy_noiseguards_44,
  142141. _psy_noisebias_impulse,
  142142. _psy_noisebias_padding,
  142143. _psy_noisebias_trans,
  142144. _psy_noisebias_long,
  142145. _psy_noise_suppress,
  142146. _psy_compand_44,
  142147. _psy_compand_short_mapping,
  142148. _psy_compand_long_mapping,
  142149. {_noise_start_short_44,_noise_start_long_44},
  142150. {_noise_part_short_44,_noise_part_long_44},
  142151. _noise_thresh_44,
  142152. _psy_ath_floater,
  142153. _psy_ath_abs,
  142154. _psy_lowpass_44,
  142155. _psy_global_44,
  142156. _global_mapping_44,
  142157. _psy_stereo_modes_44,
  142158. _floor_books,
  142159. _floor,
  142160. _floor_short_mapping_44,
  142161. _floor_long_mapping_44,
  142162. _mapres_template_44_stereo
  142163. };
  142164. /*** End of inlined file: setup_44.h ***/
  142165. /*** Start of inlined file: setup_44u.h ***/
  142166. /*** Start of inlined file: residue_44u.h ***/
  142167. /*** Start of inlined file: res_books_uncoupled.h ***/
  142168. static long _vq_quantlist__16u0__p1_0[] = {
  142169. 1,
  142170. 0,
  142171. 2,
  142172. };
  142173. static long _vq_lengthlist__16u0__p1_0[] = {
  142174. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142175. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142176. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142177. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142178. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142179. 12,
  142180. };
  142181. static float _vq_quantthresh__16u0__p1_0[] = {
  142182. -0.5, 0.5,
  142183. };
  142184. static long _vq_quantmap__16u0__p1_0[] = {
  142185. 1, 0, 2,
  142186. };
  142187. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142188. _vq_quantthresh__16u0__p1_0,
  142189. _vq_quantmap__16u0__p1_0,
  142190. 3,
  142191. 3
  142192. };
  142193. static static_codebook _16u0__p1_0 = {
  142194. 4, 81,
  142195. _vq_lengthlist__16u0__p1_0,
  142196. 1, -535822336, 1611661312, 2, 0,
  142197. _vq_quantlist__16u0__p1_0,
  142198. NULL,
  142199. &_vq_auxt__16u0__p1_0,
  142200. NULL,
  142201. 0
  142202. };
  142203. static long _vq_quantlist__16u0__p2_0[] = {
  142204. 1,
  142205. 0,
  142206. 2,
  142207. };
  142208. static long _vq_lengthlist__16u0__p2_0[] = {
  142209. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142210. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142211. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142212. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142213. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142214. 8,
  142215. };
  142216. static float _vq_quantthresh__16u0__p2_0[] = {
  142217. -0.5, 0.5,
  142218. };
  142219. static long _vq_quantmap__16u0__p2_0[] = {
  142220. 1, 0, 2,
  142221. };
  142222. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142223. _vq_quantthresh__16u0__p2_0,
  142224. _vq_quantmap__16u0__p2_0,
  142225. 3,
  142226. 3
  142227. };
  142228. static static_codebook _16u0__p2_0 = {
  142229. 4, 81,
  142230. _vq_lengthlist__16u0__p2_0,
  142231. 1, -535822336, 1611661312, 2, 0,
  142232. _vq_quantlist__16u0__p2_0,
  142233. NULL,
  142234. &_vq_auxt__16u0__p2_0,
  142235. NULL,
  142236. 0
  142237. };
  142238. static long _vq_quantlist__16u0__p3_0[] = {
  142239. 2,
  142240. 1,
  142241. 3,
  142242. 0,
  142243. 4,
  142244. };
  142245. static long _vq_lengthlist__16u0__p3_0[] = {
  142246. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142247. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142248. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142249. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142250. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142251. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142252. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142253. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142254. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142255. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142256. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142257. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142258. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142259. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142260. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142261. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142262. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142263. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142264. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142265. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142266. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142267. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142268. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142269. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142270. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142271. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142272. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142273. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142274. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142275. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142276. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142277. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142278. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142279. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142280. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142281. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142282. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142283. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142284. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142285. 18,
  142286. };
  142287. static float _vq_quantthresh__16u0__p3_0[] = {
  142288. -1.5, -0.5, 0.5, 1.5,
  142289. };
  142290. static long _vq_quantmap__16u0__p3_0[] = {
  142291. 3, 1, 0, 2, 4,
  142292. };
  142293. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142294. _vq_quantthresh__16u0__p3_0,
  142295. _vq_quantmap__16u0__p3_0,
  142296. 5,
  142297. 5
  142298. };
  142299. static static_codebook _16u0__p3_0 = {
  142300. 4, 625,
  142301. _vq_lengthlist__16u0__p3_0,
  142302. 1, -533725184, 1611661312, 3, 0,
  142303. _vq_quantlist__16u0__p3_0,
  142304. NULL,
  142305. &_vq_auxt__16u0__p3_0,
  142306. NULL,
  142307. 0
  142308. };
  142309. static long _vq_quantlist__16u0__p4_0[] = {
  142310. 2,
  142311. 1,
  142312. 3,
  142313. 0,
  142314. 4,
  142315. };
  142316. static long _vq_lengthlist__16u0__p4_0[] = {
  142317. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142318. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142319. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142320. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142321. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142322. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142323. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142324. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142325. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142326. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142327. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142328. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142329. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142330. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142331. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142332. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142333. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142334. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142335. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142336. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142337. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142338. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142339. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142340. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142341. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142342. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142343. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142344. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142345. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142346. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142347. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142348. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142349. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142350. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142351. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142352. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142353. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142354. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142355. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142356. 11,
  142357. };
  142358. static float _vq_quantthresh__16u0__p4_0[] = {
  142359. -1.5, -0.5, 0.5, 1.5,
  142360. };
  142361. static long _vq_quantmap__16u0__p4_0[] = {
  142362. 3, 1, 0, 2, 4,
  142363. };
  142364. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142365. _vq_quantthresh__16u0__p4_0,
  142366. _vq_quantmap__16u0__p4_0,
  142367. 5,
  142368. 5
  142369. };
  142370. static static_codebook _16u0__p4_0 = {
  142371. 4, 625,
  142372. _vq_lengthlist__16u0__p4_0,
  142373. 1, -533725184, 1611661312, 3, 0,
  142374. _vq_quantlist__16u0__p4_0,
  142375. NULL,
  142376. &_vq_auxt__16u0__p4_0,
  142377. NULL,
  142378. 0
  142379. };
  142380. static long _vq_quantlist__16u0__p5_0[] = {
  142381. 4,
  142382. 3,
  142383. 5,
  142384. 2,
  142385. 6,
  142386. 1,
  142387. 7,
  142388. 0,
  142389. 8,
  142390. };
  142391. static long _vq_lengthlist__16u0__p5_0[] = {
  142392. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142393. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142394. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142395. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142396. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142397. 12,
  142398. };
  142399. static float _vq_quantthresh__16u0__p5_0[] = {
  142400. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142401. };
  142402. static long _vq_quantmap__16u0__p5_0[] = {
  142403. 7, 5, 3, 1, 0, 2, 4, 6,
  142404. 8,
  142405. };
  142406. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142407. _vq_quantthresh__16u0__p5_0,
  142408. _vq_quantmap__16u0__p5_0,
  142409. 9,
  142410. 9
  142411. };
  142412. static static_codebook _16u0__p5_0 = {
  142413. 2, 81,
  142414. _vq_lengthlist__16u0__p5_0,
  142415. 1, -531628032, 1611661312, 4, 0,
  142416. _vq_quantlist__16u0__p5_0,
  142417. NULL,
  142418. &_vq_auxt__16u0__p5_0,
  142419. NULL,
  142420. 0
  142421. };
  142422. static long _vq_quantlist__16u0__p6_0[] = {
  142423. 6,
  142424. 5,
  142425. 7,
  142426. 4,
  142427. 8,
  142428. 3,
  142429. 9,
  142430. 2,
  142431. 10,
  142432. 1,
  142433. 11,
  142434. 0,
  142435. 12,
  142436. };
  142437. static long _vq_lengthlist__16u0__p6_0[] = {
  142438. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142439. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142440. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142441. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142442. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142443. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142444. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142445. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142446. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142447. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142448. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142449. };
  142450. static float _vq_quantthresh__16u0__p6_0[] = {
  142451. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142452. 12.5, 17.5, 22.5, 27.5,
  142453. };
  142454. static long _vq_quantmap__16u0__p6_0[] = {
  142455. 11, 9, 7, 5, 3, 1, 0, 2,
  142456. 4, 6, 8, 10, 12,
  142457. };
  142458. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142459. _vq_quantthresh__16u0__p6_0,
  142460. _vq_quantmap__16u0__p6_0,
  142461. 13,
  142462. 13
  142463. };
  142464. static static_codebook _16u0__p6_0 = {
  142465. 2, 169,
  142466. _vq_lengthlist__16u0__p6_0,
  142467. 1, -526516224, 1616117760, 4, 0,
  142468. _vq_quantlist__16u0__p6_0,
  142469. NULL,
  142470. &_vq_auxt__16u0__p6_0,
  142471. NULL,
  142472. 0
  142473. };
  142474. static long _vq_quantlist__16u0__p6_1[] = {
  142475. 2,
  142476. 1,
  142477. 3,
  142478. 0,
  142479. 4,
  142480. };
  142481. static long _vq_lengthlist__16u0__p6_1[] = {
  142482. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142483. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142484. };
  142485. static float _vq_quantthresh__16u0__p6_1[] = {
  142486. -1.5, -0.5, 0.5, 1.5,
  142487. };
  142488. static long _vq_quantmap__16u0__p6_1[] = {
  142489. 3, 1, 0, 2, 4,
  142490. };
  142491. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142492. _vq_quantthresh__16u0__p6_1,
  142493. _vq_quantmap__16u0__p6_1,
  142494. 5,
  142495. 5
  142496. };
  142497. static static_codebook _16u0__p6_1 = {
  142498. 2, 25,
  142499. _vq_lengthlist__16u0__p6_1,
  142500. 1, -533725184, 1611661312, 3, 0,
  142501. _vq_quantlist__16u0__p6_1,
  142502. NULL,
  142503. &_vq_auxt__16u0__p6_1,
  142504. NULL,
  142505. 0
  142506. };
  142507. static long _vq_quantlist__16u0__p7_0[] = {
  142508. 1,
  142509. 0,
  142510. 2,
  142511. };
  142512. static long _vq_lengthlist__16u0__p7_0[] = {
  142513. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142514. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142515. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142516. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142517. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142518. 7,
  142519. };
  142520. static float _vq_quantthresh__16u0__p7_0[] = {
  142521. -157.5, 157.5,
  142522. };
  142523. static long _vq_quantmap__16u0__p7_0[] = {
  142524. 1, 0, 2,
  142525. };
  142526. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142527. _vq_quantthresh__16u0__p7_0,
  142528. _vq_quantmap__16u0__p7_0,
  142529. 3,
  142530. 3
  142531. };
  142532. static static_codebook _16u0__p7_0 = {
  142533. 4, 81,
  142534. _vq_lengthlist__16u0__p7_0,
  142535. 1, -518803456, 1628680192, 2, 0,
  142536. _vq_quantlist__16u0__p7_0,
  142537. NULL,
  142538. &_vq_auxt__16u0__p7_0,
  142539. NULL,
  142540. 0
  142541. };
  142542. static long _vq_quantlist__16u0__p7_1[] = {
  142543. 7,
  142544. 6,
  142545. 8,
  142546. 5,
  142547. 9,
  142548. 4,
  142549. 10,
  142550. 3,
  142551. 11,
  142552. 2,
  142553. 12,
  142554. 1,
  142555. 13,
  142556. 0,
  142557. 14,
  142558. };
  142559. static long _vq_lengthlist__16u0__p7_1[] = {
  142560. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142561. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142562. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142563. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142564. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142565. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142568. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142569. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142570. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142571. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142572. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142573. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142574. 10,
  142575. };
  142576. static float _vq_quantthresh__16u0__p7_1[] = {
  142577. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142578. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142579. };
  142580. static long _vq_quantmap__16u0__p7_1[] = {
  142581. 13, 11, 9, 7, 5, 3, 1, 0,
  142582. 2, 4, 6, 8, 10, 12, 14,
  142583. };
  142584. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142585. _vq_quantthresh__16u0__p7_1,
  142586. _vq_quantmap__16u0__p7_1,
  142587. 15,
  142588. 15
  142589. };
  142590. static static_codebook _16u0__p7_1 = {
  142591. 2, 225,
  142592. _vq_lengthlist__16u0__p7_1,
  142593. 1, -520986624, 1620377600, 4, 0,
  142594. _vq_quantlist__16u0__p7_1,
  142595. NULL,
  142596. &_vq_auxt__16u0__p7_1,
  142597. NULL,
  142598. 0
  142599. };
  142600. static long _vq_quantlist__16u0__p7_2[] = {
  142601. 10,
  142602. 9,
  142603. 11,
  142604. 8,
  142605. 12,
  142606. 7,
  142607. 13,
  142608. 6,
  142609. 14,
  142610. 5,
  142611. 15,
  142612. 4,
  142613. 16,
  142614. 3,
  142615. 17,
  142616. 2,
  142617. 18,
  142618. 1,
  142619. 19,
  142620. 0,
  142621. 20,
  142622. };
  142623. static long _vq_lengthlist__16u0__p7_2[] = {
  142624. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142625. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142626. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142627. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142628. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142629. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142630. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142631. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142632. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142633. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142634. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142635. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142636. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142637. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142638. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142639. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142640. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142641. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142642. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142643. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142644. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142645. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142646. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142647. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142648. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142649. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142650. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142651. 10,10,12,11,10,11,11,11,10,
  142652. };
  142653. static float _vq_quantthresh__16u0__p7_2[] = {
  142654. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142655. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142656. 6.5, 7.5, 8.5, 9.5,
  142657. };
  142658. static long _vq_quantmap__16u0__p7_2[] = {
  142659. 19, 17, 15, 13, 11, 9, 7, 5,
  142660. 3, 1, 0, 2, 4, 6, 8, 10,
  142661. 12, 14, 16, 18, 20,
  142662. };
  142663. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142664. _vq_quantthresh__16u0__p7_2,
  142665. _vq_quantmap__16u0__p7_2,
  142666. 21,
  142667. 21
  142668. };
  142669. static static_codebook _16u0__p7_2 = {
  142670. 2, 441,
  142671. _vq_lengthlist__16u0__p7_2,
  142672. 1, -529268736, 1611661312, 5, 0,
  142673. _vq_quantlist__16u0__p7_2,
  142674. NULL,
  142675. &_vq_auxt__16u0__p7_2,
  142676. NULL,
  142677. 0
  142678. };
  142679. static long _huff_lengthlist__16u0__single[] = {
  142680. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142681. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142682. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142683. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142684. };
  142685. static static_codebook _huff_book__16u0__single = {
  142686. 2, 64,
  142687. _huff_lengthlist__16u0__single,
  142688. 0, 0, 0, 0, 0,
  142689. NULL,
  142690. NULL,
  142691. NULL,
  142692. NULL,
  142693. 0
  142694. };
  142695. static long _huff_lengthlist__16u1__long[] = {
  142696. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142697. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142698. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142699. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142700. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142701. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142702. 16,13,16,18,
  142703. };
  142704. static static_codebook _huff_book__16u1__long = {
  142705. 2, 100,
  142706. _huff_lengthlist__16u1__long,
  142707. 0, 0, 0, 0, 0,
  142708. NULL,
  142709. NULL,
  142710. NULL,
  142711. NULL,
  142712. 0
  142713. };
  142714. static long _vq_quantlist__16u1__p1_0[] = {
  142715. 1,
  142716. 0,
  142717. 2,
  142718. };
  142719. static long _vq_lengthlist__16u1__p1_0[] = {
  142720. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142721. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142722. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142723. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142724. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142725. 11,
  142726. };
  142727. static float _vq_quantthresh__16u1__p1_0[] = {
  142728. -0.5, 0.5,
  142729. };
  142730. static long _vq_quantmap__16u1__p1_0[] = {
  142731. 1, 0, 2,
  142732. };
  142733. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142734. _vq_quantthresh__16u1__p1_0,
  142735. _vq_quantmap__16u1__p1_0,
  142736. 3,
  142737. 3
  142738. };
  142739. static static_codebook _16u1__p1_0 = {
  142740. 4, 81,
  142741. _vq_lengthlist__16u1__p1_0,
  142742. 1, -535822336, 1611661312, 2, 0,
  142743. _vq_quantlist__16u1__p1_0,
  142744. NULL,
  142745. &_vq_auxt__16u1__p1_0,
  142746. NULL,
  142747. 0
  142748. };
  142749. static long _vq_quantlist__16u1__p2_0[] = {
  142750. 1,
  142751. 0,
  142752. 2,
  142753. };
  142754. static long _vq_lengthlist__16u1__p2_0[] = {
  142755. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142756. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142757. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142758. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142759. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142760. 8,
  142761. };
  142762. static float _vq_quantthresh__16u1__p2_0[] = {
  142763. -0.5, 0.5,
  142764. };
  142765. static long _vq_quantmap__16u1__p2_0[] = {
  142766. 1, 0, 2,
  142767. };
  142768. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142769. _vq_quantthresh__16u1__p2_0,
  142770. _vq_quantmap__16u1__p2_0,
  142771. 3,
  142772. 3
  142773. };
  142774. static static_codebook _16u1__p2_0 = {
  142775. 4, 81,
  142776. _vq_lengthlist__16u1__p2_0,
  142777. 1, -535822336, 1611661312, 2, 0,
  142778. _vq_quantlist__16u1__p2_0,
  142779. NULL,
  142780. &_vq_auxt__16u1__p2_0,
  142781. NULL,
  142782. 0
  142783. };
  142784. static long _vq_quantlist__16u1__p3_0[] = {
  142785. 2,
  142786. 1,
  142787. 3,
  142788. 0,
  142789. 4,
  142790. };
  142791. static long _vq_lengthlist__16u1__p3_0[] = {
  142792. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142793. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142794. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142795. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142796. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142797. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142798. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142799. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142800. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142801. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142802. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142803. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142804. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142805. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142806. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142807. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142808. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142809. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142810. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142811. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142812. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142813. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142814. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142815. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142816. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142817. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142818. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142819. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  142820. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  142821. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  142822. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  142823. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  142824. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  142825. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  142826. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  142827. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  142828. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  142829. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  142830. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  142831. 16,
  142832. };
  142833. static float _vq_quantthresh__16u1__p3_0[] = {
  142834. -1.5, -0.5, 0.5, 1.5,
  142835. };
  142836. static long _vq_quantmap__16u1__p3_0[] = {
  142837. 3, 1, 0, 2, 4,
  142838. };
  142839. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  142840. _vq_quantthresh__16u1__p3_0,
  142841. _vq_quantmap__16u1__p3_0,
  142842. 5,
  142843. 5
  142844. };
  142845. static static_codebook _16u1__p3_0 = {
  142846. 4, 625,
  142847. _vq_lengthlist__16u1__p3_0,
  142848. 1, -533725184, 1611661312, 3, 0,
  142849. _vq_quantlist__16u1__p3_0,
  142850. NULL,
  142851. &_vq_auxt__16u1__p3_0,
  142852. NULL,
  142853. 0
  142854. };
  142855. static long _vq_quantlist__16u1__p4_0[] = {
  142856. 2,
  142857. 1,
  142858. 3,
  142859. 0,
  142860. 4,
  142861. };
  142862. static long _vq_lengthlist__16u1__p4_0[] = {
  142863. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  142864. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  142865. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  142866. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  142867. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142868. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  142869. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  142870. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  142871. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  142872. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  142873. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  142874. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  142875. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  142876. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  142877. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  142878. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  142879. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  142880. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142881. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  142882. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  142883. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  142884. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  142885. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  142886. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  142887. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  142888. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  142889. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  142890. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  142891. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  142892. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  142893. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  142894. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  142895. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  142896. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  142897. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  142898. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  142899. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  142900. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  142901. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  142902. 11,
  142903. };
  142904. static float _vq_quantthresh__16u1__p4_0[] = {
  142905. -1.5, -0.5, 0.5, 1.5,
  142906. };
  142907. static long _vq_quantmap__16u1__p4_0[] = {
  142908. 3, 1, 0, 2, 4,
  142909. };
  142910. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  142911. _vq_quantthresh__16u1__p4_0,
  142912. _vq_quantmap__16u1__p4_0,
  142913. 5,
  142914. 5
  142915. };
  142916. static static_codebook _16u1__p4_0 = {
  142917. 4, 625,
  142918. _vq_lengthlist__16u1__p4_0,
  142919. 1, -533725184, 1611661312, 3, 0,
  142920. _vq_quantlist__16u1__p4_0,
  142921. NULL,
  142922. &_vq_auxt__16u1__p4_0,
  142923. NULL,
  142924. 0
  142925. };
  142926. static long _vq_quantlist__16u1__p5_0[] = {
  142927. 4,
  142928. 3,
  142929. 5,
  142930. 2,
  142931. 6,
  142932. 1,
  142933. 7,
  142934. 0,
  142935. 8,
  142936. };
  142937. static long _vq_lengthlist__16u1__p5_0[] = {
  142938. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142939. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142940. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142941. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  142942. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  142943. 13,
  142944. };
  142945. static float _vq_quantthresh__16u1__p5_0[] = {
  142946. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142947. };
  142948. static long _vq_quantmap__16u1__p5_0[] = {
  142949. 7, 5, 3, 1, 0, 2, 4, 6,
  142950. 8,
  142951. };
  142952. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  142953. _vq_quantthresh__16u1__p5_0,
  142954. _vq_quantmap__16u1__p5_0,
  142955. 9,
  142956. 9
  142957. };
  142958. static static_codebook _16u1__p5_0 = {
  142959. 2, 81,
  142960. _vq_lengthlist__16u1__p5_0,
  142961. 1, -531628032, 1611661312, 4, 0,
  142962. _vq_quantlist__16u1__p5_0,
  142963. NULL,
  142964. &_vq_auxt__16u1__p5_0,
  142965. NULL,
  142966. 0
  142967. };
  142968. static long _vq_quantlist__16u1__p6_0[] = {
  142969. 4,
  142970. 3,
  142971. 5,
  142972. 2,
  142973. 6,
  142974. 1,
  142975. 7,
  142976. 0,
  142977. 8,
  142978. };
  142979. static long _vq_lengthlist__16u1__p6_0[] = {
  142980. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  142981. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142982. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  142983. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  142984. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  142985. 11,
  142986. };
  142987. static float _vq_quantthresh__16u1__p6_0[] = {
  142988. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142989. };
  142990. static long _vq_quantmap__16u1__p6_0[] = {
  142991. 7, 5, 3, 1, 0, 2, 4, 6,
  142992. 8,
  142993. };
  142994. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  142995. _vq_quantthresh__16u1__p6_0,
  142996. _vq_quantmap__16u1__p6_0,
  142997. 9,
  142998. 9
  142999. };
  143000. static static_codebook _16u1__p6_0 = {
  143001. 2, 81,
  143002. _vq_lengthlist__16u1__p6_0,
  143003. 1, -531628032, 1611661312, 4, 0,
  143004. _vq_quantlist__16u1__p6_0,
  143005. NULL,
  143006. &_vq_auxt__16u1__p6_0,
  143007. NULL,
  143008. 0
  143009. };
  143010. static long _vq_quantlist__16u1__p7_0[] = {
  143011. 1,
  143012. 0,
  143013. 2,
  143014. };
  143015. static long _vq_lengthlist__16u1__p7_0[] = {
  143016. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143017. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143018. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143019. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143020. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143021. 13,
  143022. };
  143023. static float _vq_quantthresh__16u1__p7_0[] = {
  143024. -5.5, 5.5,
  143025. };
  143026. static long _vq_quantmap__16u1__p7_0[] = {
  143027. 1, 0, 2,
  143028. };
  143029. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143030. _vq_quantthresh__16u1__p7_0,
  143031. _vq_quantmap__16u1__p7_0,
  143032. 3,
  143033. 3
  143034. };
  143035. static static_codebook _16u1__p7_0 = {
  143036. 4, 81,
  143037. _vq_lengthlist__16u1__p7_0,
  143038. 1, -529137664, 1618345984, 2, 0,
  143039. _vq_quantlist__16u1__p7_0,
  143040. NULL,
  143041. &_vq_auxt__16u1__p7_0,
  143042. NULL,
  143043. 0
  143044. };
  143045. static long _vq_quantlist__16u1__p7_1[] = {
  143046. 5,
  143047. 4,
  143048. 6,
  143049. 3,
  143050. 7,
  143051. 2,
  143052. 8,
  143053. 1,
  143054. 9,
  143055. 0,
  143056. 10,
  143057. };
  143058. static long _vq_lengthlist__16u1__p7_1[] = {
  143059. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143060. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143061. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143062. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143063. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143064. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143065. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143066. 8, 9, 9,10,10,10,10,10,10,
  143067. };
  143068. static float _vq_quantthresh__16u1__p7_1[] = {
  143069. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143070. 3.5, 4.5,
  143071. };
  143072. static long _vq_quantmap__16u1__p7_1[] = {
  143073. 9, 7, 5, 3, 1, 0, 2, 4,
  143074. 6, 8, 10,
  143075. };
  143076. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143077. _vq_quantthresh__16u1__p7_1,
  143078. _vq_quantmap__16u1__p7_1,
  143079. 11,
  143080. 11
  143081. };
  143082. static static_codebook _16u1__p7_1 = {
  143083. 2, 121,
  143084. _vq_lengthlist__16u1__p7_1,
  143085. 1, -531365888, 1611661312, 4, 0,
  143086. _vq_quantlist__16u1__p7_1,
  143087. NULL,
  143088. &_vq_auxt__16u1__p7_1,
  143089. NULL,
  143090. 0
  143091. };
  143092. static long _vq_quantlist__16u1__p8_0[] = {
  143093. 5,
  143094. 4,
  143095. 6,
  143096. 3,
  143097. 7,
  143098. 2,
  143099. 8,
  143100. 1,
  143101. 9,
  143102. 0,
  143103. 10,
  143104. };
  143105. static long _vq_lengthlist__16u1__p8_0[] = {
  143106. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143107. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143108. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143109. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143110. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143111. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143112. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143113. 13,14,14,15,15,16,16,15,16,
  143114. };
  143115. static float _vq_quantthresh__16u1__p8_0[] = {
  143116. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143117. 38.5, 49.5,
  143118. };
  143119. static long _vq_quantmap__16u1__p8_0[] = {
  143120. 9, 7, 5, 3, 1, 0, 2, 4,
  143121. 6, 8, 10,
  143122. };
  143123. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143124. _vq_quantthresh__16u1__p8_0,
  143125. _vq_quantmap__16u1__p8_0,
  143126. 11,
  143127. 11
  143128. };
  143129. static static_codebook _16u1__p8_0 = {
  143130. 2, 121,
  143131. _vq_lengthlist__16u1__p8_0,
  143132. 1, -524582912, 1618345984, 4, 0,
  143133. _vq_quantlist__16u1__p8_0,
  143134. NULL,
  143135. &_vq_auxt__16u1__p8_0,
  143136. NULL,
  143137. 0
  143138. };
  143139. static long _vq_quantlist__16u1__p8_1[] = {
  143140. 5,
  143141. 4,
  143142. 6,
  143143. 3,
  143144. 7,
  143145. 2,
  143146. 8,
  143147. 1,
  143148. 9,
  143149. 0,
  143150. 10,
  143151. };
  143152. static long _vq_lengthlist__16u1__p8_1[] = {
  143153. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143154. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143155. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143156. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143157. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143158. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143159. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143160. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143161. };
  143162. static float _vq_quantthresh__16u1__p8_1[] = {
  143163. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143164. 3.5, 4.5,
  143165. };
  143166. static long _vq_quantmap__16u1__p8_1[] = {
  143167. 9, 7, 5, 3, 1, 0, 2, 4,
  143168. 6, 8, 10,
  143169. };
  143170. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143171. _vq_quantthresh__16u1__p8_1,
  143172. _vq_quantmap__16u1__p8_1,
  143173. 11,
  143174. 11
  143175. };
  143176. static static_codebook _16u1__p8_1 = {
  143177. 2, 121,
  143178. _vq_lengthlist__16u1__p8_1,
  143179. 1, -531365888, 1611661312, 4, 0,
  143180. _vq_quantlist__16u1__p8_1,
  143181. NULL,
  143182. &_vq_auxt__16u1__p8_1,
  143183. NULL,
  143184. 0
  143185. };
  143186. static long _vq_quantlist__16u1__p9_0[] = {
  143187. 7,
  143188. 6,
  143189. 8,
  143190. 5,
  143191. 9,
  143192. 4,
  143193. 10,
  143194. 3,
  143195. 11,
  143196. 2,
  143197. 12,
  143198. 1,
  143199. 13,
  143200. 0,
  143201. 14,
  143202. };
  143203. static long _vq_lengthlist__16u1__p9_0[] = {
  143204. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143205. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143206. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143207. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143208. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143209. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143210. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143211. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143212. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143213. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143214. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143215. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143216. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143217. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143218. 8,
  143219. };
  143220. static float _vq_quantthresh__16u1__p9_0[] = {
  143221. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143222. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143223. };
  143224. static long _vq_quantmap__16u1__p9_0[] = {
  143225. 13, 11, 9, 7, 5, 3, 1, 0,
  143226. 2, 4, 6, 8, 10, 12, 14,
  143227. };
  143228. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143229. _vq_quantthresh__16u1__p9_0,
  143230. _vq_quantmap__16u1__p9_0,
  143231. 15,
  143232. 15
  143233. };
  143234. static static_codebook _16u1__p9_0 = {
  143235. 2, 225,
  143236. _vq_lengthlist__16u1__p9_0,
  143237. 1, -514071552, 1627381760, 4, 0,
  143238. _vq_quantlist__16u1__p9_0,
  143239. NULL,
  143240. &_vq_auxt__16u1__p9_0,
  143241. NULL,
  143242. 0
  143243. };
  143244. static long _vq_quantlist__16u1__p9_1[] = {
  143245. 7,
  143246. 6,
  143247. 8,
  143248. 5,
  143249. 9,
  143250. 4,
  143251. 10,
  143252. 3,
  143253. 11,
  143254. 2,
  143255. 12,
  143256. 1,
  143257. 13,
  143258. 0,
  143259. 14,
  143260. };
  143261. static long _vq_lengthlist__16u1__p9_1[] = {
  143262. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143263. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143264. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143265. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143266. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143267. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143268. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143269. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143270. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143272. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143273. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143275. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143276. 9,
  143277. };
  143278. static float _vq_quantthresh__16u1__p9_1[] = {
  143279. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143280. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143281. };
  143282. static long _vq_quantmap__16u1__p9_1[] = {
  143283. 13, 11, 9, 7, 5, 3, 1, 0,
  143284. 2, 4, 6, 8, 10, 12, 14,
  143285. };
  143286. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143287. _vq_quantthresh__16u1__p9_1,
  143288. _vq_quantmap__16u1__p9_1,
  143289. 15,
  143290. 15
  143291. };
  143292. static static_codebook _16u1__p9_1 = {
  143293. 2, 225,
  143294. _vq_lengthlist__16u1__p9_1,
  143295. 1, -522338304, 1620115456, 4, 0,
  143296. _vq_quantlist__16u1__p9_1,
  143297. NULL,
  143298. &_vq_auxt__16u1__p9_1,
  143299. NULL,
  143300. 0
  143301. };
  143302. static long _vq_quantlist__16u1__p9_2[] = {
  143303. 8,
  143304. 7,
  143305. 9,
  143306. 6,
  143307. 10,
  143308. 5,
  143309. 11,
  143310. 4,
  143311. 12,
  143312. 3,
  143313. 13,
  143314. 2,
  143315. 14,
  143316. 1,
  143317. 15,
  143318. 0,
  143319. 16,
  143320. };
  143321. static long _vq_lengthlist__16u1__p9_2[] = {
  143322. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143323. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143324. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143325. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143326. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143327. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143328. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143329. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143330. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143331. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143332. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143333. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143334. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143335. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143336. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143337. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143338. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143339. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143340. 10,
  143341. };
  143342. static float _vq_quantthresh__16u1__p9_2[] = {
  143343. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143344. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143345. };
  143346. static long _vq_quantmap__16u1__p9_2[] = {
  143347. 15, 13, 11, 9, 7, 5, 3, 1,
  143348. 0, 2, 4, 6, 8, 10, 12, 14,
  143349. 16,
  143350. };
  143351. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143352. _vq_quantthresh__16u1__p9_2,
  143353. _vq_quantmap__16u1__p9_2,
  143354. 17,
  143355. 17
  143356. };
  143357. static static_codebook _16u1__p9_2 = {
  143358. 2, 289,
  143359. _vq_lengthlist__16u1__p9_2,
  143360. 1, -529530880, 1611661312, 5, 0,
  143361. _vq_quantlist__16u1__p9_2,
  143362. NULL,
  143363. &_vq_auxt__16u1__p9_2,
  143364. NULL,
  143365. 0
  143366. };
  143367. static long _huff_lengthlist__16u1__short[] = {
  143368. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143369. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143370. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143371. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143372. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143373. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143374. 16,16,16,16,
  143375. };
  143376. static static_codebook _huff_book__16u1__short = {
  143377. 2, 100,
  143378. _huff_lengthlist__16u1__short,
  143379. 0, 0, 0, 0, 0,
  143380. NULL,
  143381. NULL,
  143382. NULL,
  143383. NULL,
  143384. 0
  143385. };
  143386. static long _huff_lengthlist__16u2__long[] = {
  143387. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143388. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143389. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143390. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143391. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143392. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143393. 13,14,18,18,
  143394. };
  143395. static static_codebook _huff_book__16u2__long = {
  143396. 2, 100,
  143397. _huff_lengthlist__16u2__long,
  143398. 0, 0, 0, 0, 0,
  143399. NULL,
  143400. NULL,
  143401. NULL,
  143402. NULL,
  143403. 0
  143404. };
  143405. static long _huff_lengthlist__16u2__short[] = {
  143406. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143407. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143408. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143409. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143410. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143411. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143412. 16,16,16,16,
  143413. };
  143414. static static_codebook _huff_book__16u2__short = {
  143415. 2, 100,
  143416. _huff_lengthlist__16u2__short,
  143417. 0, 0, 0, 0, 0,
  143418. NULL,
  143419. NULL,
  143420. NULL,
  143421. NULL,
  143422. 0
  143423. };
  143424. static long _vq_quantlist__16u2_p1_0[] = {
  143425. 1,
  143426. 0,
  143427. 2,
  143428. };
  143429. static long _vq_lengthlist__16u2_p1_0[] = {
  143430. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143431. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143432. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143433. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143434. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143435. 10,
  143436. };
  143437. static float _vq_quantthresh__16u2_p1_0[] = {
  143438. -0.5, 0.5,
  143439. };
  143440. static long _vq_quantmap__16u2_p1_0[] = {
  143441. 1, 0, 2,
  143442. };
  143443. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143444. _vq_quantthresh__16u2_p1_0,
  143445. _vq_quantmap__16u2_p1_0,
  143446. 3,
  143447. 3
  143448. };
  143449. static static_codebook _16u2_p1_0 = {
  143450. 4, 81,
  143451. _vq_lengthlist__16u2_p1_0,
  143452. 1, -535822336, 1611661312, 2, 0,
  143453. _vq_quantlist__16u2_p1_0,
  143454. NULL,
  143455. &_vq_auxt__16u2_p1_0,
  143456. NULL,
  143457. 0
  143458. };
  143459. static long _vq_quantlist__16u2_p2_0[] = {
  143460. 2,
  143461. 1,
  143462. 3,
  143463. 0,
  143464. 4,
  143465. };
  143466. static long _vq_lengthlist__16u2_p2_0[] = {
  143467. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143468. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143469. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143470. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143471. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143472. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143473. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143474. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143475. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143476. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143477. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143478. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143479. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143480. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143481. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143482. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143483. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143484. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143485. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143486. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143487. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143488. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143489. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143490. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143491. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143492. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143493. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143494. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143495. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143496. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143497. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143498. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143499. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143500. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143501. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143502. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143503. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143504. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143505. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143506. 13,
  143507. };
  143508. static float _vq_quantthresh__16u2_p2_0[] = {
  143509. -1.5, -0.5, 0.5, 1.5,
  143510. };
  143511. static long _vq_quantmap__16u2_p2_0[] = {
  143512. 3, 1, 0, 2, 4,
  143513. };
  143514. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143515. _vq_quantthresh__16u2_p2_0,
  143516. _vq_quantmap__16u2_p2_0,
  143517. 5,
  143518. 5
  143519. };
  143520. static static_codebook _16u2_p2_0 = {
  143521. 4, 625,
  143522. _vq_lengthlist__16u2_p2_0,
  143523. 1, -533725184, 1611661312, 3, 0,
  143524. _vq_quantlist__16u2_p2_0,
  143525. NULL,
  143526. &_vq_auxt__16u2_p2_0,
  143527. NULL,
  143528. 0
  143529. };
  143530. static long _vq_quantlist__16u2_p3_0[] = {
  143531. 4,
  143532. 3,
  143533. 5,
  143534. 2,
  143535. 6,
  143536. 1,
  143537. 7,
  143538. 0,
  143539. 8,
  143540. };
  143541. static long _vq_lengthlist__16u2_p3_0[] = {
  143542. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143543. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143544. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143545. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143546. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143547. 11,
  143548. };
  143549. static float _vq_quantthresh__16u2_p3_0[] = {
  143550. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143551. };
  143552. static long _vq_quantmap__16u2_p3_0[] = {
  143553. 7, 5, 3, 1, 0, 2, 4, 6,
  143554. 8,
  143555. };
  143556. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143557. _vq_quantthresh__16u2_p3_0,
  143558. _vq_quantmap__16u2_p3_0,
  143559. 9,
  143560. 9
  143561. };
  143562. static static_codebook _16u2_p3_0 = {
  143563. 2, 81,
  143564. _vq_lengthlist__16u2_p3_0,
  143565. 1, -531628032, 1611661312, 4, 0,
  143566. _vq_quantlist__16u2_p3_0,
  143567. NULL,
  143568. &_vq_auxt__16u2_p3_0,
  143569. NULL,
  143570. 0
  143571. };
  143572. static long _vq_quantlist__16u2_p4_0[] = {
  143573. 8,
  143574. 7,
  143575. 9,
  143576. 6,
  143577. 10,
  143578. 5,
  143579. 11,
  143580. 4,
  143581. 12,
  143582. 3,
  143583. 13,
  143584. 2,
  143585. 14,
  143586. 1,
  143587. 15,
  143588. 0,
  143589. 16,
  143590. };
  143591. static long _vq_lengthlist__16u2_p4_0[] = {
  143592. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143593. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143594. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143595. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143596. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143597. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143598. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143599. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143600. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143601. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143602. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143603. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143604. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143605. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143606. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143607. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143608. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143609. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143610. 14,
  143611. };
  143612. static float _vq_quantthresh__16u2_p4_0[] = {
  143613. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143614. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143615. };
  143616. static long _vq_quantmap__16u2_p4_0[] = {
  143617. 15, 13, 11, 9, 7, 5, 3, 1,
  143618. 0, 2, 4, 6, 8, 10, 12, 14,
  143619. 16,
  143620. };
  143621. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143622. _vq_quantthresh__16u2_p4_0,
  143623. _vq_quantmap__16u2_p4_0,
  143624. 17,
  143625. 17
  143626. };
  143627. static static_codebook _16u2_p4_0 = {
  143628. 2, 289,
  143629. _vq_lengthlist__16u2_p4_0,
  143630. 1, -529530880, 1611661312, 5, 0,
  143631. _vq_quantlist__16u2_p4_0,
  143632. NULL,
  143633. &_vq_auxt__16u2_p4_0,
  143634. NULL,
  143635. 0
  143636. };
  143637. static long _vq_quantlist__16u2_p5_0[] = {
  143638. 1,
  143639. 0,
  143640. 2,
  143641. };
  143642. static long _vq_lengthlist__16u2_p5_0[] = {
  143643. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143644. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143645. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143646. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143647. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143648. 10,
  143649. };
  143650. static float _vq_quantthresh__16u2_p5_0[] = {
  143651. -5.5, 5.5,
  143652. };
  143653. static long _vq_quantmap__16u2_p5_0[] = {
  143654. 1, 0, 2,
  143655. };
  143656. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143657. _vq_quantthresh__16u2_p5_0,
  143658. _vq_quantmap__16u2_p5_0,
  143659. 3,
  143660. 3
  143661. };
  143662. static static_codebook _16u2_p5_0 = {
  143663. 4, 81,
  143664. _vq_lengthlist__16u2_p5_0,
  143665. 1, -529137664, 1618345984, 2, 0,
  143666. _vq_quantlist__16u2_p5_0,
  143667. NULL,
  143668. &_vq_auxt__16u2_p5_0,
  143669. NULL,
  143670. 0
  143671. };
  143672. static long _vq_quantlist__16u2_p5_1[] = {
  143673. 5,
  143674. 4,
  143675. 6,
  143676. 3,
  143677. 7,
  143678. 2,
  143679. 8,
  143680. 1,
  143681. 9,
  143682. 0,
  143683. 10,
  143684. };
  143685. static long _vq_lengthlist__16u2_p5_1[] = {
  143686. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143687. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143688. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143689. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143690. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143691. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143692. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143693. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143694. };
  143695. static float _vq_quantthresh__16u2_p5_1[] = {
  143696. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143697. 3.5, 4.5,
  143698. };
  143699. static long _vq_quantmap__16u2_p5_1[] = {
  143700. 9, 7, 5, 3, 1, 0, 2, 4,
  143701. 6, 8, 10,
  143702. };
  143703. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143704. _vq_quantthresh__16u2_p5_1,
  143705. _vq_quantmap__16u2_p5_1,
  143706. 11,
  143707. 11
  143708. };
  143709. static static_codebook _16u2_p5_1 = {
  143710. 2, 121,
  143711. _vq_lengthlist__16u2_p5_1,
  143712. 1, -531365888, 1611661312, 4, 0,
  143713. _vq_quantlist__16u2_p5_1,
  143714. NULL,
  143715. &_vq_auxt__16u2_p5_1,
  143716. NULL,
  143717. 0
  143718. };
  143719. static long _vq_quantlist__16u2_p6_0[] = {
  143720. 6,
  143721. 5,
  143722. 7,
  143723. 4,
  143724. 8,
  143725. 3,
  143726. 9,
  143727. 2,
  143728. 10,
  143729. 1,
  143730. 11,
  143731. 0,
  143732. 12,
  143733. };
  143734. static long _vq_lengthlist__16u2_p6_0[] = {
  143735. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143736. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143737. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143738. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143739. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143740. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143741. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143742. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143743. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143744. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143745. 12,13,13,14,14,14,14,15,15,
  143746. };
  143747. static float _vq_quantthresh__16u2_p6_0[] = {
  143748. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143749. 12.5, 17.5, 22.5, 27.5,
  143750. };
  143751. static long _vq_quantmap__16u2_p6_0[] = {
  143752. 11, 9, 7, 5, 3, 1, 0, 2,
  143753. 4, 6, 8, 10, 12,
  143754. };
  143755. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143756. _vq_quantthresh__16u2_p6_0,
  143757. _vq_quantmap__16u2_p6_0,
  143758. 13,
  143759. 13
  143760. };
  143761. static static_codebook _16u2_p6_0 = {
  143762. 2, 169,
  143763. _vq_lengthlist__16u2_p6_0,
  143764. 1, -526516224, 1616117760, 4, 0,
  143765. _vq_quantlist__16u2_p6_0,
  143766. NULL,
  143767. &_vq_auxt__16u2_p6_0,
  143768. NULL,
  143769. 0
  143770. };
  143771. static long _vq_quantlist__16u2_p6_1[] = {
  143772. 2,
  143773. 1,
  143774. 3,
  143775. 0,
  143776. 4,
  143777. };
  143778. static long _vq_lengthlist__16u2_p6_1[] = {
  143779. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143780. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143781. };
  143782. static float _vq_quantthresh__16u2_p6_1[] = {
  143783. -1.5, -0.5, 0.5, 1.5,
  143784. };
  143785. static long _vq_quantmap__16u2_p6_1[] = {
  143786. 3, 1, 0, 2, 4,
  143787. };
  143788. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143789. _vq_quantthresh__16u2_p6_1,
  143790. _vq_quantmap__16u2_p6_1,
  143791. 5,
  143792. 5
  143793. };
  143794. static static_codebook _16u2_p6_1 = {
  143795. 2, 25,
  143796. _vq_lengthlist__16u2_p6_1,
  143797. 1, -533725184, 1611661312, 3, 0,
  143798. _vq_quantlist__16u2_p6_1,
  143799. NULL,
  143800. &_vq_auxt__16u2_p6_1,
  143801. NULL,
  143802. 0
  143803. };
  143804. static long _vq_quantlist__16u2_p7_0[] = {
  143805. 6,
  143806. 5,
  143807. 7,
  143808. 4,
  143809. 8,
  143810. 3,
  143811. 9,
  143812. 2,
  143813. 10,
  143814. 1,
  143815. 11,
  143816. 0,
  143817. 12,
  143818. };
  143819. static long _vq_lengthlist__16u2_p7_0[] = {
  143820. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  143821. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  143822. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  143823. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  143824. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  143825. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  143826. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  143827. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  143828. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  143829. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  143830. 12,13,13,13,14,14,14,15,14,
  143831. };
  143832. static float _vq_quantthresh__16u2_p7_0[] = {
  143833. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  143834. 27.5, 38.5, 49.5, 60.5,
  143835. };
  143836. static long _vq_quantmap__16u2_p7_0[] = {
  143837. 11, 9, 7, 5, 3, 1, 0, 2,
  143838. 4, 6, 8, 10, 12,
  143839. };
  143840. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  143841. _vq_quantthresh__16u2_p7_0,
  143842. _vq_quantmap__16u2_p7_0,
  143843. 13,
  143844. 13
  143845. };
  143846. static static_codebook _16u2_p7_0 = {
  143847. 2, 169,
  143848. _vq_lengthlist__16u2_p7_0,
  143849. 1, -523206656, 1618345984, 4, 0,
  143850. _vq_quantlist__16u2_p7_0,
  143851. NULL,
  143852. &_vq_auxt__16u2_p7_0,
  143853. NULL,
  143854. 0
  143855. };
  143856. static long _vq_quantlist__16u2_p7_1[] = {
  143857. 5,
  143858. 4,
  143859. 6,
  143860. 3,
  143861. 7,
  143862. 2,
  143863. 8,
  143864. 1,
  143865. 9,
  143866. 0,
  143867. 10,
  143868. };
  143869. static long _vq_lengthlist__16u2_p7_1[] = {
  143870. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  143871. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  143872. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  143873. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  143874. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143875. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  143876. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143877. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143878. };
  143879. static float _vq_quantthresh__16u2_p7_1[] = {
  143880. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143881. 3.5, 4.5,
  143882. };
  143883. static long _vq_quantmap__16u2_p7_1[] = {
  143884. 9, 7, 5, 3, 1, 0, 2, 4,
  143885. 6, 8, 10,
  143886. };
  143887. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  143888. _vq_quantthresh__16u2_p7_1,
  143889. _vq_quantmap__16u2_p7_1,
  143890. 11,
  143891. 11
  143892. };
  143893. static static_codebook _16u2_p7_1 = {
  143894. 2, 121,
  143895. _vq_lengthlist__16u2_p7_1,
  143896. 1, -531365888, 1611661312, 4, 0,
  143897. _vq_quantlist__16u2_p7_1,
  143898. NULL,
  143899. &_vq_auxt__16u2_p7_1,
  143900. NULL,
  143901. 0
  143902. };
  143903. static long _vq_quantlist__16u2_p8_0[] = {
  143904. 7,
  143905. 6,
  143906. 8,
  143907. 5,
  143908. 9,
  143909. 4,
  143910. 10,
  143911. 3,
  143912. 11,
  143913. 2,
  143914. 12,
  143915. 1,
  143916. 13,
  143917. 0,
  143918. 14,
  143919. };
  143920. static long _vq_lengthlist__16u2_p8_0[] = {
  143921. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  143922. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  143923. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  143924. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  143925. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  143926. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  143927. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  143928. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  143929. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  143930. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  143931. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  143932. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  143933. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  143934. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  143935. 14,
  143936. };
  143937. static float _vq_quantthresh__16u2_p8_0[] = {
  143938. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143939. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143940. };
  143941. static long _vq_quantmap__16u2_p8_0[] = {
  143942. 13, 11, 9, 7, 5, 3, 1, 0,
  143943. 2, 4, 6, 8, 10, 12, 14,
  143944. };
  143945. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  143946. _vq_quantthresh__16u2_p8_0,
  143947. _vq_quantmap__16u2_p8_0,
  143948. 15,
  143949. 15
  143950. };
  143951. static static_codebook _16u2_p8_0 = {
  143952. 2, 225,
  143953. _vq_lengthlist__16u2_p8_0,
  143954. 1, -520986624, 1620377600, 4, 0,
  143955. _vq_quantlist__16u2_p8_0,
  143956. NULL,
  143957. &_vq_auxt__16u2_p8_0,
  143958. NULL,
  143959. 0
  143960. };
  143961. static long _vq_quantlist__16u2_p8_1[] = {
  143962. 10,
  143963. 9,
  143964. 11,
  143965. 8,
  143966. 12,
  143967. 7,
  143968. 13,
  143969. 6,
  143970. 14,
  143971. 5,
  143972. 15,
  143973. 4,
  143974. 16,
  143975. 3,
  143976. 17,
  143977. 2,
  143978. 18,
  143979. 1,
  143980. 19,
  143981. 0,
  143982. 20,
  143983. };
  143984. static long _vq_lengthlist__16u2_p8_1[] = {
  143985. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  143986. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  143987. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  143988. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  143989. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  143990. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  143991. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  143992. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  143993. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  143994. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  143995. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  143996. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  143997. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  143998. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  143999. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144000. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144001. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144002. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144003. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144004. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144005. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144006. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144007. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144008. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144010. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144011. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144012. 11,11,10,11,11,11,10,11,11,
  144013. };
  144014. static float _vq_quantthresh__16u2_p8_1[] = {
  144015. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144016. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144017. 6.5, 7.5, 8.5, 9.5,
  144018. };
  144019. static long _vq_quantmap__16u2_p8_1[] = {
  144020. 19, 17, 15, 13, 11, 9, 7, 5,
  144021. 3, 1, 0, 2, 4, 6, 8, 10,
  144022. 12, 14, 16, 18, 20,
  144023. };
  144024. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144025. _vq_quantthresh__16u2_p8_1,
  144026. _vq_quantmap__16u2_p8_1,
  144027. 21,
  144028. 21
  144029. };
  144030. static static_codebook _16u2_p8_1 = {
  144031. 2, 441,
  144032. _vq_lengthlist__16u2_p8_1,
  144033. 1, -529268736, 1611661312, 5, 0,
  144034. _vq_quantlist__16u2_p8_1,
  144035. NULL,
  144036. &_vq_auxt__16u2_p8_1,
  144037. NULL,
  144038. 0
  144039. };
  144040. static long _vq_quantlist__16u2_p9_0[] = {
  144041. 5586,
  144042. 4655,
  144043. 6517,
  144044. 3724,
  144045. 7448,
  144046. 2793,
  144047. 8379,
  144048. 1862,
  144049. 9310,
  144050. 931,
  144051. 10241,
  144052. 0,
  144053. 11172,
  144054. 5521,
  144055. 5651,
  144056. };
  144057. static long _vq_lengthlist__16u2_p9_0[] = {
  144058. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144059. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144060. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144061. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144062. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144063. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144064. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144065. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144066. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144067. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144068. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144069. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144070. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144071. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144072. 5,
  144073. };
  144074. static float _vq_quantthresh__16u2_p9_0[] = {
  144075. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144076. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144077. };
  144078. static long _vq_quantmap__16u2_p9_0[] = {
  144079. 11, 9, 7, 5, 3, 1, 13, 0,
  144080. 14, 2, 4, 6, 8, 10, 12,
  144081. };
  144082. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144083. _vq_quantthresh__16u2_p9_0,
  144084. _vq_quantmap__16u2_p9_0,
  144085. 15,
  144086. 15
  144087. };
  144088. static static_codebook _16u2_p9_0 = {
  144089. 2, 225,
  144090. _vq_lengthlist__16u2_p9_0,
  144091. 1, -510275072, 1611661312, 14, 0,
  144092. _vq_quantlist__16u2_p9_0,
  144093. NULL,
  144094. &_vq_auxt__16u2_p9_0,
  144095. NULL,
  144096. 0
  144097. };
  144098. static long _vq_quantlist__16u2_p9_1[] = {
  144099. 392,
  144100. 343,
  144101. 441,
  144102. 294,
  144103. 490,
  144104. 245,
  144105. 539,
  144106. 196,
  144107. 588,
  144108. 147,
  144109. 637,
  144110. 98,
  144111. 686,
  144112. 49,
  144113. 735,
  144114. 0,
  144115. 784,
  144116. 388,
  144117. 396,
  144118. };
  144119. static long _vq_lengthlist__16u2_p9_1[] = {
  144120. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144121. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144122. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144123. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144124. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144125. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144126. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144127. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144128. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144129. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144130. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144131. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144132. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144133. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144134. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144137. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144138. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144140. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144141. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144142. 11,11,11,11,11,11,11, 5, 4,
  144143. };
  144144. static float _vq_quantthresh__16u2_p9_1[] = {
  144145. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144146. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144147. 318.5, 367.5,
  144148. };
  144149. static long _vq_quantmap__16u2_p9_1[] = {
  144150. 15, 13, 11, 9, 7, 5, 3, 1,
  144151. 17, 0, 18, 2, 4, 6, 8, 10,
  144152. 12, 14, 16,
  144153. };
  144154. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144155. _vq_quantthresh__16u2_p9_1,
  144156. _vq_quantmap__16u2_p9_1,
  144157. 19,
  144158. 19
  144159. };
  144160. static static_codebook _16u2_p9_1 = {
  144161. 2, 361,
  144162. _vq_lengthlist__16u2_p9_1,
  144163. 1, -518488064, 1611661312, 10, 0,
  144164. _vq_quantlist__16u2_p9_1,
  144165. NULL,
  144166. &_vq_auxt__16u2_p9_1,
  144167. NULL,
  144168. 0
  144169. };
  144170. static long _vq_quantlist__16u2_p9_2[] = {
  144171. 24,
  144172. 23,
  144173. 25,
  144174. 22,
  144175. 26,
  144176. 21,
  144177. 27,
  144178. 20,
  144179. 28,
  144180. 19,
  144181. 29,
  144182. 18,
  144183. 30,
  144184. 17,
  144185. 31,
  144186. 16,
  144187. 32,
  144188. 15,
  144189. 33,
  144190. 14,
  144191. 34,
  144192. 13,
  144193. 35,
  144194. 12,
  144195. 36,
  144196. 11,
  144197. 37,
  144198. 10,
  144199. 38,
  144200. 9,
  144201. 39,
  144202. 8,
  144203. 40,
  144204. 7,
  144205. 41,
  144206. 6,
  144207. 42,
  144208. 5,
  144209. 43,
  144210. 4,
  144211. 44,
  144212. 3,
  144213. 45,
  144214. 2,
  144215. 46,
  144216. 1,
  144217. 47,
  144218. 0,
  144219. 48,
  144220. };
  144221. static long _vq_lengthlist__16u2_p9_2[] = {
  144222. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144223. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144224. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144225. 11,
  144226. };
  144227. static float _vq_quantthresh__16u2_p9_2[] = {
  144228. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144229. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144230. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144231. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144232. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144233. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144234. };
  144235. static long _vq_quantmap__16u2_p9_2[] = {
  144236. 47, 45, 43, 41, 39, 37, 35, 33,
  144237. 31, 29, 27, 25, 23, 21, 19, 17,
  144238. 15, 13, 11, 9, 7, 5, 3, 1,
  144239. 0, 2, 4, 6, 8, 10, 12, 14,
  144240. 16, 18, 20, 22, 24, 26, 28, 30,
  144241. 32, 34, 36, 38, 40, 42, 44, 46,
  144242. 48,
  144243. };
  144244. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144245. _vq_quantthresh__16u2_p9_2,
  144246. _vq_quantmap__16u2_p9_2,
  144247. 49,
  144248. 49
  144249. };
  144250. static static_codebook _16u2_p9_2 = {
  144251. 1, 49,
  144252. _vq_lengthlist__16u2_p9_2,
  144253. 1, -526909440, 1611661312, 6, 0,
  144254. _vq_quantlist__16u2_p9_2,
  144255. NULL,
  144256. &_vq_auxt__16u2_p9_2,
  144257. NULL,
  144258. 0
  144259. };
  144260. static long _vq_quantlist__8u0__p1_0[] = {
  144261. 1,
  144262. 0,
  144263. 2,
  144264. };
  144265. static long _vq_lengthlist__8u0__p1_0[] = {
  144266. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144267. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144268. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144269. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144270. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144271. 11,
  144272. };
  144273. static float _vq_quantthresh__8u0__p1_0[] = {
  144274. -0.5, 0.5,
  144275. };
  144276. static long _vq_quantmap__8u0__p1_0[] = {
  144277. 1, 0, 2,
  144278. };
  144279. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144280. _vq_quantthresh__8u0__p1_0,
  144281. _vq_quantmap__8u0__p1_0,
  144282. 3,
  144283. 3
  144284. };
  144285. static static_codebook _8u0__p1_0 = {
  144286. 4, 81,
  144287. _vq_lengthlist__8u0__p1_0,
  144288. 1, -535822336, 1611661312, 2, 0,
  144289. _vq_quantlist__8u0__p1_0,
  144290. NULL,
  144291. &_vq_auxt__8u0__p1_0,
  144292. NULL,
  144293. 0
  144294. };
  144295. static long _vq_quantlist__8u0__p2_0[] = {
  144296. 1,
  144297. 0,
  144298. 2,
  144299. };
  144300. static long _vq_lengthlist__8u0__p2_0[] = {
  144301. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144302. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144303. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144304. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144305. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144306. 8,
  144307. };
  144308. static float _vq_quantthresh__8u0__p2_0[] = {
  144309. -0.5, 0.5,
  144310. };
  144311. static long _vq_quantmap__8u0__p2_0[] = {
  144312. 1, 0, 2,
  144313. };
  144314. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144315. _vq_quantthresh__8u0__p2_0,
  144316. _vq_quantmap__8u0__p2_0,
  144317. 3,
  144318. 3
  144319. };
  144320. static static_codebook _8u0__p2_0 = {
  144321. 4, 81,
  144322. _vq_lengthlist__8u0__p2_0,
  144323. 1, -535822336, 1611661312, 2, 0,
  144324. _vq_quantlist__8u0__p2_0,
  144325. NULL,
  144326. &_vq_auxt__8u0__p2_0,
  144327. NULL,
  144328. 0
  144329. };
  144330. static long _vq_quantlist__8u0__p3_0[] = {
  144331. 2,
  144332. 1,
  144333. 3,
  144334. 0,
  144335. 4,
  144336. };
  144337. static long _vq_lengthlist__8u0__p3_0[] = {
  144338. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144339. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144340. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144341. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144342. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144343. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144344. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144345. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144346. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144347. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144348. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144349. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144350. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144351. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144352. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144353. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144354. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144355. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144356. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144357. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144358. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144359. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144360. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144361. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144362. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144363. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144364. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144365. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144366. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144367. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144368. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144369. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144370. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144371. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144372. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144373. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144374. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144375. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144376. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144377. 16,
  144378. };
  144379. static float _vq_quantthresh__8u0__p3_0[] = {
  144380. -1.5, -0.5, 0.5, 1.5,
  144381. };
  144382. static long _vq_quantmap__8u0__p3_0[] = {
  144383. 3, 1, 0, 2, 4,
  144384. };
  144385. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144386. _vq_quantthresh__8u0__p3_0,
  144387. _vq_quantmap__8u0__p3_0,
  144388. 5,
  144389. 5
  144390. };
  144391. static static_codebook _8u0__p3_0 = {
  144392. 4, 625,
  144393. _vq_lengthlist__8u0__p3_0,
  144394. 1, -533725184, 1611661312, 3, 0,
  144395. _vq_quantlist__8u0__p3_0,
  144396. NULL,
  144397. &_vq_auxt__8u0__p3_0,
  144398. NULL,
  144399. 0
  144400. };
  144401. static long _vq_quantlist__8u0__p4_0[] = {
  144402. 2,
  144403. 1,
  144404. 3,
  144405. 0,
  144406. 4,
  144407. };
  144408. static long _vq_lengthlist__8u0__p4_0[] = {
  144409. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144410. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144411. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144412. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144413. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144414. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144415. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144416. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144417. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144418. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144419. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144420. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144421. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144422. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144423. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144424. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144425. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144426. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144427. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144428. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144429. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144430. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144431. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144432. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144433. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144434. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144435. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144436. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144437. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144438. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144439. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144440. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144441. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144442. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144443. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144444. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144445. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144446. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144447. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144448. 12,
  144449. };
  144450. static float _vq_quantthresh__8u0__p4_0[] = {
  144451. -1.5, -0.5, 0.5, 1.5,
  144452. };
  144453. static long _vq_quantmap__8u0__p4_0[] = {
  144454. 3, 1, 0, 2, 4,
  144455. };
  144456. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144457. _vq_quantthresh__8u0__p4_0,
  144458. _vq_quantmap__8u0__p4_0,
  144459. 5,
  144460. 5
  144461. };
  144462. static static_codebook _8u0__p4_0 = {
  144463. 4, 625,
  144464. _vq_lengthlist__8u0__p4_0,
  144465. 1, -533725184, 1611661312, 3, 0,
  144466. _vq_quantlist__8u0__p4_0,
  144467. NULL,
  144468. &_vq_auxt__8u0__p4_0,
  144469. NULL,
  144470. 0
  144471. };
  144472. static long _vq_quantlist__8u0__p5_0[] = {
  144473. 4,
  144474. 3,
  144475. 5,
  144476. 2,
  144477. 6,
  144478. 1,
  144479. 7,
  144480. 0,
  144481. 8,
  144482. };
  144483. static long _vq_lengthlist__8u0__p5_0[] = {
  144484. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144485. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144486. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144487. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144488. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144489. 12,
  144490. };
  144491. static float _vq_quantthresh__8u0__p5_0[] = {
  144492. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144493. };
  144494. static long _vq_quantmap__8u0__p5_0[] = {
  144495. 7, 5, 3, 1, 0, 2, 4, 6,
  144496. 8,
  144497. };
  144498. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144499. _vq_quantthresh__8u0__p5_0,
  144500. _vq_quantmap__8u0__p5_0,
  144501. 9,
  144502. 9
  144503. };
  144504. static static_codebook _8u0__p5_0 = {
  144505. 2, 81,
  144506. _vq_lengthlist__8u0__p5_0,
  144507. 1, -531628032, 1611661312, 4, 0,
  144508. _vq_quantlist__8u0__p5_0,
  144509. NULL,
  144510. &_vq_auxt__8u0__p5_0,
  144511. NULL,
  144512. 0
  144513. };
  144514. static long _vq_quantlist__8u0__p6_0[] = {
  144515. 6,
  144516. 5,
  144517. 7,
  144518. 4,
  144519. 8,
  144520. 3,
  144521. 9,
  144522. 2,
  144523. 10,
  144524. 1,
  144525. 11,
  144526. 0,
  144527. 12,
  144528. };
  144529. static long _vq_lengthlist__8u0__p6_0[] = {
  144530. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144531. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144532. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144533. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144534. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144535. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144536. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144537. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144538. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144539. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144540. 16, 0,15, 0,17, 0, 0, 0, 0,
  144541. };
  144542. static float _vq_quantthresh__8u0__p6_0[] = {
  144543. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144544. 12.5, 17.5, 22.5, 27.5,
  144545. };
  144546. static long _vq_quantmap__8u0__p6_0[] = {
  144547. 11, 9, 7, 5, 3, 1, 0, 2,
  144548. 4, 6, 8, 10, 12,
  144549. };
  144550. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144551. _vq_quantthresh__8u0__p6_0,
  144552. _vq_quantmap__8u0__p6_0,
  144553. 13,
  144554. 13
  144555. };
  144556. static static_codebook _8u0__p6_0 = {
  144557. 2, 169,
  144558. _vq_lengthlist__8u0__p6_0,
  144559. 1, -526516224, 1616117760, 4, 0,
  144560. _vq_quantlist__8u0__p6_0,
  144561. NULL,
  144562. &_vq_auxt__8u0__p6_0,
  144563. NULL,
  144564. 0
  144565. };
  144566. static long _vq_quantlist__8u0__p6_1[] = {
  144567. 2,
  144568. 1,
  144569. 3,
  144570. 0,
  144571. 4,
  144572. };
  144573. static long _vq_lengthlist__8u0__p6_1[] = {
  144574. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144575. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144576. };
  144577. static float _vq_quantthresh__8u0__p6_1[] = {
  144578. -1.5, -0.5, 0.5, 1.5,
  144579. };
  144580. static long _vq_quantmap__8u0__p6_1[] = {
  144581. 3, 1, 0, 2, 4,
  144582. };
  144583. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144584. _vq_quantthresh__8u0__p6_1,
  144585. _vq_quantmap__8u0__p6_1,
  144586. 5,
  144587. 5
  144588. };
  144589. static static_codebook _8u0__p6_1 = {
  144590. 2, 25,
  144591. _vq_lengthlist__8u0__p6_1,
  144592. 1, -533725184, 1611661312, 3, 0,
  144593. _vq_quantlist__8u0__p6_1,
  144594. NULL,
  144595. &_vq_auxt__8u0__p6_1,
  144596. NULL,
  144597. 0
  144598. };
  144599. static long _vq_quantlist__8u0__p7_0[] = {
  144600. 1,
  144601. 0,
  144602. 2,
  144603. };
  144604. static long _vq_lengthlist__8u0__p7_0[] = {
  144605. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144606. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144607. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144608. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144609. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144610. 7,
  144611. };
  144612. static float _vq_quantthresh__8u0__p7_0[] = {
  144613. -157.5, 157.5,
  144614. };
  144615. static long _vq_quantmap__8u0__p7_0[] = {
  144616. 1, 0, 2,
  144617. };
  144618. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144619. _vq_quantthresh__8u0__p7_0,
  144620. _vq_quantmap__8u0__p7_0,
  144621. 3,
  144622. 3
  144623. };
  144624. static static_codebook _8u0__p7_0 = {
  144625. 4, 81,
  144626. _vq_lengthlist__8u0__p7_0,
  144627. 1, -518803456, 1628680192, 2, 0,
  144628. _vq_quantlist__8u0__p7_0,
  144629. NULL,
  144630. &_vq_auxt__8u0__p7_0,
  144631. NULL,
  144632. 0
  144633. };
  144634. static long _vq_quantlist__8u0__p7_1[] = {
  144635. 7,
  144636. 6,
  144637. 8,
  144638. 5,
  144639. 9,
  144640. 4,
  144641. 10,
  144642. 3,
  144643. 11,
  144644. 2,
  144645. 12,
  144646. 1,
  144647. 13,
  144648. 0,
  144649. 14,
  144650. };
  144651. static long _vq_lengthlist__8u0__p7_1[] = {
  144652. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144653. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144654. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144655. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144656. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144657. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144659. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144664. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144666. 10,
  144667. };
  144668. static float _vq_quantthresh__8u0__p7_1[] = {
  144669. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144670. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144671. };
  144672. static long _vq_quantmap__8u0__p7_1[] = {
  144673. 13, 11, 9, 7, 5, 3, 1, 0,
  144674. 2, 4, 6, 8, 10, 12, 14,
  144675. };
  144676. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144677. _vq_quantthresh__8u0__p7_1,
  144678. _vq_quantmap__8u0__p7_1,
  144679. 15,
  144680. 15
  144681. };
  144682. static static_codebook _8u0__p7_1 = {
  144683. 2, 225,
  144684. _vq_lengthlist__8u0__p7_1,
  144685. 1, -520986624, 1620377600, 4, 0,
  144686. _vq_quantlist__8u0__p7_1,
  144687. NULL,
  144688. &_vq_auxt__8u0__p7_1,
  144689. NULL,
  144690. 0
  144691. };
  144692. static long _vq_quantlist__8u0__p7_2[] = {
  144693. 10,
  144694. 9,
  144695. 11,
  144696. 8,
  144697. 12,
  144698. 7,
  144699. 13,
  144700. 6,
  144701. 14,
  144702. 5,
  144703. 15,
  144704. 4,
  144705. 16,
  144706. 3,
  144707. 17,
  144708. 2,
  144709. 18,
  144710. 1,
  144711. 19,
  144712. 0,
  144713. 20,
  144714. };
  144715. static long _vq_lengthlist__8u0__p7_2[] = {
  144716. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144717. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144718. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144719. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144720. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144721. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144722. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144723. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144724. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144725. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144726. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144727. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144728. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144729. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144730. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144731. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144732. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144733. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144734. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144735. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144736. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144737. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144738. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144739. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144740. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144741. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144742. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144743. 11,12,11,11,11,10,10,11,11,
  144744. };
  144745. static float _vq_quantthresh__8u0__p7_2[] = {
  144746. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144747. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144748. 6.5, 7.5, 8.5, 9.5,
  144749. };
  144750. static long _vq_quantmap__8u0__p7_2[] = {
  144751. 19, 17, 15, 13, 11, 9, 7, 5,
  144752. 3, 1, 0, 2, 4, 6, 8, 10,
  144753. 12, 14, 16, 18, 20,
  144754. };
  144755. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144756. _vq_quantthresh__8u0__p7_2,
  144757. _vq_quantmap__8u0__p7_2,
  144758. 21,
  144759. 21
  144760. };
  144761. static static_codebook _8u0__p7_2 = {
  144762. 2, 441,
  144763. _vq_lengthlist__8u0__p7_2,
  144764. 1, -529268736, 1611661312, 5, 0,
  144765. _vq_quantlist__8u0__p7_2,
  144766. NULL,
  144767. &_vq_auxt__8u0__p7_2,
  144768. NULL,
  144769. 0
  144770. };
  144771. static long _huff_lengthlist__8u0__single[] = {
  144772. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144773. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144774. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144775. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144776. };
  144777. static static_codebook _huff_book__8u0__single = {
  144778. 2, 64,
  144779. _huff_lengthlist__8u0__single,
  144780. 0, 0, 0, 0, 0,
  144781. NULL,
  144782. NULL,
  144783. NULL,
  144784. NULL,
  144785. 0
  144786. };
  144787. static long _vq_quantlist__8u1__p1_0[] = {
  144788. 1,
  144789. 0,
  144790. 2,
  144791. };
  144792. static long _vq_lengthlist__8u1__p1_0[] = {
  144793. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144794. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144795. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144796. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144797. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144798. 10,
  144799. };
  144800. static float _vq_quantthresh__8u1__p1_0[] = {
  144801. -0.5, 0.5,
  144802. };
  144803. static long _vq_quantmap__8u1__p1_0[] = {
  144804. 1, 0, 2,
  144805. };
  144806. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144807. _vq_quantthresh__8u1__p1_0,
  144808. _vq_quantmap__8u1__p1_0,
  144809. 3,
  144810. 3
  144811. };
  144812. static static_codebook _8u1__p1_0 = {
  144813. 4, 81,
  144814. _vq_lengthlist__8u1__p1_0,
  144815. 1, -535822336, 1611661312, 2, 0,
  144816. _vq_quantlist__8u1__p1_0,
  144817. NULL,
  144818. &_vq_auxt__8u1__p1_0,
  144819. NULL,
  144820. 0
  144821. };
  144822. static long _vq_quantlist__8u1__p2_0[] = {
  144823. 1,
  144824. 0,
  144825. 2,
  144826. };
  144827. static long _vq_lengthlist__8u1__p2_0[] = {
  144828. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  144829. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  144830. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  144831. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  144832. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  144833. 7,
  144834. };
  144835. static float _vq_quantthresh__8u1__p2_0[] = {
  144836. -0.5, 0.5,
  144837. };
  144838. static long _vq_quantmap__8u1__p2_0[] = {
  144839. 1, 0, 2,
  144840. };
  144841. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  144842. _vq_quantthresh__8u1__p2_0,
  144843. _vq_quantmap__8u1__p2_0,
  144844. 3,
  144845. 3
  144846. };
  144847. static static_codebook _8u1__p2_0 = {
  144848. 4, 81,
  144849. _vq_lengthlist__8u1__p2_0,
  144850. 1, -535822336, 1611661312, 2, 0,
  144851. _vq_quantlist__8u1__p2_0,
  144852. NULL,
  144853. &_vq_auxt__8u1__p2_0,
  144854. NULL,
  144855. 0
  144856. };
  144857. static long _vq_quantlist__8u1__p3_0[] = {
  144858. 2,
  144859. 1,
  144860. 3,
  144861. 0,
  144862. 4,
  144863. };
  144864. static long _vq_lengthlist__8u1__p3_0[] = {
  144865. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144866. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144867. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  144868. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  144869. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  144870. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  144871. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  144872. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  144873. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  144874. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  144875. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  144876. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  144877. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  144878. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  144879. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  144880. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  144881. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  144882. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  144883. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  144884. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  144885. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  144886. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  144887. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  144888. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  144889. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  144890. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  144891. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  144892. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  144893. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  144894. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  144895. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  144896. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  144897. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  144898. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  144899. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  144900. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  144901. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  144902. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  144903. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  144904. 16,
  144905. };
  144906. static float _vq_quantthresh__8u1__p3_0[] = {
  144907. -1.5, -0.5, 0.5, 1.5,
  144908. };
  144909. static long _vq_quantmap__8u1__p3_0[] = {
  144910. 3, 1, 0, 2, 4,
  144911. };
  144912. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  144913. _vq_quantthresh__8u1__p3_0,
  144914. _vq_quantmap__8u1__p3_0,
  144915. 5,
  144916. 5
  144917. };
  144918. static static_codebook _8u1__p3_0 = {
  144919. 4, 625,
  144920. _vq_lengthlist__8u1__p3_0,
  144921. 1, -533725184, 1611661312, 3, 0,
  144922. _vq_quantlist__8u1__p3_0,
  144923. NULL,
  144924. &_vq_auxt__8u1__p3_0,
  144925. NULL,
  144926. 0
  144927. };
  144928. static long _vq_quantlist__8u1__p4_0[] = {
  144929. 2,
  144930. 1,
  144931. 3,
  144932. 0,
  144933. 4,
  144934. };
  144935. static long _vq_lengthlist__8u1__p4_0[] = {
  144936. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  144937. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  144938. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  144939. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  144940. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  144941. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  144942. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  144943. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  144944. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  144945. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  144946. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  144947. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  144948. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  144949. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  144950. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  144951. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  144952. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  144953. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144954. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  144955. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  144956. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  144957. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  144958. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  144959. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  144960. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  144961. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  144962. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  144963. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  144964. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  144965. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  144966. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  144967. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  144968. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  144969. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  144970. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  144971. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  144972. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  144973. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  144974. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  144975. 10,
  144976. };
  144977. static float _vq_quantthresh__8u1__p4_0[] = {
  144978. -1.5, -0.5, 0.5, 1.5,
  144979. };
  144980. static long _vq_quantmap__8u1__p4_0[] = {
  144981. 3, 1, 0, 2, 4,
  144982. };
  144983. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  144984. _vq_quantthresh__8u1__p4_0,
  144985. _vq_quantmap__8u1__p4_0,
  144986. 5,
  144987. 5
  144988. };
  144989. static static_codebook _8u1__p4_0 = {
  144990. 4, 625,
  144991. _vq_lengthlist__8u1__p4_0,
  144992. 1, -533725184, 1611661312, 3, 0,
  144993. _vq_quantlist__8u1__p4_0,
  144994. NULL,
  144995. &_vq_auxt__8u1__p4_0,
  144996. NULL,
  144997. 0
  144998. };
  144999. static long _vq_quantlist__8u1__p5_0[] = {
  145000. 4,
  145001. 3,
  145002. 5,
  145003. 2,
  145004. 6,
  145005. 1,
  145006. 7,
  145007. 0,
  145008. 8,
  145009. };
  145010. static long _vq_lengthlist__8u1__p5_0[] = {
  145011. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145012. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145013. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145014. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145015. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145016. 13,
  145017. };
  145018. static float _vq_quantthresh__8u1__p5_0[] = {
  145019. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145020. };
  145021. static long _vq_quantmap__8u1__p5_0[] = {
  145022. 7, 5, 3, 1, 0, 2, 4, 6,
  145023. 8,
  145024. };
  145025. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145026. _vq_quantthresh__8u1__p5_0,
  145027. _vq_quantmap__8u1__p5_0,
  145028. 9,
  145029. 9
  145030. };
  145031. static static_codebook _8u1__p5_0 = {
  145032. 2, 81,
  145033. _vq_lengthlist__8u1__p5_0,
  145034. 1, -531628032, 1611661312, 4, 0,
  145035. _vq_quantlist__8u1__p5_0,
  145036. NULL,
  145037. &_vq_auxt__8u1__p5_0,
  145038. NULL,
  145039. 0
  145040. };
  145041. static long _vq_quantlist__8u1__p6_0[] = {
  145042. 4,
  145043. 3,
  145044. 5,
  145045. 2,
  145046. 6,
  145047. 1,
  145048. 7,
  145049. 0,
  145050. 8,
  145051. };
  145052. static long _vq_lengthlist__8u1__p6_0[] = {
  145053. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145054. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145055. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145056. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145057. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145058. 10,
  145059. };
  145060. static float _vq_quantthresh__8u1__p6_0[] = {
  145061. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145062. };
  145063. static long _vq_quantmap__8u1__p6_0[] = {
  145064. 7, 5, 3, 1, 0, 2, 4, 6,
  145065. 8,
  145066. };
  145067. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145068. _vq_quantthresh__8u1__p6_0,
  145069. _vq_quantmap__8u1__p6_0,
  145070. 9,
  145071. 9
  145072. };
  145073. static static_codebook _8u1__p6_0 = {
  145074. 2, 81,
  145075. _vq_lengthlist__8u1__p6_0,
  145076. 1, -531628032, 1611661312, 4, 0,
  145077. _vq_quantlist__8u1__p6_0,
  145078. NULL,
  145079. &_vq_auxt__8u1__p6_0,
  145080. NULL,
  145081. 0
  145082. };
  145083. static long _vq_quantlist__8u1__p7_0[] = {
  145084. 1,
  145085. 0,
  145086. 2,
  145087. };
  145088. static long _vq_lengthlist__8u1__p7_0[] = {
  145089. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145090. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145091. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145092. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145093. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145094. 11,
  145095. };
  145096. static float _vq_quantthresh__8u1__p7_0[] = {
  145097. -5.5, 5.5,
  145098. };
  145099. static long _vq_quantmap__8u1__p7_0[] = {
  145100. 1, 0, 2,
  145101. };
  145102. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145103. _vq_quantthresh__8u1__p7_0,
  145104. _vq_quantmap__8u1__p7_0,
  145105. 3,
  145106. 3
  145107. };
  145108. static static_codebook _8u1__p7_0 = {
  145109. 4, 81,
  145110. _vq_lengthlist__8u1__p7_0,
  145111. 1, -529137664, 1618345984, 2, 0,
  145112. _vq_quantlist__8u1__p7_0,
  145113. NULL,
  145114. &_vq_auxt__8u1__p7_0,
  145115. NULL,
  145116. 0
  145117. };
  145118. static long _vq_quantlist__8u1__p7_1[] = {
  145119. 5,
  145120. 4,
  145121. 6,
  145122. 3,
  145123. 7,
  145124. 2,
  145125. 8,
  145126. 1,
  145127. 9,
  145128. 0,
  145129. 10,
  145130. };
  145131. static long _vq_lengthlist__8u1__p7_1[] = {
  145132. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145133. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145134. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145135. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145136. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145137. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145138. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145139. 9, 9, 9, 9, 9,10,10,10,10,
  145140. };
  145141. static float _vq_quantthresh__8u1__p7_1[] = {
  145142. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145143. 3.5, 4.5,
  145144. };
  145145. static long _vq_quantmap__8u1__p7_1[] = {
  145146. 9, 7, 5, 3, 1, 0, 2, 4,
  145147. 6, 8, 10,
  145148. };
  145149. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145150. _vq_quantthresh__8u1__p7_1,
  145151. _vq_quantmap__8u1__p7_1,
  145152. 11,
  145153. 11
  145154. };
  145155. static static_codebook _8u1__p7_1 = {
  145156. 2, 121,
  145157. _vq_lengthlist__8u1__p7_1,
  145158. 1, -531365888, 1611661312, 4, 0,
  145159. _vq_quantlist__8u1__p7_1,
  145160. NULL,
  145161. &_vq_auxt__8u1__p7_1,
  145162. NULL,
  145163. 0
  145164. };
  145165. static long _vq_quantlist__8u1__p8_0[] = {
  145166. 5,
  145167. 4,
  145168. 6,
  145169. 3,
  145170. 7,
  145171. 2,
  145172. 8,
  145173. 1,
  145174. 9,
  145175. 0,
  145176. 10,
  145177. };
  145178. static long _vq_lengthlist__8u1__p8_0[] = {
  145179. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145180. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145181. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145182. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145183. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145184. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145185. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145186. 12,13,13,14,14,15,15,15,15,
  145187. };
  145188. static float _vq_quantthresh__8u1__p8_0[] = {
  145189. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145190. 38.5, 49.5,
  145191. };
  145192. static long _vq_quantmap__8u1__p8_0[] = {
  145193. 9, 7, 5, 3, 1, 0, 2, 4,
  145194. 6, 8, 10,
  145195. };
  145196. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145197. _vq_quantthresh__8u1__p8_0,
  145198. _vq_quantmap__8u1__p8_0,
  145199. 11,
  145200. 11
  145201. };
  145202. static static_codebook _8u1__p8_0 = {
  145203. 2, 121,
  145204. _vq_lengthlist__8u1__p8_0,
  145205. 1, -524582912, 1618345984, 4, 0,
  145206. _vq_quantlist__8u1__p8_0,
  145207. NULL,
  145208. &_vq_auxt__8u1__p8_0,
  145209. NULL,
  145210. 0
  145211. };
  145212. static long _vq_quantlist__8u1__p8_1[] = {
  145213. 5,
  145214. 4,
  145215. 6,
  145216. 3,
  145217. 7,
  145218. 2,
  145219. 8,
  145220. 1,
  145221. 9,
  145222. 0,
  145223. 10,
  145224. };
  145225. static long _vq_lengthlist__8u1__p8_1[] = {
  145226. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145227. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145228. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145229. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145230. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145231. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145232. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145233. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145234. };
  145235. static float _vq_quantthresh__8u1__p8_1[] = {
  145236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145237. 3.5, 4.5,
  145238. };
  145239. static long _vq_quantmap__8u1__p8_1[] = {
  145240. 9, 7, 5, 3, 1, 0, 2, 4,
  145241. 6, 8, 10,
  145242. };
  145243. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145244. _vq_quantthresh__8u1__p8_1,
  145245. _vq_quantmap__8u1__p8_1,
  145246. 11,
  145247. 11
  145248. };
  145249. static static_codebook _8u1__p8_1 = {
  145250. 2, 121,
  145251. _vq_lengthlist__8u1__p8_1,
  145252. 1, -531365888, 1611661312, 4, 0,
  145253. _vq_quantlist__8u1__p8_1,
  145254. NULL,
  145255. &_vq_auxt__8u1__p8_1,
  145256. NULL,
  145257. 0
  145258. };
  145259. static long _vq_quantlist__8u1__p9_0[] = {
  145260. 7,
  145261. 6,
  145262. 8,
  145263. 5,
  145264. 9,
  145265. 4,
  145266. 10,
  145267. 3,
  145268. 11,
  145269. 2,
  145270. 12,
  145271. 1,
  145272. 13,
  145273. 0,
  145274. 14,
  145275. };
  145276. static long _vq_lengthlist__8u1__p9_0[] = {
  145277. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145278. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145279. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145289. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145291. 10,
  145292. };
  145293. static float _vq_quantthresh__8u1__p9_0[] = {
  145294. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145295. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145296. };
  145297. static long _vq_quantmap__8u1__p9_0[] = {
  145298. 13, 11, 9, 7, 5, 3, 1, 0,
  145299. 2, 4, 6, 8, 10, 12, 14,
  145300. };
  145301. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145302. _vq_quantthresh__8u1__p9_0,
  145303. _vq_quantmap__8u1__p9_0,
  145304. 15,
  145305. 15
  145306. };
  145307. static static_codebook _8u1__p9_0 = {
  145308. 2, 225,
  145309. _vq_lengthlist__8u1__p9_0,
  145310. 1, -514071552, 1627381760, 4, 0,
  145311. _vq_quantlist__8u1__p9_0,
  145312. NULL,
  145313. &_vq_auxt__8u1__p9_0,
  145314. NULL,
  145315. 0
  145316. };
  145317. static long _vq_quantlist__8u1__p9_1[] = {
  145318. 7,
  145319. 6,
  145320. 8,
  145321. 5,
  145322. 9,
  145323. 4,
  145324. 10,
  145325. 3,
  145326. 11,
  145327. 2,
  145328. 12,
  145329. 1,
  145330. 13,
  145331. 0,
  145332. 14,
  145333. };
  145334. static long _vq_lengthlist__8u1__p9_1[] = {
  145335. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145336. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145337. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145338. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145339. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145340. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145341. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145342. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145343. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145344. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145345. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145346. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145347. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145348. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145349. 13,
  145350. };
  145351. static float _vq_quantthresh__8u1__p9_1[] = {
  145352. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145353. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145354. };
  145355. static long _vq_quantmap__8u1__p9_1[] = {
  145356. 13, 11, 9, 7, 5, 3, 1, 0,
  145357. 2, 4, 6, 8, 10, 12, 14,
  145358. };
  145359. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145360. _vq_quantthresh__8u1__p9_1,
  145361. _vq_quantmap__8u1__p9_1,
  145362. 15,
  145363. 15
  145364. };
  145365. static static_codebook _8u1__p9_1 = {
  145366. 2, 225,
  145367. _vq_lengthlist__8u1__p9_1,
  145368. 1, -522338304, 1620115456, 4, 0,
  145369. _vq_quantlist__8u1__p9_1,
  145370. NULL,
  145371. &_vq_auxt__8u1__p9_1,
  145372. NULL,
  145373. 0
  145374. };
  145375. static long _vq_quantlist__8u1__p9_2[] = {
  145376. 8,
  145377. 7,
  145378. 9,
  145379. 6,
  145380. 10,
  145381. 5,
  145382. 11,
  145383. 4,
  145384. 12,
  145385. 3,
  145386. 13,
  145387. 2,
  145388. 14,
  145389. 1,
  145390. 15,
  145391. 0,
  145392. 16,
  145393. };
  145394. static long _vq_lengthlist__8u1__p9_2[] = {
  145395. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145396. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145397. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145398. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145399. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145400. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145401. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145402. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145403. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145404. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145405. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145406. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145407. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145408. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145409. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145410. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145411. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145412. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145413. 10,
  145414. };
  145415. static float _vq_quantthresh__8u1__p9_2[] = {
  145416. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145417. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145418. };
  145419. static long _vq_quantmap__8u1__p9_2[] = {
  145420. 15, 13, 11, 9, 7, 5, 3, 1,
  145421. 0, 2, 4, 6, 8, 10, 12, 14,
  145422. 16,
  145423. };
  145424. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145425. _vq_quantthresh__8u1__p9_2,
  145426. _vq_quantmap__8u1__p9_2,
  145427. 17,
  145428. 17
  145429. };
  145430. static static_codebook _8u1__p9_2 = {
  145431. 2, 289,
  145432. _vq_lengthlist__8u1__p9_2,
  145433. 1, -529530880, 1611661312, 5, 0,
  145434. _vq_quantlist__8u1__p9_2,
  145435. NULL,
  145436. &_vq_auxt__8u1__p9_2,
  145437. NULL,
  145438. 0
  145439. };
  145440. static long _huff_lengthlist__8u1__single[] = {
  145441. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145442. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145443. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145444. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145445. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145446. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145447. 13, 8, 8,15,
  145448. };
  145449. static static_codebook _huff_book__8u1__single = {
  145450. 2, 100,
  145451. _huff_lengthlist__8u1__single,
  145452. 0, 0, 0, 0, 0,
  145453. NULL,
  145454. NULL,
  145455. NULL,
  145456. NULL,
  145457. 0
  145458. };
  145459. static long _huff_lengthlist__44u0__long[] = {
  145460. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145461. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145462. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145463. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145464. };
  145465. static static_codebook _huff_book__44u0__long = {
  145466. 2, 64,
  145467. _huff_lengthlist__44u0__long,
  145468. 0, 0, 0, 0, 0,
  145469. NULL,
  145470. NULL,
  145471. NULL,
  145472. NULL,
  145473. 0
  145474. };
  145475. static long _vq_quantlist__44u0__p1_0[] = {
  145476. 1,
  145477. 0,
  145478. 2,
  145479. };
  145480. static long _vq_lengthlist__44u0__p1_0[] = {
  145481. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145482. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145483. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145484. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145485. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145486. 13,
  145487. };
  145488. static float _vq_quantthresh__44u0__p1_0[] = {
  145489. -0.5, 0.5,
  145490. };
  145491. static long _vq_quantmap__44u0__p1_0[] = {
  145492. 1, 0, 2,
  145493. };
  145494. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145495. _vq_quantthresh__44u0__p1_0,
  145496. _vq_quantmap__44u0__p1_0,
  145497. 3,
  145498. 3
  145499. };
  145500. static static_codebook _44u0__p1_0 = {
  145501. 4, 81,
  145502. _vq_lengthlist__44u0__p1_0,
  145503. 1, -535822336, 1611661312, 2, 0,
  145504. _vq_quantlist__44u0__p1_0,
  145505. NULL,
  145506. &_vq_auxt__44u0__p1_0,
  145507. NULL,
  145508. 0
  145509. };
  145510. static long _vq_quantlist__44u0__p2_0[] = {
  145511. 1,
  145512. 0,
  145513. 2,
  145514. };
  145515. static long _vq_lengthlist__44u0__p2_0[] = {
  145516. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145517. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145518. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145519. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145520. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145521. 9,
  145522. };
  145523. static float _vq_quantthresh__44u0__p2_0[] = {
  145524. -0.5, 0.5,
  145525. };
  145526. static long _vq_quantmap__44u0__p2_0[] = {
  145527. 1, 0, 2,
  145528. };
  145529. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145530. _vq_quantthresh__44u0__p2_0,
  145531. _vq_quantmap__44u0__p2_0,
  145532. 3,
  145533. 3
  145534. };
  145535. static static_codebook _44u0__p2_0 = {
  145536. 4, 81,
  145537. _vq_lengthlist__44u0__p2_0,
  145538. 1, -535822336, 1611661312, 2, 0,
  145539. _vq_quantlist__44u0__p2_0,
  145540. NULL,
  145541. &_vq_auxt__44u0__p2_0,
  145542. NULL,
  145543. 0
  145544. };
  145545. static long _vq_quantlist__44u0__p3_0[] = {
  145546. 2,
  145547. 1,
  145548. 3,
  145549. 0,
  145550. 4,
  145551. };
  145552. static long _vq_lengthlist__44u0__p3_0[] = {
  145553. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145554. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145555. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145556. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145557. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145558. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145559. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145560. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145561. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145562. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145563. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145564. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145565. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145566. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145567. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145568. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145569. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145570. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145571. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145572. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145573. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145574. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145575. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145576. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145577. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145578. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145579. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145580. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145581. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145582. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145583. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145584. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145585. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145586. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145587. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145588. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145589. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145590. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145591. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145592. 19,
  145593. };
  145594. static float _vq_quantthresh__44u0__p3_0[] = {
  145595. -1.5, -0.5, 0.5, 1.5,
  145596. };
  145597. static long _vq_quantmap__44u0__p3_0[] = {
  145598. 3, 1, 0, 2, 4,
  145599. };
  145600. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145601. _vq_quantthresh__44u0__p3_0,
  145602. _vq_quantmap__44u0__p3_0,
  145603. 5,
  145604. 5
  145605. };
  145606. static static_codebook _44u0__p3_0 = {
  145607. 4, 625,
  145608. _vq_lengthlist__44u0__p3_0,
  145609. 1, -533725184, 1611661312, 3, 0,
  145610. _vq_quantlist__44u0__p3_0,
  145611. NULL,
  145612. &_vq_auxt__44u0__p3_0,
  145613. NULL,
  145614. 0
  145615. };
  145616. static long _vq_quantlist__44u0__p4_0[] = {
  145617. 2,
  145618. 1,
  145619. 3,
  145620. 0,
  145621. 4,
  145622. };
  145623. static long _vq_lengthlist__44u0__p4_0[] = {
  145624. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145625. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145626. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145627. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145628. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145629. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145630. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145631. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145632. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145633. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145634. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145635. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145636. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145637. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145638. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145639. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145640. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145641. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145642. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145643. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145644. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145645. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145646. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145647. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145648. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145649. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145650. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145651. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145652. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145653. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145654. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145655. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145656. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145657. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145658. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145659. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145660. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145661. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145662. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145663. 12,
  145664. };
  145665. static float _vq_quantthresh__44u0__p4_0[] = {
  145666. -1.5, -0.5, 0.5, 1.5,
  145667. };
  145668. static long _vq_quantmap__44u0__p4_0[] = {
  145669. 3, 1, 0, 2, 4,
  145670. };
  145671. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145672. _vq_quantthresh__44u0__p4_0,
  145673. _vq_quantmap__44u0__p4_0,
  145674. 5,
  145675. 5
  145676. };
  145677. static static_codebook _44u0__p4_0 = {
  145678. 4, 625,
  145679. _vq_lengthlist__44u0__p4_0,
  145680. 1, -533725184, 1611661312, 3, 0,
  145681. _vq_quantlist__44u0__p4_0,
  145682. NULL,
  145683. &_vq_auxt__44u0__p4_0,
  145684. NULL,
  145685. 0
  145686. };
  145687. static long _vq_quantlist__44u0__p5_0[] = {
  145688. 4,
  145689. 3,
  145690. 5,
  145691. 2,
  145692. 6,
  145693. 1,
  145694. 7,
  145695. 0,
  145696. 8,
  145697. };
  145698. static long _vq_lengthlist__44u0__p5_0[] = {
  145699. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145700. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145701. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145702. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145703. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145704. 12,
  145705. };
  145706. static float _vq_quantthresh__44u0__p5_0[] = {
  145707. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145708. };
  145709. static long _vq_quantmap__44u0__p5_0[] = {
  145710. 7, 5, 3, 1, 0, 2, 4, 6,
  145711. 8,
  145712. };
  145713. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145714. _vq_quantthresh__44u0__p5_0,
  145715. _vq_quantmap__44u0__p5_0,
  145716. 9,
  145717. 9
  145718. };
  145719. static static_codebook _44u0__p5_0 = {
  145720. 2, 81,
  145721. _vq_lengthlist__44u0__p5_0,
  145722. 1, -531628032, 1611661312, 4, 0,
  145723. _vq_quantlist__44u0__p5_0,
  145724. NULL,
  145725. &_vq_auxt__44u0__p5_0,
  145726. NULL,
  145727. 0
  145728. };
  145729. static long _vq_quantlist__44u0__p6_0[] = {
  145730. 6,
  145731. 5,
  145732. 7,
  145733. 4,
  145734. 8,
  145735. 3,
  145736. 9,
  145737. 2,
  145738. 10,
  145739. 1,
  145740. 11,
  145741. 0,
  145742. 12,
  145743. };
  145744. static long _vq_lengthlist__44u0__p6_0[] = {
  145745. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145746. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145747. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145748. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145749. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145750. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145751. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145752. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145753. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145754. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145755. 15,17,16,17,18,17,17,18, 0,
  145756. };
  145757. static float _vq_quantthresh__44u0__p6_0[] = {
  145758. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145759. 12.5, 17.5, 22.5, 27.5,
  145760. };
  145761. static long _vq_quantmap__44u0__p6_0[] = {
  145762. 11, 9, 7, 5, 3, 1, 0, 2,
  145763. 4, 6, 8, 10, 12,
  145764. };
  145765. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145766. _vq_quantthresh__44u0__p6_0,
  145767. _vq_quantmap__44u0__p6_0,
  145768. 13,
  145769. 13
  145770. };
  145771. static static_codebook _44u0__p6_0 = {
  145772. 2, 169,
  145773. _vq_lengthlist__44u0__p6_0,
  145774. 1, -526516224, 1616117760, 4, 0,
  145775. _vq_quantlist__44u0__p6_0,
  145776. NULL,
  145777. &_vq_auxt__44u0__p6_0,
  145778. NULL,
  145779. 0
  145780. };
  145781. static long _vq_quantlist__44u0__p6_1[] = {
  145782. 2,
  145783. 1,
  145784. 3,
  145785. 0,
  145786. 4,
  145787. };
  145788. static long _vq_lengthlist__44u0__p6_1[] = {
  145789. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145790. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145791. };
  145792. static float _vq_quantthresh__44u0__p6_1[] = {
  145793. -1.5, -0.5, 0.5, 1.5,
  145794. };
  145795. static long _vq_quantmap__44u0__p6_1[] = {
  145796. 3, 1, 0, 2, 4,
  145797. };
  145798. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145799. _vq_quantthresh__44u0__p6_1,
  145800. _vq_quantmap__44u0__p6_1,
  145801. 5,
  145802. 5
  145803. };
  145804. static static_codebook _44u0__p6_1 = {
  145805. 2, 25,
  145806. _vq_lengthlist__44u0__p6_1,
  145807. 1, -533725184, 1611661312, 3, 0,
  145808. _vq_quantlist__44u0__p6_1,
  145809. NULL,
  145810. &_vq_auxt__44u0__p6_1,
  145811. NULL,
  145812. 0
  145813. };
  145814. static long _vq_quantlist__44u0__p7_0[] = {
  145815. 2,
  145816. 1,
  145817. 3,
  145818. 0,
  145819. 4,
  145820. };
  145821. static long _vq_lengthlist__44u0__p7_0[] = {
  145822. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  145823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145825. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145829. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  145830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145852. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  145853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145861. 10,
  145862. };
  145863. static float _vq_quantthresh__44u0__p7_0[] = {
  145864. -253.5, -84.5, 84.5, 253.5,
  145865. };
  145866. static long _vq_quantmap__44u0__p7_0[] = {
  145867. 3, 1, 0, 2, 4,
  145868. };
  145869. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  145870. _vq_quantthresh__44u0__p7_0,
  145871. _vq_quantmap__44u0__p7_0,
  145872. 5,
  145873. 5
  145874. };
  145875. static static_codebook _44u0__p7_0 = {
  145876. 4, 625,
  145877. _vq_lengthlist__44u0__p7_0,
  145878. 1, -518709248, 1626677248, 3, 0,
  145879. _vq_quantlist__44u0__p7_0,
  145880. NULL,
  145881. &_vq_auxt__44u0__p7_0,
  145882. NULL,
  145883. 0
  145884. };
  145885. static long _vq_quantlist__44u0__p7_1[] = {
  145886. 6,
  145887. 5,
  145888. 7,
  145889. 4,
  145890. 8,
  145891. 3,
  145892. 9,
  145893. 2,
  145894. 10,
  145895. 1,
  145896. 11,
  145897. 0,
  145898. 12,
  145899. };
  145900. static long _vq_lengthlist__44u0__p7_1[] = {
  145901. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  145902. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  145903. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  145904. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  145905. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  145906. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  145907. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  145908. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  145909. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  145910. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  145911. 15,15,15,15,15,15,15,15,15,
  145912. };
  145913. static float _vq_quantthresh__44u0__p7_1[] = {
  145914. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  145915. 32.5, 45.5, 58.5, 71.5,
  145916. };
  145917. static long _vq_quantmap__44u0__p7_1[] = {
  145918. 11, 9, 7, 5, 3, 1, 0, 2,
  145919. 4, 6, 8, 10, 12,
  145920. };
  145921. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  145922. _vq_quantthresh__44u0__p7_1,
  145923. _vq_quantmap__44u0__p7_1,
  145924. 13,
  145925. 13
  145926. };
  145927. static static_codebook _44u0__p7_1 = {
  145928. 2, 169,
  145929. _vq_lengthlist__44u0__p7_1,
  145930. 1, -523010048, 1618608128, 4, 0,
  145931. _vq_quantlist__44u0__p7_1,
  145932. NULL,
  145933. &_vq_auxt__44u0__p7_1,
  145934. NULL,
  145935. 0
  145936. };
  145937. static long _vq_quantlist__44u0__p7_2[] = {
  145938. 6,
  145939. 5,
  145940. 7,
  145941. 4,
  145942. 8,
  145943. 3,
  145944. 9,
  145945. 2,
  145946. 10,
  145947. 1,
  145948. 11,
  145949. 0,
  145950. 12,
  145951. };
  145952. static long _vq_lengthlist__44u0__p7_2[] = {
  145953. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  145954. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  145955. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  145956. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  145957. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  145958. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  145959. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  145960. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145961. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145962. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  145963. 9, 9, 9,10, 9, 9,10,10, 9,
  145964. };
  145965. static float _vq_quantthresh__44u0__p7_2[] = {
  145966. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  145967. 2.5, 3.5, 4.5, 5.5,
  145968. };
  145969. static long _vq_quantmap__44u0__p7_2[] = {
  145970. 11, 9, 7, 5, 3, 1, 0, 2,
  145971. 4, 6, 8, 10, 12,
  145972. };
  145973. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  145974. _vq_quantthresh__44u0__p7_2,
  145975. _vq_quantmap__44u0__p7_2,
  145976. 13,
  145977. 13
  145978. };
  145979. static static_codebook _44u0__p7_2 = {
  145980. 2, 169,
  145981. _vq_lengthlist__44u0__p7_2,
  145982. 1, -531103744, 1611661312, 4, 0,
  145983. _vq_quantlist__44u0__p7_2,
  145984. NULL,
  145985. &_vq_auxt__44u0__p7_2,
  145986. NULL,
  145987. 0
  145988. };
  145989. static long _huff_lengthlist__44u0__short[] = {
  145990. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  145991. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  145992. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  145993. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  145994. };
  145995. static static_codebook _huff_book__44u0__short = {
  145996. 2, 64,
  145997. _huff_lengthlist__44u0__short,
  145998. 0, 0, 0, 0, 0,
  145999. NULL,
  146000. NULL,
  146001. NULL,
  146002. NULL,
  146003. 0
  146004. };
  146005. static long _huff_lengthlist__44u1__long[] = {
  146006. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146007. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146008. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146009. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146010. };
  146011. static static_codebook _huff_book__44u1__long = {
  146012. 2, 64,
  146013. _huff_lengthlist__44u1__long,
  146014. 0, 0, 0, 0, 0,
  146015. NULL,
  146016. NULL,
  146017. NULL,
  146018. NULL,
  146019. 0
  146020. };
  146021. static long _vq_quantlist__44u1__p1_0[] = {
  146022. 1,
  146023. 0,
  146024. 2,
  146025. };
  146026. static long _vq_lengthlist__44u1__p1_0[] = {
  146027. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146028. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146029. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146030. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146031. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146032. 13,
  146033. };
  146034. static float _vq_quantthresh__44u1__p1_0[] = {
  146035. -0.5, 0.5,
  146036. };
  146037. static long _vq_quantmap__44u1__p1_0[] = {
  146038. 1, 0, 2,
  146039. };
  146040. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146041. _vq_quantthresh__44u1__p1_0,
  146042. _vq_quantmap__44u1__p1_0,
  146043. 3,
  146044. 3
  146045. };
  146046. static static_codebook _44u1__p1_0 = {
  146047. 4, 81,
  146048. _vq_lengthlist__44u1__p1_0,
  146049. 1, -535822336, 1611661312, 2, 0,
  146050. _vq_quantlist__44u1__p1_0,
  146051. NULL,
  146052. &_vq_auxt__44u1__p1_0,
  146053. NULL,
  146054. 0
  146055. };
  146056. static long _vq_quantlist__44u1__p2_0[] = {
  146057. 1,
  146058. 0,
  146059. 2,
  146060. };
  146061. static long _vq_lengthlist__44u1__p2_0[] = {
  146062. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146063. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146064. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146065. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146066. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146067. 9,
  146068. };
  146069. static float _vq_quantthresh__44u1__p2_0[] = {
  146070. -0.5, 0.5,
  146071. };
  146072. static long _vq_quantmap__44u1__p2_0[] = {
  146073. 1, 0, 2,
  146074. };
  146075. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146076. _vq_quantthresh__44u1__p2_0,
  146077. _vq_quantmap__44u1__p2_0,
  146078. 3,
  146079. 3
  146080. };
  146081. static static_codebook _44u1__p2_0 = {
  146082. 4, 81,
  146083. _vq_lengthlist__44u1__p2_0,
  146084. 1, -535822336, 1611661312, 2, 0,
  146085. _vq_quantlist__44u1__p2_0,
  146086. NULL,
  146087. &_vq_auxt__44u1__p2_0,
  146088. NULL,
  146089. 0
  146090. };
  146091. static long _vq_quantlist__44u1__p3_0[] = {
  146092. 2,
  146093. 1,
  146094. 3,
  146095. 0,
  146096. 4,
  146097. };
  146098. static long _vq_lengthlist__44u1__p3_0[] = {
  146099. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146100. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146101. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146102. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146103. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146104. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146105. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146106. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146107. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146108. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146109. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146110. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146111. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146112. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146113. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146114. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146115. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146116. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146117. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146118. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146119. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146120. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146121. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146122. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146123. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146124. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146125. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146126. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146127. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146128. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146129. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146130. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146131. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146132. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146133. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146134. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146135. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146136. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146137. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146138. 19,
  146139. };
  146140. static float _vq_quantthresh__44u1__p3_0[] = {
  146141. -1.5, -0.5, 0.5, 1.5,
  146142. };
  146143. static long _vq_quantmap__44u1__p3_0[] = {
  146144. 3, 1, 0, 2, 4,
  146145. };
  146146. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146147. _vq_quantthresh__44u1__p3_0,
  146148. _vq_quantmap__44u1__p3_0,
  146149. 5,
  146150. 5
  146151. };
  146152. static static_codebook _44u1__p3_0 = {
  146153. 4, 625,
  146154. _vq_lengthlist__44u1__p3_0,
  146155. 1, -533725184, 1611661312, 3, 0,
  146156. _vq_quantlist__44u1__p3_0,
  146157. NULL,
  146158. &_vq_auxt__44u1__p3_0,
  146159. NULL,
  146160. 0
  146161. };
  146162. static long _vq_quantlist__44u1__p4_0[] = {
  146163. 2,
  146164. 1,
  146165. 3,
  146166. 0,
  146167. 4,
  146168. };
  146169. static long _vq_lengthlist__44u1__p4_0[] = {
  146170. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146171. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146172. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146173. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146174. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146175. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146176. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146177. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146178. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146179. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146180. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146181. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146182. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146183. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146184. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146185. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146186. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146187. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146188. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146189. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146190. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146191. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146192. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146193. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146194. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146195. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146196. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146197. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146198. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146199. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146200. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146201. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146202. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146203. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146204. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146205. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146206. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146207. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146208. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146209. 12,
  146210. };
  146211. static float _vq_quantthresh__44u1__p4_0[] = {
  146212. -1.5, -0.5, 0.5, 1.5,
  146213. };
  146214. static long _vq_quantmap__44u1__p4_0[] = {
  146215. 3, 1, 0, 2, 4,
  146216. };
  146217. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146218. _vq_quantthresh__44u1__p4_0,
  146219. _vq_quantmap__44u1__p4_0,
  146220. 5,
  146221. 5
  146222. };
  146223. static static_codebook _44u1__p4_0 = {
  146224. 4, 625,
  146225. _vq_lengthlist__44u1__p4_0,
  146226. 1, -533725184, 1611661312, 3, 0,
  146227. _vq_quantlist__44u1__p4_0,
  146228. NULL,
  146229. &_vq_auxt__44u1__p4_0,
  146230. NULL,
  146231. 0
  146232. };
  146233. static long _vq_quantlist__44u1__p5_0[] = {
  146234. 4,
  146235. 3,
  146236. 5,
  146237. 2,
  146238. 6,
  146239. 1,
  146240. 7,
  146241. 0,
  146242. 8,
  146243. };
  146244. static long _vq_lengthlist__44u1__p5_0[] = {
  146245. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146246. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146247. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146248. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146249. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146250. 12,
  146251. };
  146252. static float _vq_quantthresh__44u1__p5_0[] = {
  146253. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146254. };
  146255. static long _vq_quantmap__44u1__p5_0[] = {
  146256. 7, 5, 3, 1, 0, 2, 4, 6,
  146257. 8,
  146258. };
  146259. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146260. _vq_quantthresh__44u1__p5_0,
  146261. _vq_quantmap__44u1__p5_0,
  146262. 9,
  146263. 9
  146264. };
  146265. static static_codebook _44u1__p5_0 = {
  146266. 2, 81,
  146267. _vq_lengthlist__44u1__p5_0,
  146268. 1, -531628032, 1611661312, 4, 0,
  146269. _vq_quantlist__44u1__p5_0,
  146270. NULL,
  146271. &_vq_auxt__44u1__p5_0,
  146272. NULL,
  146273. 0
  146274. };
  146275. static long _vq_quantlist__44u1__p6_0[] = {
  146276. 6,
  146277. 5,
  146278. 7,
  146279. 4,
  146280. 8,
  146281. 3,
  146282. 9,
  146283. 2,
  146284. 10,
  146285. 1,
  146286. 11,
  146287. 0,
  146288. 12,
  146289. };
  146290. static long _vq_lengthlist__44u1__p6_0[] = {
  146291. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146292. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146293. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146294. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146295. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146296. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146297. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146298. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146299. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146300. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146301. 15,17,16,17,18,17,17,18, 0,
  146302. };
  146303. static float _vq_quantthresh__44u1__p6_0[] = {
  146304. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146305. 12.5, 17.5, 22.5, 27.5,
  146306. };
  146307. static long _vq_quantmap__44u1__p6_0[] = {
  146308. 11, 9, 7, 5, 3, 1, 0, 2,
  146309. 4, 6, 8, 10, 12,
  146310. };
  146311. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146312. _vq_quantthresh__44u1__p6_0,
  146313. _vq_quantmap__44u1__p6_0,
  146314. 13,
  146315. 13
  146316. };
  146317. static static_codebook _44u1__p6_0 = {
  146318. 2, 169,
  146319. _vq_lengthlist__44u1__p6_0,
  146320. 1, -526516224, 1616117760, 4, 0,
  146321. _vq_quantlist__44u1__p6_0,
  146322. NULL,
  146323. &_vq_auxt__44u1__p6_0,
  146324. NULL,
  146325. 0
  146326. };
  146327. static long _vq_quantlist__44u1__p6_1[] = {
  146328. 2,
  146329. 1,
  146330. 3,
  146331. 0,
  146332. 4,
  146333. };
  146334. static long _vq_lengthlist__44u1__p6_1[] = {
  146335. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146336. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146337. };
  146338. static float _vq_quantthresh__44u1__p6_1[] = {
  146339. -1.5, -0.5, 0.5, 1.5,
  146340. };
  146341. static long _vq_quantmap__44u1__p6_1[] = {
  146342. 3, 1, 0, 2, 4,
  146343. };
  146344. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146345. _vq_quantthresh__44u1__p6_1,
  146346. _vq_quantmap__44u1__p6_1,
  146347. 5,
  146348. 5
  146349. };
  146350. static static_codebook _44u1__p6_1 = {
  146351. 2, 25,
  146352. _vq_lengthlist__44u1__p6_1,
  146353. 1, -533725184, 1611661312, 3, 0,
  146354. _vq_quantlist__44u1__p6_1,
  146355. NULL,
  146356. &_vq_auxt__44u1__p6_1,
  146357. NULL,
  146358. 0
  146359. };
  146360. static long _vq_quantlist__44u1__p7_0[] = {
  146361. 3,
  146362. 2,
  146363. 4,
  146364. 1,
  146365. 5,
  146366. 0,
  146367. 6,
  146368. };
  146369. static long _vq_lengthlist__44u1__p7_0[] = {
  146370. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146371. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146372. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146373. 8,
  146374. };
  146375. static float _vq_quantthresh__44u1__p7_0[] = {
  146376. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146377. };
  146378. static long _vq_quantmap__44u1__p7_0[] = {
  146379. 5, 3, 1, 0, 2, 4, 6,
  146380. };
  146381. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146382. _vq_quantthresh__44u1__p7_0,
  146383. _vq_quantmap__44u1__p7_0,
  146384. 7,
  146385. 7
  146386. };
  146387. static static_codebook _44u1__p7_0 = {
  146388. 2, 49,
  146389. _vq_lengthlist__44u1__p7_0,
  146390. 1, -518017024, 1626677248, 3, 0,
  146391. _vq_quantlist__44u1__p7_0,
  146392. NULL,
  146393. &_vq_auxt__44u1__p7_0,
  146394. NULL,
  146395. 0
  146396. };
  146397. static long _vq_quantlist__44u1__p7_1[] = {
  146398. 6,
  146399. 5,
  146400. 7,
  146401. 4,
  146402. 8,
  146403. 3,
  146404. 9,
  146405. 2,
  146406. 10,
  146407. 1,
  146408. 11,
  146409. 0,
  146410. 12,
  146411. };
  146412. static long _vq_lengthlist__44u1__p7_1[] = {
  146413. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146414. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146415. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146416. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146417. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146418. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146419. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146420. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146421. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146422. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146423. 15,15,15,15,15,15,15,15,15,
  146424. };
  146425. static float _vq_quantthresh__44u1__p7_1[] = {
  146426. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146427. 32.5, 45.5, 58.5, 71.5,
  146428. };
  146429. static long _vq_quantmap__44u1__p7_1[] = {
  146430. 11, 9, 7, 5, 3, 1, 0, 2,
  146431. 4, 6, 8, 10, 12,
  146432. };
  146433. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146434. _vq_quantthresh__44u1__p7_1,
  146435. _vq_quantmap__44u1__p7_1,
  146436. 13,
  146437. 13
  146438. };
  146439. static static_codebook _44u1__p7_1 = {
  146440. 2, 169,
  146441. _vq_lengthlist__44u1__p7_1,
  146442. 1, -523010048, 1618608128, 4, 0,
  146443. _vq_quantlist__44u1__p7_1,
  146444. NULL,
  146445. &_vq_auxt__44u1__p7_1,
  146446. NULL,
  146447. 0
  146448. };
  146449. static long _vq_quantlist__44u1__p7_2[] = {
  146450. 6,
  146451. 5,
  146452. 7,
  146453. 4,
  146454. 8,
  146455. 3,
  146456. 9,
  146457. 2,
  146458. 10,
  146459. 1,
  146460. 11,
  146461. 0,
  146462. 12,
  146463. };
  146464. static long _vq_lengthlist__44u1__p7_2[] = {
  146465. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146466. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146467. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146468. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146469. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146470. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146471. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146472. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146473. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146474. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146475. 9, 9, 9,10, 9, 9,10,10, 9,
  146476. };
  146477. static float _vq_quantthresh__44u1__p7_2[] = {
  146478. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146479. 2.5, 3.5, 4.5, 5.5,
  146480. };
  146481. static long _vq_quantmap__44u1__p7_2[] = {
  146482. 11, 9, 7, 5, 3, 1, 0, 2,
  146483. 4, 6, 8, 10, 12,
  146484. };
  146485. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146486. _vq_quantthresh__44u1__p7_2,
  146487. _vq_quantmap__44u1__p7_2,
  146488. 13,
  146489. 13
  146490. };
  146491. static static_codebook _44u1__p7_2 = {
  146492. 2, 169,
  146493. _vq_lengthlist__44u1__p7_2,
  146494. 1, -531103744, 1611661312, 4, 0,
  146495. _vq_quantlist__44u1__p7_2,
  146496. NULL,
  146497. &_vq_auxt__44u1__p7_2,
  146498. NULL,
  146499. 0
  146500. };
  146501. static long _huff_lengthlist__44u1__short[] = {
  146502. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146503. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146504. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146505. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146506. };
  146507. static static_codebook _huff_book__44u1__short = {
  146508. 2, 64,
  146509. _huff_lengthlist__44u1__short,
  146510. 0, 0, 0, 0, 0,
  146511. NULL,
  146512. NULL,
  146513. NULL,
  146514. NULL,
  146515. 0
  146516. };
  146517. static long _huff_lengthlist__44u2__long[] = {
  146518. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146519. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146520. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146521. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146522. };
  146523. static static_codebook _huff_book__44u2__long = {
  146524. 2, 64,
  146525. _huff_lengthlist__44u2__long,
  146526. 0, 0, 0, 0, 0,
  146527. NULL,
  146528. NULL,
  146529. NULL,
  146530. NULL,
  146531. 0
  146532. };
  146533. static long _vq_quantlist__44u2__p1_0[] = {
  146534. 1,
  146535. 0,
  146536. 2,
  146537. };
  146538. static long _vq_lengthlist__44u2__p1_0[] = {
  146539. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146540. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146541. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146542. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146543. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146544. 13,
  146545. };
  146546. static float _vq_quantthresh__44u2__p1_0[] = {
  146547. -0.5, 0.5,
  146548. };
  146549. static long _vq_quantmap__44u2__p1_0[] = {
  146550. 1, 0, 2,
  146551. };
  146552. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146553. _vq_quantthresh__44u2__p1_0,
  146554. _vq_quantmap__44u2__p1_0,
  146555. 3,
  146556. 3
  146557. };
  146558. static static_codebook _44u2__p1_0 = {
  146559. 4, 81,
  146560. _vq_lengthlist__44u2__p1_0,
  146561. 1, -535822336, 1611661312, 2, 0,
  146562. _vq_quantlist__44u2__p1_0,
  146563. NULL,
  146564. &_vq_auxt__44u2__p1_0,
  146565. NULL,
  146566. 0
  146567. };
  146568. static long _vq_quantlist__44u2__p2_0[] = {
  146569. 1,
  146570. 0,
  146571. 2,
  146572. };
  146573. static long _vq_lengthlist__44u2__p2_0[] = {
  146574. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146575. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146576. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146577. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146578. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146579. 9,
  146580. };
  146581. static float _vq_quantthresh__44u2__p2_0[] = {
  146582. -0.5, 0.5,
  146583. };
  146584. static long _vq_quantmap__44u2__p2_0[] = {
  146585. 1, 0, 2,
  146586. };
  146587. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146588. _vq_quantthresh__44u2__p2_0,
  146589. _vq_quantmap__44u2__p2_0,
  146590. 3,
  146591. 3
  146592. };
  146593. static static_codebook _44u2__p2_0 = {
  146594. 4, 81,
  146595. _vq_lengthlist__44u2__p2_0,
  146596. 1, -535822336, 1611661312, 2, 0,
  146597. _vq_quantlist__44u2__p2_0,
  146598. NULL,
  146599. &_vq_auxt__44u2__p2_0,
  146600. NULL,
  146601. 0
  146602. };
  146603. static long _vq_quantlist__44u2__p3_0[] = {
  146604. 2,
  146605. 1,
  146606. 3,
  146607. 0,
  146608. 4,
  146609. };
  146610. static long _vq_lengthlist__44u2__p3_0[] = {
  146611. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146612. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146613. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146614. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146615. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146616. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146617. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146618. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146619. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146620. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146621. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146622. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146623. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146624. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146625. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146626. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146627. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146628. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146629. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146630. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146631. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146632. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146633. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146634. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146635. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146636. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146637. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146638. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146639. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146640. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146641. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146642. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146643. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146644. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146645. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146646. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146647. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146648. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146649. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146650. 0,
  146651. };
  146652. static float _vq_quantthresh__44u2__p3_0[] = {
  146653. -1.5, -0.5, 0.5, 1.5,
  146654. };
  146655. static long _vq_quantmap__44u2__p3_0[] = {
  146656. 3, 1, 0, 2, 4,
  146657. };
  146658. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146659. _vq_quantthresh__44u2__p3_0,
  146660. _vq_quantmap__44u2__p3_0,
  146661. 5,
  146662. 5
  146663. };
  146664. static static_codebook _44u2__p3_0 = {
  146665. 4, 625,
  146666. _vq_lengthlist__44u2__p3_0,
  146667. 1, -533725184, 1611661312, 3, 0,
  146668. _vq_quantlist__44u2__p3_0,
  146669. NULL,
  146670. &_vq_auxt__44u2__p3_0,
  146671. NULL,
  146672. 0
  146673. };
  146674. static long _vq_quantlist__44u2__p4_0[] = {
  146675. 2,
  146676. 1,
  146677. 3,
  146678. 0,
  146679. 4,
  146680. };
  146681. static long _vq_lengthlist__44u2__p4_0[] = {
  146682. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146683. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146684. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146685. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146686. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146687. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146688. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146689. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146690. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146691. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146692. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146693. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146694. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146695. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146696. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146697. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146698. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146699. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146700. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146701. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146702. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146703. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146704. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146705. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146706. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146707. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146708. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146709. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146710. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146711. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146712. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146713. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146714. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146715. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146716. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146717. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146718. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146719. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146720. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146721. 13,
  146722. };
  146723. static float _vq_quantthresh__44u2__p4_0[] = {
  146724. -1.5, -0.5, 0.5, 1.5,
  146725. };
  146726. static long _vq_quantmap__44u2__p4_0[] = {
  146727. 3, 1, 0, 2, 4,
  146728. };
  146729. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146730. _vq_quantthresh__44u2__p4_0,
  146731. _vq_quantmap__44u2__p4_0,
  146732. 5,
  146733. 5
  146734. };
  146735. static static_codebook _44u2__p4_0 = {
  146736. 4, 625,
  146737. _vq_lengthlist__44u2__p4_0,
  146738. 1, -533725184, 1611661312, 3, 0,
  146739. _vq_quantlist__44u2__p4_0,
  146740. NULL,
  146741. &_vq_auxt__44u2__p4_0,
  146742. NULL,
  146743. 0
  146744. };
  146745. static long _vq_quantlist__44u2__p5_0[] = {
  146746. 4,
  146747. 3,
  146748. 5,
  146749. 2,
  146750. 6,
  146751. 1,
  146752. 7,
  146753. 0,
  146754. 8,
  146755. };
  146756. static long _vq_lengthlist__44u2__p5_0[] = {
  146757. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146758. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146759. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146760. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146761. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146762. 13,
  146763. };
  146764. static float _vq_quantthresh__44u2__p5_0[] = {
  146765. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146766. };
  146767. static long _vq_quantmap__44u2__p5_0[] = {
  146768. 7, 5, 3, 1, 0, 2, 4, 6,
  146769. 8,
  146770. };
  146771. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146772. _vq_quantthresh__44u2__p5_0,
  146773. _vq_quantmap__44u2__p5_0,
  146774. 9,
  146775. 9
  146776. };
  146777. static static_codebook _44u2__p5_0 = {
  146778. 2, 81,
  146779. _vq_lengthlist__44u2__p5_0,
  146780. 1, -531628032, 1611661312, 4, 0,
  146781. _vq_quantlist__44u2__p5_0,
  146782. NULL,
  146783. &_vq_auxt__44u2__p5_0,
  146784. NULL,
  146785. 0
  146786. };
  146787. static long _vq_quantlist__44u2__p6_0[] = {
  146788. 6,
  146789. 5,
  146790. 7,
  146791. 4,
  146792. 8,
  146793. 3,
  146794. 9,
  146795. 2,
  146796. 10,
  146797. 1,
  146798. 11,
  146799. 0,
  146800. 12,
  146801. };
  146802. static long _vq_lengthlist__44u2__p6_0[] = {
  146803. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146804. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146805. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146806. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146807. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146808. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146809. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146810. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146811. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146812. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146813. 15,17,17,16,18,17,18, 0, 0,
  146814. };
  146815. static float _vq_quantthresh__44u2__p6_0[] = {
  146816. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146817. 12.5, 17.5, 22.5, 27.5,
  146818. };
  146819. static long _vq_quantmap__44u2__p6_0[] = {
  146820. 11, 9, 7, 5, 3, 1, 0, 2,
  146821. 4, 6, 8, 10, 12,
  146822. };
  146823. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  146824. _vq_quantthresh__44u2__p6_0,
  146825. _vq_quantmap__44u2__p6_0,
  146826. 13,
  146827. 13
  146828. };
  146829. static static_codebook _44u2__p6_0 = {
  146830. 2, 169,
  146831. _vq_lengthlist__44u2__p6_0,
  146832. 1, -526516224, 1616117760, 4, 0,
  146833. _vq_quantlist__44u2__p6_0,
  146834. NULL,
  146835. &_vq_auxt__44u2__p6_0,
  146836. NULL,
  146837. 0
  146838. };
  146839. static long _vq_quantlist__44u2__p6_1[] = {
  146840. 2,
  146841. 1,
  146842. 3,
  146843. 0,
  146844. 4,
  146845. };
  146846. static long _vq_lengthlist__44u2__p6_1[] = {
  146847. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  146848. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  146849. };
  146850. static float _vq_quantthresh__44u2__p6_1[] = {
  146851. -1.5, -0.5, 0.5, 1.5,
  146852. };
  146853. static long _vq_quantmap__44u2__p6_1[] = {
  146854. 3, 1, 0, 2, 4,
  146855. };
  146856. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  146857. _vq_quantthresh__44u2__p6_1,
  146858. _vq_quantmap__44u2__p6_1,
  146859. 5,
  146860. 5
  146861. };
  146862. static static_codebook _44u2__p6_1 = {
  146863. 2, 25,
  146864. _vq_lengthlist__44u2__p6_1,
  146865. 1, -533725184, 1611661312, 3, 0,
  146866. _vq_quantlist__44u2__p6_1,
  146867. NULL,
  146868. &_vq_auxt__44u2__p6_1,
  146869. NULL,
  146870. 0
  146871. };
  146872. static long _vq_quantlist__44u2__p7_0[] = {
  146873. 4,
  146874. 3,
  146875. 5,
  146876. 2,
  146877. 6,
  146878. 1,
  146879. 7,
  146880. 0,
  146881. 8,
  146882. };
  146883. static long _vq_lengthlist__44u2__p7_0[] = {
  146884. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  146885. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  146886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146889. 11,
  146890. };
  146891. static float _vq_quantthresh__44u2__p7_0[] = {
  146892. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  146893. };
  146894. static long _vq_quantmap__44u2__p7_0[] = {
  146895. 7, 5, 3, 1, 0, 2, 4, 6,
  146896. 8,
  146897. };
  146898. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  146899. _vq_quantthresh__44u2__p7_0,
  146900. _vq_quantmap__44u2__p7_0,
  146901. 9,
  146902. 9
  146903. };
  146904. static static_codebook _44u2__p7_0 = {
  146905. 2, 81,
  146906. _vq_lengthlist__44u2__p7_0,
  146907. 1, -516612096, 1626677248, 4, 0,
  146908. _vq_quantlist__44u2__p7_0,
  146909. NULL,
  146910. &_vq_auxt__44u2__p7_0,
  146911. NULL,
  146912. 0
  146913. };
  146914. static long _vq_quantlist__44u2__p7_1[] = {
  146915. 6,
  146916. 5,
  146917. 7,
  146918. 4,
  146919. 8,
  146920. 3,
  146921. 9,
  146922. 2,
  146923. 10,
  146924. 1,
  146925. 11,
  146926. 0,
  146927. 12,
  146928. };
  146929. static long _vq_lengthlist__44u2__p7_1[] = {
  146930. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  146931. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  146932. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  146933. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  146934. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  146935. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  146936. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  146937. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  146938. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  146939. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  146940. 14,14,14,17,15,17,17,17,17,
  146941. };
  146942. static float _vq_quantthresh__44u2__p7_1[] = {
  146943. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146944. 32.5, 45.5, 58.5, 71.5,
  146945. };
  146946. static long _vq_quantmap__44u2__p7_1[] = {
  146947. 11, 9, 7, 5, 3, 1, 0, 2,
  146948. 4, 6, 8, 10, 12,
  146949. };
  146950. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  146951. _vq_quantthresh__44u2__p7_1,
  146952. _vq_quantmap__44u2__p7_1,
  146953. 13,
  146954. 13
  146955. };
  146956. static static_codebook _44u2__p7_1 = {
  146957. 2, 169,
  146958. _vq_lengthlist__44u2__p7_1,
  146959. 1, -523010048, 1618608128, 4, 0,
  146960. _vq_quantlist__44u2__p7_1,
  146961. NULL,
  146962. &_vq_auxt__44u2__p7_1,
  146963. NULL,
  146964. 0
  146965. };
  146966. static long _vq_quantlist__44u2__p7_2[] = {
  146967. 6,
  146968. 5,
  146969. 7,
  146970. 4,
  146971. 8,
  146972. 3,
  146973. 9,
  146974. 2,
  146975. 10,
  146976. 1,
  146977. 11,
  146978. 0,
  146979. 12,
  146980. };
  146981. static long _vq_lengthlist__44u2__p7_2[] = {
  146982. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  146983. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  146984. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  146985. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146986. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  146987. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  146988. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146989. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146990. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  146991. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  146992. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146993. };
  146994. static float _vq_quantthresh__44u2__p7_2[] = {
  146995. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146996. 2.5, 3.5, 4.5, 5.5,
  146997. };
  146998. static long _vq_quantmap__44u2__p7_2[] = {
  146999. 11, 9, 7, 5, 3, 1, 0, 2,
  147000. 4, 6, 8, 10, 12,
  147001. };
  147002. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147003. _vq_quantthresh__44u2__p7_2,
  147004. _vq_quantmap__44u2__p7_2,
  147005. 13,
  147006. 13
  147007. };
  147008. static static_codebook _44u2__p7_2 = {
  147009. 2, 169,
  147010. _vq_lengthlist__44u2__p7_2,
  147011. 1, -531103744, 1611661312, 4, 0,
  147012. _vq_quantlist__44u2__p7_2,
  147013. NULL,
  147014. &_vq_auxt__44u2__p7_2,
  147015. NULL,
  147016. 0
  147017. };
  147018. static long _huff_lengthlist__44u2__short[] = {
  147019. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147020. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147021. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147022. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147023. };
  147024. static static_codebook _huff_book__44u2__short = {
  147025. 2, 64,
  147026. _huff_lengthlist__44u2__short,
  147027. 0, 0, 0, 0, 0,
  147028. NULL,
  147029. NULL,
  147030. NULL,
  147031. NULL,
  147032. 0
  147033. };
  147034. static long _huff_lengthlist__44u3__long[] = {
  147035. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147036. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147037. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147038. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147039. };
  147040. static static_codebook _huff_book__44u3__long = {
  147041. 2, 64,
  147042. _huff_lengthlist__44u3__long,
  147043. 0, 0, 0, 0, 0,
  147044. NULL,
  147045. NULL,
  147046. NULL,
  147047. NULL,
  147048. 0
  147049. };
  147050. static long _vq_quantlist__44u3__p1_0[] = {
  147051. 1,
  147052. 0,
  147053. 2,
  147054. };
  147055. static long _vq_lengthlist__44u3__p1_0[] = {
  147056. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147057. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147058. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147059. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147060. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147061. 13,
  147062. };
  147063. static float _vq_quantthresh__44u3__p1_0[] = {
  147064. -0.5, 0.5,
  147065. };
  147066. static long _vq_quantmap__44u3__p1_0[] = {
  147067. 1, 0, 2,
  147068. };
  147069. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147070. _vq_quantthresh__44u3__p1_0,
  147071. _vq_quantmap__44u3__p1_0,
  147072. 3,
  147073. 3
  147074. };
  147075. static static_codebook _44u3__p1_0 = {
  147076. 4, 81,
  147077. _vq_lengthlist__44u3__p1_0,
  147078. 1, -535822336, 1611661312, 2, 0,
  147079. _vq_quantlist__44u3__p1_0,
  147080. NULL,
  147081. &_vq_auxt__44u3__p1_0,
  147082. NULL,
  147083. 0
  147084. };
  147085. static long _vq_quantlist__44u3__p2_0[] = {
  147086. 1,
  147087. 0,
  147088. 2,
  147089. };
  147090. static long _vq_lengthlist__44u3__p2_0[] = {
  147091. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147092. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147093. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147094. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147095. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147096. 9,
  147097. };
  147098. static float _vq_quantthresh__44u3__p2_0[] = {
  147099. -0.5, 0.5,
  147100. };
  147101. static long _vq_quantmap__44u3__p2_0[] = {
  147102. 1, 0, 2,
  147103. };
  147104. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147105. _vq_quantthresh__44u3__p2_0,
  147106. _vq_quantmap__44u3__p2_0,
  147107. 3,
  147108. 3
  147109. };
  147110. static static_codebook _44u3__p2_0 = {
  147111. 4, 81,
  147112. _vq_lengthlist__44u3__p2_0,
  147113. 1, -535822336, 1611661312, 2, 0,
  147114. _vq_quantlist__44u3__p2_0,
  147115. NULL,
  147116. &_vq_auxt__44u3__p2_0,
  147117. NULL,
  147118. 0
  147119. };
  147120. static long _vq_quantlist__44u3__p3_0[] = {
  147121. 2,
  147122. 1,
  147123. 3,
  147124. 0,
  147125. 4,
  147126. };
  147127. static long _vq_lengthlist__44u3__p3_0[] = {
  147128. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147129. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147130. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147131. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147132. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147133. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147134. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147135. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147136. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147137. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147138. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147139. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147140. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147141. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147142. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147143. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147144. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147145. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147146. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147147. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147148. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147149. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147150. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147151. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147152. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147153. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147154. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147155. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147156. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147157. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147158. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147159. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147160. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147161. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147162. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147163. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147164. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147165. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147166. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147167. 0,
  147168. };
  147169. static float _vq_quantthresh__44u3__p3_0[] = {
  147170. -1.5, -0.5, 0.5, 1.5,
  147171. };
  147172. static long _vq_quantmap__44u3__p3_0[] = {
  147173. 3, 1, 0, 2, 4,
  147174. };
  147175. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147176. _vq_quantthresh__44u3__p3_0,
  147177. _vq_quantmap__44u3__p3_0,
  147178. 5,
  147179. 5
  147180. };
  147181. static static_codebook _44u3__p3_0 = {
  147182. 4, 625,
  147183. _vq_lengthlist__44u3__p3_0,
  147184. 1, -533725184, 1611661312, 3, 0,
  147185. _vq_quantlist__44u3__p3_0,
  147186. NULL,
  147187. &_vq_auxt__44u3__p3_0,
  147188. NULL,
  147189. 0
  147190. };
  147191. static long _vq_quantlist__44u3__p4_0[] = {
  147192. 2,
  147193. 1,
  147194. 3,
  147195. 0,
  147196. 4,
  147197. };
  147198. static long _vq_lengthlist__44u3__p4_0[] = {
  147199. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147200. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147201. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147202. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147203. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147204. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147205. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147206. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147207. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147208. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147209. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147210. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147211. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147212. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147213. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147214. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147215. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147216. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147217. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147218. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147219. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147220. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147221. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147222. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147223. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147224. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147225. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147226. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147227. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147228. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147229. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147230. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147231. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147232. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147233. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147234. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147235. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147236. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147237. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147238. 13,
  147239. };
  147240. static float _vq_quantthresh__44u3__p4_0[] = {
  147241. -1.5, -0.5, 0.5, 1.5,
  147242. };
  147243. static long _vq_quantmap__44u3__p4_0[] = {
  147244. 3, 1, 0, 2, 4,
  147245. };
  147246. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147247. _vq_quantthresh__44u3__p4_0,
  147248. _vq_quantmap__44u3__p4_0,
  147249. 5,
  147250. 5
  147251. };
  147252. static static_codebook _44u3__p4_0 = {
  147253. 4, 625,
  147254. _vq_lengthlist__44u3__p4_0,
  147255. 1, -533725184, 1611661312, 3, 0,
  147256. _vq_quantlist__44u3__p4_0,
  147257. NULL,
  147258. &_vq_auxt__44u3__p4_0,
  147259. NULL,
  147260. 0
  147261. };
  147262. static long _vq_quantlist__44u3__p5_0[] = {
  147263. 4,
  147264. 3,
  147265. 5,
  147266. 2,
  147267. 6,
  147268. 1,
  147269. 7,
  147270. 0,
  147271. 8,
  147272. };
  147273. static long _vq_lengthlist__44u3__p5_0[] = {
  147274. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147275. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147276. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147277. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147278. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147279. 12,
  147280. };
  147281. static float _vq_quantthresh__44u3__p5_0[] = {
  147282. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147283. };
  147284. static long _vq_quantmap__44u3__p5_0[] = {
  147285. 7, 5, 3, 1, 0, 2, 4, 6,
  147286. 8,
  147287. };
  147288. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147289. _vq_quantthresh__44u3__p5_0,
  147290. _vq_quantmap__44u3__p5_0,
  147291. 9,
  147292. 9
  147293. };
  147294. static static_codebook _44u3__p5_0 = {
  147295. 2, 81,
  147296. _vq_lengthlist__44u3__p5_0,
  147297. 1, -531628032, 1611661312, 4, 0,
  147298. _vq_quantlist__44u3__p5_0,
  147299. NULL,
  147300. &_vq_auxt__44u3__p5_0,
  147301. NULL,
  147302. 0
  147303. };
  147304. static long _vq_quantlist__44u3__p6_0[] = {
  147305. 6,
  147306. 5,
  147307. 7,
  147308. 4,
  147309. 8,
  147310. 3,
  147311. 9,
  147312. 2,
  147313. 10,
  147314. 1,
  147315. 11,
  147316. 0,
  147317. 12,
  147318. };
  147319. static long _vq_lengthlist__44u3__p6_0[] = {
  147320. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147321. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147322. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147323. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147324. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147325. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147326. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147327. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147328. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147329. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147330. 15,16,16,16,17,18,16,20,18,
  147331. };
  147332. static float _vq_quantthresh__44u3__p6_0[] = {
  147333. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147334. 12.5, 17.5, 22.5, 27.5,
  147335. };
  147336. static long _vq_quantmap__44u3__p6_0[] = {
  147337. 11, 9, 7, 5, 3, 1, 0, 2,
  147338. 4, 6, 8, 10, 12,
  147339. };
  147340. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147341. _vq_quantthresh__44u3__p6_0,
  147342. _vq_quantmap__44u3__p6_0,
  147343. 13,
  147344. 13
  147345. };
  147346. static static_codebook _44u3__p6_0 = {
  147347. 2, 169,
  147348. _vq_lengthlist__44u3__p6_0,
  147349. 1, -526516224, 1616117760, 4, 0,
  147350. _vq_quantlist__44u3__p6_0,
  147351. NULL,
  147352. &_vq_auxt__44u3__p6_0,
  147353. NULL,
  147354. 0
  147355. };
  147356. static long _vq_quantlist__44u3__p6_1[] = {
  147357. 2,
  147358. 1,
  147359. 3,
  147360. 0,
  147361. 4,
  147362. };
  147363. static long _vq_lengthlist__44u3__p6_1[] = {
  147364. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147365. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147366. };
  147367. static float _vq_quantthresh__44u3__p6_1[] = {
  147368. -1.5, -0.5, 0.5, 1.5,
  147369. };
  147370. static long _vq_quantmap__44u3__p6_1[] = {
  147371. 3, 1, 0, 2, 4,
  147372. };
  147373. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147374. _vq_quantthresh__44u3__p6_1,
  147375. _vq_quantmap__44u3__p6_1,
  147376. 5,
  147377. 5
  147378. };
  147379. static static_codebook _44u3__p6_1 = {
  147380. 2, 25,
  147381. _vq_lengthlist__44u3__p6_1,
  147382. 1, -533725184, 1611661312, 3, 0,
  147383. _vq_quantlist__44u3__p6_1,
  147384. NULL,
  147385. &_vq_auxt__44u3__p6_1,
  147386. NULL,
  147387. 0
  147388. };
  147389. static long _vq_quantlist__44u3__p7_0[] = {
  147390. 4,
  147391. 3,
  147392. 5,
  147393. 2,
  147394. 6,
  147395. 1,
  147396. 7,
  147397. 0,
  147398. 8,
  147399. };
  147400. static long _vq_lengthlist__44u3__p7_0[] = {
  147401. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147402. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147403. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147404. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147405. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147406. 9,
  147407. };
  147408. static float _vq_quantthresh__44u3__p7_0[] = {
  147409. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147410. };
  147411. static long _vq_quantmap__44u3__p7_0[] = {
  147412. 7, 5, 3, 1, 0, 2, 4, 6,
  147413. 8,
  147414. };
  147415. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147416. _vq_quantthresh__44u3__p7_0,
  147417. _vq_quantmap__44u3__p7_0,
  147418. 9,
  147419. 9
  147420. };
  147421. static static_codebook _44u3__p7_0 = {
  147422. 2, 81,
  147423. _vq_lengthlist__44u3__p7_0,
  147424. 1, -515907584, 1627381760, 4, 0,
  147425. _vq_quantlist__44u3__p7_0,
  147426. NULL,
  147427. &_vq_auxt__44u3__p7_0,
  147428. NULL,
  147429. 0
  147430. };
  147431. static long _vq_quantlist__44u3__p7_1[] = {
  147432. 7,
  147433. 6,
  147434. 8,
  147435. 5,
  147436. 9,
  147437. 4,
  147438. 10,
  147439. 3,
  147440. 11,
  147441. 2,
  147442. 12,
  147443. 1,
  147444. 13,
  147445. 0,
  147446. 14,
  147447. };
  147448. static long _vq_lengthlist__44u3__p7_1[] = {
  147449. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147450. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147451. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147452. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147453. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147454. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147455. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147456. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147457. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147458. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147459. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147460. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147461. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147462. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147463. 17,
  147464. };
  147465. static float _vq_quantthresh__44u3__p7_1[] = {
  147466. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147467. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147468. };
  147469. static long _vq_quantmap__44u3__p7_1[] = {
  147470. 13, 11, 9, 7, 5, 3, 1, 0,
  147471. 2, 4, 6, 8, 10, 12, 14,
  147472. };
  147473. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147474. _vq_quantthresh__44u3__p7_1,
  147475. _vq_quantmap__44u3__p7_1,
  147476. 15,
  147477. 15
  147478. };
  147479. static static_codebook _44u3__p7_1 = {
  147480. 2, 225,
  147481. _vq_lengthlist__44u3__p7_1,
  147482. 1, -522338304, 1620115456, 4, 0,
  147483. _vq_quantlist__44u3__p7_1,
  147484. NULL,
  147485. &_vq_auxt__44u3__p7_1,
  147486. NULL,
  147487. 0
  147488. };
  147489. static long _vq_quantlist__44u3__p7_2[] = {
  147490. 8,
  147491. 7,
  147492. 9,
  147493. 6,
  147494. 10,
  147495. 5,
  147496. 11,
  147497. 4,
  147498. 12,
  147499. 3,
  147500. 13,
  147501. 2,
  147502. 14,
  147503. 1,
  147504. 15,
  147505. 0,
  147506. 16,
  147507. };
  147508. static long _vq_lengthlist__44u3__p7_2[] = {
  147509. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147510. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147511. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147512. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147513. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147514. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147515. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147516. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147517. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147518. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147519. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147520. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147521. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147522. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147523. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147526. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147527. 11,
  147528. };
  147529. static float _vq_quantthresh__44u3__p7_2[] = {
  147530. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147531. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147532. };
  147533. static long _vq_quantmap__44u3__p7_2[] = {
  147534. 15, 13, 11, 9, 7, 5, 3, 1,
  147535. 0, 2, 4, 6, 8, 10, 12, 14,
  147536. 16,
  147537. };
  147538. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147539. _vq_quantthresh__44u3__p7_2,
  147540. _vq_quantmap__44u3__p7_2,
  147541. 17,
  147542. 17
  147543. };
  147544. static static_codebook _44u3__p7_2 = {
  147545. 2, 289,
  147546. _vq_lengthlist__44u3__p7_2,
  147547. 1, -529530880, 1611661312, 5, 0,
  147548. _vq_quantlist__44u3__p7_2,
  147549. NULL,
  147550. &_vq_auxt__44u3__p7_2,
  147551. NULL,
  147552. 0
  147553. };
  147554. static long _huff_lengthlist__44u3__short[] = {
  147555. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147556. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147557. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147558. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147559. };
  147560. static static_codebook _huff_book__44u3__short = {
  147561. 2, 64,
  147562. _huff_lengthlist__44u3__short,
  147563. 0, 0, 0, 0, 0,
  147564. NULL,
  147565. NULL,
  147566. NULL,
  147567. NULL,
  147568. 0
  147569. };
  147570. static long _huff_lengthlist__44u4__long[] = {
  147571. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147572. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147573. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147574. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147575. };
  147576. static static_codebook _huff_book__44u4__long = {
  147577. 2, 64,
  147578. _huff_lengthlist__44u4__long,
  147579. 0, 0, 0, 0, 0,
  147580. NULL,
  147581. NULL,
  147582. NULL,
  147583. NULL,
  147584. 0
  147585. };
  147586. static long _vq_quantlist__44u4__p1_0[] = {
  147587. 1,
  147588. 0,
  147589. 2,
  147590. };
  147591. static long _vq_lengthlist__44u4__p1_0[] = {
  147592. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147593. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147594. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147595. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147596. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147597. 13,
  147598. };
  147599. static float _vq_quantthresh__44u4__p1_0[] = {
  147600. -0.5, 0.5,
  147601. };
  147602. static long _vq_quantmap__44u4__p1_0[] = {
  147603. 1, 0, 2,
  147604. };
  147605. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147606. _vq_quantthresh__44u4__p1_0,
  147607. _vq_quantmap__44u4__p1_0,
  147608. 3,
  147609. 3
  147610. };
  147611. static static_codebook _44u4__p1_0 = {
  147612. 4, 81,
  147613. _vq_lengthlist__44u4__p1_0,
  147614. 1, -535822336, 1611661312, 2, 0,
  147615. _vq_quantlist__44u4__p1_0,
  147616. NULL,
  147617. &_vq_auxt__44u4__p1_0,
  147618. NULL,
  147619. 0
  147620. };
  147621. static long _vq_quantlist__44u4__p2_0[] = {
  147622. 1,
  147623. 0,
  147624. 2,
  147625. };
  147626. static long _vq_lengthlist__44u4__p2_0[] = {
  147627. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147628. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147629. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147630. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147631. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147632. 9,
  147633. };
  147634. static float _vq_quantthresh__44u4__p2_0[] = {
  147635. -0.5, 0.5,
  147636. };
  147637. static long _vq_quantmap__44u4__p2_0[] = {
  147638. 1, 0, 2,
  147639. };
  147640. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147641. _vq_quantthresh__44u4__p2_0,
  147642. _vq_quantmap__44u4__p2_0,
  147643. 3,
  147644. 3
  147645. };
  147646. static static_codebook _44u4__p2_0 = {
  147647. 4, 81,
  147648. _vq_lengthlist__44u4__p2_0,
  147649. 1, -535822336, 1611661312, 2, 0,
  147650. _vq_quantlist__44u4__p2_0,
  147651. NULL,
  147652. &_vq_auxt__44u4__p2_0,
  147653. NULL,
  147654. 0
  147655. };
  147656. static long _vq_quantlist__44u4__p3_0[] = {
  147657. 2,
  147658. 1,
  147659. 3,
  147660. 0,
  147661. 4,
  147662. };
  147663. static long _vq_lengthlist__44u4__p3_0[] = {
  147664. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147665. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147666. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147667. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147668. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147669. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147670. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147671. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147672. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147673. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147674. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147675. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147676. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147677. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147678. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147679. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147680. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147681. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147682. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147683. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147684. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147685. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147686. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147687. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147688. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147689. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147690. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147691. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147692. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147693. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147694. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147695. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147696. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147697. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147698. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147699. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147700. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147701. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147702. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147703. 0,
  147704. };
  147705. static float _vq_quantthresh__44u4__p3_0[] = {
  147706. -1.5, -0.5, 0.5, 1.5,
  147707. };
  147708. static long _vq_quantmap__44u4__p3_0[] = {
  147709. 3, 1, 0, 2, 4,
  147710. };
  147711. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147712. _vq_quantthresh__44u4__p3_0,
  147713. _vq_quantmap__44u4__p3_0,
  147714. 5,
  147715. 5
  147716. };
  147717. static static_codebook _44u4__p3_0 = {
  147718. 4, 625,
  147719. _vq_lengthlist__44u4__p3_0,
  147720. 1, -533725184, 1611661312, 3, 0,
  147721. _vq_quantlist__44u4__p3_0,
  147722. NULL,
  147723. &_vq_auxt__44u4__p3_0,
  147724. NULL,
  147725. 0
  147726. };
  147727. static long _vq_quantlist__44u4__p4_0[] = {
  147728. 2,
  147729. 1,
  147730. 3,
  147731. 0,
  147732. 4,
  147733. };
  147734. static long _vq_lengthlist__44u4__p4_0[] = {
  147735. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147736. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147737. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147738. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147739. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147740. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147741. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147742. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147743. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147744. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147745. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147746. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147747. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147748. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147749. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147750. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147751. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147752. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147753. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147754. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147755. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147756. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147757. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147758. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147759. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147760. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147761. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147762. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147763. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147764. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147765. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147766. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147767. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147768. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147769. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147770. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147771. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147772. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147773. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147774. 13,
  147775. };
  147776. static float _vq_quantthresh__44u4__p4_0[] = {
  147777. -1.5, -0.5, 0.5, 1.5,
  147778. };
  147779. static long _vq_quantmap__44u4__p4_0[] = {
  147780. 3, 1, 0, 2, 4,
  147781. };
  147782. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147783. _vq_quantthresh__44u4__p4_0,
  147784. _vq_quantmap__44u4__p4_0,
  147785. 5,
  147786. 5
  147787. };
  147788. static static_codebook _44u4__p4_0 = {
  147789. 4, 625,
  147790. _vq_lengthlist__44u4__p4_0,
  147791. 1, -533725184, 1611661312, 3, 0,
  147792. _vq_quantlist__44u4__p4_0,
  147793. NULL,
  147794. &_vq_auxt__44u4__p4_0,
  147795. NULL,
  147796. 0
  147797. };
  147798. static long _vq_quantlist__44u4__p5_0[] = {
  147799. 4,
  147800. 3,
  147801. 5,
  147802. 2,
  147803. 6,
  147804. 1,
  147805. 7,
  147806. 0,
  147807. 8,
  147808. };
  147809. static long _vq_lengthlist__44u4__p5_0[] = {
  147810. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147811. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147812. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147813. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147814. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147815. 12,
  147816. };
  147817. static float _vq_quantthresh__44u4__p5_0[] = {
  147818. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147819. };
  147820. static long _vq_quantmap__44u4__p5_0[] = {
  147821. 7, 5, 3, 1, 0, 2, 4, 6,
  147822. 8,
  147823. };
  147824. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  147825. _vq_quantthresh__44u4__p5_0,
  147826. _vq_quantmap__44u4__p5_0,
  147827. 9,
  147828. 9
  147829. };
  147830. static static_codebook _44u4__p5_0 = {
  147831. 2, 81,
  147832. _vq_lengthlist__44u4__p5_0,
  147833. 1, -531628032, 1611661312, 4, 0,
  147834. _vq_quantlist__44u4__p5_0,
  147835. NULL,
  147836. &_vq_auxt__44u4__p5_0,
  147837. NULL,
  147838. 0
  147839. };
  147840. static long _vq_quantlist__44u4__p6_0[] = {
  147841. 6,
  147842. 5,
  147843. 7,
  147844. 4,
  147845. 8,
  147846. 3,
  147847. 9,
  147848. 2,
  147849. 10,
  147850. 1,
  147851. 11,
  147852. 0,
  147853. 12,
  147854. };
  147855. static long _vq_lengthlist__44u4__p6_0[] = {
  147856. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  147857. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147858. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147859. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147860. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  147861. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  147862. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  147863. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  147864. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  147865. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  147866. 16,16,16,17,17,18,17,20,21,
  147867. };
  147868. static float _vq_quantthresh__44u4__p6_0[] = {
  147869. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147870. 12.5, 17.5, 22.5, 27.5,
  147871. };
  147872. static long _vq_quantmap__44u4__p6_0[] = {
  147873. 11, 9, 7, 5, 3, 1, 0, 2,
  147874. 4, 6, 8, 10, 12,
  147875. };
  147876. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  147877. _vq_quantthresh__44u4__p6_0,
  147878. _vq_quantmap__44u4__p6_0,
  147879. 13,
  147880. 13
  147881. };
  147882. static static_codebook _44u4__p6_0 = {
  147883. 2, 169,
  147884. _vq_lengthlist__44u4__p6_0,
  147885. 1, -526516224, 1616117760, 4, 0,
  147886. _vq_quantlist__44u4__p6_0,
  147887. NULL,
  147888. &_vq_auxt__44u4__p6_0,
  147889. NULL,
  147890. 0
  147891. };
  147892. static long _vq_quantlist__44u4__p6_1[] = {
  147893. 2,
  147894. 1,
  147895. 3,
  147896. 0,
  147897. 4,
  147898. };
  147899. static long _vq_lengthlist__44u4__p6_1[] = {
  147900. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147901. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147902. };
  147903. static float _vq_quantthresh__44u4__p6_1[] = {
  147904. -1.5, -0.5, 0.5, 1.5,
  147905. };
  147906. static long _vq_quantmap__44u4__p6_1[] = {
  147907. 3, 1, 0, 2, 4,
  147908. };
  147909. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  147910. _vq_quantthresh__44u4__p6_1,
  147911. _vq_quantmap__44u4__p6_1,
  147912. 5,
  147913. 5
  147914. };
  147915. static static_codebook _44u4__p6_1 = {
  147916. 2, 25,
  147917. _vq_lengthlist__44u4__p6_1,
  147918. 1, -533725184, 1611661312, 3, 0,
  147919. _vq_quantlist__44u4__p6_1,
  147920. NULL,
  147921. &_vq_auxt__44u4__p6_1,
  147922. NULL,
  147923. 0
  147924. };
  147925. static long _vq_quantlist__44u4__p7_0[] = {
  147926. 6,
  147927. 5,
  147928. 7,
  147929. 4,
  147930. 8,
  147931. 3,
  147932. 9,
  147933. 2,
  147934. 10,
  147935. 1,
  147936. 11,
  147937. 0,
  147938. 12,
  147939. };
  147940. static long _vq_lengthlist__44u4__p7_0[] = {
  147941. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  147942. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  147943. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147944. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147945. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147946. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147947. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147948. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147949. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147950. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147951. 11,11,11,11,11,11,11,11,11,
  147952. };
  147953. static float _vq_quantthresh__44u4__p7_0[] = {
  147954. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  147955. 637.5, 892.5, 1147.5, 1402.5,
  147956. };
  147957. static long _vq_quantmap__44u4__p7_0[] = {
  147958. 11, 9, 7, 5, 3, 1, 0, 2,
  147959. 4, 6, 8, 10, 12,
  147960. };
  147961. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  147962. _vq_quantthresh__44u4__p7_0,
  147963. _vq_quantmap__44u4__p7_0,
  147964. 13,
  147965. 13
  147966. };
  147967. static static_codebook _44u4__p7_0 = {
  147968. 2, 169,
  147969. _vq_lengthlist__44u4__p7_0,
  147970. 1, -514332672, 1627381760, 4, 0,
  147971. _vq_quantlist__44u4__p7_0,
  147972. NULL,
  147973. &_vq_auxt__44u4__p7_0,
  147974. NULL,
  147975. 0
  147976. };
  147977. static long _vq_quantlist__44u4__p7_1[] = {
  147978. 7,
  147979. 6,
  147980. 8,
  147981. 5,
  147982. 9,
  147983. 4,
  147984. 10,
  147985. 3,
  147986. 11,
  147987. 2,
  147988. 12,
  147989. 1,
  147990. 13,
  147991. 0,
  147992. 14,
  147993. };
  147994. static long _vq_lengthlist__44u4__p7_1[] = {
  147995. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  147996. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  147997. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  147998. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  147999. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148000. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148001. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148002. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148003. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148004. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148005. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148006. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148007. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148008. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148009. 16,
  148010. };
  148011. static float _vq_quantthresh__44u4__p7_1[] = {
  148012. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148013. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148014. };
  148015. static long _vq_quantmap__44u4__p7_1[] = {
  148016. 13, 11, 9, 7, 5, 3, 1, 0,
  148017. 2, 4, 6, 8, 10, 12, 14,
  148018. };
  148019. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148020. _vq_quantthresh__44u4__p7_1,
  148021. _vq_quantmap__44u4__p7_1,
  148022. 15,
  148023. 15
  148024. };
  148025. static static_codebook _44u4__p7_1 = {
  148026. 2, 225,
  148027. _vq_lengthlist__44u4__p7_1,
  148028. 1, -522338304, 1620115456, 4, 0,
  148029. _vq_quantlist__44u4__p7_1,
  148030. NULL,
  148031. &_vq_auxt__44u4__p7_1,
  148032. NULL,
  148033. 0
  148034. };
  148035. static long _vq_quantlist__44u4__p7_2[] = {
  148036. 8,
  148037. 7,
  148038. 9,
  148039. 6,
  148040. 10,
  148041. 5,
  148042. 11,
  148043. 4,
  148044. 12,
  148045. 3,
  148046. 13,
  148047. 2,
  148048. 14,
  148049. 1,
  148050. 15,
  148051. 0,
  148052. 16,
  148053. };
  148054. static long _vq_lengthlist__44u4__p7_2[] = {
  148055. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148056. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148057. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148058. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148059. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148060. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148061. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148062. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148063. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148064. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148065. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148066. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148067. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148068. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148069. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148070. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148071. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148072. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148073. 10,
  148074. };
  148075. static float _vq_quantthresh__44u4__p7_2[] = {
  148076. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148077. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148078. };
  148079. static long _vq_quantmap__44u4__p7_2[] = {
  148080. 15, 13, 11, 9, 7, 5, 3, 1,
  148081. 0, 2, 4, 6, 8, 10, 12, 14,
  148082. 16,
  148083. };
  148084. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148085. _vq_quantthresh__44u4__p7_2,
  148086. _vq_quantmap__44u4__p7_2,
  148087. 17,
  148088. 17
  148089. };
  148090. static static_codebook _44u4__p7_2 = {
  148091. 2, 289,
  148092. _vq_lengthlist__44u4__p7_2,
  148093. 1, -529530880, 1611661312, 5, 0,
  148094. _vq_quantlist__44u4__p7_2,
  148095. NULL,
  148096. &_vq_auxt__44u4__p7_2,
  148097. NULL,
  148098. 0
  148099. };
  148100. static long _huff_lengthlist__44u4__short[] = {
  148101. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148102. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148103. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148104. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148105. };
  148106. static static_codebook _huff_book__44u4__short = {
  148107. 2, 64,
  148108. _huff_lengthlist__44u4__short,
  148109. 0, 0, 0, 0, 0,
  148110. NULL,
  148111. NULL,
  148112. NULL,
  148113. NULL,
  148114. 0
  148115. };
  148116. static long _huff_lengthlist__44u5__long[] = {
  148117. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148118. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148119. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148120. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148121. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148122. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148123. 14, 8, 7, 8,
  148124. };
  148125. static static_codebook _huff_book__44u5__long = {
  148126. 2, 100,
  148127. _huff_lengthlist__44u5__long,
  148128. 0, 0, 0, 0, 0,
  148129. NULL,
  148130. NULL,
  148131. NULL,
  148132. NULL,
  148133. 0
  148134. };
  148135. static long _vq_quantlist__44u5__p1_0[] = {
  148136. 1,
  148137. 0,
  148138. 2,
  148139. };
  148140. static long _vq_lengthlist__44u5__p1_0[] = {
  148141. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148142. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148143. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148144. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148145. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148146. 12,
  148147. };
  148148. static float _vq_quantthresh__44u5__p1_0[] = {
  148149. -0.5, 0.5,
  148150. };
  148151. static long _vq_quantmap__44u5__p1_0[] = {
  148152. 1, 0, 2,
  148153. };
  148154. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148155. _vq_quantthresh__44u5__p1_0,
  148156. _vq_quantmap__44u5__p1_0,
  148157. 3,
  148158. 3
  148159. };
  148160. static static_codebook _44u5__p1_0 = {
  148161. 4, 81,
  148162. _vq_lengthlist__44u5__p1_0,
  148163. 1, -535822336, 1611661312, 2, 0,
  148164. _vq_quantlist__44u5__p1_0,
  148165. NULL,
  148166. &_vq_auxt__44u5__p1_0,
  148167. NULL,
  148168. 0
  148169. };
  148170. static long _vq_quantlist__44u5__p2_0[] = {
  148171. 1,
  148172. 0,
  148173. 2,
  148174. };
  148175. static long _vq_lengthlist__44u5__p2_0[] = {
  148176. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148177. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148178. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148179. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148180. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148181. 9,
  148182. };
  148183. static float _vq_quantthresh__44u5__p2_0[] = {
  148184. -0.5, 0.5,
  148185. };
  148186. static long _vq_quantmap__44u5__p2_0[] = {
  148187. 1, 0, 2,
  148188. };
  148189. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148190. _vq_quantthresh__44u5__p2_0,
  148191. _vq_quantmap__44u5__p2_0,
  148192. 3,
  148193. 3
  148194. };
  148195. static static_codebook _44u5__p2_0 = {
  148196. 4, 81,
  148197. _vq_lengthlist__44u5__p2_0,
  148198. 1, -535822336, 1611661312, 2, 0,
  148199. _vq_quantlist__44u5__p2_0,
  148200. NULL,
  148201. &_vq_auxt__44u5__p2_0,
  148202. NULL,
  148203. 0
  148204. };
  148205. static long _vq_quantlist__44u5__p3_0[] = {
  148206. 2,
  148207. 1,
  148208. 3,
  148209. 0,
  148210. 4,
  148211. };
  148212. static long _vq_lengthlist__44u5__p3_0[] = {
  148213. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148214. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148215. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148216. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148217. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148218. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148219. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148220. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148221. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148222. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148223. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148224. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148225. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148226. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148227. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148228. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148229. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148230. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148231. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148232. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148233. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148234. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148235. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148236. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148237. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148238. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148239. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148240. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148241. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148242. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148243. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148244. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148245. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148246. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148247. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148248. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148249. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148250. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148251. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148252. 0,
  148253. };
  148254. static float _vq_quantthresh__44u5__p3_0[] = {
  148255. -1.5, -0.5, 0.5, 1.5,
  148256. };
  148257. static long _vq_quantmap__44u5__p3_0[] = {
  148258. 3, 1, 0, 2, 4,
  148259. };
  148260. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148261. _vq_quantthresh__44u5__p3_0,
  148262. _vq_quantmap__44u5__p3_0,
  148263. 5,
  148264. 5
  148265. };
  148266. static static_codebook _44u5__p3_0 = {
  148267. 4, 625,
  148268. _vq_lengthlist__44u5__p3_0,
  148269. 1, -533725184, 1611661312, 3, 0,
  148270. _vq_quantlist__44u5__p3_0,
  148271. NULL,
  148272. &_vq_auxt__44u5__p3_0,
  148273. NULL,
  148274. 0
  148275. };
  148276. static long _vq_quantlist__44u5__p4_0[] = {
  148277. 2,
  148278. 1,
  148279. 3,
  148280. 0,
  148281. 4,
  148282. };
  148283. static long _vq_lengthlist__44u5__p4_0[] = {
  148284. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148285. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148286. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148287. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148288. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148289. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148290. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148291. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148292. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148293. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148294. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148295. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148296. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148297. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148298. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148299. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148300. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148301. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148302. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148303. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148304. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148305. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148306. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148307. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148308. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148309. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148310. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148311. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148312. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148313. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148314. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148315. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148316. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148317. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148318. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148319. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148320. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148321. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148322. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148323. 12,
  148324. };
  148325. static float _vq_quantthresh__44u5__p4_0[] = {
  148326. -1.5, -0.5, 0.5, 1.5,
  148327. };
  148328. static long _vq_quantmap__44u5__p4_0[] = {
  148329. 3, 1, 0, 2, 4,
  148330. };
  148331. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148332. _vq_quantthresh__44u5__p4_0,
  148333. _vq_quantmap__44u5__p4_0,
  148334. 5,
  148335. 5
  148336. };
  148337. static static_codebook _44u5__p4_0 = {
  148338. 4, 625,
  148339. _vq_lengthlist__44u5__p4_0,
  148340. 1, -533725184, 1611661312, 3, 0,
  148341. _vq_quantlist__44u5__p4_0,
  148342. NULL,
  148343. &_vq_auxt__44u5__p4_0,
  148344. NULL,
  148345. 0
  148346. };
  148347. static long _vq_quantlist__44u5__p5_0[] = {
  148348. 4,
  148349. 3,
  148350. 5,
  148351. 2,
  148352. 6,
  148353. 1,
  148354. 7,
  148355. 0,
  148356. 8,
  148357. };
  148358. static long _vq_lengthlist__44u5__p5_0[] = {
  148359. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148360. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148361. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148362. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148363. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148364. 14,
  148365. };
  148366. static float _vq_quantthresh__44u5__p5_0[] = {
  148367. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148368. };
  148369. static long _vq_quantmap__44u5__p5_0[] = {
  148370. 7, 5, 3, 1, 0, 2, 4, 6,
  148371. 8,
  148372. };
  148373. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148374. _vq_quantthresh__44u5__p5_0,
  148375. _vq_quantmap__44u5__p5_0,
  148376. 9,
  148377. 9
  148378. };
  148379. static static_codebook _44u5__p5_0 = {
  148380. 2, 81,
  148381. _vq_lengthlist__44u5__p5_0,
  148382. 1, -531628032, 1611661312, 4, 0,
  148383. _vq_quantlist__44u5__p5_0,
  148384. NULL,
  148385. &_vq_auxt__44u5__p5_0,
  148386. NULL,
  148387. 0
  148388. };
  148389. static long _vq_quantlist__44u5__p6_0[] = {
  148390. 4,
  148391. 3,
  148392. 5,
  148393. 2,
  148394. 6,
  148395. 1,
  148396. 7,
  148397. 0,
  148398. 8,
  148399. };
  148400. static long _vq_lengthlist__44u5__p6_0[] = {
  148401. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148402. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148403. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148404. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148405. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148406. 11,
  148407. };
  148408. static float _vq_quantthresh__44u5__p6_0[] = {
  148409. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148410. };
  148411. static long _vq_quantmap__44u5__p6_0[] = {
  148412. 7, 5, 3, 1, 0, 2, 4, 6,
  148413. 8,
  148414. };
  148415. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148416. _vq_quantthresh__44u5__p6_0,
  148417. _vq_quantmap__44u5__p6_0,
  148418. 9,
  148419. 9
  148420. };
  148421. static static_codebook _44u5__p6_0 = {
  148422. 2, 81,
  148423. _vq_lengthlist__44u5__p6_0,
  148424. 1, -531628032, 1611661312, 4, 0,
  148425. _vq_quantlist__44u5__p6_0,
  148426. NULL,
  148427. &_vq_auxt__44u5__p6_0,
  148428. NULL,
  148429. 0
  148430. };
  148431. static long _vq_quantlist__44u5__p7_0[] = {
  148432. 1,
  148433. 0,
  148434. 2,
  148435. };
  148436. static long _vq_lengthlist__44u5__p7_0[] = {
  148437. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148438. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148439. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148440. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148441. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148442. 12,
  148443. };
  148444. static float _vq_quantthresh__44u5__p7_0[] = {
  148445. -5.5, 5.5,
  148446. };
  148447. static long _vq_quantmap__44u5__p7_0[] = {
  148448. 1, 0, 2,
  148449. };
  148450. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148451. _vq_quantthresh__44u5__p7_0,
  148452. _vq_quantmap__44u5__p7_0,
  148453. 3,
  148454. 3
  148455. };
  148456. static static_codebook _44u5__p7_0 = {
  148457. 4, 81,
  148458. _vq_lengthlist__44u5__p7_0,
  148459. 1, -529137664, 1618345984, 2, 0,
  148460. _vq_quantlist__44u5__p7_0,
  148461. NULL,
  148462. &_vq_auxt__44u5__p7_0,
  148463. NULL,
  148464. 0
  148465. };
  148466. static long _vq_quantlist__44u5__p7_1[] = {
  148467. 5,
  148468. 4,
  148469. 6,
  148470. 3,
  148471. 7,
  148472. 2,
  148473. 8,
  148474. 1,
  148475. 9,
  148476. 0,
  148477. 10,
  148478. };
  148479. static long _vq_lengthlist__44u5__p7_1[] = {
  148480. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148481. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148482. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148483. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148484. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148485. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148486. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148487. 9, 9, 9, 9, 9,10,10,10,10,
  148488. };
  148489. static float _vq_quantthresh__44u5__p7_1[] = {
  148490. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148491. 3.5, 4.5,
  148492. };
  148493. static long _vq_quantmap__44u5__p7_1[] = {
  148494. 9, 7, 5, 3, 1, 0, 2, 4,
  148495. 6, 8, 10,
  148496. };
  148497. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148498. _vq_quantthresh__44u5__p7_1,
  148499. _vq_quantmap__44u5__p7_1,
  148500. 11,
  148501. 11
  148502. };
  148503. static static_codebook _44u5__p7_1 = {
  148504. 2, 121,
  148505. _vq_lengthlist__44u5__p7_1,
  148506. 1, -531365888, 1611661312, 4, 0,
  148507. _vq_quantlist__44u5__p7_1,
  148508. NULL,
  148509. &_vq_auxt__44u5__p7_1,
  148510. NULL,
  148511. 0
  148512. };
  148513. static long _vq_quantlist__44u5__p8_0[] = {
  148514. 5,
  148515. 4,
  148516. 6,
  148517. 3,
  148518. 7,
  148519. 2,
  148520. 8,
  148521. 1,
  148522. 9,
  148523. 0,
  148524. 10,
  148525. };
  148526. static long _vq_lengthlist__44u5__p8_0[] = {
  148527. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148528. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148529. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148530. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148531. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148532. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148533. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148534. 12,13,13,14,14,14,14,15,15,
  148535. };
  148536. static float _vq_quantthresh__44u5__p8_0[] = {
  148537. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148538. 38.5, 49.5,
  148539. };
  148540. static long _vq_quantmap__44u5__p8_0[] = {
  148541. 9, 7, 5, 3, 1, 0, 2, 4,
  148542. 6, 8, 10,
  148543. };
  148544. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148545. _vq_quantthresh__44u5__p8_0,
  148546. _vq_quantmap__44u5__p8_0,
  148547. 11,
  148548. 11
  148549. };
  148550. static static_codebook _44u5__p8_0 = {
  148551. 2, 121,
  148552. _vq_lengthlist__44u5__p8_0,
  148553. 1, -524582912, 1618345984, 4, 0,
  148554. _vq_quantlist__44u5__p8_0,
  148555. NULL,
  148556. &_vq_auxt__44u5__p8_0,
  148557. NULL,
  148558. 0
  148559. };
  148560. static long _vq_quantlist__44u5__p8_1[] = {
  148561. 5,
  148562. 4,
  148563. 6,
  148564. 3,
  148565. 7,
  148566. 2,
  148567. 8,
  148568. 1,
  148569. 9,
  148570. 0,
  148571. 10,
  148572. };
  148573. static long _vq_lengthlist__44u5__p8_1[] = {
  148574. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148575. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148576. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148577. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148578. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148579. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148580. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148581. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148582. };
  148583. static float _vq_quantthresh__44u5__p8_1[] = {
  148584. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148585. 3.5, 4.5,
  148586. };
  148587. static long _vq_quantmap__44u5__p8_1[] = {
  148588. 9, 7, 5, 3, 1, 0, 2, 4,
  148589. 6, 8, 10,
  148590. };
  148591. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148592. _vq_quantthresh__44u5__p8_1,
  148593. _vq_quantmap__44u5__p8_1,
  148594. 11,
  148595. 11
  148596. };
  148597. static static_codebook _44u5__p8_1 = {
  148598. 2, 121,
  148599. _vq_lengthlist__44u5__p8_1,
  148600. 1, -531365888, 1611661312, 4, 0,
  148601. _vq_quantlist__44u5__p8_1,
  148602. NULL,
  148603. &_vq_auxt__44u5__p8_1,
  148604. NULL,
  148605. 0
  148606. };
  148607. static long _vq_quantlist__44u5__p9_0[] = {
  148608. 6,
  148609. 5,
  148610. 7,
  148611. 4,
  148612. 8,
  148613. 3,
  148614. 9,
  148615. 2,
  148616. 10,
  148617. 1,
  148618. 11,
  148619. 0,
  148620. 12,
  148621. };
  148622. static long _vq_lengthlist__44u5__p9_0[] = {
  148623. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148624. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148625. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148626. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148627. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148628. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148629. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148630. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148631. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148632. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148633. 12,12,12,12,12,12,12,12,12,
  148634. };
  148635. static float _vq_quantthresh__44u5__p9_0[] = {
  148636. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148637. 637.5, 892.5, 1147.5, 1402.5,
  148638. };
  148639. static long _vq_quantmap__44u5__p9_0[] = {
  148640. 11, 9, 7, 5, 3, 1, 0, 2,
  148641. 4, 6, 8, 10, 12,
  148642. };
  148643. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148644. _vq_quantthresh__44u5__p9_0,
  148645. _vq_quantmap__44u5__p9_0,
  148646. 13,
  148647. 13
  148648. };
  148649. static static_codebook _44u5__p9_0 = {
  148650. 2, 169,
  148651. _vq_lengthlist__44u5__p9_0,
  148652. 1, -514332672, 1627381760, 4, 0,
  148653. _vq_quantlist__44u5__p9_0,
  148654. NULL,
  148655. &_vq_auxt__44u5__p9_0,
  148656. NULL,
  148657. 0
  148658. };
  148659. static long _vq_quantlist__44u5__p9_1[] = {
  148660. 7,
  148661. 6,
  148662. 8,
  148663. 5,
  148664. 9,
  148665. 4,
  148666. 10,
  148667. 3,
  148668. 11,
  148669. 2,
  148670. 12,
  148671. 1,
  148672. 13,
  148673. 0,
  148674. 14,
  148675. };
  148676. static long _vq_lengthlist__44u5__p9_1[] = {
  148677. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148678. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148679. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148680. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148681. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148682. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148683. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148684. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148685. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148686. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148687. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148688. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148689. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148690. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148691. 14,
  148692. };
  148693. static float _vq_quantthresh__44u5__p9_1[] = {
  148694. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148695. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148696. };
  148697. static long _vq_quantmap__44u5__p9_1[] = {
  148698. 13, 11, 9, 7, 5, 3, 1, 0,
  148699. 2, 4, 6, 8, 10, 12, 14,
  148700. };
  148701. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148702. _vq_quantthresh__44u5__p9_1,
  148703. _vq_quantmap__44u5__p9_1,
  148704. 15,
  148705. 15
  148706. };
  148707. static static_codebook _44u5__p9_1 = {
  148708. 2, 225,
  148709. _vq_lengthlist__44u5__p9_1,
  148710. 1, -522338304, 1620115456, 4, 0,
  148711. _vq_quantlist__44u5__p9_1,
  148712. NULL,
  148713. &_vq_auxt__44u5__p9_1,
  148714. NULL,
  148715. 0
  148716. };
  148717. static long _vq_quantlist__44u5__p9_2[] = {
  148718. 8,
  148719. 7,
  148720. 9,
  148721. 6,
  148722. 10,
  148723. 5,
  148724. 11,
  148725. 4,
  148726. 12,
  148727. 3,
  148728. 13,
  148729. 2,
  148730. 14,
  148731. 1,
  148732. 15,
  148733. 0,
  148734. 16,
  148735. };
  148736. static long _vq_lengthlist__44u5__p9_2[] = {
  148737. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148738. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148739. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148740. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148741. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148742. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148743. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148744. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148745. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148746. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148747. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148748. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148749. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148750. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148751. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148752. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148753. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148754. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148755. 10,
  148756. };
  148757. static float _vq_quantthresh__44u5__p9_2[] = {
  148758. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148759. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148760. };
  148761. static long _vq_quantmap__44u5__p9_2[] = {
  148762. 15, 13, 11, 9, 7, 5, 3, 1,
  148763. 0, 2, 4, 6, 8, 10, 12, 14,
  148764. 16,
  148765. };
  148766. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148767. _vq_quantthresh__44u5__p9_2,
  148768. _vq_quantmap__44u5__p9_2,
  148769. 17,
  148770. 17
  148771. };
  148772. static static_codebook _44u5__p9_2 = {
  148773. 2, 289,
  148774. _vq_lengthlist__44u5__p9_2,
  148775. 1, -529530880, 1611661312, 5, 0,
  148776. _vq_quantlist__44u5__p9_2,
  148777. NULL,
  148778. &_vq_auxt__44u5__p9_2,
  148779. NULL,
  148780. 0
  148781. };
  148782. static long _huff_lengthlist__44u5__short[] = {
  148783. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148784. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148785. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148786. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148787. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148788. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148789. 6, 8,15,17,
  148790. };
  148791. static static_codebook _huff_book__44u5__short = {
  148792. 2, 100,
  148793. _huff_lengthlist__44u5__short,
  148794. 0, 0, 0, 0, 0,
  148795. NULL,
  148796. NULL,
  148797. NULL,
  148798. NULL,
  148799. 0
  148800. };
  148801. static long _huff_lengthlist__44u6__long[] = {
  148802. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148803. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148804. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148805. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148806. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148807. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148808. 13, 8, 7, 7,
  148809. };
  148810. static static_codebook _huff_book__44u6__long = {
  148811. 2, 100,
  148812. _huff_lengthlist__44u6__long,
  148813. 0, 0, 0, 0, 0,
  148814. NULL,
  148815. NULL,
  148816. NULL,
  148817. NULL,
  148818. 0
  148819. };
  148820. static long _vq_quantlist__44u6__p1_0[] = {
  148821. 1,
  148822. 0,
  148823. 2,
  148824. };
  148825. static long _vq_lengthlist__44u6__p1_0[] = {
  148826. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148827. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148828. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148829. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  148830. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148831. 12,
  148832. };
  148833. static float _vq_quantthresh__44u6__p1_0[] = {
  148834. -0.5, 0.5,
  148835. };
  148836. static long _vq_quantmap__44u6__p1_0[] = {
  148837. 1, 0, 2,
  148838. };
  148839. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  148840. _vq_quantthresh__44u6__p1_0,
  148841. _vq_quantmap__44u6__p1_0,
  148842. 3,
  148843. 3
  148844. };
  148845. static static_codebook _44u6__p1_0 = {
  148846. 4, 81,
  148847. _vq_lengthlist__44u6__p1_0,
  148848. 1, -535822336, 1611661312, 2, 0,
  148849. _vq_quantlist__44u6__p1_0,
  148850. NULL,
  148851. &_vq_auxt__44u6__p1_0,
  148852. NULL,
  148853. 0
  148854. };
  148855. static long _vq_quantlist__44u6__p2_0[] = {
  148856. 1,
  148857. 0,
  148858. 2,
  148859. };
  148860. static long _vq_lengthlist__44u6__p2_0[] = {
  148861. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148862. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148863. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  148864. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148865. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148866. 9,
  148867. };
  148868. static float _vq_quantthresh__44u6__p2_0[] = {
  148869. -0.5, 0.5,
  148870. };
  148871. static long _vq_quantmap__44u6__p2_0[] = {
  148872. 1, 0, 2,
  148873. };
  148874. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  148875. _vq_quantthresh__44u6__p2_0,
  148876. _vq_quantmap__44u6__p2_0,
  148877. 3,
  148878. 3
  148879. };
  148880. static static_codebook _44u6__p2_0 = {
  148881. 4, 81,
  148882. _vq_lengthlist__44u6__p2_0,
  148883. 1, -535822336, 1611661312, 2, 0,
  148884. _vq_quantlist__44u6__p2_0,
  148885. NULL,
  148886. &_vq_auxt__44u6__p2_0,
  148887. NULL,
  148888. 0
  148889. };
  148890. static long _vq_quantlist__44u6__p3_0[] = {
  148891. 2,
  148892. 1,
  148893. 3,
  148894. 0,
  148895. 4,
  148896. };
  148897. static long _vq_lengthlist__44u6__p3_0[] = {
  148898. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148899. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  148900. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148901. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  148902. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  148903. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  148904. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  148905. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  148906. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  148907. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148908. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  148909. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148910. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  148911. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  148912. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  148913. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  148914. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148915. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  148916. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  148917. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  148918. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  148919. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  148920. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  148921. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  148922. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  148923. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  148924. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  148925. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  148926. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  148927. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  148928. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  148929. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  148930. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  148931. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  148932. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  148933. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  148934. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  148935. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  148936. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  148937. 19,
  148938. };
  148939. static float _vq_quantthresh__44u6__p3_0[] = {
  148940. -1.5, -0.5, 0.5, 1.5,
  148941. };
  148942. static long _vq_quantmap__44u6__p3_0[] = {
  148943. 3, 1, 0, 2, 4,
  148944. };
  148945. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  148946. _vq_quantthresh__44u6__p3_0,
  148947. _vq_quantmap__44u6__p3_0,
  148948. 5,
  148949. 5
  148950. };
  148951. static static_codebook _44u6__p3_0 = {
  148952. 4, 625,
  148953. _vq_lengthlist__44u6__p3_0,
  148954. 1, -533725184, 1611661312, 3, 0,
  148955. _vq_quantlist__44u6__p3_0,
  148956. NULL,
  148957. &_vq_auxt__44u6__p3_0,
  148958. NULL,
  148959. 0
  148960. };
  148961. static long _vq_quantlist__44u6__p4_0[] = {
  148962. 2,
  148963. 1,
  148964. 3,
  148965. 0,
  148966. 4,
  148967. };
  148968. static long _vq_lengthlist__44u6__p4_0[] = {
  148969. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148970. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148971. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148972. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  148973. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  148974. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  148975. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148976. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  148977. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  148978. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  148979. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  148980. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  148981. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148982. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  148983. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  148984. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  148985. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  148986. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  148987. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148988. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  148989. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  148990. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  148991. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  148992. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148993. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  148994. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148995. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  148996. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  148997. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  148998. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  148999. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149000. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149001. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149002. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149003. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149004. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149005. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149006. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149007. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149008. 13,
  149009. };
  149010. static float _vq_quantthresh__44u6__p4_0[] = {
  149011. -1.5, -0.5, 0.5, 1.5,
  149012. };
  149013. static long _vq_quantmap__44u6__p4_0[] = {
  149014. 3, 1, 0, 2, 4,
  149015. };
  149016. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149017. _vq_quantthresh__44u6__p4_0,
  149018. _vq_quantmap__44u6__p4_0,
  149019. 5,
  149020. 5
  149021. };
  149022. static static_codebook _44u6__p4_0 = {
  149023. 4, 625,
  149024. _vq_lengthlist__44u6__p4_0,
  149025. 1, -533725184, 1611661312, 3, 0,
  149026. _vq_quantlist__44u6__p4_0,
  149027. NULL,
  149028. &_vq_auxt__44u6__p4_0,
  149029. NULL,
  149030. 0
  149031. };
  149032. static long _vq_quantlist__44u6__p5_0[] = {
  149033. 4,
  149034. 3,
  149035. 5,
  149036. 2,
  149037. 6,
  149038. 1,
  149039. 7,
  149040. 0,
  149041. 8,
  149042. };
  149043. static long _vq_lengthlist__44u6__p5_0[] = {
  149044. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149045. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149046. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149047. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149048. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149049. 14,
  149050. };
  149051. static float _vq_quantthresh__44u6__p5_0[] = {
  149052. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149053. };
  149054. static long _vq_quantmap__44u6__p5_0[] = {
  149055. 7, 5, 3, 1, 0, 2, 4, 6,
  149056. 8,
  149057. };
  149058. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149059. _vq_quantthresh__44u6__p5_0,
  149060. _vq_quantmap__44u6__p5_0,
  149061. 9,
  149062. 9
  149063. };
  149064. static static_codebook _44u6__p5_0 = {
  149065. 2, 81,
  149066. _vq_lengthlist__44u6__p5_0,
  149067. 1, -531628032, 1611661312, 4, 0,
  149068. _vq_quantlist__44u6__p5_0,
  149069. NULL,
  149070. &_vq_auxt__44u6__p5_0,
  149071. NULL,
  149072. 0
  149073. };
  149074. static long _vq_quantlist__44u6__p6_0[] = {
  149075. 4,
  149076. 3,
  149077. 5,
  149078. 2,
  149079. 6,
  149080. 1,
  149081. 7,
  149082. 0,
  149083. 8,
  149084. };
  149085. static long _vq_lengthlist__44u6__p6_0[] = {
  149086. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149087. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149088. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149089. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149090. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149091. 12,
  149092. };
  149093. static float _vq_quantthresh__44u6__p6_0[] = {
  149094. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149095. };
  149096. static long _vq_quantmap__44u6__p6_0[] = {
  149097. 7, 5, 3, 1, 0, 2, 4, 6,
  149098. 8,
  149099. };
  149100. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149101. _vq_quantthresh__44u6__p6_0,
  149102. _vq_quantmap__44u6__p6_0,
  149103. 9,
  149104. 9
  149105. };
  149106. static static_codebook _44u6__p6_0 = {
  149107. 2, 81,
  149108. _vq_lengthlist__44u6__p6_0,
  149109. 1, -531628032, 1611661312, 4, 0,
  149110. _vq_quantlist__44u6__p6_0,
  149111. NULL,
  149112. &_vq_auxt__44u6__p6_0,
  149113. NULL,
  149114. 0
  149115. };
  149116. static long _vq_quantlist__44u6__p7_0[] = {
  149117. 1,
  149118. 0,
  149119. 2,
  149120. };
  149121. static long _vq_lengthlist__44u6__p7_0[] = {
  149122. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149123. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149124. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149125. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149126. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149127. 10,
  149128. };
  149129. static float _vq_quantthresh__44u6__p7_0[] = {
  149130. -5.5, 5.5,
  149131. };
  149132. static long _vq_quantmap__44u6__p7_0[] = {
  149133. 1, 0, 2,
  149134. };
  149135. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149136. _vq_quantthresh__44u6__p7_0,
  149137. _vq_quantmap__44u6__p7_0,
  149138. 3,
  149139. 3
  149140. };
  149141. static static_codebook _44u6__p7_0 = {
  149142. 4, 81,
  149143. _vq_lengthlist__44u6__p7_0,
  149144. 1, -529137664, 1618345984, 2, 0,
  149145. _vq_quantlist__44u6__p7_0,
  149146. NULL,
  149147. &_vq_auxt__44u6__p7_0,
  149148. NULL,
  149149. 0
  149150. };
  149151. static long _vq_quantlist__44u6__p7_1[] = {
  149152. 5,
  149153. 4,
  149154. 6,
  149155. 3,
  149156. 7,
  149157. 2,
  149158. 8,
  149159. 1,
  149160. 9,
  149161. 0,
  149162. 10,
  149163. };
  149164. static long _vq_lengthlist__44u6__p7_1[] = {
  149165. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149166. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149167. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149168. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149169. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149170. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149171. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149172. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149173. };
  149174. static float _vq_quantthresh__44u6__p7_1[] = {
  149175. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149176. 3.5, 4.5,
  149177. };
  149178. static long _vq_quantmap__44u6__p7_1[] = {
  149179. 9, 7, 5, 3, 1, 0, 2, 4,
  149180. 6, 8, 10,
  149181. };
  149182. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149183. _vq_quantthresh__44u6__p7_1,
  149184. _vq_quantmap__44u6__p7_1,
  149185. 11,
  149186. 11
  149187. };
  149188. static static_codebook _44u6__p7_1 = {
  149189. 2, 121,
  149190. _vq_lengthlist__44u6__p7_1,
  149191. 1, -531365888, 1611661312, 4, 0,
  149192. _vq_quantlist__44u6__p7_1,
  149193. NULL,
  149194. &_vq_auxt__44u6__p7_1,
  149195. NULL,
  149196. 0
  149197. };
  149198. static long _vq_quantlist__44u6__p8_0[] = {
  149199. 5,
  149200. 4,
  149201. 6,
  149202. 3,
  149203. 7,
  149204. 2,
  149205. 8,
  149206. 1,
  149207. 9,
  149208. 0,
  149209. 10,
  149210. };
  149211. static long _vq_lengthlist__44u6__p8_0[] = {
  149212. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149213. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149214. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149215. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149216. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149217. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149218. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149219. 12,13,13,14,14,14,15,15,15,
  149220. };
  149221. static float _vq_quantthresh__44u6__p8_0[] = {
  149222. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149223. 38.5, 49.5,
  149224. };
  149225. static long _vq_quantmap__44u6__p8_0[] = {
  149226. 9, 7, 5, 3, 1, 0, 2, 4,
  149227. 6, 8, 10,
  149228. };
  149229. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149230. _vq_quantthresh__44u6__p8_0,
  149231. _vq_quantmap__44u6__p8_0,
  149232. 11,
  149233. 11
  149234. };
  149235. static static_codebook _44u6__p8_0 = {
  149236. 2, 121,
  149237. _vq_lengthlist__44u6__p8_0,
  149238. 1, -524582912, 1618345984, 4, 0,
  149239. _vq_quantlist__44u6__p8_0,
  149240. NULL,
  149241. &_vq_auxt__44u6__p8_0,
  149242. NULL,
  149243. 0
  149244. };
  149245. static long _vq_quantlist__44u6__p8_1[] = {
  149246. 5,
  149247. 4,
  149248. 6,
  149249. 3,
  149250. 7,
  149251. 2,
  149252. 8,
  149253. 1,
  149254. 9,
  149255. 0,
  149256. 10,
  149257. };
  149258. static long _vq_lengthlist__44u6__p8_1[] = {
  149259. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149260. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149261. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149262. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149263. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149264. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149265. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149266. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149267. };
  149268. static float _vq_quantthresh__44u6__p8_1[] = {
  149269. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149270. 3.5, 4.5,
  149271. };
  149272. static long _vq_quantmap__44u6__p8_1[] = {
  149273. 9, 7, 5, 3, 1, 0, 2, 4,
  149274. 6, 8, 10,
  149275. };
  149276. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149277. _vq_quantthresh__44u6__p8_1,
  149278. _vq_quantmap__44u6__p8_1,
  149279. 11,
  149280. 11
  149281. };
  149282. static static_codebook _44u6__p8_1 = {
  149283. 2, 121,
  149284. _vq_lengthlist__44u6__p8_1,
  149285. 1, -531365888, 1611661312, 4, 0,
  149286. _vq_quantlist__44u6__p8_1,
  149287. NULL,
  149288. &_vq_auxt__44u6__p8_1,
  149289. NULL,
  149290. 0
  149291. };
  149292. static long _vq_quantlist__44u6__p9_0[] = {
  149293. 7,
  149294. 6,
  149295. 8,
  149296. 5,
  149297. 9,
  149298. 4,
  149299. 10,
  149300. 3,
  149301. 11,
  149302. 2,
  149303. 12,
  149304. 1,
  149305. 13,
  149306. 0,
  149307. 14,
  149308. };
  149309. static long _vq_lengthlist__44u6__p9_0[] = {
  149310. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149311. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149312. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149313. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149314. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149315. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149316. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149317. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149318. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149319. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149320. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149321. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149322. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149323. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149324. 14,
  149325. };
  149326. static float _vq_quantthresh__44u6__p9_0[] = {
  149327. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149328. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149329. };
  149330. static long _vq_quantmap__44u6__p9_0[] = {
  149331. 13, 11, 9, 7, 5, 3, 1, 0,
  149332. 2, 4, 6, 8, 10, 12, 14,
  149333. };
  149334. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149335. _vq_quantthresh__44u6__p9_0,
  149336. _vq_quantmap__44u6__p9_0,
  149337. 15,
  149338. 15
  149339. };
  149340. static static_codebook _44u6__p9_0 = {
  149341. 2, 225,
  149342. _vq_lengthlist__44u6__p9_0,
  149343. 1, -514071552, 1627381760, 4, 0,
  149344. _vq_quantlist__44u6__p9_0,
  149345. NULL,
  149346. &_vq_auxt__44u6__p9_0,
  149347. NULL,
  149348. 0
  149349. };
  149350. static long _vq_quantlist__44u6__p9_1[] = {
  149351. 7,
  149352. 6,
  149353. 8,
  149354. 5,
  149355. 9,
  149356. 4,
  149357. 10,
  149358. 3,
  149359. 11,
  149360. 2,
  149361. 12,
  149362. 1,
  149363. 13,
  149364. 0,
  149365. 14,
  149366. };
  149367. static long _vq_lengthlist__44u6__p9_1[] = {
  149368. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149369. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149370. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149371. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149372. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149373. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149374. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149375. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149376. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149377. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149378. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149379. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149380. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149381. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149382. 13,
  149383. };
  149384. static float _vq_quantthresh__44u6__p9_1[] = {
  149385. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149386. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149387. };
  149388. static long _vq_quantmap__44u6__p9_1[] = {
  149389. 13, 11, 9, 7, 5, 3, 1, 0,
  149390. 2, 4, 6, 8, 10, 12, 14,
  149391. };
  149392. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149393. _vq_quantthresh__44u6__p9_1,
  149394. _vq_quantmap__44u6__p9_1,
  149395. 15,
  149396. 15
  149397. };
  149398. static static_codebook _44u6__p9_1 = {
  149399. 2, 225,
  149400. _vq_lengthlist__44u6__p9_1,
  149401. 1, -522338304, 1620115456, 4, 0,
  149402. _vq_quantlist__44u6__p9_1,
  149403. NULL,
  149404. &_vq_auxt__44u6__p9_1,
  149405. NULL,
  149406. 0
  149407. };
  149408. static long _vq_quantlist__44u6__p9_2[] = {
  149409. 8,
  149410. 7,
  149411. 9,
  149412. 6,
  149413. 10,
  149414. 5,
  149415. 11,
  149416. 4,
  149417. 12,
  149418. 3,
  149419. 13,
  149420. 2,
  149421. 14,
  149422. 1,
  149423. 15,
  149424. 0,
  149425. 16,
  149426. };
  149427. static long _vq_lengthlist__44u6__p9_2[] = {
  149428. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149429. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149430. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149431. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149432. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149433. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149434. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149435. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149436. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149437. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149438. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149439. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149440. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149441. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149442. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149443. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149444. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149445. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149446. 10,
  149447. };
  149448. static float _vq_quantthresh__44u6__p9_2[] = {
  149449. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149450. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149451. };
  149452. static long _vq_quantmap__44u6__p9_2[] = {
  149453. 15, 13, 11, 9, 7, 5, 3, 1,
  149454. 0, 2, 4, 6, 8, 10, 12, 14,
  149455. 16,
  149456. };
  149457. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149458. _vq_quantthresh__44u6__p9_2,
  149459. _vq_quantmap__44u6__p9_2,
  149460. 17,
  149461. 17
  149462. };
  149463. static static_codebook _44u6__p9_2 = {
  149464. 2, 289,
  149465. _vq_lengthlist__44u6__p9_2,
  149466. 1, -529530880, 1611661312, 5, 0,
  149467. _vq_quantlist__44u6__p9_2,
  149468. NULL,
  149469. &_vq_auxt__44u6__p9_2,
  149470. NULL,
  149471. 0
  149472. };
  149473. static long _huff_lengthlist__44u6__short[] = {
  149474. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149475. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149476. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149477. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149478. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149479. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149480. 7, 6, 9,16,
  149481. };
  149482. static static_codebook _huff_book__44u6__short = {
  149483. 2, 100,
  149484. _huff_lengthlist__44u6__short,
  149485. 0, 0, 0, 0, 0,
  149486. NULL,
  149487. NULL,
  149488. NULL,
  149489. NULL,
  149490. 0
  149491. };
  149492. static long _huff_lengthlist__44u7__long[] = {
  149493. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149494. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149495. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149496. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149497. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149498. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149499. 12, 8, 6, 7,
  149500. };
  149501. static static_codebook _huff_book__44u7__long = {
  149502. 2, 100,
  149503. _huff_lengthlist__44u7__long,
  149504. 0, 0, 0, 0, 0,
  149505. NULL,
  149506. NULL,
  149507. NULL,
  149508. NULL,
  149509. 0
  149510. };
  149511. static long _vq_quantlist__44u7__p1_0[] = {
  149512. 1,
  149513. 0,
  149514. 2,
  149515. };
  149516. static long _vq_lengthlist__44u7__p1_0[] = {
  149517. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149518. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149519. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149520. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149521. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149522. 12,
  149523. };
  149524. static float _vq_quantthresh__44u7__p1_0[] = {
  149525. -0.5, 0.5,
  149526. };
  149527. static long _vq_quantmap__44u7__p1_0[] = {
  149528. 1, 0, 2,
  149529. };
  149530. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149531. _vq_quantthresh__44u7__p1_0,
  149532. _vq_quantmap__44u7__p1_0,
  149533. 3,
  149534. 3
  149535. };
  149536. static static_codebook _44u7__p1_0 = {
  149537. 4, 81,
  149538. _vq_lengthlist__44u7__p1_0,
  149539. 1, -535822336, 1611661312, 2, 0,
  149540. _vq_quantlist__44u7__p1_0,
  149541. NULL,
  149542. &_vq_auxt__44u7__p1_0,
  149543. NULL,
  149544. 0
  149545. };
  149546. static long _vq_quantlist__44u7__p2_0[] = {
  149547. 1,
  149548. 0,
  149549. 2,
  149550. };
  149551. static long _vq_lengthlist__44u7__p2_0[] = {
  149552. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149553. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149554. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149555. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149556. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149557. 9,
  149558. };
  149559. static float _vq_quantthresh__44u7__p2_0[] = {
  149560. -0.5, 0.5,
  149561. };
  149562. static long _vq_quantmap__44u7__p2_0[] = {
  149563. 1, 0, 2,
  149564. };
  149565. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149566. _vq_quantthresh__44u7__p2_0,
  149567. _vq_quantmap__44u7__p2_0,
  149568. 3,
  149569. 3
  149570. };
  149571. static static_codebook _44u7__p2_0 = {
  149572. 4, 81,
  149573. _vq_lengthlist__44u7__p2_0,
  149574. 1, -535822336, 1611661312, 2, 0,
  149575. _vq_quantlist__44u7__p2_0,
  149576. NULL,
  149577. &_vq_auxt__44u7__p2_0,
  149578. NULL,
  149579. 0
  149580. };
  149581. static long _vq_quantlist__44u7__p3_0[] = {
  149582. 2,
  149583. 1,
  149584. 3,
  149585. 0,
  149586. 4,
  149587. };
  149588. static long _vq_lengthlist__44u7__p3_0[] = {
  149589. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149590. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149591. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149592. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149593. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149594. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149595. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149596. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149597. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149598. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149599. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149600. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149601. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149602. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149603. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149604. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149605. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149606. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149607. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149608. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149609. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149610. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149611. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149612. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149613. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149614. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149615. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149616. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149617. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149618. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149619. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149620. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149621. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149622. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149623. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149624. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149625. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149626. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149627. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149628. 0,
  149629. };
  149630. static float _vq_quantthresh__44u7__p3_0[] = {
  149631. -1.5, -0.5, 0.5, 1.5,
  149632. };
  149633. static long _vq_quantmap__44u7__p3_0[] = {
  149634. 3, 1, 0, 2, 4,
  149635. };
  149636. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149637. _vq_quantthresh__44u7__p3_0,
  149638. _vq_quantmap__44u7__p3_0,
  149639. 5,
  149640. 5
  149641. };
  149642. static static_codebook _44u7__p3_0 = {
  149643. 4, 625,
  149644. _vq_lengthlist__44u7__p3_0,
  149645. 1, -533725184, 1611661312, 3, 0,
  149646. _vq_quantlist__44u7__p3_0,
  149647. NULL,
  149648. &_vq_auxt__44u7__p3_0,
  149649. NULL,
  149650. 0
  149651. };
  149652. static long _vq_quantlist__44u7__p4_0[] = {
  149653. 2,
  149654. 1,
  149655. 3,
  149656. 0,
  149657. 4,
  149658. };
  149659. static long _vq_lengthlist__44u7__p4_0[] = {
  149660. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149661. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149662. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149663. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149664. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149665. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149666. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149667. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149668. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149669. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149670. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149671. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149672. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149673. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149674. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149675. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149676. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149677. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149678. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149679. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149680. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149681. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149682. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149683. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149684. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149685. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149686. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149687. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149688. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149689. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149690. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149691. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149692. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149693. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149694. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149695. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149696. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149697. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149698. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149699. 14,
  149700. };
  149701. static float _vq_quantthresh__44u7__p4_0[] = {
  149702. -1.5, -0.5, 0.5, 1.5,
  149703. };
  149704. static long _vq_quantmap__44u7__p4_0[] = {
  149705. 3, 1, 0, 2, 4,
  149706. };
  149707. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149708. _vq_quantthresh__44u7__p4_0,
  149709. _vq_quantmap__44u7__p4_0,
  149710. 5,
  149711. 5
  149712. };
  149713. static static_codebook _44u7__p4_0 = {
  149714. 4, 625,
  149715. _vq_lengthlist__44u7__p4_0,
  149716. 1, -533725184, 1611661312, 3, 0,
  149717. _vq_quantlist__44u7__p4_0,
  149718. NULL,
  149719. &_vq_auxt__44u7__p4_0,
  149720. NULL,
  149721. 0
  149722. };
  149723. static long _vq_quantlist__44u7__p5_0[] = {
  149724. 4,
  149725. 3,
  149726. 5,
  149727. 2,
  149728. 6,
  149729. 1,
  149730. 7,
  149731. 0,
  149732. 8,
  149733. };
  149734. static long _vq_lengthlist__44u7__p5_0[] = {
  149735. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149736. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149737. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149738. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149739. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149740. 14,
  149741. };
  149742. static float _vq_quantthresh__44u7__p5_0[] = {
  149743. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149744. };
  149745. static long _vq_quantmap__44u7__p5_0[] = {
  149746. 7, 5, 3, 1, 0, 2, 4, 6,
  149747. 8,
  149748. };
  149749. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149750. _vq_quantthresh__44u7__p5_0,
  149751. _vq_quantmap__44u7__p5_0,
  149752. 9,
  149753. 9
  149754. };
  149755. static static_codebook _44u7__p5_0 = {
  149756. 2, 81,
  149757. _vq_lengthlist__44u7__p5_0,
  149758. 1, -531628032, 1611661312, 4, 0,
  149759. _vq_quantlist__44u7__p5_0,
  149760. NULL,
  149761. &_vq_auxt__44u7__p5_0,
  149762. NULL,
  149763. 0
  149764. };
  149765. static long _vq_quantlist__44u7__p6_0[] = {
  149766. 4,
  149767. 3,
  149768. 5,
  149769. 2,
  149770. 6,
  149771. 1,
  149772. 7,
  149773. 0,
  149774. 8,
  149775. };
  149776. static long _vq_lengthlist__44u7__p6_0[] = {
  149777. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149778. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149779. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149780. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149781. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149782. 12,
  149783. };
  149784. static float _vq_quantthresh__44u7__p6_0[] = {
  149785. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149786. };
  149787. static long _vq_quantmap__44u7__p6_0[] = {
  149788. 7, 5, 3, 1, 0, 2, 4, 6,
  149789. 8,
  149790. };
  149791. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149792. _vq_quantthresh__44u7__p6_0,
  149793. _vq_quantmap__44u7__p6_0,
  149794. 9,
  149795. 9
  149796. };
  149797. static static_codebook _44u7__p6_0 = {
  149798. 2, 81,
  149799. _vq_lengthlist__44u7__p6_0,
  149800. 1, -531628032, 1611661312, 4, 0,
  149801. _vq_quantlist__44u7__p6_0,
  149802. NULL,
  149803. &_vq_auxt__44u7__p6_0,
  149804. NULL,
  149805. 0
  149806. };
  149807. static long _vq_quantlist__44u7__p7_0[] = {
  149808. 1,
  149809. 0,
  149810. 2,
  149811. };
  149812. static long _vq_lengthlist__44u7__p7_0[] = {
  149813. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149814. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149815. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149816. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149817. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149818. 10,
  149819. };
  149820. static float _vq_quantthresh__44u7__p7_0[] = {
  149821. -5.5, 5.5,
  149822. };
  149823. static long _vq_quantmap__44u7__p7_0[] = {
  149824. 1, 0, 2,
  149825. };
  149826. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  149827. _vq_quantthresh__44u7__p7_0,
  149828. _vq_quantmap__44u7__p7_0,
  149829. 3,
  149830. 3
  149831. };
  149832. static static_codebook _44u7__p7_0 = {
  149833. 4, 81,
  149834. _vq_lengthlist__44u7__p7_0,
  149835. 1, -529137664, 1618345984, 2, 0,
  149836. _vq_quantlist__44u7__p7_0,
  149837. NULL,
  149838. &_vq_auxt__44u7__p7_0,
  149839. NULL,
  149840. 0
  149841. };
  149842. static long _vq_quantlist__44u7__p7_1[] = {
  149843. 5,
  149844. 4,
  149845. 6,
  149846. 3,
  149847. 7,
  149848. 2,
  149849. 8,
  149850. 1,
  149851. 9,
  149852. 0,
  149853. 10,
  149854. };
  149855. static long _vq_lengthlist__44u7__p7_1[] = {
  149856. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  149857. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  149858. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  149859. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  149860. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  149861. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149862. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  149863. 8, 9, 9, 9, 9, 9,10,10,10,
  149864. };
  149865. static float _vq_quantthresh__44u7__p7_1[] = {
  149866. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149867. 3.5, 4.5,
  149868. };
  149869. static long _vq_quantmap__44u7__p7_1[] = {
  149870. 9, 7, 5, 3, 1, 0, 2, 4,
  149871. 6, 8, 10,
  149872. };
  149873. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  149874. _vq_quantthresh__44u7__p7_1,
  149875. _vq_quantmap__44u7__p7_1,
  149876. 11,
  149877. 11
  149878. };
  149879. static static_codebook _44u7__p7_1 = {
  149880. 2, 121,
  149881. _vq_lengthlist__44u7__p7_1,
  149882. 1, -531365888, 1611661312, 4, 0,
  149883. _vq_quantlist__44u7__p7_1,
  149884. NULL,
  149885. &_vq_auxt__44u7__p7_1,
  149886. NULL,
  149887. 0
  149888. };
  149889. static long _vq_quantlist__44u7__p8_0[] = {
  149890. 5,
  149891. 4,
  149892. 6,
  149893. 3,
  149894. 7,
  149895. 2,
  149896. 8,
  149897. 1,
  149898. 9,
  149899. 0,
  149900. 10,
  149901. };
  149902. static long _vq_lengthlist__44u7__p8_0[] = {
  149903. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  149904. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  149905. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  149906. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  149907. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  149908. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  149909. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  149910. 12,13,13,14,14,15,15,15,16,
  149911. };
  149912. static float _vq_quantthresh__44u7__p8_0[] = {
  149913. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149914. 38.5, 49.5,
  149915. };
  149916. static long _vq_quantmap__44u7__p8_0[] = {
  149917. 9, 7, 5, 3, 1, 0, 2, 4,
  149918. 6, 8, 10,
  149919. };
  149920. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  149921. _vq_quantthresh__44u7__p8_0,
  149922. _vq_quantmap__44u7__p8_0,
  149923. 11,
  149924. 11
  149925. };
  149926. static static_codebook _44u7__p8_0 = {
  149927. 2, 121,
  149928. _vq_lengthlist__44u7__p8_0,
  149929. 1, -524582912, 1618345984, 4, 0,
  149930. _vq_quantlist__44u7__p8_0,
  149931. NULL,
  149932. &_vq_auxt__44u7__p8_0,
  149933. NULL,
  149934. 0
  149935. };
  149936. static long _vq_quantlist__44u7__p8_1[] = {
  149937. 5,
  149938. 4,
  149939. 6,
  149940. 3,
  149941. 7,
  149942. 2,
  149943. 8,
  149944. 1,
  149945. 9,
  149946. 0,
  149947. 10,
  149948. };
  149949. static long _vq_lengthlist__44u7__p8_1[] = {
  149950. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  149951. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  149952. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  149953. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149954. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149955. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  149956. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  149957. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  149958. };
  149959. static float _vq_quantthresh__44u7__p8_1[] = {
  149960. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149961. 3.5, 4.5,
  149962. };
  149963. static long _vq_quantmap__44u7__p8_1[] = {
  149964. 9, 7, 5, 3, 1, 0, 2, 4,
  149965. 6, 8, 10,
  149966. };
  149967. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  149968. _vq_quantthresh__44u7__p8_1,
  149969. _vq_quantmap__44u7__p8_1,
  149970. 11,
  149971. 11
  149972. };
  149973. static static_codebook _44u7__p8_1 = {
  149974. 2, 121,
  149975. _vq_lengthlist__44u7__p8_1,
  149976. 1, -531365888, 1611661312, 4, 0,
  149977. _vq_quantlist__44u7__p8_1,
  149978. NULL,
  149979. &_vq_auxt__44u7__p8_1,
  149980. NULL,
  149981. 0
  149982. };
  149983. static long _vq_quantlist__44u7__p9_0[] = {
  149984. 5,
  149985. 4,
  149986. 6,
  149987. 3,
  149988. 7,
  149989. 2,
  149990. 8,
  149991. 1,
  149992. 9,
  149993. 0,
  149994. 10,
  149995. };
  149996. static long _vq_lengthlist__44u7__p9_0[] = {
  149997. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  149998. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  149999. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150000. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150003. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150004. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150005. };
  150006. static float _vq_quantthresh__44u7__p9_0[] = {
  150007. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150008. 2229.5, 2866.5,
  150009. };
  150010. static long _vq_quantmap__44u7__p9_0[] = {
  150011. 9, 7, 5, 3, 1, 0, 2, 4,
  150012. 6, 8, 10,
  150013. };
  150014. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150015. _vq_quantthresh__44u7__p9_0,
  150016. _vq_quantmap__44u7__p9_0,
  150017. 11,
  150018. 11
  150019. };
  150020. static static_codebook _44u7__p9_0 = {
  150021. 2, 121,
  150022. _vq_lengthlist__44u7__p9_0,
  150023. 1, -512171520, 1630791680, 4, 0,
  150024. _vq_quantlist__44u7__p9_0,
  150025. NULL,
  150026. &_vq_auxt__44u7__p9_0,
  150027. NULL,
  150028. 0
  150029. };
  150030. static long _vq_quantlist__44u7__p9_1[] = {
  150031. 6,
  150032. 5,
  150033. 7,
  150034. 4,
  150035. 8,
  150036. 3,
  150037. 9,
  150038. 2,
  150039. 10,
  150040. 1,
  150041. 11,
  150042. 0,
  150043. 12,
  150044. };
  150045. static long _vq_lengthlist__44u7__p9_1[] = {
  150046. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150047. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150048. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150049. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150050. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150051. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150052. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150053. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150054. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150055. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150056. 15,15,15,15,17,17,16,17,16,
  150057. };
  150058. static float _vq_quantthresh__44u7__p9_1[] = {
  150059. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150060. 122.5, 171.5, 220.5, 269.5,
  150061. };
  150062. static long _vq_quantmap__44u7__p9_1[] = {
  150063. 11, 9, 7, 5, 3, 1, 0, 2,
  150064. 4, 6, 8, 10, 12,
  150065. };
  150066. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150067. _vq_quantthresh__44u7__p9_1,
  150068. _vq_quantmap__44u7__p9_1,
  150069. 13,
  150070. 13
  150071. };
  150072. static static_codebook _44u7__p9_1 = {
  150073. 2, 169,
  150074. _vq_lengthlist__44u7__p9_1,
  150075. 1, -518889472, 1622704128, 4, 0,
  150076. _vq_quantlist__44u7__p9_1,
  150077. NULL,
  150078. &_vq_auxt__44u7__p9_1,
  150079. NULL,
  150080. 0
  150081. };
  150082. static long _vq_quantlist__44u7__p9_2[] = {
  150083. 24,
  150084. 23,
  150085. 25,
  150086. 22,
  150087. 26,
  150088. 21,
  150089. 27,
  150090. 20,
  150091. 28,
  150092. 19,
  150093. 29,
  150094. 18,
  150095. 30,
  150096. 17,
  150097. 31,
  150098. 16,
  150099. 32,
  150100. 15,
  150101. 33,
  150102. 14,
  150103. 34,
  150104. 13,
  150105. 35,
  150106. 12,
  150107. 36,
  150108. 11,
  150109. 37,
  150110. 10,
  150111. 38,
  150112. 9,
  150113. 39,
  150114. 8,
  150115. 40,
  150116. 7,
  150117. 41,
  150118. 6,
  150119. 42,
  150120. 5,
  150121. 43,
  150122. 4,
  150123. 44,
  150124. 3,
  150125. 45,
  150126. 2,
  150127. 46,
  150128. 1,
  150129. 47,
  150130. 0,
  150131. 48,
  150132. };
  150133. static long _vq_lengthlist__44u7__p9_2[] = {
  150134. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150135. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150136. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150137. 8,
  150138. };
  150139. static float _vq_quantthresh__44u7__p9_2[] = {
  150140. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150141. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150142. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150143. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150144. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150145. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150146. };
  150147. static long _vq_quantmap__44u7__p9_2[] = {
  150148. 47, 45, 43, 41, 39, 37, 35, 33,
  150149. 31, 29, 27, 25, 23, 21, 19, 17,
  150150. 15, 13, 11, 9, 7, 5, 3, 1,
  150151. 0, 2, 4, 6, 8, 10, 12, 14,
  150152. 16, 18, 20, 22, 24, 26, 28, 30,
  150153. 32, 34, 36, 38, 40, 42, 44, 46,
  150154. 48,
  150155. };
  150156. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150157. _vq_quantthresh__44u7__p9_2,
  150158. _vq_quantmap__44u7__p9_2,
  150159. 49,
  150160. 49
  150161. };
  150162. static static_codebook _44u7__p9_2 = {
  150163. 1, 49,
  150164. _vq_lengthlist__44u7__p9_2,
  150165. 1, -526909440, 1611661312, 6, 0,
  150166. _vq_quantlist__44u7__p9_2,
  150167. NULL,
  150168. &_vq_auxt__44u7__p9_2,
  150169. NULL,
  150170. 0
  150171. };
  150172. static long _huff_lengthlist__44u7__short[] = {
  150173. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150174. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150175. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150176. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150177. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150178. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150179. 6, 8, 5, 9,
  150180. };
  150181. static static_codebook _huff_book__44u7__short = {
  150182. 2, 100,
  150183. _huff_lengthlist__44u7__short,
  150184. 0, 0, 0, 0, 0,
  150185. NULL,
  150186. NULL,
  150187. NULL,
  150188. NULL,
  150189. 0
  150190. };
  150191. static long _huff_lengthlist__44u8__long[] = {
  150192. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150193. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150194. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150195. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150196. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150197. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150198. 10, 8, 8, 9,
  150199. };
  150200. static static_codebook _huff_book__44u8__long = {
  150201. 2, 100,
  150202. _huff_lengthlist__44u8__long,
  150203. 0, 0, 0, 0, 0,
  150204. NULL,
  150205. NULL,
  150206. NULL,
  150207. NULL,
  150208. 0
  150209. };
  150210. static long _huff_lengthlist__44u8__short[] = {
  150211. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150212. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150213. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150214. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150215. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150216. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150217. 10,10,15,17,
  150218. };
  150219. static static_codebook _huff_book__44u8__short = {
  150220. 2, 100,
  150221. _huff_lengthlist__44u8__short,
  150222. 0, 0, 0, 0, 0,
  150223. NULL,
  150224. NULL,
  150225. NULL,
  150226. NULL,
  150227. 0
  150228. };
  150229. static long _vq_quantlist__44u8_p1_0[] = {
  150230. 1,
  150231. 0,
  150232. 2,
  150233. };
  150234. static long _vq_lengthlist__44u8_p1_0[] = {
  150235. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150236. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150237. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150238. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150239. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150240. 10,
  150241. };
  150242. static float _vq_quantthresh__44u8_p1_0[] = {
  150243. -0.5, 0.5,
  150244. };
  150245. static long _vq_quantmap__44u8_p1_0[] = {
  150246. 1, 0, 2,
  150247. };
  150248. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150249. _vq_quantthresh__44u8_p1_0,
  150250. _vq_quantmap__44u8_p1_0,
  150251. 3,
  150252. 3
  150253. };
  150254. static static_codebook _44u8_p1_0 = {
  150255. 4, 81,
  150256. _vq_lengthlist__44u8_p1_0,
  150257. 1, -535822336, 1611661312, 2, 0,
  150258. _vq_quantlist__44u8_p1_0,
  150259. NULL,
  150260. &_vq_auxt__44u8_p1_0,
  150261. NULL,
  150262. 0
  150263. };
  150264. static long _vq_quantlist__44u8_p2_0[] = {
  150265. 2,
  150266. 1,
  150267. 3,
  150268. 0,
  150269. 4,
  150270. };
  150271. static long _vq_lengthlist__44u8_p2_0[] = {
  150272. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150273. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150274. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150275. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150276. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150277. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150278. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150279. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150280. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150281. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150282. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150283. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150284. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150285. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150286. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150287. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150288. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150289. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150290. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150291. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150292. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150293. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150294. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150295. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150296. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150297. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150298. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150299. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150300. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150301. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150302. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150303. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150304. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150305. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150306. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150307. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150308. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150309. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150310. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150311. 14,
  150312. };
  150313. static float _vq_quantthresh__44u8_p2_0[] = {
  150314. -1.5, -0.5, 0.5, 1.5,
  150315. };
  150316. static long _vq_quantmap__44u8_p2_0[] = {
  150317. 3, 1, 0, 2, 4,
  150318. };
  150319. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150320. _vq_quantthresh__44u8_p2_0,
  150321. _vq_quantmap__44u8_p2_0,
  150322. 5,
  150323. 5
  150324. };
  150325. static static_codebook _44u8_p2_0 = {
  150326. 4, 625,
  150327. _vq_lengthlist__44u8_p2_0,
  150328. 1, -533725184, 1611661312, 3, 0,
  150329. _vq_quantlist__44u8_p2_0,
  150330. NULL,
  150331. &_vq_auxt__44u8_p2_0,
  150332. NULL,
  150333. 0
  150334. };
  150335. static long _vq_quantlist__44u8_p3_0[] = {
  150336. 4,
  150337. 3,
  150338. 5,
  150339. 2,
  150340. 6,
  150341. 1,
  150342. 7,
  150343. 0,
  150344. 8,
  150345. };
  150346. static long _vq_lengthlist__44u8_p3_0[] = {
  150347. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150348. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150349. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150350. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150351. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150352. 12,
  150353. };
  150354. static float _vq_quantthresh__44u8_p3_0[] = {
  150355. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150356. };
  150357. static long _vq_quantmap__44u8_p3_0[] = {
  150358. 7, 5, 3, 1, 0, 2, 4, 6,
  150359. 8,
  150360. };
  150361. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150362. _vq_quantthresh__44u8_p3_0,
  150363. _vq_quantmap__44u8_p3_0,
  150364. 9,
  150365. 9
  150366. };
  150367. static static_codebook _44u8_p3_0 = {
  150368. 2, 81,
  150369. _vq_lengthlist__44u8_p3_0,
  150370. 1, -531628032, 1611661312, 4, 0,
  150371. _vq_quantlist__44u8_p3_0,
  150372. NULL,
  150373. &_vq_auxt__44u8_p3_0,
  150374. NULL,
  150375. 0
  150376. };
  150377. static long _vq_quantlist__44u8_p4_0[] = {
  150378. 8,
  150379. 7,
  150380. 9,
  150381. 6,
  150382. 10,
  150383. 5,
  150384. 11,
  150385. 4,
  150386. 12,
  150387. 3,
  150388. 13,
  150389. 2,
  150390. 14,
  150391. 1,
  150392. 15,
  150393. 0,
  150394. 16,
  150395. };
  150396. static long _vq_lengthlist__44u8_p4_0[] = {
  150397. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150398. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150399. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150400. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150401. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150402. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150403. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150404. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150405. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150406. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150407. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150408. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150409. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150410. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150411. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150412. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150413. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150414. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150415. 14,
  150416. };
  150417. static float _vq_quantthresh__44u8_p4_0[] = {
  150418. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150419. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150420. };
  150421. static long _vq_quantmap__44u8_p4_0[] = {
  150422. 15, 13, 11, 9, 7, 5, 3, 1,
  150423. 0, 2, 4, 6, 8, 10, 12, 14,
  150424. 16,
  150425. };
  150426. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150427. _vq_quantthresh__44u8_p4_0,
  150428. _vq_quantmap__44u8_p4_0,
  150429. 17,
  150430. 17
  150431. };
  150432. static static_codebook _44u8_p4_0 = {
  150433. 2, 289,
  150434. _vq_lengthlist__44u8_p4_0,
  150435. 1, -529530880, 1611661312, 5, 0,
  150436. _vq_quantlist__44u8_p4_0,
  150437. NULL,
  150438. &_vq_auxt__44u8_p4_0,
  150439. NULL,
  150440. 0
  150441. };
  150442. static long _vq_quantlist__44u8_p5_0[] = {
  150443. 1,
  150444. 0,
  150445. 2,
  150446. };
  150447. static long _vq_lengthlist__44u8_p5_0[] = {
  150448. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150449. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150450. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150451. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150452. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150453. 10,
  150454. };
  150455. static float _vq_quantthresh__44u8_p5_0[] = {
  150456. -5.5, 5.5,
  150457. };
  150458. static long _vq_quantmap__44u8_p5_0[] = {
  150459. 1, 0, 2,
  150460. };
  150461. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150462. _vq_quantthresh__44u8_p5_0,
  150463. _vq_quantmap__44u8_p5_0,
  150464. 3,
  150465. 3
  150466. };
  150467. static static_codebook _44u8_p5_0 = {
  150468. 4, 81,
  150469. _vq_lengthlist__44u8_p5_0,
  150470. 1, -529137664, 1618345984, 2, 0,
  150471. _vq_quantlist__44u8_p5_0,
  150472. NULL,
  150473. &_vq_auxt__44u8_p5_0,
  150474. NULL,
  150475. 0
  150476. };
  150477. static long _vq_quantlist__44u8_p5_1[] = {
  150478. 5,
  150479. 4,
  150480. 6,
  150481. 3,
  150482. 7,
  150483. 2,
  150484. 8,
  150485. 1,
  150486. 9,
  150487. 0,
  150488. 10,
  150489. };
  150490. static long _vq_lengthlist__44u8_p5_1[] = {
  150491. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150492. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150493. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150494. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150495. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150496. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150497. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150498. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150499. };
  150500. static float _vq_quantthresh__44u8_p5_1[] = {
  150501. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150502. 3.5, 4.5,
  150503. };
  150504. static long _vq_quantmap__44u8_p5_1[] = {
  150505. 9, 7, 5, 3, 1, 0, 2, 4,
  150506. 6, 8, 10,
  150507. };
  150508. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150509. _vq_quantthresh__44u8_p5_1,
  150510. _vq_quantmap__44u8_p5_1,
  150511. 11,
  150512. 11
  150513. };
  150514. static static_codebook _44u8_p5_1 = {
  150515. 2, 121,
  150516. _vq_lengthlist__44u8_p5_1,
  150517. 1, -531365888, 1611661312, 4, 0,
  150518. _vq_quantlist__44u8_p5_1,
  150519. NULL,
  150520. &_vq_auxt__44u8_p5_1,
  150521. NULL,
  150522. 0
  150523. };
  150524. static long _vq_quantlist__44u8_p6_0[] = {
  150525. 6,
  150526. 5,
  150527. 7,
  150528. 4,
  150529. 8,
  150530. 3,
  150531. 9,
  150532. 2,
  150533. 10,
  150534. 1,
  150535. 11,
  150536. 0,
  150537. 12,
  150538. };
  150539. static long _vq_lengthlist__44u8_p6_0[] = {
  150540. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150541. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150542. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150543. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150544. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150545. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150546. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150547. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150548. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150549. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150550. 11,11,11,11,11,12,11,12,12,
  150551. };
  150552. static float _vq_quantthresh__44u8_p6_0[] = {
  150553. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150554. 12.5, 17.5, 22.5, 27.5,
  150555. };
  150556. static long _vq_quantmap__44u8_p6_0[] = {
  150557. 11, 9, 7, 5, 3, 1, 0, 2,
  150558. 4, 6, 8, 10, 12,
  150559. };
  150560. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150561. _vq_quantthresh__44u8_p6_0,
  150562. _vq_quantmap__44u8_p6_0,
  150563. 13,
  150564. 13
  150565. };
  150566. static static_codebook _44u8_p6_0 = {
  150567. 2, 169,
  150568. _vq_lengthlist__44u8_p6_0,
  150569. 1, -526516224, 1616117760, 4, 0,
  150570. _vq_quantlist__44u8_p6_0,
  150571. NULL,
  150572. &_vq_auxt__44u8_p6_0,
  150573. NULL,
  150574. 0
  150575. };
  150576. static long _vq_quantlist__44u8_p6_1[] = {
  150577. 2,
  150578. 1,
  150579. 3,
  150580. 0,
  150581. 4,
  150582. };
  150583. static long _vq_lengthlist__44u8_p6_1[] = {
  150584. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150585. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150586. };
  150587. static float _vq_quantthresh__44u8_p6_1[] = {
  150588. -1.5, -0.5, 0.5, 1.5,
  150589. };
  150590. static long _vq_quantmap__44u8_p6_1[] = {
  150591. 3, 1, 0, 2, 4,
  150592. };
  150593. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150594. _vq_quantthresh__44u8_p6_1,
  150595. _vq_quantmap__44u8_p6_1,
  150596. 5,
  150597. 5
  150598. };
  150599. static static_codebook _44u8_p6_1 = {
  150600. 2, 25,
  150601. _vq_lengthlist__44u8_p6_1,
  150602. 1, -533725184, 1611661312, 3, 0,
  150603. _vq_quantlist__44u8_p6_1,
  150604. NULL,
  150605. &_vq_auxt__44u8_p6_1,
  150606. NULL,
  150607. 0
  150608. };
  150609. static long _vq_quantlist__44u8_p7_0[] = {
  150610. 6,
  150611. 5,
  150612. 7,
  150613. 4,
  150614. 8,
  150615. 3,
  150616. 9,
  150617. 2,
  150618. 10,
  150619. 1,
  150620. 11,
  150621. 0,
  150622. 12,
  150623. };
  150624. static long _vq_lengthlist__44u8_p7_0[] = {
  150625. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150626. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150627. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150628. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150629. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150630. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150631. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150632. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150633. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150634. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150635. 13,13,14,14,14,15,15,15,16,
  150636. };
  150637. static float _vq_quantthresh__44u8_p7_0[] = {
  150638. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150639. 27.5, 38.5, 49.5, 60.5,
  150640. };
  150641. static long _vq_quantmap__44u8_p7_0[] = {
  150642. 11, 9, 7, 5, 3, 1, 0, 2,
  150643. 4, 6, 8, 10, 12,
  150644. };
  150645. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150646. _vq_quantthresh__44u8_p7_0,
  150647. _vq_quantmap__44u8_p7_0,
  150648. 13,
  150649. 13
  150650. };
  150651. static static_codebook _44u8_p7_0 = {
  150652. 2, 169,
  150653. _vq_lengthlist__44u8_p7_0,
  150654. 1, -523206656, 1618345984, 4, 0,
  150655. _vq_quantlist__44u8_p7_0,
  150656. NULL,
  150657. &_vq_auxt__44u8_p7_0,
  150658. NULL,
  150659. 0
  150660. };
  150661. static long _vq_quantlist__44u8_p7_1[] = {
  150662. 5,
  150663. 4,
  150664. 6,
  150665. 3,
  150666. 7,
  150667. 2,
  150668. 8,
  150669. 1,
  150670. 9,
  150671. 0,
  150672. 10,
  150673. };
  150674. static long _vq_lengthlist__44u8_p7_1[] = {
  150675. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150676. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150677. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150678. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150679. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150680. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150681. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150682. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150683. };
  150684. static float _vq_quantthresh__44u8_p7_1[] = {
  150685. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150686. 3.5, 4.5,
  150687. };
  150688. static long _vq_quantmap__44u8_p7_1[] = {
  150689. 9, 7, 5, 3, 1, 0, 2, 4,
  150690. 6, 8, 10,
  150691. };
  150692. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150693. _vq_quantthresh__44u8_p7_1,
  150694. _vq_quantmap__44u8_p7_1,
  150695. 11,
  150696. 11
  150697. };
  150698. static static_codebook _44u8_p7_1 = {
  150699. 2, 121,
  150700. _vq_lengthlist__44u8_p7_1,
  150701. 1, -531365888, 1611661312, 4, 0,
  150702. _vq_quantlist__44u8_p7_1,
  150703. NULL,
  150704. &_vq_auxt__44u8_p7_1,
  150705. NULL,
  150706. 0
  150707. };
  150708. static long _vq_quantlist__44u8_p8_0[] = {
  150709. 7,
  150710. 6,
  150711. 8,
  150712. 5,
  150713. 9,
  150714. 4,
  150715. 10,
  150716. 3,
  150717. 11,
  150718. 2,
  150719. 12,
  150720. 1,
  150721. 13,
  150722. 0,
  150723. 14,
  150724. };
  150725. static long _vq_lengthlist__44u8_p8_0[] = {
  150726. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150727. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150728. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150729. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150730. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150731. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150732. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150733. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150734. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150735. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150736. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150737. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150738. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150739. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150740. 17,
  150741. };
  150742. static float _vq_quantthresh__44u8_p8_0[] = {
  150743. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150744. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150745. };
  150746. static long _vq_quantmap__44u8_p8_0[] = {
  150747. 13, 11, 9, 7, 5, 3, 1, 0,
  150748. 2, 4, 6, 8, 10, 12, 14,
  150749. };
  150750. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150751. _vq_quantthresh__44u8_p8_0,
  150752. _vq_quantmap__44u8_p8_0,
  150753. 15,
  150754. 15
  150755. };
  150756. static static_codebook _44u8_p8_0 = {
  150757. 2, 225,
  150758. _vq_lengthlist__44u8_p8_0,
  150759. 1, -520986624, 1620377600, 4, 0,
  150760. _vq_quantlist__44u8_p8_0,
  150761. NULL,
  150762. &_vq_auxt__44u8_p8_0,
  150763. NULL,
  150764. 0
  150765. };
  150766. static long _vq_quantlist__44u8_p8_1[] = {
  150767. 10,
  150768. 9,
  150769. 11,
  150770. 8,
  150771. 12,
  150772. 7,
  150773. 13,
  150774. 6,
  150775. 14,
  150776. 5,
  150777. 15,
  150778. 4,
  150779. 16,
  150780. 3,
  150781. 17,
  150782. 2,
  150783. 18,
  150784. 1,
  150785. 19,
  150786. 0,
  150787. 20,
  150788. };
  150789. static long _vq_lengthlist__44u8_p8_1[] = {
  150790. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150791. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150792. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150793. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150794. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150795. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150796. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150797. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150798. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150799. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150800. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150801. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150802. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150803. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150804. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150805. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150806. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150807. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150808. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150809. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150810. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150811. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150812. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150813. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150814. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150815. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150816. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150817. 10,10,10,10,10,10,10,10,10,
  150818. };
  150819. static float _vq_quantthresh__44u8_p8_1[] = {
  150820. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  150821. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  150822. 6.5, 7.5, 8.5, 9.5,
  150823. };
  150824. static long _vq_quantmap__44u8_p8_1[] = {
  150825. 19, 17, 15, 13, 11, 9, 7, 5,
  150826. 3, 1, 0, 2, 4, 6, 8, 10,
  150827. 12, 14, 16, 18, 20,
  150828. };
  150829. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  150830. _vq_quantthresh__44u8_p8_1,
  150831. _vq_quantmap__44u8_p8_1,
  150832. 21,
  150833. 21
  150834. };
  150835. static static_codebook _44u8_p8_1 = {
  150836. 2, 441,
  150837. _vq_lengthlist__44u8_p8_1,
  150838. 1, -529268736, 1611661312, 5, 0,
  150839. _vq_quantlist__44u8_p8_1,
  150840. NULL,
  150841. &_vq_auxt__44u8_p8_1,
  150842. NULL,
  150843. 0
  150844. };
  150845. static long _vq_quantlist__44u8_p9_0[] = {
  150846. 4,
  150847. 3,
  150848. 5,
  150849. 2,
  150850. 6,
  150851. 1,
  150852. 7,
  150853. 0,
  150854. 8,
  150855. };
  150856. static long _vq_lengthlist__44u8_p9_0[] = {
  150857. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  150858. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150859. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150860. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150862. 8,
  150863. };
  150864. static float _vq_quantthresh__44u8_p9_0[] = {
  150865. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  150866. };
  150867. static long _vq_quantmap__44u8_p9_0[] = {
  150868. 7, 5, 3, 1, 0, 2, 4, 6,
  150869. 8,
  150870. };
  150871. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  150872. _vq_quantthresh__44u8_p9_0,
  150873. _vq_quantmap__44u8_p9_0,
  150874. 9,
  150875. 9
  150876. };
  150877. static static_codebook _44u8_p9_0 = {
  150878. 2, 81,
  150879. _vq_lengthlist__44u8_p9_0,
  150880. 1, -511895552, 1631393792, 4, 0,
  150881. _vq_quantlist__44u8_p9_0,
  150882. NULL,
  150883. &_vq_auxt__44u8_p9_0,
  150884. NULL,
  150885. 0
  150886. };
  150887. static long _vq_quantlist__44u8_p9_1[] = {
  150888. 9,
  150889. 8,
  150890. 10,
  150891. 7,
  150892. 11,
  150893. 6,
  150894. 12,
  150895. 5,
  150896. 13,
  150897. 4,
  150898. 14,
  150899. 3,
  150900. 15,
  150901. 2,
  150902. 16,
  150903. 1,
  150904. 17,
  150905. 0,
  150906. 18,
  150907. };
  150908. static long _vq_lengthlist__44u8_p9_1[] = {
  150909. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  150910. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  150911. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  150912. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  150913. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  150914. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  150915. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  150916. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  150917. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  150918. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  150919. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  150920. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  150921. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  150922. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  150923. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  150924. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  150925. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  150926. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  150927. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  150928. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  150929. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  150930. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  150931. 16,15,16,16,16,16,16,16,16,
  150932. };
  150933. static float _vq_quantthresh__44u8_p9_1[] = {
  150934. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  150935. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  150936. 367.5, 416.5,
  150937. };
  150938. static long _vq_quantmap__44u8_p9_1[] = {
  150939. 17, 15, 13, 11, 9, 7, 5, 3,
  150940. 1, 0, 2, 4, 6, 8, 10, 12,
  150941. 14, 16, 18,
  150942. };
  150943. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  150944. _vq_quantthresh__44u8_p9_1,
  150945. _vq_quantmap__44u8_p9_1,
  150946. 19,
  150947. 19
  150948. };
  150949. static static_codebook _44u8_p9_1 = {
  150950. 2, 361,
  150951. _vq_lengthlist__44u8_p9_1,
  150952. 1, -518287360, 1622704128, 5, 0,
  150953. _vq_quantlist__44u8_p9_1,
  150954. NULL,
  150955. &_vq_auxt__44u8_p9_1,
  150956. NULL,
  150957. 0
  150958. };
  150959. static long _vq_quantlist__44u8_p9_2[] = {
  150960. 24,
  150961. 23,
  150962. 25,
  150963. 22,
  150964. 26,
  150965. 21,
  150966. 27,
  150967. 20,
  150968. 28,
  150969. 19,
  150970. 29,
  150971. 18,
  150972. 30,
  150973. 17,
  150974. 31,
  150975. 16,
  150976. 32,
  150977. 15,
  150978. 33,
  150979. 14,
  150980. 34,
  150981. 13,
  150982. 35,
  150983. 12,
  150984. 36,
  150985. 11,
  150986. 37,
  150987. 10,
  150988. 38,
  150989. 9,
  150990. 39,
  150991. 8,
  150992. 40,
  150993. 7,
  150994. 41,
  150995. 6,
  150996. 42,
  150997. 5,
  150998. 43,
  150999. 4,
  151000. 44,
  151001. 3,
  151002. 45,
  151003. 2,
  151004. 46,
  151005. 1,
  151006. 47,
  151007. 0,
  151008. 48,
  151009. };
  151010. static long _vq_lengthlist__44u8_p9_2[] = {
  151011. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151012. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151013. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151014. 7,
  151015. };
  151016. static float _vq_quantthresh__44u8_p9_2[] = {
  151017. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151018. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151019. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151020. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151021. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151022. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151023. };
  151024. static long _vq_quantmap__44u8_p9_2[] = {
  151025. 47, 45, 43, 41, 39, 37, 35, 33,
  151026. 31, 29, 27, 25, 23, 21, 19, 17,
  151027. 15, 13, 11, 9, 7, 5, 3, 1,
  151028. 0, 2, 4, 6, 8, 10, 12, 14,
  151029. 16, 18, 20, 22, 24, 26, 28, 30,
  151030. 32, 34, 36, 38, 40, 42, 44, 46,
  151031. 48,
  151032. };
  151033. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151034. _vq_quantthresh__44u8_p9_2,
  151035. _vq_quantmap__44u8_p9_2,
  151036. 49,
  151037. 49
  151038. };
  151039. static static_codebook _44u8_p9_2 = {
  151040. 1, 49,
  151041. _vq_lengthlist__44u8_p9_2,
  151042. 1, -526909440, 1611661312, 6, 0,
  151043. _vq_quantlist__44u8_p9_2,
  151044. NULL,
  151045. &_vq_auxt__44u8_p9_2,
  151046. NULL,
  151047. 0
  151048. };
  151049. static long _huff_lengthlist__44u9__long[] = {
  151050. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151051. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151052. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151053. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151054. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151055. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151056. 10, 8, 8, 9,
  151057. };
  151058. static static_codebook _huff_book__44u9__long = {
  151059. 2, 100,
  151060. _huff_lengthlist__44u9__long,
  151061. 0, 0, 0, 0, 0,
  151062. NULL,
  151063. NULL,
  151064. NULL,
  151065. NULL,
  151066. 0
  151067. };
  151068. static long _huff_lengthlist__44u9__short[] = {
  151069. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151070. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151071. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151072. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151073. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151074. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151075. 9, 9,12,15,
  151076. };
  151077. static static_codebook _huff_book__44u9__short = {
  151078. 2, 100,
  151079. _huff_lengthlist__44u9__short,
  151080. 0, 0, 0, 0, 0,
  151081. NULL,
  151082. NULL,
  151083. NULL,
  151084. NULL,
  151085. 0
  151086. };
  151087. static long _vq_quantlist__44u9_p1_0[] = {
  151088. 1,
  151089. 0,
  151090. 2,
  151091. };
  151092. static long _vq_lengthlist__44u9_p1_0[] = {
  151093. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151094. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151095. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151096. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151097. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151098. 10,
  151099. };
  151100. static float _vq_quantthresh__44u9_p1_0[] = {
  151101. -0.5, 0.5,
  151102. };
  151103. static long _vq_quantmap__44u9_p1_0[] = {
  151104. 1, 0, 2,
  151105. };
  151106. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151107. _vq_quantthresh__44u9_p1_0,
  151108. _vq_quantmap__44u9_p1_0,
  151109. 3,
  151110. 3
  151111. };
  151112. static static_codebook _44u9_p1_0 = {
  151113. 4, 81,
  151114. _vq_lengthlist__44u9_p1_0,
  151115. 1, -535822336, 1611661312, 2, 0,
  151116. _vq_quantlist__44u9_p1_0,
  151117. NULL,
  151118. &_vq_auxt__44u9_p1_0,
  151119. NULL,
  151120. 0
  151121. };
  151122. static long _vq_quantlist__44u9_p2_0[] = {
  151123. 2,
  151124. 1,
  151125. 3,
  151126. 0,
  151127. 4,
  151128. };
  151129. static long _vq_lengthlist__44u9_p2_0[] = {
  151130. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151131. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151132. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151133. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151134. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151135. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151136. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151137. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151138. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151139. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151140. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151141. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151142. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151143. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151144. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151145. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151146. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151147. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151148. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151149. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151150. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151151. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151152. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151153. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151154. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151155. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151156. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151157. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151158. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151159. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151160. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151161. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151162. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151163. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151164. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151165. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151166. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151167. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151168. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151169. 14,
  151170. };
  151171. static float _vq_quantthresh__44u9_p2_0[] = {
  151172. -1.5, -0.5, 0.5, 1.5,
  151173. };
  151174. static long _vq_quantmap__44u9_p2_0[] = {
  151175. 3, 1, 0, 2, 4,
  151176. };
  151177. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151178. _vq_quantthresh__44u9_p2_0,
  151179. _vq_quantmap__44u9_p2_0,
  151180. 5,
  151181. 5
  151182. };
  151183. static static_codebook _44u9_p2_0 = {
  151184. 4, 625,
  151185. _vq_lengthlist__44u9_p2_0,
  151186. 1, -533725184, 1611661312, 3, 0,
  151187. _vq_quantlist__44u9_p2_0,
  151188. NULL,
  151189. &_vq_auxt__44u9_p2_0,
  151190. NULL,
  151191. 0
  151192. };
  151193. static long _vq_quantlist__44u9_p3_0[] = {
  151194. 4,
  151195. 3,
  151196. 5,
  151197. 2,
  151198. 6,
  151199. 1,
  151200. 7,
  151201. 0,
  151202. 8,
  151203. };
  151204. static long _vq_lengthlist__44u9_p3_0[] = {
  151205. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151206. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151207. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151208. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151209. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151210. 11,
  151211. };
  151212. static float _vq_quantthresh__44u9_p3_0[] = {
  151213. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151214. };
  151215. static long _vq_quantmap__44u9_p3_0[] = {
  151216. 7, 5, 3, 1, 0, 2, 4, 6,
  151217. 8,
  151218. };
  151219. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151220. _vq_quantthresh__44u9_p3_0,
  151221. _vq_quantmap__44u9_p3_0,
  151222. 9,
  151223. 9
  151224. };
  151225. static static_codebook _44u9_p3_0 = {
  151226. 2, 81,
  151227. _vq_lengthlist__44u9_p3_0,
  151228. 1, -531628032, 1611661312, 4, 0,
  151229. _vq_quantlist__44u9_p3_0,
  151230. NULL,
  151231. &_vq_auxt__44u9_p3_0,
  151232. NULL,
  151233. 0
  151234. };
  151235. static long _vq_quantlist__44u9_p4_0[] = {
  151236. 8,
  151237. 7,
  151238. 9,
  151239. 6,
  151240. 10,
  151241. 5,
  151242. 11,
  151243. 4,
  151244. 12,
  151245. 3,
  151246. 13,
  151247. 2,
  151248. 14,
  151249. 1,
  151250. 15,
  151251. 0,
  151252. 16,
  151253. };
  151254. static long _vq_lengthlist__44u9_p4_0[] = {
  151255. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151256. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151257. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151258. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151259. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151260. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151261. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151262. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151263. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151264. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151265. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151266. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151267. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151268. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151269. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151270. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151271. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151272. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151273. 14,
  151274. };
  151275. static float _vq_quantthresh__44u9_p4_0[] = {
  151276. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151277. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151278. };
  151279. static long _vq_quantmap__44u9_p4_0[] = {
  151280. 15, 13, 11, 9, 7, 5, 3, 1,
  151281. 0, 2, 4, 6, 8, 10, 12, 14,
  151282. 16,
  151283. };
  151284. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151285. _vq_quantthresh__44u9_p4_0,
  151286. _vq_quantmap__44u9_p4_0,
  151287. 17,
  151288. 17
  151289. };
  151290. static static_codebook _44u9_p4_0 = {
  151291. 2, 289,
  151292. _vq_lengthlist__44u9_p4_0,
  151293. 1, -529530880, 1611661312, 5, 0,
  151294. _vq_quantlist__44u9_p4_0,
  151295. NULL,
  151296. &_vq_auxt__44u9_p4_0,
  151297. NULL,
  151298. 0
  151299. };
  151300. static long _vq_quantlist__44u9_p5_0[] = {
  151301. 1,
  151302. 0,
  151303. 2,
  151304. };
  151305. static long _vq_lengthlist__44u9_p5_0[] = {
  151306. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151307. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151308. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151309. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151310. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151311. 10,
  151312. };
  151313. static float _vq_quantthresh__44u9_p5_0[] = {
  151314. -5.5, 5.5,
  151315. };
  151316. static long _vq_quantmap__44u9_p5_0[] = {
  151317. 1, 0, 2,
  151318. };
  151319. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151320. _vq_quantthresh__44u9_p5_0,
  151321. _vq_quantmap__44u9_p5_0,
  151322. 3,
  151323. 3
  151324. };
  151325. static static_codebook _44u9_p5_0 = {
  151326. 4, 81,
  151327. _vq_lengthlist__44u9_p5_0,
  151328. 1, -529137664, 1618345984, 2, 0,
  151329. _vq_quantlist__44u9_p5_0,
  151330. NULL,
  151331. &_vq_auxt__44u9_p5_0,
  151332. NULL,
  151333. 0
  151334. };
  151335. static long _vq_quantlist__44u9_p5_1[] = {
  151336. 5,
  151337. 4,
  151338. 6,
  151339. 3,
  151340. 7,
  151341. 2,
  151342. 8,
  151343. 1,
  151344. 9,
  151345. 0,
  151346. 10,
  151347. };
  151348. static long _vq_lengthlist__44u9_p5_1[] = {
  151349. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151350. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151351. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151352. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151353. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151354. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151355. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151356. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151357. };
  151358. static float _vq_quantthresh__44u9_p5_1[] = {
  151359. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151360. 3.5, 4.5,
  151361. };
  151362. static long _vq_quantmap__44u9_p5_1[] = {
  151363. 9, 7, 5, 3, 1, 0, 2, 4,
  151364. 6, 8, 10,
  151365. };
  151366. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151367. _vq_quantthresh__44u9_p5_1,
  151368. _vq_quantmap__44u9_p5_1,
  151369. 11,
  151370. 11
  151371. };
  151372. static static_codebook _44u9_p5_1 = {
  151373. 2, 121,
  151374. _vq_lengthlist__44u9_p5_1,
  151375. 1, -531365888, 1611661312, 4, 0,
  151376. _vq_quantlist__44u9_p5_1,
  151377. NULL,
  151378. &_vq_auxt__44u9_p5_1,
  151379. NULL,
  151380. 0
  151381. };
  151382. static long _vq_quantlist__44u9_p6_0[] = {
  151383. 6,
  151384. 5,
  151385. 7,
  151386. 4,
  151387. 8,
  151388. 3,
  151389. 9,
  151390. 2,
  151391. 10,
  151392. 1,
  151393. 11,
  151394. 0,
  151395. 12,
  151396. };
  151397. static long _vq_lengthlist__44u9_p6_0[] = {
  151398. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151399. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151400. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151401. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151402. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151403. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151404. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151405. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151406. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151407. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151408. 10,11,11,11,11,12,11,12,12,
  151409. };
  151410. static float _vq_quantthresh__44u9_p6_0[] = {
  151411. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151412. 12.5, 17.5, 22.5, 27.5,
  151413. };
  151414. static long _vq_quantmap__44u9_p6_0[] = {
  151415. 11, 9, 7, 5, 3, 1, 0, 2,
  151416. 4, 6, 8, 10, 12,
  151417. };
  151418. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151419. _vq_quantthresh__44u9_p6_0,
  151420. _vq_quantmap__44u9_p6_0,
  151421. 13,
  151422. 13
  151423. };
  151424. static static_codebook _44u9_p6_0 = {
  151425. 2, 169,
  151426. _vq_lengthlist__44u9_p6_0,
  151427. 1, -526516224, 1616117760, 4, 0,
  151428. _vq_quantlist__44u9_p6_0,
  151429. NULL,
  151430. &_vq_auxt__44u9_p6_0,
  151431. NULL,
  151432. 0
  151433. };
  151434. static long _vq_quantlist__44u9_p6_1[] = {
  151435. 2,
  151436. 1,
  151437. 3,
  151438. 0,
  151439. 4,
  151440. };
  151441. static long _vq_lengthlist__44u9_p6_1[] = {
  151442. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151443. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151444. };
  151445. static float _vq_quantthresh__44u9_p6_1[] = {
  151446. -1.5, -0.5, 0.5, 1.5,
  151447. };
  151448. static long _vq_quantmap__44u9_p6_1[] = {
  151449. 3, 1, 0, 2, 4,
  151450. };
  151451. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151452. _vq_quantthresh__44u9_p6_1,
  151453. _vq_quantmap__44u9_p6_1,
  151454. 5,
  151455. 5
  151456. };
  151457. static static_codebook _44u9_p6_1 = {
  151458. 2, 25,
  151459. _vq_lengthlist__44u9_p6_1,
  151460. 1, -533725184, 1611661312, 3, 0,
  151461. _vq_quantlist__44u9_p6_1,
  151462. NULL,
  151463. &_vq_auxt__44u9_p6_1,
  151464. NULL,
  151465. 0
  151466. };
  151467. static long _vq_quantlist__44u9_p7_0[] = {
  151468. 6,
  151469. 5,
  151470. 7,
  151471. 4,
  151472. 8,
  151473. 3,
  151474. 9,
  151475. 2,
  151476. 10,
  151477. 1,
  151478. 11,
  151479. 0,
  151480. 12,
  151481. };
  151482. static long _vq_lengthlist__44u9_p7_0[] = {
  151483. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151484. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151485. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151486. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151487. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151488. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151489. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151490. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151491. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151492. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151493. 12,13,13,14,14,14,15,15,15,
  151494. };
  151495. static float _vq_quantthresh__44u9_p7_0[] = {
  151496. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151497. 27.5, 38.5, 49.5, 60.5,
  151498. };
  151499. static long _vq_quantmap__44u9_p7_0[] = {
  151500. 11, 9, 7, 5, 3, 1, 0, 2,
  151501. 4, 6, 8, 10, 12,
  151502. };
  151503. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151504. _vq_quantthresh__44u9_p7_0,
  151505. _vq_quantmap__44u9_p7_0,
  151506. 13,
  151507. 13
  151508. };
  151509. static static_codebook _44u9_p7_0 = {
  151510. 2, 169,
  151511. _vq_lengthlist__44u9_p7_0,
  151512. 1, -523206656, 1618345984, 4, 0,
  151513. _vq_quantlist__44u9_p7_0,
  151514. NULL,
  151515. &_vq_auxt__44u9_p7_0,
  151516. NULL,
  151517. 0
  151518. };
  151519. static long _vq_quantlist__44u9_p7_1[] = {
  151520. 5,
  151521. 4,
  151522. 6,
  151523. 3,
  151524. 7,
  151525. 2,
  151526. 8,
  151527. 1,
  151528. 9,
  151529. 0,
  151530. 10,
  151531. };
  151532. static long _vq_lengthlist__44u9_p7_1[] = {
  151533. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151534. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151535. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151536. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151537. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151538. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151539. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151540. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151541. };
  151542. static float _vq_quantthresh__44u9_p7_1[] = {
  151543. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151544. 3.5, 4.5,
  151545. };
  151546. static long _vq_quantmap__44u9_p7_1[] = {
  151547. 9, 7, 5, 3, 1, 0, 2, 4,
  151548. 6, 8, 10,
  151549. };
  151550. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151551. _vq_quantthresh__44u9_p7_1,
  151552. _vq_quantmap__44u9_p7_1,
  151553. 11,
  151554. 11
  151555. };
  151556. static static_codebook _44u9_p7_1 = {
  151557. 2, 121,
  151558. _vq_lengthlist__44u9_p7_1,
  151559. 1, -531365888, 1611661312, 4, 0,
  151560. _vq_quantlist__44u9_p7_1,
  151561. NULL,
  151562. &_vq_auxt__44u9_p7_1,
  151563. NULL,
  151564. 0
  151565. };
  151566. static long _vq_quantlist__44u9_p8_0[] = {
  151567. 7,
  151568. 6,
  151569. 8,
  151570. 5,
  151571. 9,
  151572. 4,
  151573. 10,
  151574. 3,
  151575. 11,
  151576. 2,
  151577. 12,
  151578. 1,
  151579. 13,
  151580. 0,
  151581. 14,
  151582. };
  151583. static long _vq_lengthlist__44u9_p8_0[] = {
  151584. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151585. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151586. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151587. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151588. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151589. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151590. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151591. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151592. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151593. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151594. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151595. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151596. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151597. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151598. 15,
  151599. };
  151600. static float _vq_quantthresh__44u9_p8_0[] = {
  151601. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151602. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151603. };
  151604. static long _vq_quantmap__44u9_p8_0[] = {
  151605. 13, 11, 9, 7, 5, 3, 1, 0,
  151606. 2, 4, 6, 8, 10, 12, 14,
  151607. };
  151608. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151609. _vq_quantthresh__44u9_p8_0,
  151610. _vq_quantmap__44u9_p8_0,
  151611. 15,
  151612. 15
  151613. };
  151614. static static_codebook _44u9_p8_0 = {
  151615. 2, 225,
  151616. _vq_lengthlist__44u9_p8_0,
  151617. 1, -520986624, 1620377600, 4, 0,
  151618. _vq_quantlist__44u9_p8_0,
  151619. NULL,
  151620. &_vq_auxt__44u9_p8_0,
  151621. NULL,
  151622. 0
  151623. };
  151624. static long _vq_quantlist__44u9_p8_1[] = {
  151625. 10,
  151626. 9,
  151627. 11,
  151628. 8,
  151629. 12,
  151630. 7,
  151631. 13,
  151632. 6,
  151633. 14,
  151634. 5,
  151635. 15,
  151636. 4,
  151637. 16,
  151638. 3,
  151639. 17,
  151640. 2,
  151641. 18,
  151642. 1,
  151643. 19,
  151644. 0,
  151645. 20,
  151646. };
  151647. static long _vq_lengthlist__44u9_p8_1[] = {
  151648. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151649. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151651. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151652. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151653. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151654. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151655. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151656. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151657. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151658. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151659. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151660. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151661. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151662. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151663. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151664. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151665. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151666. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151667. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151668. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151669. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151670. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151671. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151673. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151674. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151675. 10,10,10,10,10,10,10,10,10,
  151676. };
  151677. static float _vq_quantthresh__44u9_p8_1[] = {
  151678. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151679. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151680. 6.5, 7.5, 8.5, 9.5,
  151681. };
  151682. static long _vq_quantmap__44u9_p8_1[] = {
  151683. 19, 17, 15, 13, 11, 9, 7, 5,
  151684. 3, 1, 0, 2, 4, 6, 8, 10,
  151685. 12, 14, 16, 18, 20,
  151686. };
  151687. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151688. _vq_quantthresh__44u9_p8_1,
  151689. _vq_quantmap__44u9_p8_1,
  151690. 21,
  151691. 21
  151692. };
  151693. static static_codebook _44u9_p8_1 = {
  151694. 2, 441,
  151695. _vq_lengthlist__44u9_p8_1,
  151696. 1, -529268736, 1611661312, 5, 0,
  151697. _vq_quantlist__44u9_p8_1,
  151698. NULL,
  151699. &_vq_auxt__44u9_p8_1,
  151700. NULL,
  151701. 0
  151702. };
  151703. static long _vq_quantlist__44u9_p9_0[] = {
  151704. 7,
  151705. 6,
  151706. 8,
  151707. 5,
  151708. 9,
  151709. 4,
  151710. 10,
  151711. 3,
  151712. 11,
  151713. 2,
  151714. 12,
  151715. 1,
  151716. 13,
  151717. 0,
  151718. 14,
  151719. };
  151720. static long _vq_lengthlist__44u9_p9_0[] = {
  151721. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151722. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151723. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151733. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151735. 10,
  151736. };
  151737. static float _vq_quantthresh__44u9_p9_0[] = {
  151738. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151739. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151740. };
  151741. static long _vq_quantmap__44u9_p9_0[] = {
  151742. 13, 11, 9, 7, 5, 3, 1, 0,
  151743. 2, 4, 6, 8, 10, 12, 14,
  151744. };
  151745. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151746. _vq_quantthresh__44u9_p9_0,
  151747. _vq_quantmap__44u9_p9_0,
  151748. 15,
  151749. 15
  151750. };
  151751. static static_codebook _44u9_p9_0 = {
  151752. 2, 225,
  151753. _vq_lengthlist__44u9_p9_0,
  151754. 1, -510036736, 1631393792, 4, 0,
  151755. _vq_quantlist__44u9_p9_0,
  151756. NULL,
  151757. &_vq_auxt__44u9_p9_0,
  151758. NULL,
  151759. 0
  151760. };
  151761. static long _vq_quantlist__44u9_p9_1[] = {
  151762. 9,
  151763. 8,
  151764. 10,
  151765. 7,
  151766. 11,
  151767. 6,
  151768. 12,
  151769. 5,
  151770. 13,
  151771. 4,
  151772. 14,
  151773. 3,
  151774. 15,
  151775. 2,
  151776. 16,
  151777. 1,
  151778. 17,
  151779. 0,
  151780. 18,
  151781. };
  151782. static long _vq_lengthlist__44u9_p9_1[] = {
  151783. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151784. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151785. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151786. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151787. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151788. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151789. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151790. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151791. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151792. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151793. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151794. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151795. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151796. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151797. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151798. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151799. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151800. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151801. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151802. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151803. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151804. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151805. 17,17,15,17,15,17,16,16,17,
  151806. };
  151807. static float _vq_quantthresh__44u9_p9_1[] = {
  151808. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151809. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151810. 367.5, 416.5,
  151811. };
  151812. static long _vq_quantmap__44u9_p9_1[] = {
  151813. 17, 15, 13, 11, 9, 7, 5, 3,
  151814. 1, 0, 2, 4, 6, 8, 10, 12,
  151815. 14, 16, 18,
  151816. };
  151817. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151818. _vq_quantthresh__44u9_p9_1,
  151819. _vq_quantmap__44u9_p9_1,
  151820. 19,
  151821. 19
  151822. };
  151823. static static_codebook _44u9_p9_1 = {
  151824. 2, 361,
  151825. _vq_lengthlist__44u9_p9_1,
  151826. 1, -518287360, 1622704128, 5, 0,
  151827. _vq_quantlist__44u9_p9_1,
  151828. NULL,
  151829. &_vq_auxt__44u9_p9_1,
  151830. NULL,
  151831. 0
  151832. };
  151833. static long _vq_quantlist__44u9_p9_2[] = {
  151834. 24,
  151835. 23,
  151836. 25,
  151837. 22,
  151838. 26,
  151839. 21,
  151840. 27,
  151841. 20,
  151842. 28,
  151843. 19,
  151844. 29,
  151845. 18,
  151846. 30,
  151847. 17,
  151848. 31,
  151849. 16,
  151850. 32,
  151851. 15,
  151852. 33,
  151853. 14,
  151854. 34,
  151855. 13,
  151856. 35,
  151857. 12,
  151858. 36,
  151859. 11,
  151860. 37,
  151861. 10,
  151862. 38,
  151863. 9,
  151864. 39,
  151865. 8,
  151866. 40,
  151867. 7,
  151868. 41,
  151869. 6,
  151870. 42,
  151871. 5,
  151872. 43,
  151873. 4,
  151874. 44,
  151875. 3,
  151876. 45,
  151877. 2,
  151878. 46,
  151879. 1,
  151880. 47,
  151881. 0,
  151882. 48,
  151883. };
  151884. static long _vq_lengthlist__44u9_p9_2[] = {
  151885. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151886. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151887. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151888. 7,
  151889. };
  151890. static float _vq_quantthresh__44u9_p9_2[] = {
  151891. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151892. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151893. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151894. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151895. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151896. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151897. };
  151898. static long _vq_quantmap__44u9_p9_2[] = {
  151899. 47, 45, 43, 41, 39, 37, 35, 33,
  151900. 31, 29, 27, 25, 23, 21, 19, 17,
  151901. 15, 13, 11, 9, 7, 5, 3, 1,
  151902. 0, 2, 4, 6, 8, 10, 12, 14,
  151903. 16, 18, 20, 22, 24, 26, 28, 30,
  151904. 32, 34, 36, 38, 40, 42, 44, 46,
  151905. 48,
  151906. };
  151907. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  151908. _vq_quantthresh__44u9_p9_2,
  151909. _vq_quantmap__44u9_p9_2,
  151910. 49,
  151911. 49
  151912. };
  151913. static static_codebook _44u9_p9_2 = {
  151914. 1, 49,
  151915. _vq_lengthlist__44u9_p9_2,
  151916. 1, -526909440, 1611661312, 6, 0,
  151917. _vq_quantlist__44u9_p9_2,
  151918. NULL,
  151919. &_vq_auxt__44u9_p9_2,
  151920. NULL,
  151921. 0
  151922. };
  151923. static long _huff_lengthlist__44un1__long[] = {
  151924. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  151925. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  151926. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  151927. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  151928. };
  151929. static static_codebook _huff_book__44un1__long = {
  151930. 2, 64,
  151931. _huff_lengthlist__44un1__long,
  151932. 0, 0, 0, 0, 0,
  151933. NULL,
  151934. NULL,
  151935. NULL,
  151936. NULL,
  151937. 0
  151938. };
  151939. static long _vq_quantlist__44un1__p1_0[] = {
  151940. 1,
  151941. 0,
  151942. 2,
  151943. };
  151944. static long _vq_lengthlist__44un1__p1_0[] = {
  151945. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  151946. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  151947. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  151948. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  151949. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  151950. 12,
  151951. };
  151952. static float _vq_quantthresh__44un1__p1_0[] = {
  151953. -0.5, 0.5,
  151954. };
  151955. static long _vq_quantmap__44un1__p1_0[] = {
  151956. 1, 0, 2,
  151957. };
  151958. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  151959. _vq_quantthresh__44un1__p1_0,
  151960. _vq_quantmap__44un1__p1_0,
  151961. 3,
  151962. 3
  151963. };
  151964. static static_codebook _44un1__p1_0 = {
  151965. 4, 81,
  151966. _vq_lengthlist__44un1__p1_0,
  151967. 1, -535822336, 1611661312, 2, 0,
  151968. _vq_quantlist__44un1__p1_0,
  151969. NULL,
  151970. &_vq_auxt__44un1__p1_0,
  151971. NULL,
  151972. 0
  151973. };
  151974. static long _vq_quantlist__44un1__p2_0[] = {
  151975. 1,
  151976. 0,
  151977. 2,
  151978. };
  151979. static long _vq_lengthlist__44un1__p2_0[] = {
  151980. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  151981. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  151982. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  151983. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  151984. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  151985. 8,
  151986. };
  151987. static float _vq_quantthresh__44un1__p2_0[] = {
  151988. -0.5, 0.5,
  151989. };
  151990. static long _vq_quantmap__44un1__p2_0[] = {
  151991. 1, 0, 2,
  151992. };
  151993. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  151994. _vq_quantthresh__44un1__p2_0,
  151995. _vq_quantmap__44un1__p2_0,
  151996. 3,
  151997. 3
  151998. };
  151999. static static_codebook _44un1__p2_0 = {
  152000. 4, 81,
  152001. _vq_lengthlist__44un1__p2_0,
  152002. 1, -535822336, 1611661312, 2, 0,
  152003. _vq_quantlist__44un1__p2_0,
  152004. NULL,
  152005. &_vq_auxt__44un1__p2_0,
  152006. NULL,
  152007. 0
  152008. };
  152009. static long _vq_quantlist__44un1__p3_0[] = {
  152010. 2,
  152011. 1,
  152012. 3,
  152013. 0,
  152014. 4,
  152015. };
  152016. static long _vq_lengthlist__44un1__p3_0[] = {
  152017. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152018. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152019. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152020. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152021. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152022. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152023. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152024. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152025. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152026. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152027. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152028. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152029. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152030. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152031. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152032. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152033. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152034. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152035. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152036. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152037. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152038. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152039. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152040. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152041. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152042. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152043. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152044. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152045. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152046. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152047. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152048. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152049. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152050. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152051. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152052. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152053. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152054. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152055. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152056. 17,
  152057. };
  152058. static float _vq_quantthresh__44un1__p3_0[] = {
  152059. -1.5, -0.5, 0.5, 1.5,
  152060. };
  152061. static long _vq_quantmap__44un1__p3_0[] = {
  152062. 3, 1, 0, 2, 4,
  152063. };
  152064. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152065. _vq_quantthresh__44un1__p3_0,
  152066. _vq_quantmap__44un1__p3_0,
  152067. 5,
  152068. 5
  152069. };
  152070. static static_codebook _44un1__p3_0 = {
  152071. 4, 625,
  152072. _vq_lengthlist__44un1__p3_0,
  152073. 1, -533725184, 1611661312, 3, 0,
  152074. _vq_quantlist__44un1__p3_0,
  152075. NULL,
  152076. &_vq_auxt__44un1__p3_0,
  152077. NULL,
  152078. 0
  152079. };
  152080. static long _vq_quantlist__44un1__p4_0[] = {
  152081. 2,
  152082. 1,
  152083. 3,
  152084. 0,
  152085. 4,
  152086. };
  152087. static long _vq_lengthlist__44un1__p4_0[] = {
  152088. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152089. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152090. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152091. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152092. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152093. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152094. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152095. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152096. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152097. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152098. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152099. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152100. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152101. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152102. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152103. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152104. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152105. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152106. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152107. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152108. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152109. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152110. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152111. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152112. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152113. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152114. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152115. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152116. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152117. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152118. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152119. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152120. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152121. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152122. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152123. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152124. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152125. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152126. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152127. 12,
  152128. };
  152129. static float _vq_quantthresh__44un1__p4_0[] = {
  152130. -1.5, -0.5, 0.5, 1.5,
  152131. };
  152132. static long _vq_quantmap__44un1__p4_0[] = {
  152133. 3, 1, 0, 2, 4,
  152134. };
  152135. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152136. _vq_quantthresh__44un1__p4_0,
  152137. _vq_quantmap__44un1__p4_0,
  152138. 5,
  152139. 5
  152140. };
  152141. static static_codebook _44un1__p4_0 = {
  152142. 4, 625,
  152143. _vq_lengthlist__44un1__p4_0,
  152144. 1, -533725184, 1611661312, 3, 0,
  152145. _vq_quantlist__44un1__p4_0,
  152146. NULL,
  152147. &_vq_auxt__44un1__p4_0,
  152148. NULL,
  152149. 0
  152150. };
  152151. static long _vq_quantlist__44un1__p5_0[] = {
  152152. 4,
  152153. 3,
  152154. 5,
  152155. 2,
  152156. 6,
  152157. 1,
  152158. 7,
  152159. 0,
  152160. 8,
  152161. };
  152162. static long _vq_lengthlist__44un1__p5_0[] = {
  152163. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152164. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152165. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152166. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152167. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152168. 12,
  152169. };
  152170. static float _vq_quantthresh__44un1__p5_0[] = {
  152171. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152172. };
  152173. static long _vq_quantmap__44un1__p5_0[] = {
  152174. 7, 5, 3, 1, 0, 2, 4, 6,
  152175. 8,
  152176. };
  152177. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152178. _vq_quantthresh__44un1__p5_0,
  152179. _vq_quantmap__44un1__p5_0,
  152180. 9,
  152181. 9
  152182. };
  152183. static static_codebook _44un1__p5_0 = {
  152184. 2, 81,
  152185. _vq_lengthlist__44un1__p5_0,
  152186. 1, -531628032, 1611661312, 4, 0,
  152187. _vq_quantlist__44un1__p5_0,
  152188. NULL,
  152189. &_vq_auxt__44un1__p5_0,
  152190. NULL,
  152191. 0
  152192. };
  152193. static long _vq_quantlist__44un1__p6_0[] = {
  152194. 6,
  152195. 5,
  152196. 7,
  152197. 4,
  152198. 8,
  152199. 3,
  152200. 9,
  152201. 2,
  152202. 10,
  152203. 1,
  152204. 11,
  152205. 0,
  152206. 12,
  152207. };
  152208. static long _vq_lengthlist__44un1__p6_0[] = {
  152209. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152210. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152211. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152212. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152213. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152214. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152215. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152216. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152217. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152218. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152219. 16, 0,15,18,18, 0,16, 0, 0,
  152220. };
  152221. static float _vq_quantthresh__44un1__p6_0[] = {
  152222. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152223. 12.5, 17.5, 22.5, 27.5,
  152224. };
  152225. static long _vq_quantmap__44un1__p6_0[] = {
  152226. 11, 9, 7, 5, 3, 1, 0, 2,
  152227. 4, 6, 8, 10, 12,
  152228. };
  152229. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152230. _vq_quantthresh__44un1__p6_0,
  152231. _vq_quantmap__44un1__p6_0,
  152232. 13,
  152233. 13
  152234. };
  152235. static static_codebook _44un1__p6_0 = {
  152236. 2, 169,
  152237. _vq_lengthlist__44un1__p6_0,
  152238. 1, -526516224, 1616117760, 4, 0,
  152239. _vq_quantlist__44un1__p6_0,
  152240. NULL,
  152241. &_vq_auxt__44un1__p6_0,
  152242. NULL,
  152243. 0
  152244. };
  152245. static long _vq_quantlist__44un1__p6_1[] = {
  152246. 2,
  152247. 1,
  152248. 3,
  152249. 0,
  152250. 4,
  152251. };
  152252. static long _vq_lengthlist__44un1__p6_1[] = {
  152253. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152254. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152255. };
  152256. static float _vq_quantthresh__44un1__p6_1[] = {
  152257. -1.5, -0.5, 0.5, 1.5,
  152258. };
  152259. static long _vq_quantmap__44un1__p6_1[] = {
  152260. 3, 1, 0, 2, 4,
  152261. };
  152262. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152263. _vq_quantthresh__44un1__p6_1,
  152264. _vq_quantmap__44un1__p6_1,
  152265. 5,
  152266. 5
  152267. };
  152268. static static_codebook _44un1__p6_1 = {
  152269. 2, 25,
  152270. _vq_lengthlist__44un1__p6_1,
  152271. 1, -533725184, 1611661312, 3, 0,
  152272. _vq_quantlist__44un1__p6_1,
  152273. NULL,
  152274. &_vq_auxt__44un1__p6_1,
  152275. NULL,
  152276. 0
  152277. };
  152278. static long _vq_quantlist__44un1__p7_0[] = {
  152279. 2,
  152280. 1,
  152281. 3,
  152282. 0,
  152283. 4,
  152284. };
  152285. static long _vq_lengthlist__44un1__p7_0[] = {
  152286. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152287. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152289. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152293. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152299. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152300. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152301. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152302. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152303. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152304. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152305. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152306. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152307. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152308. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152309. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152310. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152314. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152316. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152317. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152318. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152319. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152320. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152321. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152322. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152323. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152324. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152325. 10,
  152326. };
  152327. static float _vq_quantthresh__44un1__p7_0[] = {
  152328. -253.5, -84.5, 84.5, 253.5,
  152329. };
  152330. static long _vq_quantmap__44un1__p7_0[] = {
  152331. 3, 1, 0, 2, 4,
  152332. };
  152333. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152334. _vq_quantthresh__44un1__p7_0,
  152335. _vq_quantmap__44un1__p7_0,
  152336. 5,
  152337. 5
  152338. };
  152339. static static_codebook _44un1__p7_0 = {
  152340. 4, 625,
  152341. _vq_lengthlist__44un1__p7_0,
  152342. 1, -518709248, 1626677248, 3, 0,
  152343. _vq_quantlist__44un1__p7_0,
  152344. NULL,
  152345. &_vq_auxt__44un1__p7_0,
  152346. NULL,
  152347. 0
  152348. };
  152349. static long _vq_quantlist__44un1__p7_1[] = {
  152350. 6,
  152351. 5,
  152352. 7,
  152353. 4,
  152354. 8,
  152355. 3,
  152356. 9,
  152357. 2,
  152358. 10,
  152359. 1,
  152360. 11,
  152361. 0,
  152362. 12,
  152363. };
  152364. static long _vq_lengthlist__44un1__p7_1[] = {
  152365. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152366. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152367. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152368. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152369. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152370. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152371. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152372. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152373. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152374. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152375. 12,13,13,12,13,13,14,14,14,
  152376. };
  152377. static float _vq_quantthresh__44un1__p7_1[] = {
  152378. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152379. 32.5, 45.5, 58.5, 71.5,
  152380. };
  152381. static long _vq_quantmap__44un1__p7_1[] = {
  152382. 11, 9, 7, 5, 3, 1, 0, 2,
  152383. 4, 6, 8, 10, 12,
  152384. };
  152385. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152386. _vq_quantthresh__44un1__p7_1,
  152387. _vq_quantmap__44un1__p7_1,
  152388. 13,
  152389. 13
  152390. };
  152391. static static_codebook _44un1__p7_1 = {
  152392. 2, 169,
  152393. _vq_lengthlist__44un1__p7_1,
  152394. 1, -523010048, 1618608128, 4, 0,
  152395. _vq_quantlist__44un1__p7_1,
  152396. NULL,
  152397. &_vq_auxt__44un1__p7_1,
  152398. NULL,
  152399. 0
  152400. };
  152401. static long _vq_quantlist__44un1__p7_2[] = {
  152402. 6,
  152403. 5,
  152404. 7,
  152405. 4,
  152406. 8,
  152407. 3,
  152408. 9,
  152409. 2,
  152410. 10,
  152411. 1,
  152412. 11,
  152413. 0,
  152414. 12,
  152415. };
  152416. static long _vq_lengthlist__44un1__p7_2[] = {
  152417. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152418. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152419. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152420. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152421. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152422. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152423. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152424. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152425. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152426. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152427. 9, 9, 9,10,10,10,10,10,10,
  152428. };
  152429. static float _vq_quantthresh__44un1__p7_2[] = {
  152430. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152431. 2.5, 3.5, 4.5, 5.5,
  152432. };
  152433. static long _vq_quantmap__44un1__p7_2[] = {
  152434. 11, 9, 7, 5, 3, 1, 0, 2,
  152435. 4, 6, 8, 10, 12,
  152436. };
  152437. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152438. _vq_quantthresh__44un1__p7_2,
  152439. _vq_quantmap__44un1__p7_2,
  152440. 13,
  152441. 13
  152442. };
  152443. static static_codebook _44un1__p7_2 = {
  152444. 2, 169,
  152445. _vq_lengthlist__44un1__p7_2,
  152446. 1, -531103744, 1611661312, 4, 0,
  152447. _vq_quantlist__44un1__p7_2,
  152448. NULL,
  152449. &_vq_auxt__44un1__p7_2,
  152450. NULL,
  152451. 0
  152452. };
  152453. static long _huff_lengthlist__44un1__short[] = {
  152454. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152455. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152456. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152457. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152458. };
  152459. static static_codebook _huff_book__44un1__short = {
  152460. 2, 64,
  152461. _huff_lengthlist__44un1__short,
  152462. 0, 0, 0, 0, 0,
  152463. NULL,
  152464. NULL,
  152465. NULL,
  152466. NULL,
  152467. 0
  152468. };
  152469. /*** End of inlined file: res_books_uncoupled.h ***/
  152470. /***** residue backends *********************************************/
  152471. static vorbis_info_residue0 _residue_44_low_un={
  152472. 0,-1, -1, 8,-1,
  152473. {0},
  152474. {-1},
  152475. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152476. { -1, 25, -1, 45, -1, -1, -1}
  152477. };
  152478. static vorbis_info_residue0 _residue_44_mid_un={
  152479. 0,-1, -1, 10,-1,
  152480. /* 0 1 2 3 4 5 6 7 8 9 */
  152481. {0},
  152482. {-1},
  152483. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152484. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152485. };
  152486. static vorbis_info_residue0 _residue_44_hi_un={
  152487. 0,-1, -1, 10,-1,
  152488. /* 0 1 2 3 4 5 6 7 8 9 */
  152489. {0},
  152490. {-1},
  152491. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152492. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152493. };
  152494. /* mapping conventions:
  152495. only one submap (this would change for efficient 5.1 support for example)*/
  152496. /* Four psychoacoustic profiles are used, one for each blocktype */
  152497. static vorbis_info_mapping0 _map_nominal_u[2]={
  152498. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152499. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152500. };
  152501. static static_bookblock _resbook_44u_n1={
  152502. {
  152503. {0},
  152504. {0,0,&_44un1__p1_0},
  152505. {0,0,&_44un1__p2_0},
  152506. {0,0,&_44un1__p3_0},
  152507. {0,0,&_44un1__p4_0},
  152508. {0,0,&_44un1__p5_0},
  152509. {&_44un1__p6_0,&_44un1__p6_1},
  152510. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152511. }
  152512. };
  152513. static static_bookblock _resbook_44u_0={
  152514. {
  152515. {0},
  152516. {0,0,&_44u0__p1_0},
  152517. {0,0,&_44u0__p2_0},
  152518. {0,0,&_44u0__p3_0},
  152519. {0,0,&_44u0__p4_0},
  152520. {0,0,&_44u0__p5_0},
  152521. {&_44u0__p6_0,&_44u0__p6_1},
  152522. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152523. }
  152524. };
  152525. static static_bookblock _resbook_44u_1={
  152526. {
  152527. {0},
  152528. {0,0,&_44u1__p1_0},
  152529. {0,0,&_44u1__p2_0},
  152530. {0,0,&_44u1__p3_0},
  152531. {0,0,&_44u1__p4_0},
  152532. {0,0,&_44u1__p5_0},
  152533. {&_44u1__p6_0,&_44u1__p6_1},
  152534. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152535. }
  152536. };
  152537. static static_bookblock _resbook_44u_2={
  152538. {
  152539. {0},
  152540. {0,0,&_44u2__p1_0},
  152541. {0,0,&_44u2__p2_0},
  152542. {0,0,&_44u2__p3_0},
  152543. {0,0,&_44u2__p4_0},
  152544. {0,0,&_44u2__p5_0},
  152545. {&_44u2__p6_0,&_44u2__p6_1},
  152546. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152547. }
  152548. };
  152549. static static_bookblock _resbook_44u_3={
  152550. {
  152551. {0},
  152552. {0,0,&_44u3__p1_0},
  152553. {0,0,&_44u3__p2_0},
  152554. {0,0,&_44u3__p3_0},
  152555. {0,0,&_44u3__p4_0},
  152556. {0,0,&_44u3__p5_0},
  152557. {&_44u3__p6_0,&_44u3__p6_1},
  152558. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152559. }
  152560. };
  152561. static static_bookblock _resbook_44u_4={
  152562. {
  152563. {0},
  152564. {0,0,&_44u4__p1_0},
  152565. {0,0,&_44u4__p2_0},
  152566. {0,0,&_44u4__p3_0},
  152567. {0,0,&_44u4__p4_0},
  152568. {0,0,&_44u4__p5_0},
  152569. {&_44u4__p6_0,&_44u4__p6_1},
  152570. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152571. }
  152572. };
  152573. static static_bookblock _resbook_44u_5={
  152574. {
  152575. {0},
  152576. {0,0,&_44u5__p1_0},
  152577. {0,0,&_44u5__p2_0},
  152578. {0,0,&_44u5__p3_0},
  152579. {0,0,&_44u5__p4_0},
  152580. {0,0,&_44u5__p5_0},
  152581. {0,0,&_44u5__p6_0},
  152582. {&_44u5__p7_0,&_44u5__p7_1},
  152583. {&_44u5__p8_0,&_44u5__p8_1},
  152584. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152585. }
  152586. };
  152587. static static_bookblock _resbook_44u_6={
  152588. {
  152589. {0},
  152590. {0,0,&_44u6__p1_0},
  152591. {0,0,&_44u6__p2_0},
  152592. {0,0,&_44u6__p3_0},
  152593. {0,0,&_44u6__p4_0},
  152594. {0,0,&_44u6__p5_0},
  152595. {0,0,&_44u6__p6_0},
  152596. {&_44u6__p7_0,&_44u6__p7_1},
  152597. {&_44u6__p8_0,&_44u6__p8_1},
  152598. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152599. }
  152600. };
  152601. static static_bookblock _resbook_44u_7={
  152602. {
  152603. {0},
  152604. {0,0,&_44u7__p1_0},
  152605. {0,0,&_44u7__p2_0},
  152606. {0,0,&_44u7__p3_0},
  152607. {0,0,&_44u7__p4_0},
  152608. {0,0,&_44u7__p5_0},
  152609. {0,0,&_44u7__p6_0},
  152610. {&_44u7__p7_0,&_44u7__p7_1},
  152611. {&_44u7__p8_0,&_44u7__p8_1},
  152612. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152613. }
  152614. };
  152615. static static_bookblock _resbook_44u_8={
  152616. {
  152617. {0},
  152618. {0,0,&_44u8_p1_0},
  152619. {0,0,&_44u8_p2_0},
  152620. {0,0,&_44u8_p3_0},
  152621. {0,0,&_44u8_p4_0},
  152622. {&_44u8_p5_0,&_44u8_p5_1},
  152623. {&_44u8_p6_0,&_44u8_p6_1},
  152624. {&_44u8_p7_0,&_44u8_p7_1},
  152625. {&_44u8_p8_0,&_44u8_p8_1},
  152626. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152627. }
  152628. };
  152629. static static_bookblock _resbook_44u_9={
  152630. {
  152631. {0},
  152632. {0,0,&_44u9_p1_0},
  152633. {0,0,&_44u9_p2_0},
  152634. {0,0,&_44u9_p3_0},
  152635. {0,0,&_44u9_p4_0},
  152636. {&_44u9_p5_0,&_44u9_p5_1},
  152637. {&_44u9_p6_0,&_44u9_p6_1},
  152638. {&_44u9_p7_0,&_44u9_p7_1},
  152639. {&_44u9_p8_0,&_44u9_p8_1},
  152640. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152641. }
  152642. };
  152643. static vorbis_residue_template _res_44u_n1[]={
  152644. {1,0, &_residue_44_low_un,
  152645. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152646. &_resbook_44u_n1,&_resbook_44u_n1},
  152647. {1,0, &_residue_44_low_un,
  152648. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152649. &_resbook_44u_n1,&_resbook_44u_n1}
  152650. };
  152651. static vorbis_residue_template _res_44u_0[]={
  152652. {1,0, &_residue_44_low_un,
  152653. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152654. &_resbook_44u_0,&_resbook_44u_0},
  152655. {1,0, &_residue_44_low_un,
  152656. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152657. &_resbook_44u_0,&_resbook_44u_0}
  152658. };
  152659. static vorbis_residue_template _res_44u_1[]={
  152660. {1,0, &_residue_44_low_un,
  152661. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152662. &_resbook_44u_1,&_resbook_44u_1},
  152663. {1,0, &_residue_44_low_un,
  152664. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152665. &_resbook_44u_1,&_resbook_44u_1}
  152666. };
  152667. static vorbis_residue_template _res_44u_2[]={
  152668. {1,0, &_residue_44_low_un,
  152669. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152670. &_resbook_44u_2,&_resbook_44u_2},
  152671. {1,0, &_residue_44_low_un,
  152672. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152673. &_resbook_44u_2,&_resbook_44u_2}
  152674. };
  152675. static vorbis_residue_template _res_44u_3[]={
  152676. {1,0, &_residue_44_low_un,
  152677. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152678. &_resbook_44u_3,&_resbook_44u_3},
  152679. {1,0, &_residue_44_low_un,
  152680. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152681. &_resbook_44u_3,&_resbook_44u_3}
  152682. };
  152683. static vorbis_residue_template _res_44u_4[]={
  152684. {1,0, &_residue_44_low_un,
  152685. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152686. &_resbook_44u_4,&_resbook_44u_4},
  152687. {1,0, &_residue_44_low_un,
  152688. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152689. &_resbook_44u_4,&_resbook_44u_4}
  152690. };
  152691. static vorbis_residue_template _res_44u_5[]={
  152692. {1,0, &_residue_44_mid_un,
  152693. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152694. &_resbook_44u_5,&_resbook_44u_5},
  152695. {1,0, &_residue_44_mid_un,
  152696. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152697. &_resbook_44u_5,&_resbook_44u_5}
  152698. };
  152699. static vorbis_residue_template _res_44u_6[]={
  152700. {1,0, &_residue_44_mid_un,
  152701. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152702. &_resbook_44u_6,&_resbook_44u_6},
  152703. {1,0, &_residue_44_mid_un,
  152704. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152705. &_resbook_44u_6,&_resbook_44u_6}
  152706. };
  152707. static vorbis_residue_template _res_44u_7[]={
  152708. {1,0, &_residue_44_mid_un,
  152709. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152710. &_resbook_44u_7,&_resbook_44u_7},
  152711. {1,0, &_residue_44_mid_un,
  152712. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152713. &_resbook_44u_7,&_resbook_44u_7}
  152714. };
  152715. static vorbis_residue_template _res_44u_8[]={
  152716. {1,0, &_residue_44_hi_un,
  152717. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152718. &_resbook_44u_8,&_resbook_44u_8},
  152719. {1,0, &_residue_44_hi_un,
  152720. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152721. &_resbook_44u_8,&_resbook_44u_8}
  152722. };
  152723. static vorbis_residue_template _res_44u_9[]={
  152724. {1,0, &_residue_44_hi_un,
  152725. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152726. &_resbook_44u_9,&_resbook_44u_9},
  152727. {1,0, &_residue_44_hi_un,
  152728. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152729. &_resbook_44u_9,&_resbook_44u_9}
  152730. };
  152731. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152732. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152733. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152734. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152735. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152736. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152737. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152738. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152739. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152740. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152741. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152742. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152743. };
  152744. /*** End of inlined file: residue_44u.h ***/
  152745. static double rate_mapping_44_un[12]={
  152746. 32000.,48000.,60000.,70000.,80000.,86000.,
  152747. 96000.,110000.,120000.,140000.,160000.,240001.
  152748. };
  152749. ve_setup_data_template ve_setup_44_uncoupled={
  152750. 11,
  152751. rate_mapping_44_un,
  152752. quality_mapping_44,
  152753. -1,
  152754. 40000,
  152755. 50000,
  152756. blocksize_short_44,
  152757. blocksize_long_44,
  152758. _psy_tone_masteratt_44,
  152759. _psy_tone_0dB,
  152760. _psy_tone_suppress,
  152761. _vp_tonemask_adj_otherblock,
  152762. _vp_tonemask_adj_longblock,
  152763. _vp_tonemask_adj_otherblock,
  152764. _psy_noiseguards_44,
  152765. _psy_noisebias_impulse,
  152766. _psy_noisebias_padding,
  152767. _psy_noisebias_trans,
  152768. _psy_noisebias_long,
  152769. _psy_noise_suppress,
  152770. _psy_compand_44,
  152771. _psy_compand_short_mapping,
  152772. _psy_compand_long_mapping,
  152773. {_noise_start_short_44,_noise_start_long_44},
  152774. {_noise_part_short_44,_noise_part_long_44},
  152775. _noise_thresh_44,
  152776. _psy_ath_floater,
  152777. _psy_ath_abs,
  152778. _psy_lowpass_44,
  152779. _psy_global_44,
  152780. _global_mapping_44,
  152781. NULL,
  152782. _floor_books,
  152783. _floor,
  152784. _floor_short_mapping_44,
  152785. _floor_long_mapping_44,
  152786. _mapres_template_44_uncoupled
  152787. };
  152788. /*** End of inlined file: setup_44u.h ***/
  152789. /*** Start of inlined file: setup_32.h ***/
  152790. static double rate_mapping_32[12]={
  152791. 18000.,28000.,35000.,45000.,56000.,60000.,
  152792. 75000.,90000.,100000.,115000.,150000.,190000.,
  152793. };
  152794. static double rate_mapping_32_un[12]={
  152795. 30000.,42000.,52000.,64000.,72000.,78000.,
  152796. 86000.,92000.,110000.,120000.,140000.,190000.,
  152797. };
  152798. static double _psy_lowpass_32[12]={
  152799. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152800. };
  152801. ve_setup_data_template ve_setup_32_stereo={
  152802. 11,
  152803. rate_mapping_32,
  152804. quality_mapping_44,
  152805. 2,
  152806. 26000,
  152807. 40000,
  152808. blocksize_short_44,
  152809. blocksize_long_44,
  152810. _psy_tone_masteratt_44,
  152811. _psy_tone_0dB,
  152812. _psy_tone_suppress,
  152813. _vp_tonemask_adj_otherblock,
  152814. _vp_tonemask_adj_longblock,
  152815. _vp_tonemask_adj_otherblock,
  152816. _psy_noiseguards_44,
  152817. _psy_noisebias_impulse,
  152818. _psy_noisebias_padding,
  152819. _psy_noisebias_trans,
  152820. _psy_noisebias_long,
  152821. _psy_noise_suppress,
  152822. _psy_compand_44,
  152823. _psy_compand_short_mapping,
  152824. _psy_compand_long_mapping,
  152825. {_noise_start_short_44,_noise_start_long_44},
  152826. {_noise_part_short_44,_noise_part_long_44},
  152827. _noise_thresh_44,
  152828. _psy_ath_floater,
  152829. _psy_ath_abs,
  152830. _psy_lowpass_32,
  152831. _psy_global_44,
  152832. _global_mapping_44,
  152833. _psy_stereo_modes_44,
  152834. _floor_books,
  152835. _floor,
  152836. _floor_short_mapping_44,
  152837. _floor_long_mapping_44,
  152838. _mapres_template_44_stereo
  152839. };
  152840. ve_setup_data_template ve_setup_32_uncoupled={
  152841. 11,
  152842. rate_mapping_32_un,
  152843. quality_mapping_44,
  152844. -1,
  152845. 26000,
  152846. 40000,
  152847. blocksize_short_44,
  152848. blocksize_long_44,
  152849. _psy_tone_masteratt_44,
  152850. _psy_tone_0dB,
  152851. _psy_tone_suppress,
  152852. _vp_tonemask_adj_otherblock,
  152853. _vp_tonemask_adj_longblock,
  152854. _vp_tonemask_adj_otherblock,
  152855. _psy_noiseguards_44,
  152856. _psy_noisebias_impulse,
  152857. _psy_noisebias_padding,
  152858. _psy_noisebias_trans,
  152859. _psy_noisebias_long,
  152860. _psy_noise_suppress,
  152861. _psy_compand_44,
  152862. _psy_compand_short_mapping,
  152863. _psy_compand_long_mapping,
  152864. {_noise_start_short_44,_noise_start_long_44},
  152865. {_noise_part_short_44,_noise_part_long_44},
  152866. _noise_thresh_44,
  152867. _psy_ath_floater,
  152868. _psy_ath_abs,
  152869. _psy_lowpass_32,
  152870. _psy_global_44,
  152871. _global_mapping_44,
  152872. NULL,
  152873. _floor_books,
  152874. _floor,
  152875. _floor_short_mapping_44,
  152876. _floor_long_mapping_44,
  152877. _mapres_template_44_uncoupled
  152878. };
  152879. /*** End of inlined file: setup_32.h ***/
  152880. /*** Start of inlined file: setup_8.h ***/
  152881. /*** Start of inlined file: psych_8.h ***/
  152882. static att3 _psy_tone_masteratt_8[3]={
  152883. {{ 32, 25, 12}, 0, 0}, /* 0 */
  152884. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152885. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152886. };
  152887. static vp_adjblock _vp_tonemask_adj_8[3]={
  152888. /* adjust for mode zero */
  152889. /* 63 125 250 500 1 2 4 8 16 */
  152890. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152891. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152892. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  152893. };
  152894. static noise3 _psy_noisebias_8[3]={
  152895. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152896. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152897. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  152898. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152899. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152900. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152901. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152902. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152903. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152904. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152905. };
  152906. /* stereo mode by base quality level */
  152907. static adj_stereo _psy_stereo_modes_8[3]={
  152908. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152909. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152910. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152911. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152912. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152913. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152914. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152915. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152916. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152917. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152918. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152919. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152920. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152921. };
  152922. static noiseguard _psy_noiseguards_8[2]={
  152923. {10,10,-1},
  152924. {10,10,-1},
  152925. };
  152926. static compandblock _psy_compand_8[2]={
  152927. {{
  152928. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  152929. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  152930. 12,12,13,13,14,14,15, 15, /* 23dB */
  152931. 16,16,17,17,17,18,18, 19, /* 31dB */
  152932. 19,19,20,21,22,23,24, 25, /* 39dB */
  152933. }},
  152934. {{
  152935. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  152936. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  152937. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  152938. 9,10,11,12,13,14,15, 16, /* 31dB */
  152939. 17,18,19,20,21,22,23, 24, /* 39dB */
  152940. }},
  152941. };
  152942. static double _psy_lowpass_8[3]={3.,4.,4.};
  152943. static int _noise_start_8[2]={
  152944. 64,64,
  152945. };
  152946. static int _noise_part_8[2]={
  152947. 8,8,
  152948. };
  152949. static int _psy_ath_floater_8[3]={
  152950. -100,-100,-105,
  152951. };
  152952. static int _psy_ath_abs_8[3]={
  152953. -130,-130,-140,
  152954. };
  152955. /*** End of inlined file: psych_8.h ***/
  152956. /*** Start of inlined file: residue_8.h ***/
  152957. /***** residue backends *********************************************/
  152958. static static_bookblock _resbook_8s_0={
  152959. {
  152960. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  152961. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  152962. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  152963. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  152964. }
  152965. };
  152966. static static_bookblock _resbook_8s_1={
  152967. {
  152968. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  152969. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  152970. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  152971. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  152972. }
  152973. };
  152974. static vorbis_residue_template _res_8s_0[]={
  152975. {2,0, &_residue_44_mid,
  152976. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  152977. &_resbook_8s_0,&_resbook_8s_0},
  152978. };
  152979. static vorbis_residue_template _res_8s_1[]={
  152980. {2,0, &_residue_44_mid,
  152981. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  152982. &_resbook_8s_1,&_resbook_8s_1},
  152983. };
  152984. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  152985. { _map_nominal, _res_8s_0 }, /* 0 */
  152986. { _map_nominal, _res_8s_1 }, /* 1 */
  152987. };
  152988. static static_bookblock _resbook_8u_0={
  152989. {
  152990. {0},
  152991. {0,0,&_8u0__p1_0},
  152992. {0,0,&_8u0__p2_0},
  152993. {0,0,&_8u0__p3_0},
  152994. {0,0,&_8u0__p4_0},
  152995. {0,0,&_8u0__p5_0},
  152996. {&_8u0__p6_0,&_8u0__p6_1},
  152997. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  152998. }
  152999. };
  153000. static static_bookblock _resbook_8u_1={
  153001. {
  153002. {0},
  153003. {0,0,&_8u1__p1_0},
  153004. {0,0,&_8u1__p2_0},
  153005. {0,0,&_8u1__p3_0},
  153006. {0,0,&_8u1__p4_0},
  153007. {0,0,&_8u1__p5_0},
  153008. {0,0,&_8u1__p6_0},
  153009. {&_8u1__p7_0,&_8u1__p7_1},
  153010. {&_8u1__p8_0,&_8u1__p8_1},
  153011. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153012. }
  153013. };
  153014. static vorbis_residue_template _res_8u_0[]={
  153015. {1,0, &_residue_44_low_un,
  153016. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153017. &_resbook_8u_0,&_resbook_8u_0},
  153018. };
  153019. static vorbis_residue_template _res_8u_1[]={
  153020. {1,0, &_residue_44_mid_un,
  153021. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153022. &_resbook_8u_1,&_resbook_8u_1},
  153023. };
  153024. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153025. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153026. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153027. };
  153028. /*** End of inlined file: residue_8.h ***/
  153029. static int blocksize_8[2]={
  153030. 512,512
  153031. };
  153032. static int _floor_mapping_8[2]={
  153033. 6,6,
  153034. };
  153035. static double rate_mapping_8[3]={
  153036. 6000.,9000.,32000.,
  153037. };
  153038. static double rate_mapping_8_uncoupled[3]={
  153039. 8000.,14000.,42000.,
  153040. };
  153041. static double quality_mapping_8[3]={
  153042. -.1,.0,1.
  153043. };
  153044. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153045. static double _global_mapping_8[3]={ 1., 2., 3. };
  153046. ve_setup_data_template ve_setup_8_stereo={
  153047. 2,
  153048. rate_mapping_8,
  153049. quality_mapping_8,
  153050. 2,
  153051. 8000,
  153052. 9000,
  153053. blocksize_8,
  153054. blocksize_8,
  153055. _psy_tone_masteratt_8,
  153056. _psy_tone_0dB,
  153057. _psy_tone_suppress,
  153058. _vp_tonemask_adj_8,
  153059. NULL,
  153060. _vp_tonemask_adj_8,
  153061. _psy_noiseguards_8,
  153062. _psy_noisebias_8,
  153063. _psy_noisebias_8,
  153064. NULL,
  153065. NULL,
  153066. _psy_noise_suppress,
  153067. _psy_compand_8,
  153068. _psy_compand_8_mapping,
  153069. NULL,
  153070. {_noise_start_8,_noise_start_8},
  153071. {_noise_part_8,_noise_part_8},
  153072. _noise_thresh_5only,
  153073. _psy_ath_floater_8,
  153074. _psy_ath_abs_8,
  153075. _psy_lowpass_8,
  153076. _psy_global_44,
  153077. _global_mapping_8,
  153078. _psy_stereo_modes_8,
  153079. _floor_books,
  153080. _floor,
  153081. _floor_mapping_8,
  153082. NULL,
  153083. _mapres_template_8_stereo
  153084. };
  153085. ve_setup_data_template ve_setup_8_uncoupled={
  153086. 2,
  153087. rate_mapping_8_uncoupled,
  153088. quality_mapping_8,
  153089. -1,
  153090. 8000,
  153091. 9000,
  153092. blocksize_8,
  153093. blocksize_8,
  153094. _psy_tone_masteratt_8,
  153095. _psy_tone_0dB,
  153096. _psy_tone_suppress,
  153097. _vp_tonemask_adj_8,
  153098. NULL,
  153099. _vp_tonemask_adj_8,
  153100. _psy_noiseguards_8,
  153101. _psy_noisebias_8,
  153102. _psy_noisebias_8,
  153103. NULL,
  153104. NULL,
  153105. _psy_noise_suppress,
  153106. _psy_compand_8,
  153107. _psy_compand_8_mapping,
  153108. NULL,
  153109. {_noise_start_8,_noise_start_8},
  153110. {_noise_part_8,_noise_part_8},
  153111. _noise_thresh_5only,
  153112. _psy_ath_floater_8,
  153113. _psy_ath_abs_8,
  153114. _psy_lowpass_8,
  153115. _psy_global_44,
  153116. _global_mapping_8,
  153117. _psy_stereo_modes_8,
  153118. _floor_books,
  153119. _floor,
  153120. _floor_mapping_8,
  153121. NULL,
  153122. _mapres_template_8_uncoupled
  153123. };
  153124. /*** End of inlined file: setup_8.h ***/
  153125. /*** Start of inlined file: setup_11.h ***/
  153126. /*** Start of inlined file: psych_11.h ***/
  153127. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153128. static att3 _psy_tone_masteratt_11[3]={
  153129. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153130. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153131. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153132. };
  153133. static vp_adjblock _vp_tonemask_adj_11[3]={
  153134. /* adjust for mode zero */
  153135. /* 63 125 250 500 1 2 4 8 16 */
  153136. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153137. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153138. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153139. };
  153140. static noise3 _psy_noisebias_11[3]={
  153141. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153142. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153143. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153144. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153145. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153146. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153147. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153148. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153149. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153150. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153151. };
  153152. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153153. /*** End of inlined file: psych_11.h ***/
  153154. static int blocksize_11[2]={
  153155. 512,512
  153156. };
  153157. static int _floor_mapping_11[2]={
  153158. 6,6,
  153159. };
  153160. static double rate_mapping_11[3]={
  153161. 8000.,13000.,44000.,
  153162. };
  153163. static double rate_mapping_11_uncoupled[3]={
  153164. 12000.,20000.,50000.,
  153165. };
  153166. static double quality_mapping_11[3]={
  153167. -.1,.0,1.
  153168. };
  153169. ve_setup_data_template ve_setup_11_stereo={
  153170. 2,
  153171. rate_mapping_11,
  153172. quality_mapping_11,
  153173. 2,
  153174. 9000,
  153175. 15000,
  153176. blocksize_11,
  153177. blocksize_11,
  153178. _psy_tone_masteratt_11,
  153179. _psy_tone_0dB,
  153180. _psy_tone_suppress,
  153181. _vp_tonemask_adj_11,
  153182. NULL,
  153183. _vp_tonemask_adj_11,
  153184. _psy_noiseguards_8,
  153185. _psy_noisebias_11,
  153186. _psy_noisebias_11,
  153187. NULL,
  153188. NULL,
  153189. _psy_noise_suppress,
  153190. _psy_compand_8,
  153191. _psy_compand_8_mapping,
  153192. NULL,
  153193. {_noise_start_8,_noise_start_8},
  153194. {_noise_part_8,_noise_part_8},
  153195. _noise_thresh_11,
  153196. _psy_ath_floater_8,
  153197. _psy_ath_abs_8,
  153198. _psy_lowpass_11,
  153199. _psy_global_44,
  153200. _global_mapping_8,
  153201. _psy_stereo_modes_8,
  153202. _floor_books,
  153203. _floor,
  153204. _floor_mapping_11,
  153205. NULL,
  153206. _mapres_template_8_stereo
  153207. };
  153208. ve_setup_data_template ve_setup_11_uncoupled={
  153209. 2,
  153210. rate_mapping_11_uncoupled,
  153211. quality_mapping_11,
  153212. -1,
  153213. 9000,
  153214. 15000,
  153215. blocksize_11,
  153216. blocksize_11,
  153217. _psy_tone_masteratt_11,
  153218. _psy_tone_0dB,
  153219. _psy_tone_suppress,
  153220. _vp_tonemask_adj_11,
  153221. NULL,
  153222. _vp_tonemask_adj_11,
  153223. _psy_noiseguards_8,
  153224. _psy_noisebias_11,
  153225. _psy_noisebias_11,
  153226. NULL,
  153227. NULL,
  153228. _psy_noise_suppress,
  153229. _psy_compand_8,
  153230. _psy_compand_8_mapping,
  153231. NULL,
  153232. {_noise_start_8,_noise_start_8},
  153233. {_noise_part_8,_noise_part_8},
  153234. _noise_thresh_11,
  153235. _psy_ath_floater_8,
  153236. _psy_ath_abs_8,
  153237. _psy_lowpass_11,
  153238. _psy_global_44,
  153239. _global_mapping_8,
  153240. _psy_stereo_modes_8,
  153241. _floor_books,
  153242. _floor,
  153243. _floor_mapping_11,
  153244. NULL,
  153245. _mapres_template_8_uncoupled
  153246. };
  153247. /*** End of inlined file: setup_11.h ***/
  153248. /*** Start of inlined file: setup_16.h ***/
  153249. /*** Start of inlined file: psych_16.h ***/
  153250. /* stereo mode by base quality level */
  153251. static adj_stereo _psy_stereo_modes_16[4]={
  153252. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153253. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153254. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153255. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153256. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153257. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153258. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153259. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153260. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153261. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153262. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153263. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153264. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153265. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153266. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153267. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153268. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153269. };
  153270. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153271. static att3 _psy_tone_masteratt_16[4]={
  153272. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153273. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153274. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153275. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153276. };
  153277. static vp_adjblock _vp_tonemask_adj_16[4]={
  153278. /* adjust for mode zero */
  153279. /* 63 125 250 500 1 2 4 8 16 */
  153280. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153281. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153282. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153283. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153284. };
  153285. static noise3 _psy_noisebias_16_short[4]={
  153286. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153287. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153288. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153289. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153290. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153291. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153292. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153293. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153294. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153295. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153296. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153297. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153298. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153299. };
  153300. static noise3 _psy_noisebias_16_impulse[4]={
  153301. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153302. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153303. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153304. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153305. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153306. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153307. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153308. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153309. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153310. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153311. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153312. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153313. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153314. };
  153315. static noise3 _psy_noisebias_16[4]={
  153316. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153317. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153318. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153319. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153320. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153321. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153322. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153323. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153324. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153325. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153326. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153327. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153328. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153329. };
  153330. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153331. static int _noise_start_16[3]={ 256,256,9999 };
  153332. static int _noise_part_16[4]={ 8,8,8,8 };
  153333. static int _psy_ath_floater_16[4]={
  153334. -100,-100,-100,-105,
  153335. };
  153336. static int _psy_ath_abs_16[4]={
  153337. -130,-130,-130,-140,
  153338. };
  153339. /*** End of inlined file: psych_16.h ***/
  153340. /*** Start of inlined file: residue_16.h ***/
  153341. /***** residue backends *********************************************/
  153342. static static_bookblock _resbook_16s_0={
  153343. {
  153344. {0},
  153345. {0,0,&_16c0_s_p1_0},
  153346. {0,0,&_16c0_s_p2_0},
  153347. {0,0,&_16c0_s_p3_0},
  153348. {0,0,&_16c0_s_p4_0},
  153349. {0,0,&_16c0_s_p5_0},
  153350. {0,0,&_16c0_s_p6_0},
  153351. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153352. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153353. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153354. }
  153355. };
  153356. static static_bookblock _resbook_16s_1={
  153357. {
  153358. {0},
  153359. {0,0,&_16c1_s_p1_0},
  153360. {0,0,&_16c1_s_p2_0},
  153361. {0,0,&_16c1_s_p3_0},
  153362. {0,0,&_16c1_s_p4_0},
  153363. {0,0,&_16c1_s_p5_0},
  153364. {0,0,&_16c1_s_p6_0},
  153365. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153366. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153367. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153368. }
  153369. };
  153370. static static_bookblock _resbook_16s_2={
  153371. {
  153372. {0},
  153373. {0,0,&_16c2_s_p1_0},
  153374. {0,0,&_16c2_s_p2_0},
  153375. {0,0,&_16c2_s_p3_0},
  153376. {0,0,&_16c2_s_p4_0},
  153377. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153378. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153379. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153380. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153381. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153382. }
  153383. };
  153384. static vorbis_residue_template _res_16s_0[]={
  153385. {2,0, &_residue_44_mid,
  153386. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153387. &_resbook_16s_0,&_resbook_16s_0},
  153388. };
  153389. static vorbis_residue_template _res_16s_1[]={
  153390. {2,0, &_residue_44_mid,
  153391. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153392. &_resbook_16s_1,&_resbook_16s_1},
  153393. {2,0, &_residue_44_mid,
  153394. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153395. &_resbook_16s_1,&_resbook_16s_1}
  153396. };
  153397. static vorbis_residue_template _res_16s_2[]={
  153398. {2,0, &_residue_44_high,
  153399. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153400. &_resbook_16s_2,&_resbook_16s_2},
  153401. {2,0, &_residue_44_high,
  153402. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153403. &_resbook_16s_2,&_resbook_16s_2}
  153404. };
  153405. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153406. { _map_nominal, _res_16s_0 }, /* 0 */
  153407. { _map_nominal, _res_16s_1 }, /* 1 */
  153408. { _map_nominal, _res_16s_2 }, /* 2 */
  153409. };
  153410. static static_bookblock _resbook_16u_0={
  153411. {
  153412. {0},
  153413. {0,0,&_16u0__p1_0},
  153414. {0,0,&_16u0__p2_0},
  153415. {0,0,&_16u0__p3_0},
  153416. {0,0,&_16u0__p4_0},
  153417. {0,0,&_16u0__p5_0},
  153418. {&_16u0__p6_0,&_16u0__p6_1},
  153419. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153420. }
  153421. };
  153422. static static_bookblock _resbook_16u_1={
  153423. {
  153424. {0},
  153425. {0,0,&_16u1__p1_0},
  153426. {0,0,&_16u1__p2_0},
  153427. {0,0,&_16u1__p3_0},
  153428. {0,0,&_16u1__p4_0},
  153429. {0,0,&_16u1__p5_0},
  153430. {0,0,&_16u1__p6_0},
  153431. {&_16u1__p7_0,&_16u1__p7_1},
  153432. {&_16u1__p8_0,&_16u1__p8_1},
  153433. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153434. }
  153435. };
  153436. static static_bookblock _resbook_16u_2={
  153437. {
  153438. {0},
  153439. {0,0,&_16u2_p1_0},
  153440. {0,0,&_16u2_p2_0},
  153441. {0,0,&_16u2_p3_0},
  153442. {0,0,&_16u2_p4_0},
  153443. {&_16u2_p5_0,&_16u2_p5_1},
  153444. {&_16u2_p6_0,&_16u2_p6_1},
  153445. {&_16u2_p7_0,&_16u2_p7_1},
  153446. {&_16u2_p8_0,&_16u2_p8_1},
  153447. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153448. }
  153449. };
  153450. static vorbis_residue_template _res_16u_0[]={
  153451. {1,0, &_residue_44_low_un,
  153452. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153453. &_resbook_16u_0,&_resbook_16u_0},
  153454. };
  153455. static vorbis_residue_template _res_16u_1[]={
  153456. {1,0, &_residue_44_mid_un,
  153457. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153458. &_resbook_16u_1,&_resbook_16u_1},
  153459. {1,0, &_residue_44_mid_un,
  153460. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153461. &_resbook_16u_1,&_resbook_16u_1}
  153462. };
  153463. static vorbis_residue_template _res_16u_2[]={
  153464. {1,0, &_residue_44_hi_un,
  153465. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153466. &_resbook_16u_2,&_resbook_16u_2},
  153467. {1,0, &_residue_44_hi_un,
  153468. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153469. &_resbook_16u_2,&_resbook_16u_2}
  153470. };
  153471. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153472. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153473. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153474. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153475. };
  153476. /*** End of inlined file: residue_16.h ***/
  153477. static int blocksize_16_short[3]={
  153478. 1024,512,512
  153479. };
  153480. static int blocksize_16_long[3]={
  153481. 1024,1024,1024
  153482. };
  153483. static int _floor_mapping_16_short[3]={
  153484. 9,3,3
  153485. };
  153486. static int _floor_mapping_16[3]={
  153487. 9,9,9
  153488. };
  153489. static double rate_mapping_16[4]={
  153490. 12000.,20000.,44000.,86000.
  153491. };
  153492. static double rate_mapping_16_uncoupled[4]={
  153493. 16000.,28000.,64000.,100000.
  153494. };
  153495. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153496. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153497. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153498. ve_setup_data_template ve_setup_16_stereo={
  153499. 3,
  153500. rate_mapping_16,
  153501. quality_mapping_16,
  153502. 2,
  153503. 15000,
  153504. 19000,
  153505. blocksize_16_short,
  153506. blocksize_16_long,
  153507. _psy_tone_masteratt_16,
  153508. _psy_tone_0dB,
  153509. _psy_tone_suppress,
  153510. _vp_tonemask_adj_16,
  153511. _vp_tonemask_adj_16,
  153512. _vp_tonemask_adj_16,
  153513. _psy_noiseguards_8,
  153514. _psy_noisebias_16_impulse,
  153515. _psy_noisebias_16_short,
  153516. _psy_noisebias_16_short,
  153517. _psy_noisebias_16,
  153518. _psy_noise_suppress,
  153519. _psy_compand_8,
  153520. _psy_compand_16_mapping,
  153521. _psy_compand_16_mapping,
  153522. {_noise_start_16,_noise_start_16},
  153523. { _noise_part_16, _noise_part_16},
  153524. _noise_thresh_16,
  153525. _psy_ath_floater_16,
  153526. _psy_ath_abs_16,
  153527. _psy_lowpass_16,
  153528. _psy_global_44,
  153529. _global_mapping_16,
  153530. _psy_stereo_modes_16,
  153531. _floor_books,
  153532. _floor,
  153533. _floor_mapping_16_short,
  153534. _floor_mapping_16,
  153535. _mapres_template_16_stereo
  153536. };
  153537. ve_setup_data_template ve_setup_16_uncoupled={
  153538. 3,
  153539. rate_mapping_16_uncoupled,
  153540. quality_mapping_16,
  153541. -1,
  153542. 15000,
  153543. 19000,
  153544. blocksize_16_short,
  153545. blocksize_16_long,
  153546. _psy_tone_masteratt_16,
  153547. _psy_tone_0dB,
  153548. _psy_tone_suppress,
  153549. _vp_tonemask_adj_16,
  153550. _vp_tonemask_adj_16,
  153551. _vp_tonemask_adj_16,
  153552. _psy_noiseguards_8,
  153553. _psy_noisebias_16_impulse,
  153554. _psy_noisebias_16_short,
  153555. _psy_noisebias_16_short,
  153556. _psy_noisebias_16,
  153557. _psy_noise_suppress,
  153558. _psy_compand_8,
  153559. _psy_compand_16_mapping,
  153560. _psy_compand_16_mapping,
  153561. {_noise_start_16,_noise_start_16},
  153562. { _noise_part_16, _noise_part_16},
  153563. _noise_thresh_16,
  153564. _psy_ath_floater_16,
  153565. _psy_ath_abs_16,
  153566. _psy_lowpass_16,
  153567. _psy_global_44,
  153568. _global_mapping_16,
  153569. _psy_stereo_modes_16,
  153570. _floor_books,
  153571. _floor,
  153572. _floor_mapping_16_short,
  153573. _floor_mapping_16,
  153574. _mapres_template_16_uncoupled
  153575. };
  153576. /*** End of inlined file: setup_16.h ***/
  153577. /*** Start of inlined file: setup_22.h ***/
  153578. static double rate_mapping_22[4]={
  153579. 15000.,20000.,44000.,86000.
  153580. };
  153581. static double rate_mapping_22_uncoupled[4]={
  153582. 16000.,28000.,50000.,90000.
  153583. };
  153584. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153585. ve_setup_data_template ve_setup_22_stereo={
  153586. 3,
  153587. rate_mapping_22,
  153588. quality_mapping_16,
  153589. 2,
  153590. 19000,
  153591. 26000,
  153592. blocksize_16_short,
  153593. blocksize_16_long,
  153594. _psy_tone_masteratt_16,
  153595. _psy_tone_0dB,
  153596. _psy_tone_suppress,
  153597. _vp_tonemask_adj_16,
  153598. _vp_tonemask_adj_16,
  153599. _vp_tonemask_adj_16,
  153600. _psy_noiseguards_8,
  153601. _psy_noisebias_16_impulse,
  153602. _psy_noisebias_16_short,
  153603. _psy_noisebias_16_short,
  153604. _psy_noisebias_16,
  153605. _psy_noise_suppress,
  153606. _psy_compand_8,
  153607. _psy_compand_8_mapping,
  153608. _psy_compand_8_mapping,
  153609. {_noise_start_16,_noise_start_16},
  153610. { _noise_part_16, _noise_part_16},
  153611. _noise_thresh_16,
  153612. _psy_ath_floater_16,
  153613. _psy_ath_abs_16,
  153614. _psy_lowpass_22,
  153615. _psy_global_44,
  153616. _global_mapping_16,
  153617. _psy_stereo_modes_16,
  153618. _floor_books,
  153619. _floor,
  153620. _floor_mapping_16_short,
  153621. _floor_mapping_16,
  153622. _mapres_template_16_stereo
  153623. };
  153624. ve_setup_data_template ve_setup_22_uncoupled={
  153625. 3,
  153626. rate_mapping_22_uncoupled,
  153627. quality_mapping_16,
  153628. -1,
  153629. 19000,
  153630. 26000,
  153631. blocksize_16_short,
  153632. blocksize_16_long,
  153633. _psy_tone_masteratt_16,
  153634. _psy_tone_0dB,
  153635. _psy_tone_suppress,
  153636. _vp_tonemask_adj_16,
  153637. _vp_tonemask_adj_16,
  153638. _vp_tonemask_adj_16,
  153639. _psy_noiseguards_8,
  153640. _psy_noisebias_16_impulse,
  153641. _psy_noisebias_16_short,
  153642. _psy_noisebias_16_short,
  153643. _psy_noisebias_16,
  153644. _psy_noise_suppress,
  153645. _psy_compand_8,
  153646. _psy_compand_8_mapping,
  153647. _psy_compand_8_mapping,
  153648. {_noise_start_16,_noise_start_16},
  153649. { _noise_part_16, _noise_part_16},
  153650. _noise_thresh_16,
  153651. _psy_ath_floater_16,
  153652. _psy_ath_abs_16,
  153653. _psy_lowpass_22,
  153654. _psy_global_44,
  153655. _global_mapping_16,
  153656. _psy_stereo_modes_16,
  153657. _floor_books,
  153658. _floor,
  153659. _floor_mapping_16_short,
  153660. _floor_mapping_16,
  153661. _mapres_template_16_uncoupled
  153662. };
  153663. /*** End of inlined file: setup_22.h ***/
  153664. /*** Start of inlined file: setup_X.h ***/
  153665. static double rate_mapping_X[12]={
  153666. -1.,-1.,-1.,-1.,-1.,-1.,
  153667. -1.,-1.,-1.,-1.,-1.,-1.
  153668. };
  153669. ve_setup_data_template ve_setup_X_stereo={
  153670. 11,
  153671. rate_mapping_X,
  153672. quality_mapping_44,
  153673. 2,
  153674. 50000,
  153675. 200000,
  153676. blocksize_short_44,
  153677. blocksize_long_44,
  153678. _psy_tone_masteratt_44,
  153679. _psy_tone_0dB,
  153680. _psy_tone_suppress,
  153681. _vp_tonemask_adj_otherblock,
  153682. _vp_tonemask_adj_longblock,
  153683. _vp_tonemask_adj_otherblock,
  153684. _psy_noiseguards_44,
  153685. _psy_noisebias_impulse,
  153686. _psy_noisebias_padding,
  153687. _psy_noisebias_trans,
  153688. _psy_noisebias_long,
  153689. _psy_noise_suppress,
  153690. _psy_compand_44,
  153691. _psy_compand_short_mapping,
  153692. _psy_compand_long_mapping,
  153693. {_noise_start_short_44,_noise_start_long_44},
  153694. {_noise_part_short_44,_noise_part_long_44},
  153695. _noise_thresh_44,
  153696. _psy_ath_floater,
  153697. _psy_ath_abs,
  153698. _psy_lowpass_44,
  153699. _psy_global_44,
  153700. _global_mapping_44,
  153701. _psy_stereo_modes_44,
  153702. _floor_books,
  153703. _floor,
  153704. _floor_short_mapping_44,
  153705. _floor_long_mapping_44,
  153706. _mapres_template_44_stereo
  153707. };
  153708. ve_setup_data_template ve_setup_X_uncoupled={
  153709. 11,
  153710. rate_mapping_X,
  153711. quality_mapping_44,
  153712. -1,
  153713. 50000,
  153714. 200000,
  153715. blocksize_short_44,
  153716. blocksize_long_44,
  153717. _psy_tone_masteratt_44,
  153718. _psy_tone_0dB,
  153719. _psy_tone_suppress,
  153720. _vp_tonemask_adj_otherblock,
  153721. _vp_tonemask_adj_longblock,
  153722. _vp_tonemask_adj_otherblock,
  153723. _psy_noiseguards_44,
  153724. _psy_noisebias_impulse,
  153725. _psy_noisebias_padding,
  153726. _psy_noisebias_trans,
  153727. _psy_noisebias_long,
  153728. _psy_noise_suppress,
  153729. _psy_compand_44,
  153730. _psy_compand_short_mapping,
  153731. _psy_compand_long_mapping,
  153732. {_noise_start_short_44,_noise_start_long_44},
  153733. {_noise_part_short_44,_noise_part_long_44},
  153734. _noise_thresh_44,
  153735. _psy_ath_floater,
  153736. _psy_ath_abs,
  153737. _psy_lowpass_44,
  153738. _psy_global_44,
  153739. _global_mapping_44,
  153740. NULL,
  153741. _floor_books,
  153742. _floor,
  153743. _floor_short_mapping_44,
  153744. _floor_long_mapping_44,
  153745. _mapres_template_44_uncoupled
  153746. };
  153747. ve_setup_data_template ve_setup_XX_stereo={
  153748. 2,
  153749. rate_mapping_X,
  153750. quality_mapping_8,
  153751. 2,
  153752. 0,
  153753. 8000,
  153754. blocksize_8,
  153755. blocksize_8,
  153756. _psy_tone_masteratt_8,
  153757. _psy_tone_0dB,
  153758. _psy_tone_suppress,
  153759. _vp_tonemask_adj_8,
  153760. NULL,
  153761. _vp_tonemask_adj_8,
  153762. _psy_noiseguards_8,
  153763. _psy_noisebias_8,
  153764. _psy_noisebias_8,
  153765. NULL,
  153766. NULL,
  153767. _psy_noise_suppress,
  153768. _psy_compand_8,
  153769. _psy_compand_8_mapping,
  153770. NULL,
  153771. {_noise_start_8,_noise_start_8},
  153772. {_noise_part_8,_noise_part_8},
  153773. _noise_thresh_5only,
  153774. _psy_ath_floater_8,
  153775. _psy_ath_abs_8,
  153776. _psy_lowpass_8,
  153777. _psy_global_44,
  153778. _global_mapping_8,
  153779. _psy_stereo_modes_8,
  153780. _floor_books,
  153781. _floor,
  153782. _floor_mapping_8,
  153783. NULL,
  153784. _mapres_template_8_stereo
  153785. };
  153786. ve_setup_data_template ve_setup_XX_uncoupled={
  153787. 2,
  153788. rate_mapping_X,
  153789. quality_mapping_8,
  153790. -1,
  153791. 0,
  153792. 8000,
  153793. blocksize_8,
  153794. blocksize_8,
  153795. _psy_tone_masteratt_8,
  153796. _psy_tone_0dB,
  153797. _psy_tone_suppress,
  153798. _vp_tonemask_adj_8,
  153799. NULL,
  153800. _vp_tonemask_adj_8,
  153801. _psy_noiseguards_8,
  153802. _psy_noisebias_8,
  153803. _psy_noisebias_8,
  153804. NULL,
  153805. NULL,
  153806. _psy_noise_suppress,
  153807. _psy_compand_8,
  153808. _psy_compand_8_mapping,
  153809. NULL,
  153810. {_noise_start_8,_noise_start_8},
  153811. {_noise_part_8,_noise_part_8},
  153812. _noise_thresh_5only,
  153813. _psy_ath_floater_8,
  153814. _psy_ath_abs_8,
  153815. _psy_lowpass_8,
  153816. _psy_global_44,
  153817. _global_mapping_8,
  153818. _psy_stereo_modes_8,
  153819. _floor_books,
  153820. _floor,
  153821. _floor_mapping_8,
  153822. NULL,
  153823. _mapres_template_8_uncoupled
  153824. };
  153825. /*** End of inlined file: setup_X.h ***/
  153826. static ve_setup_data_template *setup_list[]={
  153827. &ve_setup_44_stereo,
  153828. &ve_setup_44_uncoupled,
  153829. &ve_setup_32_stereo,
  153830. &ve_setup_32_uncoupled,
  153831. &ve_setup_22_stereo,
  153832. &ve_setup_22_uncoupled,
  153833. &ve_setup_16_stereo,
  153834. &ve_setup_16_uncoupled,
  153835. &ve_setup_11_stereo,
  153836. &ve_setup_11_uncoupled,
  153837. &ve_setup_8_stereo,
  153838. &ve_setup_8_uncoupled,
  153839. &ve_setup_X_stereo,
  153840. &ve_setup_X_uncoupled,
  153841. &ve_setup_XX_stereo,
  153842. &ve_setup_XX_uncoupled,
  153843. 0
  153844. };
  153845. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  153846. if(vi && vi->codec_setup){
  153847. vi->version=0;
  153848. vi->channels=ch;
  153849. vi->rate=rate;
  153850. return(0);
  153851. }
  153852. return(OV_EINVAL);
  153853. }
  153854. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  153855. static_codebook ***books,
  153856. vorbis_info_floor1 *in,
  153857. int *x){
  153858. int i,k,is=s;
  153859. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  153860. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153861. memcpy(f,in+x[is],sizeof(*f));
  153862. /* fill in the lowpass field, even if it's temporary */
  153863. f->n=ci->blocksizes[block]>>1;
  153864. /* books */
  153865. {
  153866. int partitions=f->partitions;
  153867. int maxclass=-1;
  153868. int maxbook=-1;
  153869. for(i=0;i<partitions;i++)
  153870. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  153871. for(i=0;i<=maxclass;i++){
  153872. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  153873. f->class_book[i]+=ci->books;
  153874. for(k=0;k<(1<<f->class_subs[i]);k++){
  153875. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  153876. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  153877. }
  153878. }
  153879. for(i=0;i<=maxbook;i++)
  153880. ci->book_param[ci->books++]=books[x[is]][i];
  153881. }
  153882. /* for now, we're only using floor 1 */
  153883. ci->floor_type[ci->floors]=1;
  153884. ci->floor_param[ci->floors]=f;
  153885. ci->floors++;
  153886. return;
  153887. }
  153888. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  153889. vorbis_info_psy_global *in,
  153890. double *x){
  153891. int i,is=s;
  153892. double ds=s-is;
  153893. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153894. vorbis_info_psy_global *g=&ci->psy_g_param;
  153895. memcpy(g,in+(int)x[is],sizeof(*g));
  153896. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153897. is=(int)ds;
  153898. ds-=is;
  153899. if(ds==0 && is>0){
  153900. is--;
  153901. ds=1.;
  153902. }
  153903. /* interpolate the trigger threshholds */
  153904. for(i=0;i<4;i++){
  153905. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  153906. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  153907. }
  153908. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  153909. return;
  153910. }
  153911. static void vorbis_encode_global_stereo(vorbis_info *vi,
  153912. highlevel_encode_setup *hi,
  153913. adj_stereo *p){
  153914. float s=hi->stereo_point_setting;
  153915. int i,is=s;
  153916. double ds=s-is;
  153917. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153918. vorbis_info_psy_global *g=&ci->psy_g_param;
  153919. if(p){
  153920. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  153921. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  153922. if(hi->managed){
  153923. /* interpolate the kHz threshholds */
  153924. for(i=0;i<PACKETBLOBS;i++){
  153925. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  153926. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153927. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153928. g->coupling_pkHz[i]=kHz;
  153929. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  153930. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153931. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153932. }
  153933. }else{
  153934. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  153935. for(i=0;i<PACKETBLOBS;i++){
  153936. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153937. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153938. g->coupling_pkHz[i]=kHz;
  153939. }
  153940. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  153941. for(i=0;i<PACKETBLOBS;i++){
  153942. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153943. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153944. }
  153945. }
  153946. }else{
  153947. for(i=0;i<PACKETBLOBS;i++){
  153948. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  153949. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  153950. }
  153951. }
  153952. return;
  153953. }
  153954. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  153955. int *nn_start,
  153956. int *nn_partition,
  153957. double *nn_thresh,
  153958. int block){
  153959. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153960. vorbis_info_psy *p=ci->psy_param[block];
  153961. highlevel_encode_setup *hi=&ci->hi;
  153962. int is=s;
  153963. if(block>=ci->psys)
  153964. ci->psys=block+1;
  153965. if(!p){
  153966. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  153967. ci->psy_param[block]=p;
  153968. }
  153969. memcpy(p,&_psy_info_template,sizeof(*p));
  153970. p->blockflag=block>>1;
  153971. if(hi->noise_normalize_p){
  153972. p->normal_channel_p=1;
  153973. p->normal_point_p=1;
  153974. p->normal_start=nn_start[is];
  153975. p->normal_partition=nn_partition[is];
  153976. p->normal_thresh=nn_thresh[is];
  153977. }
  153978. return;
  153979. }
  153980. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  153981. att3 *att,
  153982. int *max,
  153983. vp_adjblock *in){
  153984. int i,is=s;
  153985. double ds=s-is;
  153986. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153987. vorbis_info_psy *p=ci->psy_param[block];
  153988. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  153989. filling the values in here */
  153990. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  153991. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  153992. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  153993. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  153994. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  153995. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  153996. for(i=0;i<P_BANDS;i++)
  153997. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  153998. return;
  153999. }
  154000. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154001. compandblock *in, double *x){
  154002. int i,is=s;
  154003. double ds=s-is;
  154004. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154005. vorbis_info_psy *p=ci->psy_param[block];
  154006. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154007. is=(int)ds;
  154008. ds-=is;
  154009. if(ds==0 && is>0){
  154010. is--;
  154011. ds=1.;
  154012. }
  154013. /* interpolate the compander settings */
  154014. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154015. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154016. return;
  154017. }
  154018. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154019. int *suppress){
  154020. int is=s;
  154021. double ds=s-is;
  154022. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154023. vorbis_info_psy *p=ci->psy_param[block];
  154024. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154025. return;
  154026. }
  154027. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154028. int *suppress,
  154029. noise3 *in,
  154030. noiseguard *guard,
  154031. double userbias){
  154032. int i,is=s,j;
  154033. double ds=s-is;
  154034. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154035. vorbis_info_psy *p=ci->psy_param[block];
  154036. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154037. p->noisewindowlomin=guard[block].lo;
  154038. p->noisewindowhimin=guard[block].hi;
  154039. p->noisewindowfixed=guard[block].fixed;
  154040. for(j=0;j<P_NOISECURVES;j++)
  154041. for(i=0;i<P_BANDS;i++)
  154042. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154043. /* impulse blocks may take a user specified bias to boost the
  154044. nominal/high noise encoding depth */
  154045. for(j=0;j<P_NOISECURVES;j++){
  154046. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154047. for(i=0;i<P_BANDS;i++){
  154048. p->noiseoff[j][i]+=userbias;
  154049. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154050. }
  154051. }
  154052. return;
  154053. }
  154054. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154055. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154056. vorbis_info_psy *p=ci->psy_param[block];
  154057. p->ath_adjatt=ci->hi.ath_floating_dB;
  154058. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154059. return;
  154060. }
  154061. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154062. int i;
  154063. for(i=0;i<ci->books;i++)
  154064. if(ci->book_param[i]==book)return(i);
  154065. return(ci->books++);
  154066. }
  154067. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154068. int *shortb,int *longb){
  154069. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154070. int is=s;
  154071. int blockshort=shortb[is];
  154072. int blocklong=longb[is];
  154073. ci->blocksizes[0]=blockshort;
  154074. ci->blocksizes[1]=blocklong;
  154075. }
  154076. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154077. int number, int block,
  154078. vorbis_residue_template *res){
  154079. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154080. int i,n;
  154081. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154082. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154083. memcpy(r,res->res,sizeof(*r));
  154084. if(ci->residues<=number)ci->residues=number+1;
  154085. switch(ci->blocksizes[block]){
  154086. case 64:case 128:case 256:
  154087. r->grouping=16;
  154088. break;
  154089. default:
  154090. r->grouping=32;
  154091. break;
  154092. }
  154093. ci->residue_type[number]=res->res_type;
  154094. /* to be adjusted by lowpass/pointlimit later */
  154095. n=r->end=ci->blocksizes[block]>>1;
  154096. if(res->res_type==2)
  154097. n=r->end*=vi->channels;
  154098. /* fill in all the books */
  154099. {
  154100. int booklist=0,k;
  154101. if(ci->hi.managed){
  154102. for(i=0;i<r->partitions;i++)
  154103. for(k=0;k<3;k++)
  154104. if(res->books_base_managed->books[i][k])
  154105. r->secondstages[i]|=(1<<k);
  154106. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154107. ci->book_param[r->groupbook]=res->book_aux_managed;
  154108. for(i=0;i<r->partitions;i++){
  154109. for(k=0;k<3;k++){
  154110. if(res->books_base_managed->books[i][k]){
  154111. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154112. r->booklist[booklist++]=bookid;
  154113. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154114. }
  154115. }
  154116. }
  154117. }else{
  154118. for(i=0;i<r->partitions;i++)
  154119. for(k=0;k<3;k++)
  154120. if(res->books_base->books[i][k])
  154121. r->secondstages[i]|=(1<<k);
  154122. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154123. ci->book_param[r->groupbook]=res->book_aux;
  154124. for(i=0;i<r->partitions;i++){
  154125. for(k=0;k<3;k++){
  154126. if(res->books_base->books[i][k]){
  154127. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154128. r->booklist[booklist++]=bookid;
  154129. ci->book_param[bookid]=res->books_base->books[i][k];
  154130. }
  154131. }
  154132. }
  154133. }
  154134. }
  154135. /* lowpass setup/pointlimit */
  154136. {
  154137. double freq=ci->hi.lowpass_kHz*1000.;
  154138. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154139. double nyq=vi->rate/2.;
  154140. long blocksize=ci->blocksizes[block]>>1;
  154141. /* lowpass needs to be set in the floor and the residue. */
  154142. if(freq>nyq)freq=nyq;
  154143. /* in the floor, the granularity can be very fine; it doesn't alter
  154144. the encoding structure, only the samples used to fit the floor
  154145. approximation */
  154146. f->n=freq/nyq*blocksize;
  154147. /* this res may by limited by the maximum pointlimit of the mode,
  154148. not the lowpass. the floor is always lowpass limited. */
  154149. if(res->limit_type){
  154150. if(ci->hi.managed)
  154151. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154152. else
  154153. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154154. if(freq>nyq)freq=nyq;
  154155. }
  154156. /* in the residue, we're constrained, physically, by partition
  154157. boundaries. We still lowpass 'wherever', but we have to round up
  154158. here to next boundary, or the vorbis spec will round it *down* to
  154159. previous boundary in encode/decode */
  154160. if(ci->residue_type[block]==2)
  154161. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154162. r->grouping;
  154163. else
  154164. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154165. r->grouping;
  154166. }
  154167. }
  154168. /* we assume two maps in this encoder */
  154169. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154170. vorbis_mapping_template *maps){
  154171. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154172. int i,j,is=s,modes=2;
  154173. vorbis_info_mapping0 *map=maps[is].map;
  154174. vorbis_info_mode *mode=_mode_template;
  154175. vorbis_residue_template *res=maps[is].res;
  154176. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154177. for(i=0;i<modes;i++){
  154178. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154179. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154180. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154181. if(i>=ci->modes)ci->modes=i+1;
  154182. ci->map_type[i]=0;
  154183. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154184. if(i>=ci->maps)ci->maps=i+1;
  154185. for(j=0;j<map[i].submaps;j++)
  154186. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154187. ,res+map[i].residuesubmap[j]);
  154188. }
  154189. }
  154190. static double setting_to_approx_bitrate(vorbis_info *vi){
  154191. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154192. highlevel_encode_setup *hi=&ci->hi;
  154193. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154194. int is=hi->base_setting;
  154195. double ds=hi->base_setting-is;
  154196. int ch=vi->channels;
  154197. double *r=setup->rate_mapping;
  154198. if(r==NULL)
  154199. return(-1);
  154200. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154201. }
  154202. static void get_setup_template(vorbis_info *vi,
  154203. long ch,long srate,
  154204. double req,int q_or_bitrate){
  154205. int i=0,j;
  154206. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154207. highlevel_encode_setup *hi=&ci->hi;
  154208. if(q_or_bitrate)req/=ch;
  154209. while(setup_list[i]){
  154210. if(setup_list[i]->coupling_restriction==-1 ||
  154211. setup_list[i]->coupling_restriction==ch){
  154212. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154213. srate<=setup_list[i]->samplerate_max_restriction){
  154214. int mappings=setup_list[i]->mappings;
  154215. double *map=(q_or_bitrate?
  154216. setup_list[i]->rate_mapping:
  154217. setup_list[i]->quality_mapping);
  154218. /* the template matches. Does the requested quality mode
  154219. fall within this template's modes? */
  154220. if(req<map[0]){++i;continue;}
  154221. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154222. for(j=0;j<mappings;j++)
  154223. if(req>=map[j] && req<map[j+1])break;
  154224. /* an all-points match */
  154225. hi->setup=setup_list[i];
  154226. if(j==mappings)
  154227. hi->base_setting=j-.001;
  154228. else{
  154229. float low=map[j];
  154230. float high=map[j+1];
  154231. float del=(req-low)/(high-low);
  154232. hi->base_setting=j+del;
  154233. }
  154234. return;
  154235. }
  154236. }
  154237. i++;
  154238. }
  154239. hi->setup=NULL;
  154240. }
  154241. /* encoders will need to use vorbis_info_init beforehand and call
  154242. vorbis_info clear when all done */
  154243. /* two interfaces; this, more detailed one, and later a convenience
  154244. layer on top */
  154245. /* the final setup call */
  154246. int vorbis_encode_setup_init(vorbis_info *vi){
  154247. int i0=0,singleblock=0;
  154248. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154249. ve_setup_data_template *setup=NULL;
  154250. highlevel_encode_setup *hi=&ci->hi;
  154251. if(ci==NULL)return(OV_EINVAL);
  154252. if(!hi->impulse_block_p)i0=1;
  154253. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154254. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154255. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154256. /* again, bound this to avoid the app shooting itself int he foot
  154257. too badly */
  154258. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154259. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154260. /* get the appropriate setup template; matches the fetch in previous
  154261. stages */
  154262. setup=(ve_setup_data_template *)hi->setup;
  154263. if(setup==NULL)return(OV_EINVAL);
  154264. hi->set_in_stone=1;
  154265. /* choose block sizes from configured sizes as well as paying
  154266. attention to long_block_p and short_block_p. If the configured
  154267. short and long blocks are the same length, we set long_block_p
  154268. and unset short_block_p */
  154269. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154270. setup->blocksize_short,
  154271. setup->blocksize_long);
  154272. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154273. /* floor setup; choose proper floor params. Allocated on the floor
  154274. stack in order; if we alloc only long floor, it's 0 */
  154275. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154276. setup->floor_books,
  154277. setup->floor_params,
  154278. setup->floor_short_mapping);
  154279. if(!singleblock)
  154280. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154281. setup->floor_books,
  154282. setup->floor_params,
  154283. setup->floor_long_mapping);
  154284. /* setup of [mostly] short block detection and stereo*/
  154285. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154286. setup->global_params,
  154287. setup->global_mapping);
  154288. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154289. /* basic psych setup and noise normalization */
  154290. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154291. setup->psy_noise_normal_start[0],
  154292. setup->psy_noise_normal_partition[0],
  154293. setup->psy_noise_normal_thresh,
  154294. 0);
  154295. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154296. setup->psy_noise_normal_start[0],
  154297. setup->psy_noise_normal_partition[0],
  154298. setup->psy_noise_normal_thresh,
  154299. 1);
  154300. if(!singleblock){
  154301. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154302. setup->psy_noise_normal_start[1],
  154303. setup->psy_noise_normal_partition[1],
  154304. setup->psy_noise_normal_thresh,
  154305. 2);
  154306. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154307. setup->psy_noise_normal_start[1],
  154308. setup->psy_noise_normal_partition[1],
  154309. setup->psy_noise_normal_thresh,
  154310. 3);
  154311. }
  154312. /* tone masking setup */
  154313. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154314. setup->psy_tone_masteratt,
  154315. setup->psy_tone_0dB,
  154316. setup->psy_tone_adj_impulse);
  154317. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154318. setup->psy_tone_masteratt,
  154319. setup->psy_tone_0dB,
  154320. setup->psy_tone_adj_other);
  154321. if(!singleblock){
  154322. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154323. setup->psy_tone_masteratt,
  154324. setup->psy_tone_0dB,
  154325. setup->psy_tone_adj_other);
  154326. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154327. setup->psy_tone_masteratt,
  154328. setup->psy_tone_0dB,
  154329. setup->psy_tone_adj_long);
  154330. }
  154331. /* noise companding setup */
  154332. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154333. setup->psy_noise_compand,
  154334. setup->psy_noise_compand_short_mapping);
  154335. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154336. setup->psy_noise_compand,
  154337. setup->psy_noise_compand_short_mapping);
  154338. if(!singleblock){
  154339. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154340. setup->psy_noise_compand,
  154341. setup->psy_noise_compand_long_mapping);
  154342. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154343. setup->psy_noise_compand,
  154344. setup->psy_noise_compand_long_mapping);
  154345. }
  154346. /* peak guarding setup */
  154347. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154348. setup->psy_tone_dBsuppress);
  154349. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154350. setup->psy_tone_dBsuppress);
  154351. if(!singleblock){
  154352. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154353. setup->psy_tone_dBsuppress);
  154354. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154355. setup->psy_tone_dBsuppress);
  154356. }
  154357. /* noise bias setup */
  154358. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154359. setup->psy_noise_dBsuppress,
  154360. setup->psy_noise_bias_impulse,
  154361. setup->psy_noiseguards,
  154362. (i0==0?hi->impulse_noisetune:0.));
  154363. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154364. setup->psy_noise_dBsuppress,
  154365. setup->psy_noise_bias_padding,
  154366. setup->psy_noiseguards,0.);
  154367. if(!singleblock){
  154368. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154369. setup->psy_noise_dBsuppress,
  154370. setup->psy_noise_bias_trans,
  154371. setup->psy_noiseguards,0.);
  154372. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154373. setup->psy_noise_dBsuppress,
  154374. setup->psy_noise_bias_long,
  154375. setup->psy_noiseguards,0.);
  154376. }
  154377. vorbis_encode_ath_setup(vi,0);
  154378. vorbis_encode_ath_setup(vi,1);
  154379. if(!singleblock){
  154380. vorbis_encode_ath_setup(vi,2);
  154381. vorbis_encode_ath_setup(vi,3);
  154382. }
  154383. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154384. /* set bitrate readonlies and management */
  154385. if(hi->bitrate_av>0)
  154386. vi->bitrate_nominal=hi->bitrate_av;
  154387. else{
  154388. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154389. }
  154390. vi->bitrate_lower=hi->bitrate_min;
  154391. vi->bitrate_upper=hi->bitrate_max;
  154392. if(hi->bitrate_av)
  154393. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154394. else
  154395. vi->bitrate_window=0.;
  154396. if(hi->managed){
  154397. ci->bi.avg_rate=hi->bitrate_av;
  154398. ci->bi.min_rate=hi->bitrate_min;
  154399. ci->bi.max_rate=hi->bitrate_max;
  154400. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154401. ci->bi.reservoir_bias=
  154402. hi->bitrate_reservoir_bias;
  154403. ci->bi.slew_damp=hi->bitrate_av_damp;
  154404. }
  154405. return(0);
  154406. }
  154407. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154408. long channels,
  154409. long rate){
  154410. int ret=0,i,is;
  154411. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154412. highlevel_encode_setup *hi=&ci->hi;
  154413. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154414. double ds;
  154415. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154416. if(ret)return(ret);
  154417. is=hi->base_setting;
  154418. ds=hi->base_setting-is;
  154419. hi->short_setting=hi->base_setting;
  154420. hi->long_setting=hi->base_setting;
  154421. hi->managed=0;
  154422. hi->impulse_block_p=1;
  154423. hi->noise_normalize_p=1;
  154424. hi->stereo_point_setting=hi->base_setting;
  154425. hi->lowpass_kHz=
  154426. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154427. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154428. setup->psy_ath_float[is+1]*ds;
  154429. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154430. setup->psy_ath_abs[is+1]*ds;
  154431. hi->amplitude_track_dBpersec=-6.;
  154432. hi->trigger_setting=hi->base_setting;
  154433. for(i=0;i<4;i++){
  154434. hi->block[i].tone_mask_setting=hi->base_setting;
  154435. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154436. hi->block[i].noise_bias_setting=hi->base_setting;
  154437. hi->block[i].noise_compand_setting=hi->base_setting;
  154438. }
  154439. return(ret);
  154440. }
  154441. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154442. long channels,
  154443. long rate,
  154444. float quality){
  154445. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154446. highlevel_encode_setup *hi=&ci->hi;
  154447. quality+=.0000001;
  154448. if(quality>=1.)quality=.9999;
  154449. get_setup_template(vi,channels,rate,quality,0);
  154450. if(!hi->setup)return OV_EIMPL;
  154451. return vorbis_encode_setup_setting(vi,channels,rate);
  154452. }
  154453. int vorbis_encode_init_vbr(vorbis_info *vi,
  154454. long channels,
  154455. long rate,
  154456. float base_quality /* 0. to 1. */
  154457. ){
  154458. int ret=0;
  154459. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154460. if(ret){
  154461. vorbis_info_clear(vi);
  154462. return ret;
  154463. }
  154464. ret=vorbis_encode_setup_init(vi);
  154465. if(ret)
  154466. vorbis_info_clear(vi);
  154467. return(ret);
  154468. }
  154469. int vorbis_encode_setup_managed(vorbis_info *vi,
  154470. long channels,
  154471. long rate,
  154472. long max_bitrate,
  154473. long nominal_bitrate,
  154474. long min_bitrate){
  154475. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154476. highlevel_encode_setup *hi=&ci->hi;
  154477. double tnominal=nominal_bitrate;
  154478. int ret=0;
  154479. if(nominal_bitrate<=0.){
  154480. if(max_bitrate>0.){
  154481. if(min_bitrate>0.)
  154482. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154483. else
  154484. nominal_bitrate=max_bitrate*.875;
  154485. }else{
  154486. if(min_bitrate>0.){
  154487. nominal_bitrate=min_bitrate;
  154488. }else{
  154489. return(OV_EINVAL);
  154490. }
  154491. }
  154492. }
  154493. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154494. if(!hi->setup)return OV_EIMPL;
  154495. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154496. if(ret){
  154497. vorbis_info_clear(vi);
  154498. return ret;
  154499. }
  154500. /* initialize management with sane defaults */
  154501. hi->managed=1;
  154502. hi->bitrate_min=min_bitrate;
  154503. hi->bitrate_max=max_bitrate;
  154504. hi->bitrate_av=tnominal;
  154505. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154506. hi->bitrate_reservoir=nominal_bitrate*2;
  154507. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154508. return(ret);
  154509. }
  154510. int vorbis_encode_init(vorbis_info *vi,
  154511. long channels,
  154512. long rate,
  154513. long max_bitrate,
  154514. long nominal_bitrate,
  154515. long min_bitrate){
  154516. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154517. max_bitrate,
  154518. nominal_bitrate,
  154519. min_bitrate);
  154520. if(ret){
  154521. vorbis_info_clear(vi);
  154522. return(ret);
  154523. }
  154524. ret=vorbis_encode_setup_init(vi);
  154525. if(ret)
  154526. vorbis_info_clear(vi);
  154527. return(ret);
  154528. }
  154529. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154530. if(vi){
  154531. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154532. highlevel_encode_setup *hi=&ci->hi;
  154533. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154534. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154535. switch(number){
  154536. /* now deprecated *****************/
  154537. case OV_ECTL_RATEMANAGE_GET:
  154538. {
  154539. struct ovectl_ratemanage_arg *ai=
  154540. (struct ovectl_ratemanage_arg *)arg;
  154541. ai->management_active=hi->managed;
  154542. ai->bitrate_hard_window=ai->bitrate_av_window=
  154543. (double)hi->bitrate_reservoir/vi->rate;
  154544. ai->bitrate_av_window_center=1.;
  154545. ai->bitrate_hard_min=hi->bitrate_min;
  154546. ai->bitrate_hard_max=hi->bitrate_max;
  154547. ai->bitrate_av_lo=hi->bitrate_av;
  154548. ai->bitrate_av_hi=hi->bitrate_av;
  154549. }
  154550. return(0);
  154551. /* now deprecated *****************/
  154552. case OV_ECTL_RATEMANAGE_SET:
  154553. {
  154554. struct ovectl_ratemanage_arg *ai=
  154555. (struct ovectl_ratemanage_arg *)arg;
  154556. if(ai==NULL){
  154557. hi->managed=0;
  154558. }else{
  154559. hi->managed=ai->management_active;
  154560. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154561. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154562. }
  154563. }
  154564. return 0;
  154565. /* now deprecated *****************/
  154566. case OV_ECTL_RATEMANAGE_AVG:
  154567. {
  154568. struct ovectl_ratemanage_arg *ai=
  154569. (struct ovectl_ratemanage_arg *)arg;
  154570. if(ai==NULL){
  154571. hi->bitrate_av=0;
  154572. }else{
  154573. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154574. }
  154575. }
  154576. return(0);
  154577. /* now deprecated *****************/
  154578. case OV_ECTL_RATEMANAGE_HARD:
  154579. {
  154580. struct ovectl_ratemanage_arg *ai=
  154581. (struct ovectl_ratemanage_arg *)arg;
  154582. if(ai==NULL){
  154583. hi->bitrate_min=0;
  154584. hi->bitrate_max=0;
  154585. }else{
  154586. hi->bitrate_min=ai->bitrate_hard_min;
  154587. hi->bitrate_max=ai->bitrate_hard_max;
  154588. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154589. (hi->bitrate_max+hi->bitrate_min)*.5;
  154590. }
  154591. if(hi->bitrate_reservoir<128.)
  154592. hi->bitrate_reservoir=128.;
  154593. }
  154594. return(0);
  154595. /* replacement ratemanage interface */
  154596. case OV_ECTL_RATEMANAGE2_GET:
  154597. {
  154598. struct ovectl_ratemanage2_arg *ai=
  154599. (struct ovectl_ratemanage2_arg *)arg;
  154600. if(ai==NULL)return OV_EINVAL;
  154601. ai->management_active=hi->managed;
  154602. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154603. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154604. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154605. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154606. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154607. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154608. }
  154609. return (0);
  154610. case OV_ECTL_RATEMANAGE2_SET:
  154611. {
  154612. struct ovectl_ratemanage2_arg *ai=
  154613. (struct ovectl_ratemanage2_arg *)arg;
  154614. if(ai==NULL){
  154615. hi->managed=0;
  154616. }else{
  154617. /* sanity check; only catch invariant violations */
  154618. if(ai->bitrate_limit_min_kbps>0 &&
  154619. ai->bitrate_average_kbps>0 &&
  154620. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154621. return OV_EINVAL;
  154622. if(ai->bitrate_limit_max_kbps>0 &&
  154623. ai->bitrate_average_kbps>0 &&
  154624. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154625. return OV_EINVAL;
  154626. if(ai->bitrate_limit_min_kbps>0 &&
  154627. ai->bitrate_limit_max_kbps>0 &&
  154628. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154629. return OV_EINVAL;
  154630. if(ai->bitrate_average_damping <= 0.)
  154631. return OV_EINVAL;
  154632. if(ai->bitrate_limit_reservoir_bits < 0)
  154633. return OV_EINVAL;
  154634. if(ai->bitrate_limit_reservoir_bias < 0.)
  154635. return OV_EINVAL;
  154636. if(ai->bitrate_limit_reservoir_bias > 1.)
  154637. return OV_EINVAL;
  154638. hi->managed=ai->management_active;
  154639. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154640. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154641. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154642. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154643. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154644. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154645. }
  154646. }
  154647. return 0;
  154648. case OV_ECTL_LOWPASS_GET:
  154649. {
  154650. double *farg=(double *)arg;
  154651. *farg=hi->lowpass_kHz;
  154652. }
  154653. return(0);
  154654. case OV_ECTL_LOWPASS_SET:
  154655. {
  154656. double *farg=(double *)arg;
  154657. hi->lowpass_kHz=*farg;
  154658. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154659. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154660. }
  154661. return(0);
  154662. case OV_ECTL_IBLOCK_GET:
  154663. {
  154664. double *farg=(double *)arg;
  154665. *farg=hi->impulse_noisetune;
  154666. }
  154667. return(0);
  154668. case OV_ECTL_IBLOCK_SET:
  154669. {
  154670. double *farg=(double *)arg;
  154671. hi->impulse_noisetune=*farg;
  154672. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154673. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154674. }
  154675. return(0);
  154676. }
  154677. return(OV_EIMPL);
  154678. }
  154679. return(OV_EINVAL);
  154680. }
  154681. #endif
  154682. /*** End of inlined file: vorbisenc.c ***/
  154683. /*** Start of inlined file: vorbisfile.c ***/
  154684. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154685. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154686. // tasks..
  154687. #if JUCE_MSVC
  154688. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154689. #endif
  154690. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154691. #if JUCE_USE_OGGVORBIS
  154692. #include <stdlib.h>
  154693. #include <stdio.h>
  154694. #include <errno.h>
  154695. #include <string.h>
  154696. #include <math.h>
  154697. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154698. one logical bitstream arranged end to end (the only form of Ogg
  154699. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154700. multiplexing] is not allowed in Vorbis) */
  154701. /* A Vorbis file can be played beginning to end (streamed) without
  154702. worrying ahead of time about chaining (see decoder_example.c). If
  154703. we have the whole file, however, and want random access
  154704. (seeking/scrubbing) or desire to know the total length/time of a
  154705. file, we need to account for the possibility of chaining. */
  154706. /* We can handle things a number of ways; we can determine the entire
  154707. bitstream structure right off the bat, or find pieces on demand.
  154708. This example determines and caches structure for the entire
  154709. bitstream, but builds a virtual decoder on the fly when moving
  154710. between links in the chain. */
  154711. /* There are also different ways to implement seeking. Enough
  154712. information exists in an Ogg bitstream to seek to
  154713. sample-granularity positions in the output. Or, one can seek by
  154714. picking some portion of the stream roughly in the desired area if
  154715. we only want coarse navigation through the stream. */
  154716. /*************************************************************************
  154717. * Many, many internal helpers. The intention is not to be confusing;
  154718. * rampant duplication and monolithic function implementation would be
  154719. * harder to understand anyway. The high level functions are last. Begin
  154720. * grokking near the end of the file */
  154721. /* read a little more data from the file/pipe into the ogg_sync framer
  154722. */
  154723. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154724. over 8k gets what they deserve */
  154725. static long _get_data(OggVorbis_File *vf){
  154726. errno=0;
  154727. if(vf->datasource){
  154728. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154729. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154730. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154731. if(bytes==0 && errno)return(-1);
  154732. return(bytes);
  154733. }else
  154734. return(0);
  154735. }
  154736. /* save a tiny smidge of verbosity to make the code more readable */
  154737. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154738. if(vf->datasource){
  154739. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154740. vf->offset=offset;
  154741. ogg_sync_reset(&vf->oy);
  154742. }else{
  154743. /* shouldn't happen unless someone writes a broken callback */
  154744. return;
  154745. }
  154746. }
  154747. /* The read/seek functions track absolute position within the stream */
  154748. /* from the head of the stream, get the next page. boundary specifies
  154749. if the function is allowed to fetch more data from the stream (and
  154750. how much) or only use internally buffered data.
  154751. boundary: -1) unbounded search
  154752. 0) read no additional data; use cached only
  154753. n) search for a new page beginning for n bytes
  154754. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154755. n) found a page at absolute offset n */
  154756. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154757. ogg_int64_t boundary){
  154758. if(boundary>0)boundary+=vf->offset;
  154759. while(1){
  154760. long more;
  154761. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154762. more=ogg_sync_pageseek(&vf->oy,og);
  154763. if(more<0){
  154764. /* skipped n bytes */
  154765. vf->offset-=more;
  154766. }else{
  154767. if(more==0){
  154768. /* send more paramedics */
  154769. if(!boundary)return(OV_FALSE);
  154770. {
  154771. long ret=_get_data(vf);
  154772. if(ret==0)return(OV_EOF);
  154773. if(ret<0)return(OV_EREAD);
  154774. }
  154775. }else{
  154776. /* got a page. Return the offset at the page beginning,
  154777. advance the internal offset past the page end */
  154778. ogg_int64_t ret=vf->offset;
  154779. vf->offset+=more;
  154780. return(ret);
  154781. }
  154782. }
  154783. }
  154784. }
  154785. /* find the latest page beginning before the current stream cursor
  154786. position. Much dirtier than the above as Ogg doesn't have any
  154787. backward search linkage. no 'readp' as it will certainly have to
  154788. read. */
  154789. /* returns offset or OV_EREAD, OV_FAULT */
  154790. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154791. ogg_int64_t begin=vf->offset;
  154792. ogg_int64_t end=begin;
  154793. ogg_int64_t ret;
  154794. ogg_int64_t offset=-1;
  154795. while(offset==-1){
  154796. begin-=CHUNKSIZE;
  154797. if(begin<0)
  154798. begin=0;
  154799. _seek_helper(vf,begin);
  154800. while(vf->offset<end){
  154801. ret=_get_next_page(vf,og,end-vf->offset);
  154802. if(ret==OV_EREAD)return(OV_EREAD);
  154803. if(ret<0){
  154804. break;
  154805. }else{
  154806. offset=ret;
  154807. }
  154808. }
  154809. }
  154810. /* we have the offset. Actually snork and hold the page now */
  154811. _seek_helper(vf,offset);
  154812. ret=_get_next_page(vf,og,CHUNKSIZE);
  154813. if(ret<0)
  154814. /* this shouldn't be possible */
  154815. return(OV_EFAULT);
  154816. return(offset);
  154817. }
  154818. /* finds each bitstream link one at a time using a bisection search
  154819. (has to begin by knowing the offset of the lb's initial page).
  154820. Recurses for each link so it can alloc the link storage after
  154821. finding them all, then unroll and fill the cache at the same time */
  154822. static int _bisect_forward_serialno(OggVorbis_File *vf,
  154823. ogg_int64_t begin,
  154824. ogg_int64_t searched,
  154825. ogg_int64_t end,
  154826. long currentno,
  154827. long m){
  154828. ogg_int64_t endsearched=end;
  154829. ogg_int64_t next=end;
  154830. ogg_page og;
  154831. ogg_int64_t ret;
  154832. /* the below guards against garbage seperating the last and
  154833. first pages of two links. */
  154834. while(searched<endsearched){
  154835. ogg_int64_t bisect;
  154836. if(endsearched-searched<CHUNKSIZE){
  154837. bisect=searched;
  154838. }else{
  154839. bisect=(searched+endsearched)/2;
  154840. }
  154841. _seek_helper(vf,bisect);
  154842. ret=_get_next_page(vf,&og,-1);
  154843. if(ret==OV_EREAD)return(OV_EREAD);
  154844. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  154845. endsearched=bisect;
  154846. if(ret>=0)next=ret;
  154847. }else{
  154848. searched=ret+og.header_len+og.body_len;
  154849. }
  154850. }
  154851. _seek_helper(vf,next);
  154852. ret=_get_next_page(vf,&og,-1);
  154853. if(ret==OV_EREAD)return(OV_EREAD);
  154854. if(searched>=end || ret<0){
  154855. vf->links=m+1;
  154856. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  154857. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  154858. vf->offsets[m+1]=searched;
  154859. }else{
  154860. ret=_bisect_forward_serialno(vf,next,vf->offset,
  154861. end,ogg_page_serialno(&og),m+1);
  154862. if(ret==OV_EREAD)return(OV_EREAD);
  154863. }
  154864. vf->offsets[m]=begin;
  154865. vf->serialnos[m]=currentno;
  154866. return(0);
  154867. }
  154868. /* uses the local ogg_stream storage in vf; this is important for
  154869. non-streaming input sources */
  154870. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  154871. long *serialno,ogg_page *og_ptr){
  154872. ogg_page og;
  154873. ogg_packet op;
  154874. int i,ret;
  154875. if(!og_ptr){
  154876. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  154877. if(llret==OV_EREAD)return(OV_EREAD);
  154878. if(llret<0)return OV_ENOTVORBIS;
  154879. og_ptr=&og;
  154880. }
  154881. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  154882. if(serialno)*serialno=vf->os.serialno;
  154883. vf->ready_state=STREAMSET;
  154884. /* extract the initial header from the first page and verify that the
  154885. Ogg bitstream is in fact Vorbis data */
  154886. vorbis_info_init(vi);
  154887. vorbis_comment_init(vc);
  154888. i=0;
  154889. while(i<3){
  154890. ogg_stream_pagein(&vf->os,og_ptr);
  154891. while(i<3){
  154892. int result=ogg_stream_packetout(&vf->os,&op);
  154893. if(result==0)break;
  154894. if(result==-1){
  154895. ret=OV_EBADHEADER;
  154896. goto bail_header;
  154897. }
  154898. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  154899. goto bail_header;
  154900. }
  154901. i++;
  154902. }
  154903. if(i<3)
  154904. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  154905. ret=OV_EBADHEADER;
  154906. goto bail_header;
  154907. }
  154908. }
  154909. return 0;
  154910. bail_header:
  154911. vorbis_info_clear(vi);
  154912. vorbis_comment_clear(vc);
  154913. vf->ready_state=OPENED;
  154914. return ret;
  154915. }
  154916. /* last step of the OggVorbis_File initialization; get all the
  154917. vorbis_info structs and PCM positions. Only called by the seekable
  154918. initialization (local stream storage is hacked slightly; pay
  154919. attention to how that's done) */
  154920. /* this is void and does not propogate errors up because we want to be
  154921. able to open and use damaged bitstreams as well as we can. Just
  154922. watch out for missing information for links in the OggVorbis_File
  154923. struct */
  154924. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  154925. ogg_page og;
  154926. int i;
  154927. ogg_int64_t ret;
  154928. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  154929. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  154930. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  154931. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  154932. for(i=0;i<vf->links;i++){
  154933. if(i==0){
  154934. /* we already grabbed the initial header earlier. Just set the offset */
  154935. vf->dataoffsets[i]=dataoffset;
  154936. _seek_helper(vf,dataoffset);
  154937. }else{
  154938. /* seek to the location of the initial header */
  154939. _seek_helper(vf,vf->offsets[i]);
  154940. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  154941. vf->dataoffsets[i]=-1;
  154942. }else{
  154943. vf->dataoffsets[i]=vf->offset;
  154944. }
  154945. }
  154946. /* fetch beginning PCM offset */
  154947. if(vf->dataoffsets[i]!=-1){
  154948. ogg_int64_t accumulated=0;
  154949. long lastblock=-1;
  154950. int result;
  154951. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  154952. while(1){
  154953. ogg_packet op;
  154954. ret=_get_next_page(vf,&og,-1);
  154955. if(ret<0)
  154956. /* this should not be possible unless the file is
  154957. truncated/mangled */
  154958. break;
  154959. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  154960. break;
  154961. /* count blocksizes of all frames in the page */
  154962. ogg_stream_pagein(&vf->os,&og);
  154963. while((result=ogg_stream_packetout(&vf->os,&op))){
  154964. if(result>0){ /* ignore holes */
  154965. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  154966. if(lastblock!=-1)
  154967. accumulated+=(lastblock+thisblock)>>2;
  154968. lastblock=thisblock;
  154969. }
  154970. }
  154971. if(ogg_page_granulepos(&og)!=-1){
  154972. /* pcm offset of last packet on the first audio page */
  154973. accumulated= ogg_page_granulepos(&og)-accumulated;
  154974. break;
  154975. }
  154976. }
  154977. /* less than zero? This is a stream with samples trimmed off
  154978. the beginning, a normal occurrence; set the offset to zero */
  154979. if(accumulated<0)accumulated=0;
  154980. vf->pcmlengths[i*2]=accumulated;
  154981. }
  154982. /* get the PCM length of this link. To do this,
  154983. get the last page of the stream */
  154984. {
  154985. ogg_int64_t end=vf->offsets[i+1];
  154986. _seek_helper(vf,end);
  154987. while(1){
  154988. ret=_get_prev_page(vf,&og);
  154989. if(ret<0){
  154990. /* this should not be possible */
  154991. vorbis_info_clear(vf->vi+i);
  154992. vorbis_comment_clear(vf->vc+i);
  154993. break;
  154994. }
  154995. if(ogg_page_granulepos(&og)!=-1){
  154996. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  154997. break;
  154998. }
  154999. vf->offset=ret;
  155000. }
  155001. }
  155002. }
  155003. }
  155004. static int _make_decode_ready(OggVorbis_File *vf){
  155005. if(vf->ready_state>STREAMSET)return 0;
  155006. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155007. if(vf->seekable){
  155008. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155009. return OV_EBADLINK;
  155010. }else{
  155011. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155012. return OV_EBADLINK;
  155013. }
  155014. vorbis_block_init(&vf->vd,&vf->vb);
  155015. vf->ready_state=INITSET;
  155016. vf->bittrack=0.f;
  155017. vf->samptrack=0.f;
  155018. return 0;
  155019. }
  155020. static int _open_seekable2(OggVorbis_File *vf){
  155021. long serialno=vf->current_serialno;
  155022. ogg_int64_t dataoffset=vf->offset, end;
  155023. ogg_page og;
  155024. /* we're partially open and have a first link header state in
  155025. storage in vf */
  155026. /* we can seek, so set out learning all about this file */
  155027. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155028. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155029. /* We get the offset for the last page of the physical bitstream.
  155030. Most OggVorbis files will contain a single logical bitstream */
  155031. end=_get_prev_page(vf,&og);
  155032. if(end<0)return(end);
  155033. /* more than one logical bitstream? */
  155034. if(ogg_page_serialno(&og)!=serialno){
  155035. /* Chained bitstream. Bisect-search each logical bitstream
  155036. section. Do so based on serial number only */
  155037. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155038. }else{
  155039. /* Only one logical bitstream */
  155040. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155041. }
  155042. /* the initial header memory is referenced by vf after; don't free it */
  155043. _prefetch_all_headers(vf,dataoffset);
  155044. return(ov_raw_seek(vf,0));
  155045. }
  155046. /* clear out the current logical bitstream decoder */
  155047. static void _decode_clear(OggVorbis_File *vf){
  155048. vorbis_dsp_clear(&vf->vd);
  155049. vorbis_block_clear(&vf->vb);
  155050. vf->ready_state=OPENED;
  155051. }
  155052. /* fetch and process a packet. Handles the case where we're at a
  155053. bitstream boundary and dumps the decoding machine. If the decoding
  155054. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155055. date (seek and read both use this. seek uses a special hack with
  155056. readp).
  155057. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155058. 0) need more data (only if readp==0)
  155059. 1) got a packet
  155060. */
  155061. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155062. ogg_packet *op_in,
  155063. int readp,
  155064. int spanp){
  155065. ogg_page og;
  155066. /* handle one packet. Try to fetch it from current stream state */
  155067. /* extract packets from page */
  155068. while(1){
  155069. /* process a packet if we can. If the machine isn't loaded,
  155070. neither is a page */
  155071. if(vf->ready_state==INITSET){
  155072. while(1) {
  155073. ogg_packet op;
  155074. ogg_packet *op_ptr=(op_in?op_in:&op);
  155075. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155076. ogg_int64_t granulepos;
  155077. op_in=NULL;
  155078. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155079. if(result>0){
  155080. /* got a packet. process it */
  155081. granulepos=op_ptr->granulepos;
  155082. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155083. header handling. The
  155084. header packets aren't
  155085. audio, so if/when we
  155086. submit them,
  155087. vorbis_synthesis will
  155088. reject them */
  155089. /* suck in the synthesis data and track bitrate */
  155090. {
  155091. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155092. /* for proper use of libvorbis within libvorbisfile,
  155093. oldsamples will always be zero. */
  155094. if(oldsamples)return(OV_EFAULT);
  155095. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155096. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155097. vf->bittrack+=op_ptr->bytes*8;
  155098. }
  155099. /* update the pcm offset. */
  155100. if(granulepos!=-1 && !op_ptr->e_o_s){
  155101. int link=(vf->seekable?vf->current_link:0);
  155102. int i,samples;
  155103. /* this packet has a pcm_offset on it (the last packet
  155104. completed on a page carries the offset) After processing
  155105. (above), we know the pcm position of the *last* sample
  155106. ready to be returned. Find the offset of the *first*
  155107. As an aside, this trick is inaccurate if we begin
  155108. reading anew right at the last page; the end-of-stream
  155109. granulepos declares the last frame in the stream, and the
  155110. last packet of the last page may be a partial frame.
  155111. So, we need a previous granulepos from an in-sequence page
  155112. to have a reference point. Thus the !op_ptr->e_o_s clause
  155113. above */
  155114. if(vf->seekable && link>0)
  155115. granulepos-=vf->pcmlengths[link*2];
  155116. if(granulepos<0)granulepos=0; /* actually, this
  155117. shouldn't be possible
  155118. here unless the stream
  155119. is very broken */
  155120. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155121. granulepos-=samples;
  155122. for(i=0;i<link;i++)
  155123. granulepos+=vf->pcmlengths[i*2+1];
  155124. vf->pcm_offset=granulepos;
  155125. }
  155126. return(1);
  155127. }
  155128. }
  155129. else
  155130. break;
  155131. }
  155132. }
  155133. if(vf->ready_state>=OPENED){
  155134. ogg_int64_t ret;
  155135. if(!readp)return(0);
  155136. if((ret=_get_next_page(vf,&og,-1))<0){
  155137. return(OV_EOF); /* eof.
  155138. leave unitialized */
  155139. }
  155140. /* bitrate tracking; add the header's bytes here, the body bytes
  155141. are done by packet above */
  155142. vf->bittrack+=og.header_len*8;
  155143. /* has our decoding just traversed a bitstream boundary? */
  155144. if(vf->ready_state==INITSET){
  155145. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155146. if(!spanp)
  155147. return(OV_EOF);
  155148. _decode_clear(vf);
  155149. if(!vf->seekable){
  155150. vorbis_info_clear(vf->vi);
  155151. vorbis_comment_clear(vf->vc);
  155152. }
  155153. }
  155154. }
  155155. }
  155156. /* Do we need to load a new machine before submitting the page? */
  155157. /* This is different in the seekable and non-seekable cases.
  155158. In the seekable case, we already have all the header
  155159. information loaded and cached; we just initialize the machine
  155160. with it and continue on our merry way.
  155161. In the non-seekable (streaming) case, we'll only be at a
  155162. boundary if we just left the previous logical bitstream and
  155163. we're now nominally at the header of the next bitstream
  155164. */
  155165. if(vf->ready_state!=INITSET){
  155166. int link;
  155167. if(vf->ready_state<STREAMSET){
  155168. if(vf->seekable){
  155169. vf->current_serialno=ogg_page_serialno(&og);
  155170. /* match the serialno to bitstream section. We use this rather than
  155171. offset positions to avoid problems near logical bitstream
  155172. boundaries */
  155173. for(link=0;link<vf->links;link++)
  155174. if(vf->serialnos[link]==vf->current_serialno)break;
  155175. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155176. stream. error out,
  155177. leave machine
  155178. uninitialized */
  155179. vf->current_link=link;
  155180. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155181. vf->ready_state=STREAMSET;
  155182. }else{
  155183. /* we're streaming */
  155184. /* fetch the three header packets, build the info struct */
  155185. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155186. if(ret)return(ret);
  155187. vf->current_link++;
  155188. link=0;
  155189. }
  155190. }
  155191. {
  155192. int ret=_make_decode_ready(vf);
  155193. if(ret<0)return ret;
  155194. }
  155195. }
  155196. ogg_stream_pagein(&vf->os,&og);
  155197. }
  155198. }
  155199. /* if, eg, 64 bit stdio is configured by default, this will build with
  155200. fseek64 */
  155201. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155202. if(f==NULL)return(-1);
  155203. return fseek(f,off,whence);
  155204. }
  155205. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155206. long ibytes, ov_callbacks callbacks){
  155207. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155208. int ret;
  155209. memset(vf,0,sizeof(*vf));
  155210. vf->datasource=f;
  155211. vf->callbacks = callbacks;
  155212. /* init the framing state */
  155213. ogg_sync_init(&vf->oy);
  155214. /* perhaps some data was previously read into a buffer for testing
  155215. against other stream types. Allow initialization from this
  155216. previously read data (as we may be reading from a non-seekable
  155217. stream) */
  155218. if(initial){
  155219. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155220. memcpy(buffer,initial,ibytes);
  155221. ogg_sync_wrote(&vf->oy,ibytes);
  155222. }
  155223. /* can we seek? Stevens suggests the seek test was portable */
  155224. if(offsettest!=-1)vf->seekable=1;
  155225. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155226. entry for partial open */
  155227. vf->links=1;
  155228. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155229. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155230. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155231. /* Try to fetch the headers, maintaining all the storage */
  155232. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155233. vf->datasource=NULL;
  155234. ov_clear(vf);
  155235. }else
  155236. vf->ready_state=PARTOPEN;
  155237. return(ret);
  155238. }
  155239. static int _ov_open2(OggVorbis_File *vf){
  155240. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155241. vf->ready_state=OPENED;
  155242. if(vf->seekable){
  155243. int ret=_open_seekable2(vf);
  155244. if(ret){
  155245. vf->datasource=NULL;
  155246. ov_clear(vf);
  155247. }
  155248. return(ret);
  155249. }else
  155250. vf->ready_state=STREAMSET;
  155251. return 0;
  155252. }
  155253. /* clear out the OggVorbis_File struct */
  155254. int ov_clear(OggVorbis_File *vf){
  155255. if(vf){
  155256. vorbis_block_clear(&vf->vb);
  155257. vorbis_dsp_clear(&vf->vd);
  155258. ogg_stream_clear(&vf->os);
  155259. if(vf->vi && vf->links){
  155260. int i;
  155261. for(i=0;i<vf->links;i++){
  155262. vorbis_info_clear(vf->vi+i);
  155263. vorbis_comment_clear(vf->vc+i);
  155264. }
  155265. _ogg_free(vf->vi);
  155266. _ogg_free(vf->vc);
  155267. }
  155268. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155269. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155270. if(vf->serialnos)_ogg_free(vf->serialnos);
  155271. if(vf->offsets)_ogg_free(vf->offsets);
  155272. ogg_sync_clear(&vf->oy);
  155273. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155274. memset(vf,0,sizeof(*vf));
  155275. }
  155276. #ifdef DEBUG_LEAKS
  155277. _VDBG_dump();
  155278. #endif
  155279. return(0);
  155280. }
  155281. /* inspects the OggVorbis file and finds/documents all the logical
  155282. bitstreams contained in it. Tries to be tolerant of logical
  155283. bitstream sections that are truncated/woogie.
  155284. return: -1) error
  155285. 0) OK
  155286. */
  155287. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155288. ov_callbacks callbacks){
  155289. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155290. if(ret)return ret;
  155291. return _ov_open2(vf);
  155292. }
  155293. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155294. ov_callbacks callbacks = {
  155295. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155296. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155297. (int (*)(void *)) fclose,
  155298. (long (*)(void *)) ftell
  155299. };
  155300. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155301. }
  155302. /* cheap hack for game usage where downsampling is desirable; there's
  155303. no need for SRC as we can just do it cheaply in libvorbis. */
  155304. int ov_halfrate(OggVorbis_File *vf,int flag){
  155305. int i;
  155306. if(vf->vi==NULL)return OV_EINVAL;
  155307. if(!vf->seekable)return OV_EINVAL;
  155308. if(vf->ready_state>=STREAMSET)
  155309. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155310. will be able to swap this on the fly, but
  155311. for now dumping the decode machine is needed
  155312. to reinit the MDCT lookups. 1.1 libvorbis
  155313. is planned to be able to switch on the fly */
  155314. for(i=0;i<vf->links;i++){
  155315. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155316. ov_halfrate(vf,0);
  155317. return OV_EINVAL;
  155318. }
  155319. }
  155320. return 0;
  155321. }
  155322. int ov_halfrate_p(OggVorbis_File *vf){
  155323. if(vf->vi==NULL)return OV_EINVAL;
  155324. return vorbis_synthesis_halfrate_p(vf->vi);
  155325. }
  155326. /* Only partially open the vorbis file; test for Vorbisness, and load
  155327. the headers for the first chain. Do not seek (although test for
  155328. seekability). Use ov_test_open to finish opening the file, else
  155329. ov_clear to close/free it. Same return codes as open. */
  155330. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155331. ov_callbacks callbacks)
  155332. {
  155333. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155334. }
  155335. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155336. ov_callbacks callbacks = {
  155337. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155338. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155339. (int (*)(void *)) fclose,
  155340. (long (*)(void *)) ftell
  155341. };
  155342. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155343. }
  155344. int ov_test_open(OggVorbis_File *vf){
  155345. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155346. return _ov_open2(vf);
  155347. }
  155348. /* How many logical bitstreams in this physical bitstream? */
  155349. long ov_streams(OggVorbis_File *vf){
  155350. return vf->links;
  155351. }
  155352. /* Is the FILE * associated with vf seekable? */
  155353. long ov_seekable(OggVorbis_File *vf){
  155354. return vf->seekable;
  155355. }
  155356. /* returns the bitrate for a given logical bitstream or the entire
  155357. physical bitstream. If the file is open for random access, it will
  155358. find the *actual* average bitrate. If the file is streaming, it
  155359. returns the nominal bitrate (if set) else the average of the
  155360. upper/lower bounds (if set) else -1 (unset).
  155361. If you want the actual bitrate field settings, get them from the
  155362. vorbis_info structs */
  155363. long ov_bitrate(OggVorbis_File *vf,int i){
  155364. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155365. if(i>=vf->links)return(OV_EINVAL);
  155366. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155367. if(i<0){
  155368. ogg_int64_t bits=0;
  155369. int i;
  155370. float br;
  155371. for(i=0;i<vf->links;i++)
  155372. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155373. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155374. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155375. * so this is slightly transformed to make it work.
  155376. */
  155377. br = bits/ov_time_total(vf,-1);
  155378. return(rint(br));
  155379. }else{
  155380. if(vf->seekable){
  155381. /* return the actual bitrate */
  155382. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155383. }else{
  155384. /* return nominal if set */
  155385. if(vf->vi[i].bitrate_nominal>0){
  155386. return vf->vi[i].bitrate_nominal;
  155387. }else{
  155388. if(vf->vi[i].bitrate_upper>0){
  155389. if(vf->vi[i].bitrate_lower>0){
  155390. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155391. }else{
  155392. return vf->vi[i].bitrate_upper;
  155393. }
  155394. }
  155395. return(OV_FALSE);
  155396. }
  155397. }
  155398. }
  155399. }
  155400. /* returns the actual bitrate since last call. returns -1 if no
  155401. additional data to offer since last call (or at beginning of stream),
  155402. EINVAL if stream is only partially open
  155403. */
  155404. long ov_bitrate_instant(OggVorbis_File *vf){
  155405. int link=(vf->seekable?vf->current_link:0);
  155406. long ret;
  155407. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155408. if(vf->samptrack==0)return(OV_FALSE);
  155409. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155410. vf->bittrack=0.f;
  155411. vf->samptrack=0.f;
  155412. return(ret);
  155413. }
  155414. /* Guess */
  155415. long ov_serialnumber(OggVorbis_File *vf,int i){
  155416. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155417. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155418. if(i<0){
  155419. return(vf->current_serialno);
  155420. }else{
  155421. return(vf->serialnos[i]);
  155422. }
  155423. }
  155424. /* returns: total raw (compressed) length of content if i==-1
  155425. raw (compressed) length of that logical bitstream for i==0 to n
  155426. OV_EINVAL if the stream is not seekable (we can't know the length)
  155427. or if stream is only partially open
  155428. */
  155429. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155430. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155431. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155432. if(i<0){
  155433. ogg_int64_t acc=0;
  155434. int i;
  155435. for(i=0;i<vf->links;i++)
  155436. acc+=ov_raw_total(vf,i);
  155437. return(acc);
  155438. }else{
  155439. return(vf->offsets[i+1]-vf->offsets[i]);
  155440. }
  155441. }
  155442. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155443. (samples) of that logical bitstream for i==0 to n
  155444. OV_EINVAL if the stream is not seekable (we can't know the
  155445. length) or only partially open
  155446. */
  155447. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155448. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155449. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155450. if(i<0){
  155451. ogg_int64_t acc=0;
  155452. int i;
  155453. for(i=0;i<vf->links;i++)
  155454. acc+=ov_pcm_total(vf,i);
  155455. return(acc);
  155456. }else{
  155457. return(vf->pcmlengths[i*2+1]);
  155458. }
  155459. }
  155460. /* returns: total seconds of content if i==-1
  155461. seconds in that logical bitstream for i==0 to n
  155462. OV_EINVAL if the stream is not seekable (we can't know the
  155463. length) or only partially open
  155464. */
  155465. double ov_time_total(OggVorbis_File *vf,int i){
  155466. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155467. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155468. if(i<0){
  155469. double acc=0;
  155470. int i;
  155471. for(i=0;i<vf->links;i++)
  155472. acc+=ov_time_total(vf,i);
  155473. return(acc);
  155474. }else{
  155475. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155476. }
  155477. }
  155478. /* seek to an offset relative to the *compressed* data. This also
  155479. scans packets to update the PCM cursor. It will cross a logical
  155480. bitstream boundary, but only if it can't get any packets out of the
  155481. tail of the bitstream we seek to (so no surprises).
  155482. returns zero on success, nonzero on failure */
  155483. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155484. ogg_stream_state work_os;
  155485. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155486. if(!vf->seekable)
  155487. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155488. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155489. /* don't yet clear out decoding machine (if it's initialized), in
  155490. the case we're in the same link. Restart the decode lapping, and
  155491. let _fetch_and_process_packet deal with a potential bitstream
  155492. boundary */
  155493. vf->pcm_offset=-1;
  155494. ogg_stream_reset_serialno(&vf->os,
  155495. vf->current_serialno); /* must set serialno */
  155496. vorbis_synthesis_restart(&vf->vd);
  155497. _seek_helper(vf,pos);
  155498. /* we need to make sure the pcm_offset is set, but we don't want to
  155499. advance the raw cursor past good packets just to get to the first
  155500. with a granulepos. That's not equivalent behavior to beginning
  155501. decoding as immediately after the seek position as possible.
  155502. So, a hack. We use two stream states; a local scratch state and
  155503. the shared vf->os stream state. We use the local state to
  155504. scan, and the shared state as a buffer for later decode.
  155505. Unfortuantely, on the last page we still advance to last packet
  155506. because the granulepos on the last page is not necessarily on a
  155507. packet boundary, and we need to make sure the granpos is
  155508. correct.
  155509. */
  155510. {
  155511. ogg_page og;
  155512. ogg_packet op;
  155513. int lastblock=0;
  155514. int accblock=0;
  155515. int thisblock;
  155516. int eosflag;
  155517. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155518. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155519. return from not necessarily
  155520. starting from the beginning */
  155521. while(1){
  155522. if(vf->ready_state>=STREAMSET){
  155523. /* snarf/scan a packet if we can */
  155524. int result=ogg_stream_packetout(&work_os,&op);
  155525. if(result>0){
  155526. if(vf->vi[vf->current_link].codec_setup){
  155527. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155528. if(thisblock<0){
  155529. ogg_stream_packetout(&vf->os,NULL);
  155530. thisblock=0;
  155531. }else{
  155532. if(eosflag)
  155533. ogg_stream_packetout(&vf->os,NULL);
  155534. else
  155535. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155536. }
  155537. if(op.granulepos!=-1){
  155538. int i,link=vf->current_link;
  155539. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155540. if(granulepos<0)granulepos=0;
  155541. for(i=0;i<link;i++)
  155542. granulepos+=vf->pcmlengths[i*2+1];
  155543. vf->pcm_offset=granulepos-accblock;
  155544. break;
  155545. }
  155546. lastblock=thisblock;
  155547. continue;
  155548. }else
  155549. ogg_stream_packetout(&vf->os,NULL);
  155550. }
  155551. }
  155552. if(!lastblock){
  155553. if(_get_next_page(vf,&og,-1)<0){
  155554. vf->pcm_offset=ov_pcm_total(vf,-1);
  155555. break;
  155556. }
  155557. }else{
  155558. /* huh? Bogus stream with packets but no granulepos */
  155559. vf->pcm_offset=-1;
  155560. break;
  155561. }
  155562. /* has our decoding just traversed a bitstream boundary? */
  155563. if(vf->ready_state>=STREAMSET)
  155564. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155565. _decode_clear(vf); /* clear out stream state */
  155566. ogg_stream_clear(&work_os);
  155567. }
  155568. if(vf->ready_state<STREAMSET){
  155569. int link;
  155570. vf->current_serialno=ogg_page_serialno(&og);
  155571. for(link=0;link<vf->links;link++)
  155572. if(vf->serialnos[link]==vf->current_serialno)break;
  155573. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155574. error out, leave
  155575. machine uninitialized */
  155576. vf->current_link=link;
  155577. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155578. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155579. vf->ready_state=STREAMSET;
  155580. }
  155581. ogg_stream_pagein(&vf->os,&og);
  155582. ogg_stream_pagein(&work_os,&og);
  155583. eosflag=ogg_page_eos(&og);
  155584. }
  155585. }
  155586. ogg_stream_clear(&work_os);
  155587. vf->bittrack=0.f;
  155588. vf->samptrack=0.f;
  155589. return(0);
  155590. seek_error:
  155591. /* dump the machine so we're in a known state */
  155592. vf->pcm_offset=-1;
  155593. ogg_stream_clear(&work_os);
  155594. _decode_clear(vf);
  155595. return OV_EBADLINK;
  155596. }
  155597. /* Page granularity seek (faster than sample granularity because we
  155598. don't do the last bit of decode to find a specific sample).
  155599. Seek to the last [granule marked] page preceeding the specified pos
  155600. location, such that decoding past the returned point will quickly
  155601. arrive at the requested position. */
  155602. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155603. int link=-1;
  155604. ogg_int64_t result=0;
  155605. ogg_int64_t total=ov_pcm_total(vf,-1);
  155606. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155607. if(!vf->seekable)return(OV_ENOSEEK);
  155608. if(pos<0 || pos>total)return(OV_EINVAL);
  155609. /* which bitstream section does this pcm offset occur in? */
  155610. for(link=vf->links-1;link>=0;link--){
  155611. total-=vf->pcmlengths[link*2+1];
  155612. if(pos>=total)break;
  155613. }
  155614. /* search within the logical bitstream for the page with the highest
  155615. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155616. missing pages or incorrect frame number information in the
  155617. bitstream could make our task impossible. Account for that (it
  155618. would be an error condition) */
  155619. /* new search algorithm by HB (Nicholas Vinen) */
  155620. {
  155621. ogg_int64_t end=vf->offsets[link+1];
  155622. ogg_int64_t begin=vf->offsets[link];
  155623. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155624. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155625. ogg_int64_t target=pos-total+begintime;
  155626. ogg_int64_t best=begin;
  155627. ogg_page og;
  155628. while(begin<end){
  155629. ogg_int64_t bisect;
  155630. if(end-begin<CHUNKSIZE){
  155631. bisect=begin;
  155632. }else{
  155633. /* take a (pretty decent) guess. */
  155634. bisect=begin +
  155635. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155636. if(bisect<=begin)
  155637. bisect=begin+1;
  155638. }
  155639. _seek_helper(vf,bisect);
  155640. while(begin<end){
  155641. result=_get_next_page(vf,&og,end-vf->offset);
  155642. if(result==OV_EREAD) goto seek_error;
  155643. if(result<0){
  155644. if(bisect<=begin+1)
  155645. end=begin; /* found it */
  155646. else{
  155647. if(bisect==0) goto seek_error;
  155648. bisect-=CHUNKSIZE;
  155649. if(bisect<=begin)bisect=begin+1;
  155650. _seek_helper(vf,bisect);
  155651. }
  155652. }else{
  155653. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155654. if(granulepos==-1)continue;
  155655. if(granulepos<target){
  155656. best=result; /* raw offset of packet with granulepos */
  155657. begin=vf->offset; /* raw offset of next page */
  155658. begintime=granulepos;
  155659. if(target-begintime>44100)break;
  155660. bisect=begin; /* *not* begin + 1 */
  155661. }else{
  155662. if(bisect<=begin+1)
  155663. end=begin; /* found it */
  155664. else{
  155665. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155666. end=result;
  155667. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155668. if(bisect<=begin)bisect=begin+1;
  155669. _seek_helper(vf,bisect);
  155670. }else{
  155671. end=result;
  155672. endtime=granulepos;
  155673. break;
  155674. }
  155675. }
  155676. }
  155677. }
  155678. }
  155679. }
  155680. /* found our page. seek to it, update pcm offset. Easier case than
  155681. raw_seek, don't keep packets preceeding granulepos. */
  155682. {
  155683. ogg_page og;
  155684. ogg_packet op;
  155685. /* seek */
  155686. _seek_helper(vf,best);
  155687. vf->pcm_offset=-1;
  155688. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155689. if(link!=vf->current_link){
  155690. /* Different link; dump entire decode machine */
  155691. _decode_clear(vf);
  155692. vf->current_link=link;
  155693. vf->current_serialno=ogg_page_serialno(&og);
  155694. vf->ready_state=STREAMSET;
  155695. }else{
  155696. vorbis_synthesis_restart(&vf->vd);
  155697. }
  155698. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155699. ogg_stream_pagein(&vf->os,&og);
  155700. /* pull out all but last packet; the one with granulepos */
  155701. while(1){
  155702. result=ogg_stream_packetpeek(&vf->os,&op);
  155703. if(result==0){
  155704. /* !!! the packet finishing this page originated on a
  155705. preceeding page. Keep fetching previous pages until we
  155706. get one with a granulepos or without the 'continued' flag
  155707. set. Then just use raw_seek for simplicity. */
  155708. _seek_helper(vf,best);
  155709. while(1){
  155710. result=_get_prev_page(vf,&og);
  155711. if(result<0) goto seek_error;
  155712. if(ogg_page_granulepos(&og)>-1 ||
  155713. !ogg_page_continued(&og)){
  155714. return ov_raw_seek(vf,result);
  155715. }
  155716. vf->offset=result;
  155717. }
  155718. }
  155719. if(result<0){
  155720. result = OV_EBADPACKET;
  155721. goto seek_error;
  155722. }
  155723. if(op.granulepos!=-1){
  155724. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155725. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155726. vf->pcm_offset+=total;
  155727. break;
  155728. }else
  155729. result=ogg_stream_packetout(&vf->os,NULL);
  155730. }
  155731. }
  155732. }
  155733. /* verify result */
  155734. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155735. result=OV_EFAULT;
  155736. goto seek_error;
  155737. }
  155738. vf->bittrack=0.f;
  155739. vf->samptrack=0.f;
  155740. return(0);
  155741. seek_error:
  155742. /* dump machine so we're in a known state */
  155743. vf->pcm_offset=-1;
  155744. _decode_clear(vf);
  155745. return (int)result;
  155746. }
  155747. /* seek to a sample offset relative to the decompressed pcm stream
  155748. returns zero on success, nonzero on failure */
  155749. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155750. int thisblock,lastblock=0;
  155751. int ret=ov_pcm_seek_page(vf,pos);
  155752. if(ret<0)return(ret);
  155753. if((ret=_make_decode_ready(vf)))return ret;
  155754. /* discard leading packets we don't need for the lapping of the
  155755. position we want; don't decode them */
  155756. while(1){
  155757. ogg_packet op;
  155758. ogg_page og;
  155759. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155760. if(ret>0){
  155761. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155762. if(thisblock<0){
  155763. ogg_stream_packetout(&vf->os,NULL);
  155764. continue; /* non audio packet */
  155765. }
  155766. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155767. if(vf->pcm_offset+((thisblock+
  155768. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155769. /* remove the packet from packet queue and track its granulepos */
  155770. ogg_stream_packetout(&vf->os,NULL);
  155771. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155772. only tracking, no
  155773. pcm_decode */
  155774. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155775. /* end of logical stream case is hard, especially with exact
  155776. length positioning. */
  155777. if(op.granulepos>-1){
  155778. int i;
  155779. /* always believe the stream markers */
  155780. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155781. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155782. for(i=0;i<vf->current_link;i++)
  155783. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155784. }
  155785. lastblock=thisblock;
  155786. }else{
  155787. if(ret<0 && ret!=OV_HOLE)break;
  155788. /* suck in a new page */
  155789. if(_get_next_page(vf,&og,-1)<0)break;
  155790. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155791. if(vf->ready_state<STREAMSET){
  155792. int link;
  155793. vf->current_serialno=ogg_page_serialno(&og);
  155794. for(link=0;link<vf->links;link++)
  155795. if(vf->serialnos[link]==vf->current_serialno)break;
  155796. if(link==vf->links)return(OV_EBADLINK);
  155797. vf->current_link=link;
  155798. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155799. vf->ready_state=STREAMSET;
  155800. ret=_make_decode_ready(vf);
  155801. if(ret)return ret;
  155802. lastblock=0;
  155803. }
  155804. ogg_stream_pagein(&vf->os,&og);
  155805. }
  155806. }
  155807. vf->bittrack=0.f;
  155808. vf->samptrack=0.f;
  155809. /* discard samples until we reach the desired position. Crossing a
  155810. logical bitstream boundary with abandon is OK. */
  155811. while(vf->pcm_offset<pos){
  155812. ogg_int64_t target=pos-vf->pcm_offset;
  155813. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155814. if(samples>target)samples=target;
  155815. vorbis_synthesis_read(&vf->vd,samples);
  155816. vf->pcm_offset+=samples;
  155817. if(samples<target)
  155818. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155819. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  155820. }
  155821. return 0;
  155822. }
  155823. /* seek to a playback time relative to the decompressed pcm stream
  155824. returns zero on success, nonzero on failure */
  155825. int ov_time_seek(OggVorbis_File *vf,double seconds){
  155826. /* translate time to PCM position and call ov_pcm_seek */
  155827. int link=-1;
  155828. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155829. double time_total=ov_time_total(vf,-1);
  155830. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155831. if(!vf->seekable)return(OV_ENOSEEK);
  155832. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155833. /* which bitstream section does this time offset occur in? */
  155834. for(link=vf->links-1;link>=0;link--){
  155835. pcm_total-=vf->pcmlengths[link*2+1];
  155836. time_total-=ov_time_total(vf,link);
  155837. if(seconds>=time_total)break;
  155838. }
  155839. /* enough information to convert time offset to pcm offset */
  155840. {
  155841. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155842. return(ov_pcm_seek(vf,target));
  155843. }
  155844. }
  155845. /* page-granularity version of ov_time_seek
  155846. returns zero on success, nonzero on failure */
  155847. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  155848. /* translate time to PCM position and call ov_pcm_seek */
  155849. int link=-1;
  155850. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155851. double time_total=ov_time_total(vf,-1);
  155852. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155853. if(!vf->seekable)return(OV_ENOSEEK);
  155854. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155855. /* which bitstream section does this time offset occur in? */
  155856. for(link=vf->links-1;link>=0;link--){
  155857. pcm_total-=vf->pcmlengths[link*2+1];
  155858. time_total-=ov_time_total(vf,link);
  155859. if(seconds>=time_total)break;
  155860. }
  155861. /* enough information to convert time offset to pcm offset */
  155862. {
  155863. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155864. return(ov_pcm_seek_page(vf,target));
  155865. }
  155866. }
  155867. /* tell the current stream offset cursor. Note that seek followed by
  155868. tell will likely not give the set offset due to caching */
  155869. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  155870. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155871. return(vf->offset);
  155872. }
  155873. /* return PCM offset (sample) of next PCM sample to be read */
  155874. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  155875. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155876. return(vf->pcm_offset);
  155877. }
  155878. /* return time offset (seconds) of next PCM sample to be read */
  155879. double ov_time_tell(OggVorbis_File *vf){
  155880. int link=0;
  155881. ogg_int64_t pcm_total=0;
  155882. double time_total=0.f;
  155883. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155884. if(vf->seekable){
  155885. pcm_total=ov_pcm_total(vf,-1);
  155886. time_total=ov_time_total(vf,-1);
  155887. /* which bitstream section does this time offset occur in? */
  155888. for(link=vf->links-1;link>=0;link--){
  155889. pcm_total-=vf->pcmlengths[link*2+1];
  155890. time_total-=ov_time_total(vf,link);
  155891. if(vf->pcm_offset>=pcm_total)break;
  155892. }
  155893. }
  155894. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  155895. }
  155896. /* link: -1) return the vorbis_info struct for the bitstream section
  155897. currently being decoded
  155898. 0-n) to request information for a specific bitstream section
  155899. In the case of a non-seekable bitstream, any call returns the
  155900. current bitstream. NULL in the case that the machine is not
  155901. initialized */
  155902. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  155903. if(vf->seekable){
  155904. if(link<0)
  155905. if(vf->ready_state>=STREAMSET)
  155906. return vf->vi+vf->current_link;
  155907. else
  155908. return vf->vi;
  155909. else
  155910. if(link>=vf->links)
  155911. return NULL;
  155912. else
  155913. return vf->vi+link;
  155914. }else{
  155915. return vf->vi;
  155916. }
  155917. }
  155918. /* grr, strong typing, grr, no templates/inheritence, grr */
  155919. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  155920. if(vf->seekable){
  155921. if(link<0)
  155922. if(vf->ready_state>=STREAMSET)
  155923. return vf->vc+vf->current_link;
  155924. else
  155925. return vf->vc;
  155926. else
  155927. if(link>=vf->links)
  155928. return NULL;
  155929. else
  155930. return vf->vc+link;
  155931. }else{
  155932. return vf->vc;
  155933. }
  155934. }
  155935. static int host_is_big_endian() {
  155936. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  155937. unsigned char *bytewise = (unsigned char *)&pattern;
  155938. if (bytewise[0] == 0xfe) return 1;
  155939. return 0;
  155940. }
  155941. /* up to this point, everything could more or less hide the multiple
  155942. logical bitstream nature of chaining from the toplevel application
  155943. if the toplevel application didn't particularly care. However, at
  155944. the point that we actually read audio back, the multiple-section
  155945. nature must surface: Multiple bitstream sections do not necessarily
  155946. have to have the same number of channels or sampling rate.
  155947. ov_read returns the sequential logical bitstream number currently
  155948. being decoded along with the PCM data in order that the toplevel
  155949. application can take action on channel/sample rate changes. This
  155950. number will be incremented even for streamed (non-seekable) streams
  155951. (for seekable streams, it represents the actual logical bitstream
  155952. index within the physical bitstream. Note that the accessor
  155953. functions above are aware of this dichotomy).
  155954. input values: buffer) a buffer to hold packed PCM data for return
  155955. length) the byte length requested to be placed into buffer
  155956. bigendianp) should the data be packed LSB first (0) or
  155957. MSB first (1)
  155958. word) word size for output. currently 1 (byte) or
  155959. 2 (16 bit short)
  155960. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155961. 0) EOF
  155962. n) number of bytes of PCM actually returned. The
  155963. below works on a packet-by-packet basis, so the
  155964. return length is not related to the 'length' passed
  155965. in, just guaranteed to fit.
  155966. *section) set to the logical bitstream number */
  155967. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  155968. int bigendianp,int word,int sgned,int *bitstream){
  155969. int i,j;
  155970. int host_endian = host_is_big_endian();
  155971. float **pcm;
  155972. long samples;
  155973. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155974. while(1){
  155975. if(vf->ready_state==INITSET){
  155976. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155977. if(samples)break;
  155978. }
  155979. /* suck in another packet */
  155980. {
  155981. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155982. if(ret==OV_EOF)
  155983. return(0);
  155984. if(ret<=0)
  155985. return(ret);
  155986. }
  155987. }
  155988. if(samples>0){
  155989. /* yay! proceed to pack data into the byte buffer */
  155990. long channels=ov_info(vf,-1)->channels;
  155991. long bytespersample=word * channels;
  155992. vorbis_fpu_control fpu;
  155993. (void) fpu; // (to avoid a warning about it being unused)
  155994. if(samples>length/bytespersample)samples=length/bytespersample;
  155995. if(samples <= 0)
  155996. return OV_EINVAL;
  155997. /* a tight loop to pack each size */
  155998. {
  155999. int val;
  156000. if(word==1){
  156001. int off=(sgned?0:128);
  156002. vorbis_fpu_setround(&fpu);
  156003. for(j=0;j<samples;j++)
  156004. for(i=0;i<channels;i++){
  156005. val=vorbis_ftoi(pcm[i][j]*128.f);
  156006. if(val>127)val=127;
  156007. else if(val<-128)val=-128;
  156008. *buffer++=val+off;
  156009. }
  156010. vorbis_fpu_restore(fpu);
  156011. }else{
  156012. int off=(sgned?0:32768);
  156013. if(host_endian==bigendianp){
  156014. if(sgned){
  156015. vorbis_fpu_setround(&fpu);
  156016. for(i=0;i<channels;i++) { /* It's faster in this order */
  156017. float *src=pcm[i];
  156018. short *dest=((short *)buffer)+i;
  156019. for(j=0;j<samples;j++) {
  156020. val=vorbis_ftoi(src[j]*32768.f);
  156021. if(val>32767)val=32767;
  156022. else if(val<-32768)val=-32768;
  156023. *dest=val;
  156024. dest+=channels;
  156025. }
  156026. }
  156027. vorbis_fpu_restore(fpu);
  156028. }else{
  156029. vorbis_fpu_setround(&fpu);
  156030. for(i=0;i<channels;i++) {
  156031. float *src=pcm[i];
  156032. short *dest=((short *)buffer)+i;
  156033. for(j=0;j<samples;j++) {
  156034. val=vorbis_ftoi(src[j]*32768.f);
  156035. if(val>32767)val=32767;
  156036. else if(val<-32768)val=-32768;
  156037. *dest=val+off;
  156038. dest+=channels;
  156039. }
  156040. }
  156041. vorbis_fpu_restore(fpu);
  156042. }
  156043. }else if(bigendianp){
  156044. vorbis_fpu_setround(&fpu);
  156045. for(j=0;j<samples;j++)
  156046. for(i=0;i<channels;i++){
  156047. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156048. if(val>32767)val=32767;
  156049. else if(val<-32768)val=-32768;
  156050. val+=off;
  156051. *buffer++=(val>>8);
  156052. *buffer++=(val&0xff);
  156053. }
  156054. vorbis_fpu_restore(fpu);
  156055. }else{
  156056. int val;
  156057. vorbis_fpu_setround(&fpu);
  156058. for(j=0;j<samples;j++)
  156059. for(i=0;i<channels;i++){
  156060. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156061. if(val>32767)val=32767;
  156062. else if(val<-32768)val=-32768;
  156063. val+=off;
  156064. *buffer++=(val&0xff);
  156065. *buffer++=(val>>8);
  156066. }
  156067. vorbis_fpu_restore(fpu);
  156068. }
  156069. }
  156070. }
  156071. vorbis_synthesis_read(&vf->vd,samples);
  156072. vf->pcm_offset+=samples;
  156073. if(bitstream)*bitstream=vf->current_link;
  156074. return(samples*bytespersample);
  156075. }else{
  156076. return(samples);
  156077. }
  156078. }
  156079. /* input values: pcm_channels) a float vector per channel of output
  156080. length) the sample length being read by the app
  156081. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156082. 0) EOF
  156083. n) number of samples of PCM actually returned. The
  156084. below works on a packet-by-packet basis, so the
  156085. return length is not related to the 'length' passed
  156086. in, just guaranteed to fit.
  156087. *section) set to the logical bitstream number */
  156088. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156089. int *bitstream){
  156090. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156091. while(1){
  156092. if(vf->ready_state==INITSET){
  156093. float **pcm;
  156094. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156095. if(samples){
  156096. if(pcm_channels)*pcm_channels=pcm;
  156097. if(samples>length)samples=length;
  156098. vorbis_synthesis_read(&vf->vd,samples);
  156099. vf->pcm_offset+=samples;
  156100. if(bitstream)*bitstream=vf->current_link;
  156101. return samples;
  156102. }
  156103. }
  156104. /* suck in another packet */
  156105. {
  156106. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156107. if(ret==OV_EOF)return(0);
  156108. if(ret<=0)return(ret);
  156109. }
  156110. }
  156111. }
  156112. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156113. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156114. ogg_int64_t off);
  156115. static void _ov_splice(float **pcm,float **lappcm,
  156116. int n1, int n2,
  156117. int ch1, int ch2,
  156118. float *w1, float *w2){
  156119. int i,j;
  156120. float *w=w1;
  156121. int n=n1;
  156122. if(n1>n2){
  156123. n=n2;
  156124. w=w2;
  156125. }
  156126. /* splice */
  156127. for(j=0;j<ch1 && j<ch2;j++){
  156128. float *s=lappcm[j];
  156129. float *d=pcm[j];
  156130. for(i=0;i<n;i++){
  156131. float wd=w[i]*w[i];
  156132. float ws=1.-wd;
  156133. d[i]=d[i]*wd + s[i]*ws;
  156134. }
  156135. }
  156136. /* window from zero */
  156137. for(;j<ch2;j++){
  156138. float *d=pcm[j];
  156139. for(i=0;i<n;i++){
  156140. float wd=w[i]*w[i];
  156141. d[i]=d[i]*wd;
  156142. }
  156143. }
  156144. }
  156145. /* make sure vf is INITSET */
  156146. static int _ov_initset(OggVorbis_File *vf){
  156147. while(1){
  156148. if(vf->ready_state==INITSET)break;
  156149. /* suck in another packet */
  156150. {
  156151. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156152. if(ret<0 && ret!=OV_HOLE)return(ret);
  156153. }
  156154. }
  156155. return 0;
  156156. }
  156157. /* make sure vf is INITSET and that we have a primed buffer; if
  156158. we're crosslapping at a stream section boundary, this also makes
  156159. sure we're sanity checking against the right stream information */
  156160. static int _ov_initprime(OggVorbis_File *vf){
  156161. vorbis_dsp_state *vd=&vf->vd;
  156162. while(1){
  156163. if(vf->ready_state==INITSET)
  156164. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156165. /* suck in another packet */
  156166. {
  156167. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156168. if(ret<0 && ret!=OV_HOLE)return(ret);
  156169. }
  156170. }
  156171. return 0;
  156172. }
  156173. /* grab enough data for lapping from vf; this may be in the form of
  156174. unreturned, already-decoded pcm, remaining PCM we will need to
  156175. decode, or synthetic postextrapolation from last packets. */
  156176. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156177. float **lappcm,int lapsize){
  156178. int lapcount=0,i;
  156179. float **pcm;
  156180. /* try first to decode the lapping data */
  156181. while(lapcount<lapsize){
  156182. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156183. if(samples){
  156184. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156185. for(i=0;i<vi->channels;i++)
  156186. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156187. lapcount+=samples;
  156188. vorbis_synthesis_read(vd,samples);
  156189. }else{
  156190. /* suck in another packet */
  156191. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156192. if(ret==OV_EOF)break;
  156193. }
  156194. }
  156195. if(lapcount<lapsize){
  156196. /* failed to get lapping data from normal decode; pry it from the
  156197. postextrapolation buffering, or the second half of the MDCT
  156198. from the last packet */
  156199. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156200. if(samples==0){
  156201. for(i=0;i<vi->channels;i++)
  156202. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156203. lapcount=lapsize;
  156204. }else{
  156205. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156206. for(i=0;i<vi->channels;i++)
  156207. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156208. lapcount+=samples;
  156209. }
  156210. }
  156211. }
  156212. /* this sets up crosslapping of a sample by using trailing data from
  156213. sample 1 and lapping it into the windowing buffer of sample 2 */
  156214. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156215. vorbis_info *vi1,*vi2;
  156216. float **lappcm;
  156217. float **pcm;
  156218. float *w1,*w2;
  156219. int n1,n2,i,ret,hs1,hs2;
  156220. if(vf1==vf2)return(0); /* degenerate case */
  156221. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156222. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156223. /* the relevant overlap buffers must be pre-checked and pre-primed
  156224. before looking at settings in the event that priming would cross
  156225. a bitstream boundary. So, do it now */
  156226. ret=_ov_initset(vf1);
  156227. if(ret)return(ret);
  156228. ret=_ov_initprime(vf2);
  156229. if(ret)return(ret);
  156230. vi1=ov_info(vf1,-1);
  156231. vi2=ov_info(vf2,-1);
  156232. hs1=ov_halfrate_p(vf1);
  156233. hs2=ov_halfrate_p(vf2);
  156234. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156235. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156236. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156237. w1=vorbis_window(&vf1->vd,0);
  156238. w2=vorbis_window(&vf2->vd,0);
  156239. for(i=0;i<vi1->channels;i++)
  156240. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156241. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156242. /* have a lapping buffer from vf1; now to splice it into the lapping
  156243. buffer of vf2 */
  156244. /* consolidate and expose the buffer. */
  156245. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156246. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156247. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156248. /* splice */
  156249. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156250. /* done */
  156251. return(0);
  156252. }
  156253. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156254. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156255. vorbis_info *vi;
  156256. float **lappcm;
  156257. float **pcm;
  156258. float *w1,*w2;
  156259. int n1,n2,ch1,ch2,hs;
  156260. int i,ret;
  156261. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156262. ret=_ov_initset(vf);
  156263. if(ret)return(ret);
  156264. vi=ov_info(vf,-1);
  156265. hs=ov_halfrate_p(vf);
  156266. ch1=vi->channels;
  156267. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156268. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156269. persistent; even if the decode state
  156270. from this link gets dumped, this
  156271. window array continues to exist */
  156272. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156273. for(i=0;i<ch1;i++)
  156274. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156275. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156276. /* have lapping data; seek and prime the buffer */
  156277. ret=localseek(vf,pos);
  156278. if(ret)return ret;
  156279. ret=_ov_initprime(vf);
  156280. if(ret)return(ret);
  156281. /* Guard against cross-link changes; they're perfectly legal */
  156282. vi=ov_info(vf,-1);
  156283. ch2=vi->channels;
  156284. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156285. w2=vorbis_window(&vf->vd,0);
  156286. /* consolidate and expose the buffer. */
  156287. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156288. /* splice */
  156289. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156290. /* done */
  156291. return(0);
  156292. }
  156293. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156294. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156295. }
  156296. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156297. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156298. }
  156299. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156300. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156301. }
  156302. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156303. int (*localseek)(OggVorbis_File *,double)){
  156304. vorbis_info *vi;
  156305. float **lappcm;
  156306. float **pcm;
  156307. float *w1,*w2;
  156308. int n1,n2,ch1,ch2,hs;
  156309. int i,ret;
  156310. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156311. ret=_ov_initset(vf);
  156312. if(ret)return(ret);
  156313. vi=ov_info(vf,-1);
  156314. hs=ov_halfrate_p(vf);
  156315. ch1=vi->channels;
  156316. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156317. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156318. persistent; even if the decode state
  156319. from this link gets dumped, this
  156320. window array continues to exist */
  156321. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156322. for(i=0;i<ch1;i++)
  156323. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156324. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156325. /* have lapping data; seek and prime the buffer */
  156326. ret=localseek(vf,pos);
  156327. if(ret)return ret;
  156328. ret=_ov_initprime(vf);
  156329. if(ret)return(ret);
  156330. /* Guard against cross-link changes; they're perfectly legal */
  156331. vi=ov_info(vf,-1);
  156332. ch2=vi->channels;
  156333. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156334. w2=vorbis_window(&vf->vd,0);
  156335. /* consolidate and expose the buffer. */
  156336. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156337. /* splice */
  156338. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156339. /* done */
  156340. return(0);
  156341. }
  156342. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156343. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156344. }
  156345. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156346. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156347. }
  156348. #endif
  156349. /*** End of inlined file: vorbisfile.c ***/
  156350. /*** Start of inlined file: window.c ***/
  156351. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156352. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156353. // tasks..
  156354. #if JUCE_MSVC
  156355. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156356. #endif
  156357. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156358. #if JUCE_USE_OGGVORBIS
  156359. #include <stdlib.h>
  156360. #include <math.h>
  156361. static float vwin64[32] = {
  156362. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156363. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156364. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156365. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156366. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156367. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156368. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156369. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156370. };
  156371. static float vwin128[64] = {
  156372. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156373. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156374. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156375. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156376. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156377. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156378. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156379. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156380. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156381. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156382. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156383. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156384. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156385. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156386. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156387. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156388. };
  156389. static float vwin256[128] = {
  156390. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156391. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156392. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156393. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156394. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156395. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156396. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156397. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156398. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156399. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156400. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156401. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156402. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156403. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156404. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156405. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156406. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156407. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156408. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156409. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156410. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156411. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156412. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156413. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156414. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156415. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156416. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156417. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156418. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156419. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156420. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156421. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156422. };
  156423. static float vwin512[256] = {
  156424. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156425. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156426. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156427. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156428. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156429. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156430. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156431. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156432. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156433. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156434. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156435. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156436. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156437. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156438. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156439. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156440. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156441. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156442. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156443. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156444. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156445. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156446. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156447. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156448. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156449. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156450. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156451. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156452. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156453. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156454. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156455. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156456. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156457. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156458. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156459. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156460. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156461. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156462. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156463. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156464. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156465. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156466. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156467. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156468. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156469. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156470. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156471. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156472. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156473. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156474. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156475. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156476. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156477. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156478. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156479. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156480. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156481. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156482. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156483. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156484. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156485. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156486. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156487. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156488. };
  156489. static float vwin1024[512] = {
  156490. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156491. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156492. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156493. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156494. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156495. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156496. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156497. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156498. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156499. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156500. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156501. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156502. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156503. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156504. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156505. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156506. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156507. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156508. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156509. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156510. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156511. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156512. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156513. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156514. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156515. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156516. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156517. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156518. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156519. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156520. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156521. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156522. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156523. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156524. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156525. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156526. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156527. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156528. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156529. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156530. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156531. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156532. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156533. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156534. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156535. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156536. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156537. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156538. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156539. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156540. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156541. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156542. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156543. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156544. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156545. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156546. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156547. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156548. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156549. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156550. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156551. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156552. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156553. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156554. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156555. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156556. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156557. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156558. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156559. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156560. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156561. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156562. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156563. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156564. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156565. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156566. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156567. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156568. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156569. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156570. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156571. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156572. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156573. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156574. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156575. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156576. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156577. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156578. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156579. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156580. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156581. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156582. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156583. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156584. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156585. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156586. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156587. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156588. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156589. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156590. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156591. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156592. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156593. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156594. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156595. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156596. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156597. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156598. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156599. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156600. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156601. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156602. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156603. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156604. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156605. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156606. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156607. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156608. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156609. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156610. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156611. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156612. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156613. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156614. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156615. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156616. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156617. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156618. };
  156619. static float vwin2048[1024] = {
  156620. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156621. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156622. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156623. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156624. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156625. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156626. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156627. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156628. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156629. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156630. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156631. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156632. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156633. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156634. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156635. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156636. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156637. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156638. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156639. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156640. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156641. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156642. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156643. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156644. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156645. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156646. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156647. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156648. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156649. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156650. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156651. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156652. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156653. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156654. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156655. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156656. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156657. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156658. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156659. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156660. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156661. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156662. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156663. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156664. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156665. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156666. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156667. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156668. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156669. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156670. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156671. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156672. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156673. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156674. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156675. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156676. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156677. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156678. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156679. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156680. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156681. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156682. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156683. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156684. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156685. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156686. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156687. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156688. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156689. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156690. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156691. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156692. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156693. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156694. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156695. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156696. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156697. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156698. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156699. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156700. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156701. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156702. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156703. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156704. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156705. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156706. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156707. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156708. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156709. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156710. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156711. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156712. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156713. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156714. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156715. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156716. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156717. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156718. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156719. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156720. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156721. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156722. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156723. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156724. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156725. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156726. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156727. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156728. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156729. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156730. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156731. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156732. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156733. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156734. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156735. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156736. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156737. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156738. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156739. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156740. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156741. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156742. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156743. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156744. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156745. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156746. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156747. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156748. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156749. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156750. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156751. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156752. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156753. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156754. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156755. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156756. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156757. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156758. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156759. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156760. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156761. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156762. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156763. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156764. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156765. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156766. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156767. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156768. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156769. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156770. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156771. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156772. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156773. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156774. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156775. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156776. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156777. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156778. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156779. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156780. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156781. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156782. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156783. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156784. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156785. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156786. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156787. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156788. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156789. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156790. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156791. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156792. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156793. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156794. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156795. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156796. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156797. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156798. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156799. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156800. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156801. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156802. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156803. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156804. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156805. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156806. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156807. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156808. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156809. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156810. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156811. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156812. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156813. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156814. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156815. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156816. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156817. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156818. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156819. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  156820. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  156821. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  156822. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  156823. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  156824. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  156825. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  156826. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  156827. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  156828. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  156829. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  156830. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  156831. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  156832. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  156833. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  156834. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  156835. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  156836. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  156837. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  156838. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  156839. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  156840. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  156841. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  156842. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  156843. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  156844. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  156845. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  156846. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  156847. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  156848. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  156849. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  156850. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  156851. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  156852. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  156853. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  156854. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  156855. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  156856. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  156857. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  156858. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  156859. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  156860. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  156861. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  156862. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  156863. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  156864. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  156865. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  156866. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  156867. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  156868. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  156869. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  156870. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  156871. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  156872. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  156873. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  156874. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  156875. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  156876. };
  156877. static float vwin4096[2048] = {
  156878. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  156879. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  156880. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  156881. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  156882. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  156883. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  156884. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  156885. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  156886. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  156887. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  156888. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  156889. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  156890. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  156891. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  156892. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  156893. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  156894. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  156895. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  156896. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  156897. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  156898. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  156899. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  156900. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  156901. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  156902. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  156903. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  156904. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  156905. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  156906. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  156907. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  156908. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  156909. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  156910. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  156911. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  156912. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  156913. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  156914. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  156915. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  156916. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  156917. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  156918. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  156919. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  156920. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  156921. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  156922. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  156923. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  156924. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  156925. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  156926. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  156927. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  156928. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  156929. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  156930. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  156931. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  156932. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  156933. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  156934. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  156935. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  156936. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  156937. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  156938. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  156939. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  156940. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  156941. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  156942. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  156943. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  156944. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  156945. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  156946. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  156947. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  156948. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  156949. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  156950. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  156951. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  156952. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  156953. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  156954. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  156955. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  156956. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  156957. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  156958. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  156959. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  156960. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  156961. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  156962. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  156963. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  156964. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  156965. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  156966. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  156967. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  156968. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  156969. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  156970. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  156971. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  156972. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  156973. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  156974. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  156975. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  156976. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  156977. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  156978. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  156979. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  156980. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  156981. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  156982. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  156983. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  156984. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  156985. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  156986. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  156987. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  156988. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  156989. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  156990. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  156991. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  156992. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  156993. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  156994. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  156995. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  156996. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  156997. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  156998. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  156999. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157000. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157001. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157002. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157003. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157004. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157005. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157006. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157007. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157008. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157009. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157010. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157011. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157012. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157013. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157014. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157015. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157016. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157017. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157018. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157019. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157020. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157021. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157022. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157023. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157024. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157025. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157026. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157027. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157028. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157029. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157030. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157031. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157032. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157033. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157034. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157035. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157036. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157037. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157038. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157039. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157040. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157041. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157042. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157043. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157044. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157045. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157046. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157047. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157048. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157049. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157050. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157051. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157052. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157053. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157054. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157055. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157056. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157057. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157058. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157059. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157060. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157061. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157062. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157063. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157064. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157065. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157066. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157067. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157068. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157069. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157070. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157071. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157072. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157073. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157074. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157075. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157076. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157077. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157078. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157079. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157080. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157081. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157082. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157083. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157084. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157085. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157086. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157087. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157088. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157089. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157090. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157091. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157092. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157093. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157094. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157095. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157096. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157097. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157098. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157099. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157100. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157101. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157102. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157103. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157104. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157105. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157106. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157107. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157108. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157109. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157110. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157111. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157112. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157113. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157114. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157115. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157116. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157117. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157118. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157119. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157120. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157121. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157122. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157123. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157124. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157125. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157126. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157127. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157128. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157129. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157130. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157131. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157132. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157133. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157134. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157135. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157136. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157137. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157138. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157139. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157140. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157141. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157142. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157143. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157144. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157145. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157146. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157147. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157148. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157149. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157150. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157151. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157152. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157153. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157154. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157155. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157156. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157157. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157158. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157159. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157160. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157161. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157162. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157163. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157164. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157165. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157166. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157167. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157168. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157169. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157170. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157171. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157172. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157173. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157174. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157175. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157176. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157177. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157178. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157179. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157180. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157181. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157182. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157183. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157184. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157185. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157186. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157187. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157188. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157189. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157190. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157191. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157192. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157193. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157194. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157195. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157196. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157197. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157198. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157199. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157200. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157201. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157202. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157203. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157204. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157205. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157206. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157207. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157208. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157209. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157210. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157211. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157212. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157213. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157214. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157215. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157216. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157217. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157218. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157219. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157220. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157221. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157222. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157223. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157224. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157225. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157226. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157227. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157228. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157229. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157230. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157231. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157232. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157233. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157234. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157235. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157236. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157237. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157238. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157239. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157240. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157241. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157242. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157243. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157244. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157245. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157246. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157247. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157248. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157249. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157250. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157251. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157252. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157253. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157254. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157255. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157256. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157257. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157258. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157259. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157260. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157261. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157262. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157263. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157264. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157265. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157266. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157267. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157268. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157269. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157270. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157271. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157272. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157273. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157274. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157275. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157276. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157277. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157278. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157279. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157280. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157281. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157282. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157283. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157284. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157285. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157286. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157287. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157288. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157289. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157290. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157291. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157292. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157293. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157294. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157295. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157296. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157297. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157298. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157299. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157300. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157301. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157302. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157303. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157304. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157305. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157306. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157307. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157308. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157309. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157310. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157311. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157312. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157313. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157314. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157315. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157316. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157317. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157318. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157319. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157320. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157321. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157322. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157323. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157324. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157325. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157326. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157327. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157328. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157329. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157330. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157331. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157332. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157333. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157334. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157335. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157336. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157337. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157338. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157339. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157340. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157341. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157342. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157343. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157344. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157345. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157346. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157347. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157348. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157349. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157350. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157351. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157352. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157353. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157354. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157355. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157356. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157357. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157358. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157359. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157360. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157361. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157362. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157363. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157364. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157365. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157366. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157367. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157368. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157369. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157370. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157371. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157372. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157373. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157374. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157375. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157376. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157377. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157378. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157379. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157380. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157381. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157382. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157383. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157384. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157385. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157386. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157387. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157388. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157389. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157390. };
  157391. static float vwin8192[4096] = {
  157392. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157393. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157394. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157395. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157396. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157397. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157398. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157399. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157400. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157401. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157402. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157403. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157404. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157405. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157406. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157407. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157408. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157409. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157410. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157411. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157412. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157413. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157414. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157415. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157416. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157417. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157418. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157419. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157420. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157421. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157422. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157423. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157424. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157425. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157426. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157427. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157428. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157429. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157430. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157431. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157432. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157433. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157434. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157435. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157436. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157437. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157438. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157439. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157440. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157441. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157442. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157443. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157444. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157445. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157446. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157447. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157448. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157449. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157450. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157451. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157452. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157453. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157454. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157455. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157456. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157457. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157458. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157459. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157460. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157461. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157462. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157463. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157464. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157465. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157466. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157467. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157468. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157469. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157470. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157471. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157472. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157473. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157474. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157475. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157476. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157477. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157478. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157479. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157480. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157481. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157482. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157483. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157484. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157485. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157486. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157487. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157488. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157489. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157490. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157491. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157492. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157493. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157494. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157495. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157496. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157497. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157498. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157499. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157500. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157501. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157502. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157503. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157504. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157505. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157506. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157507. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157508. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157509. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157510. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157511. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157512. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157513. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157514. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157515. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157516. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157517. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157518. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157519. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157520. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157521. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157522. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157523. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157524. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157525. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157526. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157527. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157528. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157529. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157530. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157531. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157532. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157533. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157534. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157535. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157536. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157537. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157538. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157539. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157540. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157541. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157542. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157543. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157544. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157545. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157546. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157547. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157548. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157549. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157550. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157551. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157552. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157553. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157554. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157555. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157556. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157557. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157558. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157559. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157560. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157561. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157562. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157563. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157564. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157565. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157566. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157567. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157568. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157569. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157570. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157571. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157572. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157573. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157574. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157575. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157576. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157577. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157578. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157579. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157580. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157581. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157582. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157583. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157584. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157585. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157586. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157587. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157588. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157589. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157590. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157591. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157592. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157593. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157594. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157595. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157596. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157597. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157598. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157599. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157600. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157601. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157602. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157603. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157604. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157605. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157606. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157607. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157608. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157609. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157610. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157611. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157612. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157613. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157614. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157615. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157616. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157617. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157618. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157619. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157620. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157621. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157622. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157623. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157624. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157625. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157626. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157627. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157628. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157629. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157630. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157631. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157632. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157633. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157634. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157635. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157636. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157637. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157638. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157639. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157640. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157641. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157642. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157643. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157644. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157645. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157646. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157647. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157648. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157649. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157650. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157651. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157652. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157653. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157654. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157655. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157656. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157657. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157658. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157659. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157660. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157661. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157662. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157663. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157664. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157665. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157666. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157667. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157668. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157669. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157670. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157671. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157672. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157673. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157674. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157675. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157676. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157677. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157678. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157679. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157680. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157681. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157682. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157683. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157684. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157685. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157686. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157687. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157688. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157689. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157690. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157691. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157692. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157693. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157694. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157695. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157696. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157697. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157698. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157699. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157700. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157701. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157702. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157703. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157704. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157705. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157706. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157707. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157708. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157709. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157710. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157711. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157712. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157713. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157714. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157715. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157716. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157717. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157718. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157719. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157720. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157721. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157722. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157723. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157724. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157725. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157726. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157727. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157728. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157729. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157730. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157731. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157732. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157733. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157734. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157735. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157736. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157737. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157738. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157739. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157740. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157741. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157742. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157743. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157744. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157745. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157746. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157747. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157748. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157749. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157750. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157751. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157752. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157753. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157754. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157755. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157756. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157757. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157758. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157759. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157760. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157761. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157762. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157763. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157764. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157765. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157766. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157767. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157768. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157769. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157770. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157771. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157772. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157773. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157774. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157775. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157776. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157777. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157778. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157779. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157780. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157781. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157782. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157783. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157784. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157785. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157786. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157787. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157788. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157789. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157790. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157791. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157792. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157793. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157794. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157795. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157796. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157797. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157798. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157799. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157800. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157801. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157802. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157803. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157804. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157805. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157806. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157807. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157808. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157809. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157810. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157811. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157812. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157813. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157814. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157815. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157816. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157817. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157818. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157819. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  157820. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  157821. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  157822. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  157823. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  157824. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  157825. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  157826. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  157827. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  157828. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  157829. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  157830. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  157831. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  157832. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  157833. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  157834. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  157835. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  157836. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  157837. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  157838. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  157839. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  157840. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  157841. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  157842. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  157843. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  157844. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  157845. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  157846. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  157847. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  157848. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  157849. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  157850. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  157851. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  157852. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  157853. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  157854. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  157855. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  157856. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  157857. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  157858. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  157859. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  157860. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  157861. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  157862. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  157863. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  157864. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  157865. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  157866. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  157867. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  157868. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  157869. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  157870. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  157871. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  157872. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  157873. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  157874. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  157875. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  157876. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  157877. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  157878. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  157879. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  157880. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  157881. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  157882. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  157883. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  157884. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  157885. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  157886. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  157887. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  157888. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  157889. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  157890. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  157891. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  157892. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  157893. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  157894. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  157895. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  157896. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  157897. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  157898. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  157899. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  157900. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  157901. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  157902. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  157903. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  157904. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  157905. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  157906. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  157907. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  157908. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  157909. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  157910. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  157911. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  157912. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  157913. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  157914. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  157915. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  157916. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  157917. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  157918. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  157919. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  157920. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  157921. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  157922. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  157923. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  157924. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  157925. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  157926. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  157927. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  157928. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  157929. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  157930. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  157931. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  157932. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  157933. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  157934. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  157935. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  157936. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  157937. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  157938. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  157939. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  157940. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  157941. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  157942. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  157943. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  157944. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  157945. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  157946. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  157947. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  157948. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  157949. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  157950. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  157951. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  157952. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  157953. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  157954. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  157955. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  157956. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  157957. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  157958. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  157959. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  157960. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  157961. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  157962. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  157963. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  157964. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  157965. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  157966. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  157967. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  157968. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  157969. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  157970. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  157971. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  157972. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  157973. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  157974. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  157975. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  157976. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  157977. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  157978. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  157979. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  157980. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  157981. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  157982. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  157983. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  157984. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  157985. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  157986. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  157987. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  157988. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  157989. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  157990. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  157991. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  157992. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  157993. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  157994. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  157995. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  157996. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  157997. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  157998. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  157999. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158000. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158001. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158002. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158003. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158004. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158005. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158006. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158007. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158008. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158009. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158010. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158011. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158012. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158013. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158014. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158015. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158016. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158017. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158018. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158019. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158020. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158021. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158022. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158023. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158024. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158025. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158026. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158027. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158028. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158029. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158030. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158031. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158032. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158033. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158034. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158035. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158036. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158037. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158038. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158039. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158040. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158041. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158042. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158043. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158044. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158045. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158046. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158047. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158048. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158049. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158050. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158051. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158052. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158053. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158054. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158055. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158056. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158057. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158058. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158059. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158060. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158061. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158062. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158063. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158064. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158065. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158066. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158067. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158068. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158069. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158070. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158071. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158072. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158073. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158074. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158075. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158076. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158077. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158078. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158079. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158080. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158081. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158082. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158083. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158084. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158085. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158086. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158087. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158088. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158089. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158090. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158091. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158092. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158093. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158094. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158095. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158096. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158097. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158098. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158099. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158100. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158101. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158102. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158103. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158104. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158105. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158106. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158107. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158108. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158109. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158110. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158111. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158112. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158113. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158114. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158115. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158116. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158117. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158118. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158119. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158120. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158121. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158122. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158123. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158124. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158125. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158126. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158127. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158128. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158129. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158130. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158131. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158132. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158133. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158134. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158135. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158136. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158137. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158138. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158139. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158140. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158141. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158142. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158143. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158144. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158145. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158146. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158147. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158148. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158149. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158150. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158151. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158152. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158153. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158154. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158155. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158156. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158157. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158158. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158159. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158160. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158161. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158162. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158163. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158164. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158165. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158166. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158167. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158168. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158169. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158170. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158171. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158172. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158173. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158174. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158175. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158176. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158177. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158178. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158179. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158180. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158181. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158182. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158183. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158184. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158185. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158186. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158187. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158188. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158189. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158190. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158191. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158192. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158193. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158194. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158195. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158196. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158197. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158198. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158199. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158200. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158201. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158202. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158203. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158204. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158205. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158206. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158207. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158208. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158209. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158210. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158211. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158212. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158213. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158214. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158215. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158216. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158217. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158218. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158219. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158220. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158221. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158222. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158223. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158224. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158225. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158226. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158227. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158228. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158229. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158230. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158231. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158232. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158233. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158234. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158235. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158236. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158237. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158238. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158239. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158240. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158241. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158242. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158243. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158244. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158245. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158246. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158247. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158248. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158249. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158250. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158251. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158252. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158253. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158254. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158255. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158256. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158257. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158258. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158259. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158260. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158261. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158262. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158263. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158264. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158265. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158266. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158267. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158268. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158269. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158270. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158271. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158272. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158273. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158274. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158275. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158276. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158277. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158278. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158279. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158280. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158281. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158282. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158283. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158284. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158285. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158286. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158287. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158288. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158289. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158290. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158291. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158292. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158293. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158294. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158295. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158296. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158297. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158298. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158299. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158300. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158301. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158302. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158303. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158304. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158305. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158306. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158307. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158308. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158309. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158310. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158311. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158312. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158313. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158314. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158315. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158316. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158317. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158318. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158319. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158320. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158321. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158322. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158323. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158324. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158325. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158326. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158327. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158328. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158329. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158330. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158331. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158332. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158333. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158334. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158335. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158336. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158337. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158338. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158339. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158340. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158341. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158342. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158343. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158344. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158345. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158346. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158347. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158348. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158349. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158350. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158351. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158352. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158353. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158354. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158355. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158356. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158357. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158358. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158359. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158360. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158361. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158362. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158363. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158364. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158365. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158366. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158367. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158368. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158369. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158370. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158371. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158372. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158373. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158374. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158375. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158376. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158377. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158378. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158379. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158380. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158381. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158382. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158383. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158384. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158385. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158386. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158387. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158388. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158389. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158390. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158391. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158392. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158393. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158394. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158395. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158396. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158397. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158398. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158399. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158400. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158401. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158402. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158403. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158404. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158405. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158406. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158407. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158408. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158409. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158410. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158411. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158412. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158413. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158414. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158415. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158416. };
  158417. static float *vwin[8] = {
  158418. vwin64,
  158419. vwin128,
  158420. vwin256,
  158421. vwin512,
  158422. vwin1024,
  158423. vwin2048,
  158424. vwin4096,
  158425. vwin8192,
  158426. };
  158427. float *_vorbis_window_get(int n){
  158428. return vwin[n];
  158429. }
  158430. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158431. int lW,int W,int nW){
  158432. lW=(W?lW:0);
  158433. nW=(W?nW:0);
  158434. {
  158435. float *windowLW=vwin[winno[lW]];
  158436. float *windowNW=vwin[winno[nW]];
  158437. long n=blocksizes[W];
  158438. long ln=blocksizes[lW];
  158439. long rn=blocksizes[nW];
  158440. long leftbegin=n/4-ln/4;
  158441. long leftend=leftbegin+ln/2;
  158442. long rightbegin=n/2+n/4-rn/4;
  158443. long rightend=rightbegin+rn/2;
  158444. int i,p;
  158445. for(i=0;i<leftbegin;i++)
  158446. d[i]=0.f;
  158447. for(p=0;i<leftend;i++,p++)
  158448. d[i]*=windowLW[p];
  158449. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158450. d[i]*=windowNW[p];
  158451. for(;i<n;i++)
  158452. d[i]=0.f;
  158453. }
  158454. }
  158455. #endif
  158456. /*** End of inlined file: window.c ***/
  158457. #else
  158458. #include <vorbis/vorbisenc.h>
  158459. #include <vorbis/codec.h>
  158460. #include <vorbis/vorbisfile.h>
  158461. #endif
  158462. }
  158463. #undef max
  158464. #undef min
  158465. BEGIN_JUCE_NAMESPACE
  158466. static const char* const oggFormatName = "Ogg-Vorbis file";
  158467. static const char* const oggExtensions[] = { ".ogg", 0 };
  158468. class OggReader : public AudioFormatReader
  158469. {
  158470. OggVorbisNamespace::OggVorbis_File ovFile;
  158471. OggVorbisNamespace::ov_callbacks callbacks;
  158472. AudioSampleBuffer reservoir;
  158473. int reservoirStart, samplesInReservoir;
  158474. public:
  158475. OggReader (InputStream* const inp)
  158476. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158477. reservoir (2, 4096),
  158478. reservoirStart (0),
  158479. samplesInReservoir (0)
  158480. {
  158481. using namespace OggVorbisNamespace;
  158482. sampleRate = 0;
  158483. usesFloatingPointData = true;
  158484. callbacks.read_func = &oggReadCallback;
  158485. callbacks.seek_func = &oggSeekCallback;
  158486. callbacks.close_func = &oggCloseCallback;
  158487. callbacks.tell_func = &oggTellCallback;
  158488. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158489. if (err == 0)
  158490. {
  158491. vorbis_info* info = ov_info (&ovFile, -1);
  158492. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158493. numChannels = info->channels;
  158494. bitsPerSample = 16;
  158495. sampleRate = info->rate;
  158496. reservoir.setSize (numChannels,
  158497. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158498. }
  158499. }
  158500. ~OggReader()
  158501. {
  158502. OggVorbisNamespace::ov_clear (&ovFile);
  158503. }
  158504. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158505. int64 startSampleInFile, int numSamples)
  158506. {
  158507. while (numSamples > 0)
  158508. {
  158509. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158510. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158511. {
  158512. // got a few samples overlapping, so use them before seeking..
  158513. const int numToUse = jmin (numSamples, numAvailable);
  158514. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158515. if (destSamples[i] != 0)
  158516. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158517. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158518. sizeof (float) * numToUse);
  158519. startSampleInFile += numToUse;
  158520. numSamples -= numToUse;
  158521. startOffsetInDestBuffer += numToUse;
  158522. if (numSamples == 0)
  158523. break;
  158524. }
  158525. if (startSampleInFile < reservoirStart
  158526. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158527. {
  158528. // buffer miss, so refill the reservoir
  158529. int bitStream = 0;
  158530. reservoirStart = jmax (0, (int) startSampleInFile);
  158531. samplesInReservoir = reservoir.getNumSamples();
  158532. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158533. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158534. int offset = 0;
  158535. int numToRead = samplesInReservoir;
  158536. while (numToRead > 0)
  158537. {
  158538. float** dataIn = 0;
  158539. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158540. if (samps <= 0)
  158541. break;
  158542. jassert (samps <= numToRead);
  158543. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158544. {
  158545. memcpy (reservoir.getSampleData (i, offset),
  158546. dataIn[i],
  158547. sizeof (float) * samps);
  158548. }
  158549. numToRead -= samps;
  158550. offset += samps;
  158551. }
  158552. if (numToRead > 0)
  158553. reservoir.clear (offset, numToRead);
  158554. }
  158555. }
  158556. if (numSamples > 0)
  158557. {
  158558. for (int i = numDestChannels; --i >= 0;)
  158559. if (destSamples[i] != 0)
  158560. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158561. sizeof (int) * numSamples);
  158562. }
  158563. return true;
  158564. }
  158565. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158566. {
  158567. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158568. }
  158569. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158570. {
  158571. InputStream* const in = static_cast <InputStream*> (datasource);
  158572. if (whence == SEEK_CUR)
  158573. offset += in->getPosition();
  158574. else if (whence == SEEK_END)
  158575. offset += in->getTotalLength();
  158576. in->setPosition (offset);
  158577. return 0;
  158578. }
  158579. static int oggCloseCallback (void*)
  158580. {
  158581. return 0;
  158582. }
  158583. static long oggTellCallback (void* datasource)
  158584. {
  158585. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158586. }
  158587. juce_UseDebuggingNewOperator
  158588. };
  158589. class OggWriter : public AudioFormatWriter
  158590. {
  158591. OggVorbisNamespace::ogg_stream_state os;
  158592. OggVorbisNamespace::ogg_page og;
  158593. OggVorbisNamespace::ogg_packet op;
  158594. OggVorbisNamespace::vorbis_info vi;
  158595. OggVorbisNamespace::vorbis_comment vc;
  158596. OggVorbisNamespace::vorbis_dsp_state vd;
  158597. OggVorbisNamespace::vorbis_block vb;
  158598. public:
  158599. bool ok;
  158600. OggWriter (OutputStream* const out,
  158601. const double sampleRate,
  158602. const int numChannels,
  158603. const int bitsPerSample,
  158604. const int qualityIndex)
  158605. : AudioFormatWriter (out, TRANS (oggFormatName),
  158606. sampleRate,
  158607. numChannels,
  158608. bitsPerSample)
  158609. {
  158610. using namespace OggVorbisNamespace;
  158611. ok = false;
  158612. vorbis_info_init (&vi);
  158613. if (vorbis_encode_init_vbr (&vi,
  158614. numChannels,
  158615. (int) sampleRate,
  158616. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158617. {
  158618. vorbis_comment_init (&vc);
  158619. if (JUCEApplication::getInstance() != 0)
  158620. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158621. vorbis_analysis_init (&vd, &vi);
  158622. vorbis_block_init (&vd, &vb);
  158623. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158624. ogg_packet header;
  158625. ogg_packet header_comm;
  158626. ogg_packet header_code;
  158627. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158628. ogg_stream_packetin (&os, &header);
  158629. ogg_stream_packetin (&os, &header_comm);
  158630. ogg_stream_packetin (&os, &header_code);
  158631. for (;;)
  158632. {
  158633. if (ogg_stream_flush (&os, &og) == 0)
  158634. break;
  158635. output->write (og.header, og.header_len);
  158636. output->write (og.body, og.body_len);
  158637. }
  158638. ok = true;
  158639. }
  158640. }
  158641. ~OggWriter()
  158642. {
  158643. using namespace OggVorbisNamespace;
  158644. if (ok)
  158645. {
  158646. // write a zero-length packet to show ogg that we're finished..
  158647. write (0, 0);
  158648. ogg_stream_clear (&os);
  158649. vorbis_block_clear (&vb);
  158650. vorbis_dsp_clear (&vd);
  158651. vorbis_comment_clear (&vc);
  158652. vorbis_info_clear (&vi);
  158653. output->flush();
  158654. }
  158655. else
  158656. {
  158657. vorbis_info_clear (&vi);
  158658. output = 0; // to stop the base class deleting this, as it needs to be returned
  158659. // to the caller of createWriter()
  158660. }
  158661. }
  158662. bool write (const int** samplesToWrite, int numSamples)
  158663. {
  158664. using namespace OggVorbisNamespace;
  158665. if (! ok)
  158666. return false;
  158667. if (numSamples > 0)
  158668. {
  158669. const double gain = 1.0 / 0x80000000u;
  158670. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158671. for (int i = numChannels; --i >= 0;)
  158672. {
  158673. float* const dst = vorbisBuffer[i];
  158674. const int* const src = samplesToWrite [i];
  158675. if (src != 0 && dst != 0)
  158676. {
  158677. for (int j = 0; j < numSamples; ++j)
  158678. dst[j] = (float) (src[j] * gain);
  158679. }
  158680. }
  158681. }
  158682. vorbis_analysis_wrote (&vd, numSamples);
  158683. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158684. {
  158685. vorbis_analysis (&vb, 0);
  158686. vorbis_bitrate_addblock (&vb);
  158687. while (vorbis_bitrate_flushpacket (&vd, &op))
  158688. {
  158689. ogg_stream_packetin (&os, &op);
  158690. for (;;)
  158691. {
  158692. if (ogg_stream_pageout (&os, &og) == 0)
  158693. break;
  158694. output->write (og.header, og.header_len);
  158695. output->write (og.body, og.body_len);
  158696. if (ogg_page_eos (&og))
  158697. break;
  158698. }
  158699. }
  158700. }
  158701. return true;
  158702. }
  158703. juce_UseDebuggingNewOperator
  158704. };
  158705. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158706. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158707. {
  158708. }
  158709. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158710. {
  158711. }
  158712. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158713. {
  158714. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158715. return Array <int> (rates);
  158716. }
  158717. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158718. {
  158719. Array <int> depths;
  158720. depths.add (32);
  158721. return depths;
  158722. }
  158723. bool OggVorbisAudioFormat::canDoStereo()
  158724. {
  158725. return true;
  158726. }
  158727. bool OggVorbisAudioFormat::canDoMono()
  158728. {
  158729. return true;
  158730. }
  158731. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158732. const bool deleteStreamIfOpeningFails)
  158733. {
  158734. ScopedPointer <OggReader> r (new OggReader (in));
  158735. if (r->sampleRate != 0)
  158736. return r.release();
  158737. if (! deleteStreamIfOpeningFails)
  158738. r->input = 0;
  158739. return 0;
  158740. }
  158741. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158742. double sampleRate,
  158743. unsigned int numChannels,
  158744. int bitsPerSample,
  158745. const StringPairArray& /*metadataValues*/,
  158746. int qualityOptionIndex)
  158747. {
  158748. ScopedPointer <OggWriter> w (new OggWriter (out,
  158749. sampleRate,
  158750. numChannels,
  158751. bitsPerSample,
  158752. qualityOptionIndex));
  158753. return w->ok ? w.release() : 0;
  158754. }
  158755. bool OggVorbisAudioFormat::isCompressed()
  158756. {
  158757. return true;
  158758. }
  158759. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158760. {
  158761. StringArray s;
  158762. s.add ("Low Quality");
  158763. s.add ("Medium Quality");
  158764. s.add ("High Quality");
  158765. return s;
  158766. }
  158767. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158768. {
  158769. FileInputStream* const in = source.createInputStream();
  158770. if (in != 0)
  158771. {
  158772. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158773. if (r != 0)
  158774. {
  158775. const int64 numSamps = r->lengthInSamples;
  158776. r = 0;
  158777. const int64 fileNumSamps = source.getSize() / 4;
  158778. const double ratio = numSamps / (double) fileNumSamps;
  158779. if (ratio > 12.0)
  158780. return 0;
  158781. else if (ratio > 6.0)
  158782. return 1;
  158783. else
  158784. return 2;
  158785. }
  158786. }
  158787. return 1;
  158788. }
  158789. END_JUCE_NAMESPACE
  158790. #endif
  158791. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158792. #endif
  158793. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158794. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158795. #if JUCE_MSVC
  158796. #pragma warning (push)
  158797. #endif
  158798. namespace jpeglibNamespace
  158799. {
  158800. #if JUCE_INCLUDE_JPEGLIB_CODE
  158801. #if JUCE_MINGW
  158802. typedef unsigned char boolean;
  158803. #endif
  158804. extern "C"
  158805. {
  158806. #define JPEG_INTERNALS
  158807. #undef FAR
  158808. /*** Start of inlined file: jpeglib.h ***/
  158809. #ifndef JPEGLIB_H
  158810. #define JPEGLIB_H
  158811. /*
  158812. * First we include the configuration files that record how this
  158813. * installation of the JPEG library is set up. jconfig.h can be
  158814. * generated automatically for many systems. jmorecfg.h contains
  158815. * manual configuration options that most people need not worry about.
  158816. */
  158817. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158818. /*** Start of inlined file: jconfig.h ***/
  158819. /* see jconfig.doc for explanations */
  158820. // disable all the warnings under MSVC
  158821. #ifdef _MSC_VER
  158822. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158823. #endif
  158824. #ifdef __BORLANDC__
  158825. #pragma warn -8057
  158826. #pragma warn -8019
  158827. #pragma warn -8004
  158828. #pragma warn -8008
  158829. #endif
  158830. #define HAVE_PROTOTYPES
  158831. #define HAVE_UNSIGNED_CHAR
  158832. #define HAVE_UNSIGNED_SHORT
  158833. /* #define void char */
  158834. /* #define const */
  158835. #undef CHAR_IS_UNSIGNED
  158836. #define HAVE_STDDEF_H
  158837. #define HAVE_STDLIB_H
  158838. #undef NEED_BSD_STRINGS
  158839. #undef NEED_SYS_TYPES_H
  158840. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158841. #undef NEED_SHORT_EXTERNAL_NAMES
  158842. #undef INCOMPLETE_TYPES_BROKEN
  158843. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158844. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158845. typedef unsigned char boolean;
  158846. #endif
  158847. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158848. #ifdef JPEG_INTERNALS
  158849. #undef RIGHT_SHIFT_IS_UNSIGNED
  158850. #endif /* JPEG_INTERNALS */
  158851. #ifdef JPEG_CJPEG_DJPEG
  158852. #define BMP_SUPPORTED /* BMP image file format */
  158853. #define GIF_SUPPORTED /* GIF image file format */
  158854. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158855. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158856. #define TARGA_SUPPORTED /* Targa image file format */
  158857. #define TWO_FILE_COMMANDLINE /* optional */
  158858. #define USE_SETMODE /* Microsoft has setmode() */
  158859. #undef NEED_SIGNAL_CATCHER
  158860. #undef DONT_USE_B_MODE
  158861. #undef PROGRESS_REPORT /* optional */
  158862. #endif /* JPEG_CJPEG_DJPEG */
  158863. /*** End of inlined file: jconfig.h ***/
  158864. /* widely used configuration options */
  158865. #endif
  158866. /*** Start of inlined file: jmorecfg.h ***/
  158867. /*
  158868. * Define BITS_IN_JSAMPLE as either
  158869. * 8 for 8-bit sample values (the usual setting)
  158870. * 12 for 12-bit sample values
  158871. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  158872. * JPEG standard, and the IJG code does not support anything else!
  158873. * We do not support run-time selection of data precision, sorry.
  158874. */
  158875. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  158876. /*
  158877. * Maximum number of components (color channels) allowed in JPEG image.
  158878. * To meet the letter of the JPEG spec, set this to 255. However, darn
  158879. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  158880. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  158881. * really short on memory. (Each allowed component costs a hundred or so
  158882. * bytes of storage, whether actually used in an image or not.)
  158883. */
  158884. #define MAX_COMPONENTS 10 /* maximum number of image components */
  158885. /*
  158886. * Basic data types.
  158887. * You may need to change these if you have a machine with unusual data
  158888. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  158889. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  158890. * but it had better be at least 16.
  158891. */
  158892. /* Representation of a single sample (pixel element value).
  158893. * We frequently allocate large arrays of these, so it's important to keep
  158894. * them small. But if you have memory to burn and access to char or short
  158895. * arrays is very slow on your hardware, you might want to change these.
  158896. */
  158897. #if BITS_IN_JSAMPLE == 8
  158898. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  158899. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  158900. */
  158901. #ifdef HAVE_UNSIGNED_CHAR
  158902. typedef unsigned char JSAMPLE;
  158903. #define GETJSAMPLE(value) ((int) (value))
  158904. #else /* not HAVE_UNSIGNED_CHAR */
  158905. typedef char JSAMPLE;
  158906. #ifdef CHAR_IS_UNSIGNED
  158907. #define GETJSAMPLE(value) ((int) (value))
  158908. #else
  158909. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  158910. #endif /* CHAR_IS_UNSIGNED */
  158911. #endif /* HAVE_UNSIGNED_CHAR */
  158912. #define MAXJSAMPLE 255
  158913. #define CENTERJSAMPLE 128
  158914. #endif /* BITS_IN_JSAMPLE == 8 */
  158915. #if BITS_IN_JSAMPLE == 12
  158916. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  158917. * On nearly all machines "short" will do nicely.
  158918. */
  158919. typedef short JSAMPLE;
  158920. #define GETJSAMPLE(value) ((int) (value))
  158921. #define MAXJSAMPLE 4095
  158922. #define CENTERJSAMPLE 2048
  158923. #endif /* BITS_IN_JSAMPLE == 12 */
  158924. /* Representation of a DCT frequency coefficient.
  158925. * This should be a signed value of at least 16 bits; "short" is usually OK.
  158926. * Again, we allocate large arrays of these, but you can change to int
  158927. * if you have memory to burn and "short" is really slow.
  158928. */
  158929. typedef short JCOEF;
  158930. /* Compressed datastreams are represented as arrays of JOCTET.
  158931. * These must be EXACTLY 8 bits wide, at least once they are written to
  158932. * external storage. Note that when using the stdio data source/destination
  158933. * managers, this is also the data type passed to fread/fwrite.
  158934. */
  158935. #ifdef HAVE_UNSIGNED_CHAR
  158936. typedef unsigned char JOCTET;
  158937. #define GETJOCTET(value) (value)
  158938. #else /* not HAVE_UNSIGNED_CHAR */
  158939. typedef char JOCTET;
  158940. #ifdef CHAR_IS_UNSIGNED
  158941. #define GETJOCTET(value) (value)
  158942. #else
  158943. #define GETJOCTET(value) ((value) & 0xFF)
  158944. #endif /* CHAR_IS_UNSIGNED */
  158945. #endif /* HAVE_UNSIGNED_CHAR */
  158946. /* These typedefs are used for various table entries and so forth.
  158947. * They must be at least as wide as specified; but making them too big
  158948. * won't cost a huge amount of memory, so we don't provide special
  158949. * extraction code like we did for JSAMPLE. (In other words, these
  158950. * typedefs live at a different point on the speed/space tradeoff curve.)
  158951. */
  158952. /* UINT8 must hold at least the values 0..255. */
  158953. #ifdef HAVE_UNSIGNED_CHAR
  158954. typedef unsigned char UINT8;
  158955. #else /* not HAVE_UNSIGNED_CHAR */
  158956. #ifdef CHAR_IS_UNSIGNED
  158957. typedef char UINT8;
  158958. #else /* not CHAR_IS_UNSIGNED */
  158959. typedef short UINT8;
  158960. #endif /* CHAR_IS_UNSIGNED */
  158961. #endif /* HAVE_UNSIGNED_CHAR */
  158962. /* UINT16 must hold at least the values 0..65535. */
  158963. #ifdef HAVE_UNSIGNED_SHORT
  158964. typedef unsigned short UINT16;
  158965. #else /* not HAVE_UNSIGNED_SHORT */
  158966. typedef unsigned int UINT16;
  158967. #endif /* HAVE_UNSIGNED_SHORT */
  158968. /* INT16 must hold at least the values -32768..32767. */
  158969. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  158970. typedef short INT16;
  158971. #endif
  158972. /* INT32 must hold at least signed 32-bit values. */
  158973. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  158974. typedef long INT32;
  158975. #endif
  158976. /* Datatype used for image dimensions. The JPEG standard only supports
  158977. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  158978. * "unsigned int" is sufficient on all machines. However, if you need to
  158979. * handle larger images and you don't mind deviating from the spec, you
  158980. * can change this datatype.
  158981. */
  158982. typedef unsigned int JDIMENSION;
  158983. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  158984. /* These macros are used in all function definitions and extern declarations.
  158985. * You could modify them if you need to change function linkage conventions;
  158986. * in particular, you'll need to do that to make the library a Windows DLL.
  158987. * Another application is to make all functions global for use with debuggers
  158988. * or code profilers that require it.
  158989. */
  158990. /* a function called through method pointers: */
  158991. #define METHODDEF(type) static type
  158992. /* a function used only in its module: */
  158993. #define LOCAL(type) static type
  158994. /* a function referenced thru EXTERNs: */
  158995. #define GLOBAL(type) type
  158996. /* a reference to a GLOBAL function: */
  158997. #define EXTERN(type) extern type
  158998. /* This macro is used to declare a "method", that is, a function pointer.
  158999. * We want to supply prototype parameters if the compiler can cope.
  159000. * Note that the arglist parameter must be parenthesized!
  159001. * Again, you can customize this if you need special linkage keywords.
  159002. */
  159003. #ifdef HAVE_PROTOTYPES
  159004. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159005. #else
  159006. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159007. #endif
  159008. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159009. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159010. * by just saying "FAR *" where such a pointer is needed. In a few places
  159011. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159012. */
  159013. #ifdef NEED_FAR_POINTERS
  159014. #define FAR far
  159015. #else
  159016. #define FAR
  159017. #endif
  159018. /*
  159019. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159020. * in standard header files. Or you may have conflicts with application-
  159021. * specific header files that you want to include together with these files.
  159022. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159023. */
  159024. #ifndef HAVE_BOOLEAN
  159025. typedef int boolean;
  159026. #endif
  159027. #ifndef FALSE /* in case these macros already exist */
  159028. #define FALSE 0 /* values of boolean */
  159029. #endif
  159030. #ifndef TRUE
  159031. #define TRUE 1
  159032. #endif
  159033. /*
  159034. * The remaining options affect code selection within the JPEG library,
  159035. * but they don't need to be visible to most applications using the library.
  159036. * To minimize application namespace pollution, the symbols won't be
  159037. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159038. */
  159039. #ifdef JPEG_INTERNALS
  159040. #define JPEG_INTERNAL_OPTIONS
  159041. #endif
  159042. #ifdef JPEG_INTERNAL_OPTIONS
  159043. /*
  159044. * These defines indicate whether to include various optional functions.
  159045. * Undefining some of these symbols will produce a smaller but less capable
  159046. * library. Note that you can leave certain source files out of the
  159047. * compilation/linking process if you've #undef'd the corresponding symbols.
  159048. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159049. */
  159050. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159051. /* Capability options common to encoder and decoder: */
  159052. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159053. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159054. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159055. /* Encoder capability options: */
  159056. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159057. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159058. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159059. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159060. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159061. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159062. * precision, so jchuff.c normally uses entropy optimization to compute
  159063. * usable tables for higher precision. If you don't want to do optimization,
  159064. * you'll have to supply different default Huffman tables.
  159065. * The exact same statements apply for progressive JPEG: the default tables
  159066. * don't work for progressive mode. (This may get fixed, however.)
  159067. */
  159068. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159069. /* Decoder capability options: */
  159070. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159071. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159072. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159073. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159074. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159075. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159076. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159077. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159078. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159079. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159080. /* more capability options later, no doubt */
  159081. /*
  159082. * Ordering of RGB data in scanlines passed to or from the application.
  159083. * If your application wants to deal with data in the order B,G,R, just
  159084. * change these macros. You can also deal with formats such as R,G,B,X
  159085. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159086. * the offsets will also change the order in which colormap data is organized.
  159087. * RESTRICTIONS:
  159088. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159089. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159090. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159091. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159092. * is not 3 (they don't understand about dummy color components!). So you
  159093. * can't use color quantization if you change that value.
  159094. */
  159095. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159096. #define RGB_GREEN 1 /* Offset of Green */
  159097. #define RGB_BLUE 2 /* Offset of Blue */
  159098. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159099. /* Definitions for speed-related optimizations. */
  159100. /* If your compiler supports inline functions, define INLINE
  159101. * as the inline keyword; otherwise define it as empty.
  159102. */
  159103. #ifndef INLINE
  159104. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159105. #define INLINE __inline__
  159106. #endif
  159107. #ifndef INLINE
  159108. #define INLINE /* default is to define it as empty */
  159109. #endif
  159110. #endif
  159111. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159112. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159113. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159114. */
  159115. #ifndef MULTIPLIER
  159116. #define MULTIPLIER int /* type for fastest integer multiply */
  159117. #endif
  159118. /* FAST_FLOAT should be either float or double, whichever is done faster
  159119. * by your compiler. (Note that this type is only used in the floating point
  159120. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159121. * Typically, float is faster in ANSI C compilers, while double is faster in
  159122. * pre-ANSI compilers (because they insist on converting to double anyway).
  159123. * The code below therefore chooses float if we have ANSI-style prototypes.
  159124. */
  159125. #ifndef FAST_FLOAT
  159126. #ifdef HAVE_PROTOTYPES
  159127. #define FAST_FLOAT float
  159128. #else
  159129. #define FAST_FLOAT double
  159130. #endif
  159131. #endif
  159132. #endif /* JPEG_INTERNAL_OPTIONS */
  159133. /*** End of inlined file: jmorecfg.h ***/
  159134. /* seldom changed options */
  159135. /* Version ID for the JPEG library.
  159136. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159137. */
  159138. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159139. /* Various constants determining the sizes of things.
  159140. * All of these are specified by the JPEG standard, so don't change them
  159141. * if you want to be compatible.
  159142. */
  159143. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159144. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159145. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159146. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159147. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159148. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159149. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159150. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159151. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159152. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159153. * to handle it. We even let you do this from the jconfig.h file. However,
  159154. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159155. * sometimes emits noncompliant files doesn't mean you should too.
  159156. */
  159157. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159158. #ifndef D_MAX_BLOCKS_IN_MCU
  159159. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159160. #endif
  159161. /* Data structures for images (arrays of samples and of DCT coefficients).
  159162. * On 80x86 machines, the image arrays are too big for near pointers,
  159163. * but the pointer arrays can fit in near memory.
  159164. */
  159165. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159166. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159167. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159168. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159169. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159170. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159171. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159172. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159173. /* Types for JPEG compression parameters and working tables. */
  159174. /* DCT coefficient quantization tables. */
  159175. typedef struct {
  159176. /* This array gives the coefficient quantizers in natural array order
  159177. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159178. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159179. */
  159180. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159181. /* This field is used only during compression. It's initialized FALSE when
  159182. * the table is created, and set TRUE when it's been output to the file.
  159183. * You could suppress output of a table by setting this to TRUE.
  159184. * (See jpeg_suppress_tables for an example.)
  159185. */
  159186. boolean sent_table; /* TRUE when table has been output */
  159187. } JQUANT_TBL;
  159188. /* Huffman coding tables. */
  159189. typedef struct {
  159190. /* These two fields directly represent the contents of a JPEG DHT marker */
  159191. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159192. /* length k bits; bits[0] is unused */
  159193. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159194. /* This field is used only during compression. It's initialized FALSE when
  159195. * the table is created, and set TRUE when it's been output to the file.
  159196. * You could suppress output of a table by setting this to TRUE.
  159197. * (See jpeg_suppress_tables for an example.)
  159198. */
  159199. boolean sent_table; /* TRUE when table has been output */
  159200. } JHUFF_TBL;
  159201. /* Basic info about one component (color channel). */
  159202. typedef struct {
  159203. /* These values are fixed over the whole image. */
  159204. /* For compression, they must be supplied by parameter setup; */
  159205. /* for decompression, they are read from the SOF marker. */
  159206. int component_id; /* identifier for this component (0..255) */
  159207. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159208. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159209. int v_samp_factor; /* vertical sampling factor (1..4) */
  159210. int quant_tbl_no; /* quantization table selector (0..3) */
  159211. /* These values may vary between scans. */
  159212. /* For compression, they must be supplied by parameter setup; */
  159213. /* for decompression, they are read from the SOS marker. */
  159214. /* The decompressor output side may not use these variables. */
  159215. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159216. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159217. /* Remaining fields should be treated as private by applications. */
  159218. /* These values are computed during compression or decompression startup: */
  159219. /* Component's size in DCT blocks.
  159220. * Any dummy blocks added to complete an MCU are not counted; therefore
  159221. * these values do not depend on whether a scan is interleaved or not.
  159222. */
  159223. JDIMENSION width_in_blocks;
  159224. JDIMENSION height_in_blocks;
  159225. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159226. * For decompression this is the size of the output from one DCT block,
  159227. * reflecting any scaling we choose to apply during the IDCT step.
  159228. * Values of 1,2,4,8 are likely to be supported. Note that different
  159229. * components may receive different IDCT scalings.
  159230. */
  159231. int DCT_scaled_size;
  159232. /* The downsampled dimensions are the component's actual, unpadded number
  159233. * of samples at the main buffer (preprocessing/compression interface), thus
  159234. * downsampled_width = ceil(image_width * Hi/Hmax)
  159235. * and similarly for height. For decompression, IDCT scaling is included, so
  159236. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159237. */
  159238. JDIMENSION downsampled_width; /* actual width in samples */
  159239. JDIMENSION downsampled_height; /* actual height in samples */
  159240. /* This flag is used only for decompression. In cases where some of the
  159241. * components will be ignored (eg grayscale output from YCbCr image),
  159242. * we can skip most computations for the unused components.
  159243. */
  159244. boolean component_needed; /* do we need the value of this component? */
  159245. /* These values are computed before starting a scan of the component. */
  159246. /* The decompressor output side may not use these variables. */
  159247. int MCU_width; /* number of blocks per MCU, horizontally */
  159248. int MCU_height; /* number of blocks per MCU, vertically */
  159249. int MCU_blocks; /* MCU_width * MCU_height */
  159250. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159251. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159252. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159253. /* Saved quantization table for component; NULL if none yet saved.
  159254. * See jdinput.c comments about the need for this information.
  159255. * This field is currently used only for decompression.
  159256. */
  159257. JQUANT_TBL * quant_table;
  159258. /* Private per-component storage for DCT or IDCT subsystem. */
  159259. void * dct_table;
  159260. } jpeg_component_info;
  159261. /* The script for encoding a multiple-scan file is an array of these: */
  159262. typedef struct {
  159263. int comps_in_scan; /* number of components encoded in this scan */
  159264. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159265. int Ss, Se; /* progressive JPEG spectral selection parms */
  159266. int Ah, Al; /* progressive JPEG successive approx. parms */
  159267. } jpeg_scan_info;
  159268. /* The decompressor can save APPn and COM markers in a list of these: */
  159269. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159270. struct jpeg_marker_struct {
  159271. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159272. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159273. unsigned int original_length; /* # bytes of data in the file */
  159274. unsigned int data_length; /* # bytes of data saved at data[] */
  159275. JOCTET FAR * data; /* the data contained in the marker */
  159276. /* the marker length word is not counted in data_length or original_length */
  159277. };
  159278. /* Known color spaces. */
  159279. typedef enum {
  159280. JCS_UNKNOWN, /* error/unspecified */
  159281. JCS_GRAYSCALE, /* monochrome */
  159282. JCS_RGB, /* red/green/blue */
  159283. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159284. JCS_CMYK, /* C/M/Y/K */
  159285. JCS_YCCK /* Y/Cb/Cr/K */
  159286. } J_COLOR_SPACE;
  159287. /* DCT/IDCT algorithm options. */
  159288. typedef enum {
  159289. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159290. JDCT_IFAST, /* faster, less accurate integer method */
  159291. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159292. } J_DCT_METHOD;
  159293. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159294. #define JDCT_DEFAULT JDCT_ISLOW
  159295. #endif
  159296. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159297. #define JDCT_FASTEST JDCT_IFAST
  159298. #endif
  159299. /* Dithering options for decompression. */
  159300. typedef enum {
  159301. JDITHER_NONE, /* no dithering */
  159302. JDITHER_ORDERED, /* simple ordered dither */
  159303. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159304. } J_DITHER_MODE;
  159305. /* Common fields between JPEG compression and decompression master structs. */
  159306. #define jpeg_common_fields \
  159307. struct jpeg_error_mgr * err; /* Error handler module */\
  159308. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159309. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159310. void * client_data; /* Available for use by application */\
  159311. boolean is_decompressor; /* So common code can tell which is which */\
  159312. int global_state /* For checking call sequence validity */
  159313. /* Routines that are to be used by both halves of the library are declared
  159314. * to receive a pointer to this structure. There are no actual instances of
  159315. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159316. */
  159317. struct jpeg_common_struct {
  159318. jpeg_common_fields; /* Fields common to both master struct types */
  159319. /* Additional fields follow in an actual jpeg_compress_struct or
  159320. * jpeg_decompress_struct. All three structs must agree on these
  159321. * initial fields! (This would be a lot cleaner in C++.)
  159322. */
  159323. };
  159324. typedef struct jpeg_common_struct * j_common_ptr;
  159325. typedef struct jpeg_compress_struct * j_compress_ptr;
  159326. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159327. /* Master record for a compression instance */
  159328. struct jpeg_compress_struct {
  159329. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159330. /* Destination for compressed data */
  159331. struct jpeg_destination_mgr * dest;
  159332. /* Description of source image --- these fields must be filled in by
  159333. * outer application before starting compression. in_color_space must
  159334. * be correct before you can even call jpeg_set_defaults().
  159335. */
  159336. JDIMENSION image_width; /* input image width */
  159337. JDIMENSION image_height; /* input image height */
  159338. int input_components; /* # of color components in input image */
  159339. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159340. double input_gamma; /* image gamma of input image */
  159341. /* Compression parameters --- these fields must be set before calling
  159342. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159343. * initialize everything to reasonable defaults, then changing anything
  159344. * the application specifically wants to change. That way you won't get
  159345. * burnt when new parameters are added. Also note that there are several
  159346. * helper routines to simplify changing parameters.
  159347. */
  159348. int data_precision; /* bits of precision in image data */
  159349. int num_components; /* # of color components in JPEG image */
  159350. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159351. jpeg_component_info * comp_info;
  159352. /* comp_info[i] describes component that appears i'th in SOF */
  159353. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159354. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159355. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159356. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159357. /* ptrs to Huffman coding tables, or NULL if not defined */
  159358. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159359. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159360. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159361. int num_scans; /* # of entries in scan_info array */
  159362. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159363. /* The default value of scan_info is NULL, which causes a single-scan
  159364. * sequential JPEG file to be emitted. To create a multi-scan file,
  159365. * set num_scans and scan_info to point to an array of scan definitions.
  159366. */
  159367. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159368. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159369. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159370. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159371. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159372. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159373. /* The restart interval can be specified in absolute MCUs by setting
  159374. * restart_interval, or in MCU rows by setting restart_in_rows
  159375. * (in which case the correct restart_interval will be figured
  159376. * for each scan).
  159377. */
  159378. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159379. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159380. /* Parameters controlling emission of special markers. */
  159381. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159382. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159383. UINT8 JFIF_minor_version;
  159384. /* These three values are not used by the JPEG code, merely copied */
  159385. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159386. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159387. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159388. UINT8 density_unit; /* JFIF code for pixel size units */
  159389. UINT16 X_density; /* Horizontal pixel density */
  159390. UINT16 Y_density; /* Vertical pixel density */
  159391. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159392. /* State variable: index of next scanline to be written to
  159393. * jpeg_write_scanlines(). Application may use this to control its
  159394. * processing loop, e.g., "while (next_scanline < image_height)".
  159395. */
  159396. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159397. /* Remaining fields are known throughout compressor, but generally
  159398. * should not be touched by a surrounding application.
  159399. */
  159400. /*
  159401. * These fields are computed during compression startup
  159402. */
  159403. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159404. int max_h_samp_factor; /* largest h_samp_factor */
  159405. int max_v_samp_factor; /* largest v_samp_factor */
  159406. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159407. /* The coefficient controller receives data in units of MCU rows as defined
  159408. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159409. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159410. * "iMCU" (interleaved MCU) row.
  159411. */
  159412. /*
  159413. * These fields are valid during any one scan.
  159414. * They describe the components and MCUs actually appearing in the scan.
  159415. */
  159416. int comps_in_scan; /* # of JPEG components in this scan */
  159417. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159418. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159419. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159420. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159421. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159422. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159423. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159424. /* i'th block in an MCU */
  159425. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159426. /*
  159427. * Links to compression subobjects (methods and private variables of modules)
  159428. */
  159429. struct jpeg_comp_master * master;
  159430. struct jpeg_c_main_controller * main;
  159431. struct jpeg_c_prep_controller * prep;
  159432. struct jpeg_c_coef_controller * coef;
  159433. struct jpeg_marker_writer * marker;
  159434. struct jpeg_color_converter * cconvert;
  159435. struct jpeg_downsampler * downsample;
  159436. struct jpeg_forward_dct * fdct;
  159437. struct jpeg_entropy_encoder * entropy;
  159438. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159439. int script_space_size;
  159440. };
  159441. /* Master record for a decompression instance */
  159442. struct jpeg_decompress_struct {
  159443. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159444. /* Source of compressed data */
  159445. struct jpeg_source_mgr * src;
  159446. /* Basic description of image --- filled in by jpeg_read_header(). */
  159447. /* Application may inspect these values to decide how to process image. */
  159448. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159449. JDIMENSION image_height; /* nominal image height */
  159450. int num_components; /* # of color components in JPEG image */
  159451. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159452. /* Decompression processing parameters --- these fields must be set before
  159453. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159454. * them to default values.
  159455. */
  159456. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159457. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159458. double output_gamma; /* image gamma wanted in output */
  159459. boolean buffered_image; /* TRUE=multiple output passes */
  159460. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159461. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159462. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159463. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159464. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159465. /* the following are ignored if not quantize_colors: */
  159466. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159467. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159468. int desired_number_of_colors; /* max # colors to use in created colormap */
  159469. /* these are significant only in buffered-image mode: */
  159470. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159471. boolean enable_external_quant;/* enable future use of external colormap */
  159472. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159473. /* Description of actual output image that will be returned to application.
  159474. * These fields are computed by jpeg_start_decompress().
  159475. * You can also use jpeg_calc_output_dimensions() to determine these values
  159476. * in advance of calling jpeg_start_decompress().
  159477. */
  159478. JDIMENSION output_width; /* scaled image width */
  159479. JDIMENSION output_height; /* scaled image height */
  159480. int out_color_components; /* # of color components in out_color_space */
  159481. int output_components; /* # of color components returned */
  159482. /* output_components is 1 (a colormap index) when quantizing colors;
  159483. * otherwise it equals out_color_components.
  159484. */
  159485. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159486. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159487. * high, space and time will be wasted due to unnecessary data copying.
  159488. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159489. */
  159490. /* When quantizing colors, the output colormap is described by these fields.
  159491. * The application can supply a colormap by setting colormap non-NULL before
  159492. * calling jpeg_start_decompress; otherwise a colormap is created during
  159493. * jpeg_start_decompress or jpeg_start_output.
  159494. * The map has out_color_components rows and actual_number_of_colors columns.
  159495. */
  159496. int actual_number_of_colors; /* number of entries in use */
  159497. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159498. /* State variables: these variables indicate the progress of decompression.
  159499. * The application may examine these but must not modify them.
  159500. */
  159501. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159502. * Application may use this to control its processing loop, e.g.,
  159503. * "while (output_scanline < output_height)".
  159504. */
  159505. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159506. /* Current input scan number and number of iMCU rows completed in scan.
  159507. * These indicate the progress of the decompressor input side.
  159508. */
  159509. int input_scan_number; /* Number of SOS markers seen so far */
  159510. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159511. /* The "output scan number" is the notional scan being displayed by the
  159512. * output side. The decompressor will not allow output scan/row number
  159513. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159514. */
  159515. int output_scan_number; /* Nominal scan number being displayed */
  159516. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159517. /* Current progression status. coef_bits[c][i] indicates the precision
  159518. * with which component c's DCT coefficient i (in zigzag order) is known.
  159519. * It is -1 when no data has yet been received, otherwise it is the point
  159520. * transform (shift) value for the most recent scan of the coefficient
  159521. * (thus, 0 at completion of the progression).
  159522. * This pointer is NULL when reading a non-progressive file.
  159523. */
  159524. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159525. /* Internal JPEG parameters --- the application usually need not look at
  159526. * these fields. Note that the decompressor output side may not use
  159527. * any parameters that can change between scans.
  159528. */
  159529. /* Quantization and Huffman tables are carried forward across input
  159530. * datastreams when processing abbreviated JPEG datastreams.
  159531. */
  159532. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159533. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159534. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159535. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159536. /* ptrs to Huffman coding tables, or NULL if not defined */
  159537. /* These parameters are never carried across datastreams, since they
  159538. * are given in SOF/SOS markers or defined to be reset by SOI.
  159539. */
  159540. int data_precision; /* bits of precision in image data */
  159541. jpeg_component_info * comp_info;
  159542. /* comp_info[i] describes component that appears i'th in SOF */
  159543. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159544. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159545. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159546. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159547. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159548. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159549. /* These fields record data obtained from optional markers recognized by
  159550. * the JPEG library.
  159551. */
  159552. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159553. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159554. UINT8 JFIF_major_version; /* JFIF version number */
  159555. UINT8 JFIF_minor_version;
  159556. UINT8 density_unit; /* JFIF code for pixel size units */
  159557. UINT16 X_density; /* Horizontal pixel density */
  159558. UINT16 Y_density; /* Vertical pixel density */
  159559. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159560. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159561. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159562. /* Aside from the specific data retained from APPn markers known to the
  159563. * library, the uninterpreted contents of any or all APPn and COM markers
  159564. * can be saved in a list for examination by the application.
  159565. */
  159566. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159567. /* Remaining fields are known throughout decompressor, but generally
  159568. * should not be touched by a surrounding application.
  159569. */
  159570. /*
  159571. * These fields are computed during decompression startup
  159572. */
  159573. int max_h_samp_factor; /* largest h_samp_factor */
  159574. int max_v_samp_factor; /* largest v_samp_factor */
  159575. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159576. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159577. /* The coefficient controller's input and output progress is measured in
  159578. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159579. * in fully interleaved JPEG scans, but are used whether the scan is
  159580. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159581. * rows of each component. Therefore, the IDCT output contains
  159582. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159583. */
  159584. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159585. /*
  159586. * These fields are valid during any one scan.
  159587. * They describe the components and MCUs actually appearing in the scan.
  159588. * Note that the decompressor output side must not use these fields.
  159589. */
  159590. int comps_in_scan; /* # of JPEG components in this scan */
  159591. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159592. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159593. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159594. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159595. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159596. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159597. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159598. /* i'th block in an MCU */
  159599. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159600. /* This field is shared between entropy decoder and marker parser.
  159601. * It is either zero or the code of a JPEG marker that has been
  159602. * read from the data source, but has not yet been processed.
  159603. */
  159604. int unread_marker;
  159605. /*
  159606. * Links to decompression subobjects (methods, private variables of modules)
  159607. */
  159608. struct jpeg_decomp_master * master;
  159609. struct jpeg_d_main_controller * main;
  159610. struct jpeg_d_coef_controller * coef;
  159611. struct jpeg_d_post_controller * post;
  159612. struct jpeg_input_controller * inputctl;
  159613. struct jpeg_marker_reader * marker;
  159614. struct jpeg_entropy_decoder * entropy;
  159615. struct jpeg_inverse_dct * idct;
  159616. struct jpeg_upsampler * upsample;
  159617. struct jpeg_color_deconverter * cconvert;
  159618. struct jpeg_color_quantizer * cquantize;
  159619. };
  159620. /* "Object" declarations for JPEG modules that may be supplied or called
  159621. * directly by the surrounding application.
  159622. * As with all objects in the JPEG library, these structs only define the
  159623. * publicly visible methods and state variables of a module. Additional
  159624. * private fields may exist after the public ones.
  159625. */
  159626. /* Error handler object */
  159627. struct jpeg_error_mgr {
  159628. /* Error exit handler: does not return to caller */
  159629. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159630. /* Conditionally emit a trace or warning message */
  159631. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159632. /* Routine that actually outputs a trace or error message */
  159633. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159634. /* Format a message string for the most recent JPEG error or message */
  159635. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159636. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159637. /* Reset error state variables at start of a new image */
  159638. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159639. /* The message ID code and any parameters are saved here.
  159640. * A message can have one string parameter or up to 8 int parameters.
  159641. */
  159642. int msg_code;
  159643. #define JMSG_STR_PARM_MAX 80
  159644. union {
  159645. int i[8];
  159646. char s[JMSG_STR_PARM_MAX];
  159647. } msg_parm;
  159648. /* Standard state variables for error facility */
  159649. int trace_level; /* max msg_level that will be displayed */
  159650. /* For recoverable corrupt-data errors, we emit a warning message,
  159651. * but keep going unless emit_message chooses to abort. emit_message
  159652. * should count warnings in num_warnings. The surrounding application
  159653. * can check for bad data by seeing if num_warnings is nonzero at the
  159654. * end of processing.
  159655. */
  159656. long num_warnings; /* number of corrupt-data warnings */
  159657. /* These fields point to the table(s) of error message strings.
  159658. * An application can change the table pointer to switch to a different
  159659. * message list (typically, to change the language in which errors are
  159660. * reported). Some applications may wish to add additional error codes
  159661. * that will be handled by the JPEG library error mechanism; the second
  159662. * table pointer is used for this purpose.
  159663. *
  159664. * First table includes all errors generated by JPEG library itself.
  159665. * Error code 0 is reserved for a "no such error string" message.
  159666. */
  159667. const char * const * jpeg_message_table; /* Library errors */
  159668. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159669. /* Second table can be added by application (see cjpeg/djpeg for example).
  159670. * It contains strings numbered first_addon_message..last_addon_message.
  159671. */
  159672. const char * const * addon_message_table; /* Non-library errors */
  159673. int first_addon_message; /* code for first string in addon table */
  159674. int last_addon_message; /* code for last string in addon table */
  159675. };
  159676. /* Progress monitor object */
  159677. struct jpeg_progress_mgr {
  159678. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159679. long pass_counter; /* work units completed in this pass */
  159680. long pass_limit; /* total number of work units in this pass */
  159681. int completed_passes; /* passes completed so far */
  159682. int total_passes; /* total number of passes expected */
  159683. };
  159684. /* Data destination object for compression */
  159685. struct jpeg_destination_mgr {
  159686. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159687. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159688. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159689. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159690. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159691. };
  159692. /* Data source object for decompression */
  159693. struct jpeg_source_mgr {
  159694. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159695. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159696. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159697. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159698. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159699. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159700. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159701. };
  159702. /* Memory manager object.
  159703. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159704. * and "really big" objects (virtual arrays with backing store if needed).
  159705. * The memory manager does not allow individual objects to be freed; rather,
  159706. * each created object is assigned to a pool, and whole pools can be freed
  159707. * at once. This is faster and more convenient than remembering exactly what
  159708. * to free, especially where malloc()/free() are not too speedy.
  159709. * NB: alloc routines never return NULL. They exit to error_exit if not
  159710. * successful.
  159711. */
  159712. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159713. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159714. #define JPOOL_NUMPOOLS 2
  159715. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159716. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159717. struct jpeg_memory_mgr {
  159718. /* Method pointers */
  159719. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159720. size_t sizeofobject));
  159721. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159722. size_t sizeofobject));
  159723. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159724. JDIMENSION samplesperrow,
  159725. JDIMENSION numrows));
  159726. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159727. JDIMENSION blocksperrow,
  159728. JDIMENSION numrows));
  159729. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159730. int pool_id,
  159731. boolean pre_zero,
  159732. JDIMENSION samplesperrow,
  159733. JDIMENSION numrows,
  159734. JDIMENSION maxaccess));
  159735. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159736. int pool_id,
  159737. boolean pre_zero,
  159738. JDIMENSION blocksperrow,
  159739. JDIMENSION numrows,
  159740. JDIMENSION maxaccess));
  159741. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159742. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159743. jvirt_sarray_ptr ptr,
  159744. JDIMENSION start_row,
  159745. JDIMENSION num_rows,
  159746. boolean writable));
  159747. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159748. jvirt_barray_ptr ptr,
  159749. JDIMENSION start_row,
  159750. JDIMENSION num_rows,
  159751. boolean writable));
  159752. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159753. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159754. /* Limit on memory allocation for this JPEG object. (Note that this is
  159755. * merely advisory, not a guaranteed maximum; it only affects the space
  159756. * used for virtual-array buffers.) May be changed by outer application
  159757. * after creating the JPEG object.
  159758. */
  159759. long max_memory_to_use;
  159760. /* Maximum allocation request accepted by alloc_large. */
  159761. long max_alloc_chunk;
  159762. };
  159763. /* Routine signature for application-supplied marker processing methods.
  159764. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159765. */
  159766. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159767. /* Declarations for routines called by application.
  159768. * The JPP macro hides prototype parameters from compilers that can't cope.
  159769. * Note JPP requires double parentheses.
  159770. */
  159771. #ifdef HAVE_PROTOTYPES
  159772. #define JPP(arglist) arglist
  159773. #else
  159774. #define JPP(arglist) ()
  159775. #endif
  159776. /* Short forms of external names for systems with brain-damaged linkers.
  159777. * We shorten external names to be unique in the first six letters, which
  159778. * is good enough for all known systems.
  159779. * (If your compiler itself needs names to be unique in less than 15
  159780. * characters, you are out of luck. Get a better compiler.)
  159781. */
  159782. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159783. #define jpeg_std_error jStdError
  159784. #define jpeg_CreateCompress jCreaCompress
  159785. #define jpeg_CreateDecompress jCreaDecompress
  159786. #define jpeg_destroy_compress jDestCompress
  159787. #define jpeg_destroy_decompress jDestDecompress
  159788. #define jpeg_stdio_dest jStdDest
  159789. #define jpeg_stdio_src jStdSrc
  159790. #define jpeg_set_defaults jSetDefaults
  159791. #define jpeg_set_colorspace jSetColorspace
  159792. #define jpeg_default_colorspace jDefColorspace
  159793. #define jpeg_set_quality jSetQuality
  159794. #define jpeg_set_linear_quality jSetLQuality
  159795. #define jpeg_add_quant_table jAddQuantTable
  159796. #define jpeg_quality_scaling jQualityScaling
  159797. #define jpeg_simple_progression jSimProgress
  159798. #define jpeg_suppress_tables jSuppressTables
  159799. #define jpeg_alloc_quant_table jAlcQTable
  159800. #define jpeg_alloc_huff_table jAlcHTable
  159801. #define jpeg_start_compress jStrtCompress
  159802. #define jpeg_write_scanlines jWrtScanlines
  159803. #define jpeg_finish_compress jFinCompress
  159804. #define jpeg_write_raw_data jWrtRawData
  159805. #define jpeg_write_marker jWrtMarker
  159806. #define jpeg_write_m_header jWrtMHeader
  159807. #define jpeg_write_m_byte jWrtMByte
  159808. #define jpeg_write_tables jWrtTables
  159809. #define jpeg_read_header jReadHeader
  159810. #define jpeg_start_decompress jStrtDecompress
  159811. #define jpeg_read_scanlines jReadScanlines
  159812. #define jpeg_finish_decompress jFinDecompress
  159813. #define jpeg_read_raw_data jReadRawData
  159814. #define jpeg_has_multiple_scans jHasMultScn
  159815. #define jpeg_start_output jStrtOutput
  159816. #define jpeg_finish_output jFinOutput
  159817. #define jpeg_input_complete jInComplete
  159818. #define jpeg_new_colormap jNewCMap
  159819. #define jpeg_consume_input jConsumeInput
  159820. #define jpeg_calc_output_dimensions jCalcDimensions
  159821. #define jpeg_save_markers jSaveMarkers
  159822. #define jpeg_set_marker_processor jSetMarker
  159823. #define jpeg_read_coefficients jReadCoefs
  159824. #define jpeg_write_coefficients jWrtCoefs
  159825. #define jpeg_copy_critical_parameters jCopyCrit
  159826. #define jpeg_abort_compress jAbrtCompress
  159827. #define jpeg_abort_decompress jAbrtDecompress
  159828. #define jpeg_abort jAbort
  159829. #define jpeg_destroy jDestroy
  159830. #define jpeg_resync_to_restart jResyncRestart
  159831. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159832. /* Default error-management setup */
  159833. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  159834. JPP((struct jpeg_error_mgr * err));
  159835. /* Initialization of JPEG compression objects.
  159836. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  159837. * names that applications should call. These expand to calls on
  159838. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  159839. * passed for version mismatch checking.
  159840. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  159841. */
  159842. #define jpeg_create_compress(cinfo) \
  159843. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  159844. (size_t) sizeof(struct jpeg_compress_struct))
  159845. #define jpeg_create_decompress(cinfo) \
  159846. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  159847. (size_t) sizeof(struct jpeg_decompress_struct))
  159848. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  159849. int version, size_t structsize));
  159850. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  159851. int version, size_t structsize));
  159852. /* Destruction of JPEG compression objects */
  159853. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  159854. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  159855. /* Standard data source and destination managers: stdio streams. */
  159856. /* Caller is responsible for opening the file before and closing after. */
  159857. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  159858. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  159859. /* Default parameter setup for compression */
  159860. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  159861. /* Compression parameter setup aids */
  159862. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  159863. J_COLOR_SPACE colorspace));
  159864. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  159865. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  159866. boolean force_baseline));
  159867. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  159868. int scale_factor,
  159869. boolean force_baseline));
  159870. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  159871. const unsigned int *basic_table,
  159872. int scale_factor,
  159873. boolean force_baseline));
  159874. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  159875. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  159876. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  159877. boolean suppress));
  159878. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  159879. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  159880. /* Main entry points for compression */
  159881. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  159882. boolean write_all_tables));
  159883. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  159884. JSAMPARRAY scanlines,
  159885. JDIMENSION num_lines));
  159886. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  159887. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  159888. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  159889. JSAMPIMAGE data,
  159890. JDIMENSION num_lines));
  159891. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  159892. EXTERN(void) jpeg_write_marker
  159893. JPP((j_compress_ptr cinfo, int marker,
  159894. const JOCTET * dataptr, unsigned int datalen));
  159895. /* Same, but piecemeal. */
  159896. EXTERN(void) jpeg_write_m_header
  159897. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  159898. EXTERN(void) jpeg_write_m_byte
  159899. JPP((j_compress_ptr cinfo, int val));
  159900. /* Alternate compression function: just write an abbreviated table file */
  159901. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  159902. /* Decompression startup: read start of JPEG datastream to see what's there */
  159903. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  159904. boolean require_image));
  159905. /* Return value is one of: */
  159906. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  159907. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  159908. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  159909. /* If you pass require_image = TRUE (normal case), you need not check for
  159910. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  159911. * JPEG_SUSPENDED is only possible if you use a data source module that can
  159912. * give a suspension return (the stdio source module doesn't).
  159913. */
  159914. /* Main entry points for decompression */
  159915. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  159916. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  159917. JSAMPARRAY scanlines,
  159918. JDIMENSION max_lines));
  159919. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  159920. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  159921. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  159922. JSAMPIMAGE data,
  159923. JDIMENSION max_lines));
  159924. /* Additional entry points for buffered-image mode. */
  159925. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  159926. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  159927. int scan_number));
  159928. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  159929. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  159930. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  159931. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  159932. /* Return value is one of: */
  159933. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  159934. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  159935. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  159936. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  159937. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  159938. /* Precalculate output dimensions for current decompression parameters. */
  159939. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  159940. /* Control saving of COM and APPn markers into marker_list. */
  159941. EXTERN(void) jpeg_save_markers
  159942. JPP((j_decompress_ptr cinfo, int marker_code,
  159943. unsigned int length_limit));
  159944. /* Install a special processing method for COM or APPn markers. */
  159945. EXTERN(void) jpeg_set_marker_processor
  159946. JPP((j_decompress_ptr cinfo, int marker_code,
  159947. jpeg_marker_parser_method routine));
  159948. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  159949. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  159950. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  159951. jvirt_barray_ptr * coef_arrays));
  159952. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  159953. j_compress_ptr dstinfo));
  159954. /* If you choose to abort compression or decompression before completing
  159955. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  159956. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  159957. * if you're done with the JPEG object, but if you want to clean it up and
  159958. * reuse it, call this:
  159959. */
  159960. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  159961. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  159962. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  159963. * flavor of JPEG object. These may be more convenient in some places.
  159964. */
  159965. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  159966. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  159967. /* Default restart-marker-resync procedure for use by data source modules */
  159968. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  159969. int desired));
  159970. /* These marker codes are exported since applications and data source modules
  159971. * are likely to want to use them.
  159972. */
  159973. #define JPEG_RST0 0xD0 /* RST0 marker code */
  159974. #define JPEG_EOI 0xD9 /* EOI marker code */
  159975. #define JPEG_APP0 0xE0 /* APP0 marker code */
  159976. #define JPEG_COM 0xFE /* COM marker code */
  159977. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  159978. * for structure definitions that are never filled in, keep it quiet by
  159979. * supplying dummy definitions for the various substructures.
  159980. */
  159981. #ifdef INCOMPLETE_TYPES_BROKEN
  159982. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  159983. struct jvirt_sarray_control { long dummy; };
  159984. struct jvirt_barray_control { long dummy; };
  159985. struct jpeg_comp_master { long dummy; };
  159986. struct jpeg_c_main_controller { long dummy; };
  159987. struct jpeg_c_prep_controller { long dummy; };
  159988. struct jpeg_c_coef_controller { long dummy; };
  159989. struct jpeg_marker_writer { long dummy; };
  159990. struct jpeg_color_converter { long dummy; };
  159991. struct jpeg_downsampler { long dummy; };
  159992. struct jpeg_forward_dct { long dummy; };
  159993. struct jpeg_entropy_encoder { long dummy; };
  159994. struct jpeg_decomp_master { long dummy; };
  159995. struct jpeg_d_main_controller { long dummy; };
  159996. struct jpeg_d_coef_controller { long dummy; };
  159997. struct jpeg_d_post_controller { long dummy; };
  159998. struct jpeg_input_controller { long dummy; };
  159999. struct jpeg_marker_reader { long dummy; };
  160000. struct jpeg_entropy_decoder { long dummy; };
  160001. struct jpeg_inverse_dct { long dummy; };
  160002. struct jpeg_upsampler { long dummy; };
  160003. struct jpeg_color_deconverter { long dummy; };
  160004. struct jpeg_color_quantizer { long dummy; };
  160005. #endif /* JPEG_INTERNALS */
  160006. #endif /* INCOMPLETE_TYPES_BROKEN */
  160007. /*
  160008. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160009. * The internal structure declarations are read only when that is true.
  160010. * Applications using the library should not include jpegint.h, but may wish
  160011. * to include jerror.h.
  160012. */
  160013. #ifdef JPEG_INTERNALS
  160014. /*** Start of inlined file: jpegint.h ***/
  160015. /* Declarations for both compression & decompression */
  160016. typedef enum { /* Operating modes for buffer controllers */
  160017. JBUF_PASS_THRU, /* Plain stripwise operation */
  160018. /* Remaining modes require a full-image buffer to have been created */
  160019. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160020. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160021. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160022. } J_BUF_MODE;
  160023. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160024. #define CSTATE_START 100 /* after create_compress */
  160025. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160026. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160027. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160028. #define DSTATE_START 200 /* after create_decompress */
  160029. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160030. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160031. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160032. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160033. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160034. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160035. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160036. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160037. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160038. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160039. /* Declarations for compression modules */
  160040. /* Master control module */
  160041. struct jpeg_comp_master {
  160042. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160043. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160044. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160045. /* State variables made visible to other modules */
  160046. boolean call_pass_startup; /* True if pass_startup must be called */
  160047. boolean is_last_pass; /* True during last pass */
  160048. };
  160049. /* Main buffer control (downsampled-data buffer) */
  160050. struct jpeg_c_main_controller {
  160051. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160052. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160053. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160054. JDIMENSION in_rows_avail));
  160055. };
  160056. /* Compression preprocessing (downsampling input buffer control) */
  160057. struct jpeg_c_prep_controller {
  160058. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160059. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160060. JSAMPARRAY input_buf,
  160061. JDIMENSION *in_row_ctr,
  160062. JDIMENSION in_rows_avail,
  160063. JSAMPIMAGE output_buf,
  160064. JDIMENSION *out_row_group_ctr,
  160065. JDIMENSION out_row_groups_avail));
  160066. };
  160067. /* Coefficient buffer control */
  160068. struct jpeg_c_coef_controller {
  160069. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160070. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160071. JSAMPIMAGE input_buf));
  160072. };
  160073. /* Colorspace conversion */
  160074. struct jpeg_color_converter {
  160075. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160076. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160077. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160078. JDIMENSION output_row, int num_rows));
  160079. };
  160080. /* Downsampling */
  160081. struct jpeg_downsampler {
  160082. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160083. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160084. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160085. JSAMPIMAGE output_buf,
  160086. JDIMENSION out_row_group_index));
  160087. boolean need_context_rows; /* TRUE if need rows above & below */
  160088. };
  160089. /* Forward DCT (also controls coefficient quantization) */
  160090. struct jpeg_forward_dct {
  160091. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160092. /* perhaps this should be an array??? */
  160093. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160094. jpeg_component_info * compptr,
  160095. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160096. JDIMENSION start_row, JDIMENSION start_col,
  160097. JDIMENSION num_blocks));
  160098. };
  160099. /* Entropy encoding */
  160100. struct jpeg_entropy_encoder {
  160101. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160102. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160103. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160104. };
  160105. /* Marker writing */
  160106. struct jpeg_marker_writer {
  160107. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160108. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160109. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160110. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160111. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160112. /* These routines are exported to allow insertion of extra markers */
  160113. /* Probably only COM and APPn markers should be written this way */
  160114. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160115. unsigned int datalen));
  160116. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160117. };
  160118. /* Declarations for decompression modules */
  160119. /* Master control module */
  160120. struct jpeg_decomp_master {
  160121. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160122. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160123. /* State variables made visible to other modules */
  160124. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160125. };
  160126. /* Input control module */
  160127. struct jpeg_input_controller {
  160128. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160129. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160130. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160131. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160132. /* State variables made visible to other modules */
  160133. boolean has_multiple_scans; /* True if file has multiple scans */
  160134. boolean eoi_reached; /* True when EOI has been consumed */
  160135. };
  160136. /* Main buffer control (downsampled-data buffer) */
  160137. struct jpeg_d_main_controller {
  160138. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160139. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160140. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160141. JDIMENSION out_rows_avail));
  160142. };
  160143. /* Coefficient buffer control */
  160144. struct jpeg_d_coef_controller {
  160145. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160146. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160147. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160148. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160149. JSAMPIMAGE output_buf));
  160150. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160151. jvirt_barray_ptr *coef_arrays;
  160152. };
  160153. /* Decompression postprocessing (color quantization buffer control) */
  160154. struct jpeg_d_post_controller {
  160155. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160156. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160157. JSAMPIMAGE input_buf,
  160158. JDIMENSION *in_row_group_ctr,
  160159. JDIMENSION in_row_groups_avail,
  160160. JSAMPARRAY output_buf,
  160161. JDIMENSION *out_row_ctr,
  160162. JDIMENSION out_rows_avail));
  160163. };
  160164. /* Marker reading & parsing */
  160165. struct jpeg_marker_reader {
  160166. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160167. /* Read markers until SOS or EOI.
  160168. * Returns same codes as are defined for jpeg_consume_input:
  160169. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160170. */
  160171. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160172. /* Read a restart marker --- exported for use by entropy decoder only */
  160173. jpeg_marker_parser_method read_restart_marker;
  160174. /* State of marker reader --- nominally internal, but applications
  160175. * supplying COM or APPn handlers might like to know the state.
  160176. */
  160177. boolean saw_SOI; /* found SOI? */
  160178. boolean saw_SOF; /* found SOF? */
  160179. int next_restart_num; /* next restart number expected (0-7) */
  160180. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160181. };
  160182. /* Entropy decoding */
  160183. struct jpeg_entropy_decoder {
  160184. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160185. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160186. JBLOCKROW *MCU_data));
  160187. /* This is here to share code between baseline and progressive decoders; */
  160188. /* other modules probably should not use it */
  160189. boolean insufficient_data; /* set TRUE after emitting warning */
  160190. };
  160191. /* Inverse DCT (also performs dequantization) */
  160192. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160193. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160194. JCOEFPTR coef_block,
  160195. JSAMPARRAY output_buf, JDIMENSION output_col));
  160196. struct jpeg_inverse_dct {
  160197. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160198. /* It is useful to allow each component to have a separate IDCT method. */
  160199. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160200. };
  160201. /* Upsampling (note that upsampler must also call color converter) */
  160202. struct jpeg_upsampler {
  160203. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160204. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160205. JSAMPIMAGE input_buf,
  160206. JDIMENSION *in_row_group_ctr,
  160207. JDIMENSION in_row_groups_avail,
  160208. JSAMPARRAY output_buf,
  160209. JDIMENSION *out_row_ctr,
  160210. JDIMENSION out_rows_avail));
  160211. boolean need_context_rows; /* TRUE if need rows above & below */
  160212. };
  160213. /* Colorspace conversion */
  160214. struct jpeg_color_deconverter {
  160215. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160216. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160217. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160218. JSAMPARRAY output_buf, int num_rows));
  160219. };
  160220. /* Color quantization or color precision reduction */
  160221. struct jpeg_color_quantizer {
  160222. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160223. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160224. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160225. int num_rows));
  160226. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160227. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160228. };
  160229. /* Miscellaneous useful macros */
  160230. #undef MAX
  160231. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160232. #undef MIN
  160233. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160234. /* We assume that right shift corresponds to signed division by 2 with
  160235. * rounding towards minus infinity. This is correct for typical "arithmetic
  160236. * shift" instructions that shift in copies of the sign bit. But some
  160237. * C compilers implement >> with an unsigned shift. For these machines you
  160238. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160239. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160240. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160241. * included in the variables of any routine using RIGHT_SHIFT.
  160242. */
  160243. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160244. #define SHIFT_TEMPS INT32 shift_temp;
  160245. #define RIGHT_SHIFT(x,shft) \
  160246. ((shift_temp = (x)) < 0 ? \
  160247. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160248. (shift_temp >> (shft)))
  160249. #else
  160250. #define SHIFT_TEMPS
  160251. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160252. #endif
  160253. /* Short forms of external names for systems with brain-damaged linkers. */
  160254. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160255. #define jinit_compress_master jICompress
  160256. #define jinit_c_master_control jICMaster
  160257. #define jinit_c_main_controller jICMainC
  160258. #define jinit_c_prep_controller jICPrepC
  160259. #define jinit_c_coef_controller jICCoefC
  160260. #define jinit_color_converter jICColor
  160261. #define jinit_downsampler jIDownsampler
  160262. #define jinit_forward_dct jIFDCT
  160263. #define jinit_huff_encoder jIHEncoder
  160264. #define jinit_phuff_encoder jIPHEncoder
  160265. #define jinit_marker_writer jIMWriter
  160266. #define jinit_master_decompress jIDMaster
  160267. #define jinit_d_main_controller jIDMainC
  160268. #define jinit_d_coef_controller jIDCoefC
  160269. #define jinit_d_post_controller jIDPostC
  160270. #define jinit_input_controller jIInCtlr
  160271. #define jinit_marker_reader jIMReader
  160272. #define jinit_huff_decoder jIHDecoder
  160273. #define jinit_phuff_decoder jIPHDecoder
  160274. #define jinit_inverse_dct jIIDCT
  160275. #define jinit_upsampler jIUpsampler
  160276. #define jinit_color_deconverter jIDColor
  160277. #define jinit_1pass_quantizer jI1Quant
  160278. #define jinit_2pass_quantizer jI2Quant
  160279. #define jinit_merged_upsampler jIMUpsampler
  160280. #define jinit_memory_mgr jIMemMgr
  160281. #define jdiv_round_up jDivRound
  160282. #define jround_up jRound
  160283. #define jcopy_sample_rows jCopySamples
  160284. #define jcopy_block_row jCopyBlocks
  160285. #define jzero_far jZeroFar
  160286. #define jpeg_zigzag_order jZIGTable
  160287. #define jpeg_natural_order jZAGTable
  160288. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160289. /* Compression module initialization routines */
  160290. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160291. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160292. boolean transcode_only));
  160293. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160294. boolean need_full_buffer));
  160295. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160296. boolean need_full_buffer));
  160297. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160298. boolean need_full_buffer));
  160299. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160300. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160301. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160302. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160303. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160304. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160305. /* Decompression module initialization routines */
  160306. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160307. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160308. boolean need_full_buffer));
  160309. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160310. boolean need_full_buffer));
  160311. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160312. boolean need_full_buffer));
  160313. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160314. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160315. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160316. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160317. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160318. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160319. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160320. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160321. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160322. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160323. /* Memory manager initialization */
  160324. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160325. /* Utility routines in jutils.c */
  160326. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160327. EXTERN(long) jround_up JPP((long a, long b));
  160328. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160329. JSAMPARRAY output_array, int dest_row,
  160330. int num_rows, JDIMENSION num_cols));
  160331. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160332. JDIMENSION num_blocks));
  160333. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160334. /* Constant tables in jutils.c */
  160335. #if 0 /* This table is not actually needed in v6a */
  160336. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160337. #endif
  160338. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160339. /* Suppress undefined-structure complaints if necessary. */
  160340. #ifdef INCOMPLETE_TYPES_BROKEN
  160341. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160342. struct jvirt_sarray_control { long dummy; };
  160343. struct jvirt_barray_control { long dummy; };
  160344. #endif
  160345. #endif /* INCOMPLETE_TYPES_BROKEN */
  160346. /*** End of inlined file: jpegint.h ***/
  160347. /* fetch private declarations */
  160348. /*** Start of inlined file: jerror.h ***/
  160349. /*
  160350. * To define the enum list of message codes, include this file without
  160351. * defining macro JMESSAGE. To create a message string table, include it
  160352. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160353. */
  160354. #ifndef JMESSAGE
  160355. #ifndef JERROR_H
  160356. /* First time through, define the enum list */
  160357. #define JMAKE_ENUM_LIST
  160358. #else
  160359. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160360. #define JMESSAGE(code,string)
  160361. #endif /* JERROR_H */
  160362. #endif /* JMESSAGE */
  160363. #ifdef JMAKE_ENUM_LIST
  160364. typedef enum {
  160365. #define JMESSAGE(code,string) code ,
  160366. #endif /* JMAKE_ENUM_LIST */
  160367. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160368. /* For maintenance convenience, list is alphabetical by message code name */
  160369. JMESSAGE(JERR_ARITH_NOTIMPL,
  160370. "Sorry, there are legal restrictions on arithmetic coding")
  160371. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160372. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160373. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160374. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160375. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160376. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160377. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160378. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160379. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160380. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160381. JMESSAGE(JERR_BAD_LIB_VERSION,
  160382. "Wrong JPEG library version: library is %d, caller expects %d")
  160383. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160384. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160385. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160386. JMESSAGE(JERR_BAD_PROGRESSION,
  160387. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160388. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160389. "Invalid progressive parameters at scan script entry %d")
  160390. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160391. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160392. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160393. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160394. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160395. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160396. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160397. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160398. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160399. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160400. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160401. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160402. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160403. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160404. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160405. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160406. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160407. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160408. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160409. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160410. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160411. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160412. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160413. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160414. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160415. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160416. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160417. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160418. "Cannot transcode due to multiple use of quantization table %d")
  160419. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160420. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160421. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160422. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160423. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160424. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160425. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160426. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160427. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160428. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160429. JMESSAGE(JERR_QUANT_COMPONENTS,
  160430. "Cannot quantize more than %d color components")
  160431. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160432. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160433. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160434. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160435. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160436. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160437. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160438. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160439. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160440. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160441. JMESSAGE(JERR_TFILE_WRITE,
  160442. "Write failed on temporary file --- out of disk space?")
  160443. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160444. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160445. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160446. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160447. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160448. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160449. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160450. JMESSAGE(JMSG_VERSION, JVERSION)
  160451. JMESSAGE(JTRC_16BIT_TABLES,
  160452. "Caution: quantization tables are too coarse for baseline JPEG")
  160453. JMESSAGE(JTRC_ADOBE,
  160454. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160455. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160456. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160457. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160458. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160459. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160460. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160461. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160462. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160463. JMESSAGE(JTRC_EOI, "End Of Image")
  160464. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160465. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160466. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160467. "Warning: thumbnail image size does not match data length %u")
  160468. JMESSAGE(JTRC_JFIF_EXTENSION,
  160469. "JFIF extension marker: type 0x%02x, length %u")
  160470. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160471. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160472. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160473. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160474. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160475. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160476. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160477. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160478. JMESSAGE(JTRC_RST, "RST%d")
  160479. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160480. "Smoothing not supported with nonstandard sampling ratios")
  160481. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160482. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160483. JMESSAGE(JTRC_SOI, "Start of Image")
  160484. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160485. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160486. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160487. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160488. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160489. JMESSAGE(JTRC_THUMB_JPEG,
  160490. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160491. JMESSAGE(JTRC_THUMB_PALETTE,
  160492. "JFIF extension marker: palette thumbnail image, length %u")
  160493. JMESSAGE(JTRC_THUMB_RGB,
  160494. "JFIF extension marker: RGB thumbnail image, length %u")
  160495. JMESSAGE(JTRC_UNKNOWN_IDS,
  160496. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160497. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160498. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160499. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160500. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160501. "Inconsistent progression sequence for component %d coefficient %d")
  160502. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160503. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160504. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160505. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160506. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160507. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160508. JMESSAGE(JWRN_MUST_RESYNC,
  160509. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160510. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160511. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160512. #ifdef JMAKE_ENUM_LIST
  160513. JMSG_LASTMSGCODE
  160514. } J_MESSAGE_CODE;
  160515. #undef JMAKE_ENUM_LIST
  160516. #endif /* JMAKE_ENUM_LIST */
  160517. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160518. #undef JMESSAGE
  160519. #ifndef JERROR_H
  160520. #define JERROR_H
  160521. /* Macros to simplify using the error and trace message stuff */
  160522. /* The first parameter is either type of cinfo pointer */
  160523. /* Fatal errors (print message and exit) */
  160524. #define ERREXIT(cinfo,code) \
  160525. ((cinfo)->err->msg_code = (code), \
  160526. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160527. #define ERREXIT1(cinfo,code,p1) \
  160528. ((cinfo)->err->msg_code = (code), \
  160529. (cinfo)->err->msg_parm.i[0] = (p1), \
  160530. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160531. #define ERREXIT2(cinfo,code,p1,p2) \
  160532. ((cinfo)->err->msg_code = (code), \
  160533. (cinfo)->err->msg_parm.i[0] = (p1), \
  160534. (cinfo)->err->msg_parm.i[1] = (p2), \
  160535. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160536. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160537. ((cinfo)->err->msg_code = (code), \
  160538. (cinfo)->err->msg_parm.i[0] = (p1), \
  160539. (cinfo)->err->msg_parm.i[1] = (p2), \
  160540. (cinfo)->err->msg_parm.i[2] = (p3), \
  160541. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160542. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160543. ((cinfo)->err->msg_code = (code), \
  160544. (cinfo)->err->msg_parm.i[0] = (p1), \
  160545. (cinfo)->err->msg_parm.i[1] = (p2), \
  160546. (cinfo)->err->msg_parm.i[2] = (p3), \
  160547. (cinfo)->err->msg_parm.i[3] = (p4), \
  160548. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160549. #define ERREXITS(cinfo,code,str) \
  160550. ((cinfo)->err->msg_code = (code), \
  160551. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160552. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160553. #define MAKESTMT(stuff) do { stuff } while (0)
  160554. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160555. #define WARNMS(cinfo,code) \
  160556. ((cinfo)->err->msg_code = (code), \
  160557. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160558. #define WARNMS1(cinfo,code,p1) \
  160559. ((cinfo)->err->msg_code = (code), \
  160560. (cinfo)->err->msg_parm.i[0] = (p1), \
  160561. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160562. #define WARNMS2(cinfo,code,p1,p2) \
  160563. ((cinfo)->err->msg_code = (code), \
  160564. (cinfo)->err->msg_parm.i[0] = (p1), \
  160565. (cinfo)->err->msg_parm.i[1] = (p2), \
  160566. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160567. /* Informational/debugging messages */
  160568. #define TRACEMS(cinfo,lvl,code) \
  160569. ((cinfo)->err->msg_code = (code), \
  160570. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160571. #define TRACEMS1(cinfo,lvl,code,p1) \
  160572. ((cinfo)->err->msg_code = (code), \
  160573. (cinfo)->err->msg_parm.i[0] = (p1), \
  160574. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160575. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160576. ((cinfo)->err->msg_code = (code), \
  160577. (cinfo)->err->msg_parm.i[0] = (p1), \
  160578. (cinfo)->err->msg_parm.i[1] = (p2), \
  160579. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160580. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160581. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160582. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160583. (cinfo)->err->msg_code = (code); \
  160584. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160585. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160586. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160587. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160588. (cinfo)->err->msg_code = (code); \
  160589. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160590. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160591. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160592. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160593. _mp[4] = (p5); \
  160594. (cinfo)->err->msg_code = (code); \
  160595. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160596. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160597. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160598. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160599. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160600. (cinfo)->err->msg_code = (code); \
  160601. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160602. #define TRACEMSS(cinfo,lvl,code,str) \
  160603. ((cinfo)->err->msg_code = (code), \
  160604. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160605. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160606. #endif /* JERROR_H */
  160607. /*** End of inlined file: jerror.h ***/
  160608. /* fetch error codes too */
  160609. #endif
  160610. #endif /* JPEGLIB_H */
  160611. /*** End of inlined file: jpeglib.h ***/
  160612. /*** Start of inlined file: jcapimin.c ***/
  160613. #define JPEG_INTERNALS
  160614. /*** Start of inlined file: jinclude.h ***/
  160615. /* Include auto-config file to find out which system include files we need. */
  160616. #ifndef __jinclude_h__
  160617. #define __jinclude_h__
  160618. /*** Start of inlined file: jconfig.h ***/
  160619. /* see jconfig.doc for explanations */
  160620. // disable all the warnings under MSVC
  160621. #ifdef _MSC_VER
  160622. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160623. #endif
  160624. #ifdef __BORLANDC__
  160625. #pragma warn -8057
  160626. #pragma warn -8019
  160627. #pragma warn -8004
  160628. #pragma warn -8008
  160629. #endif
  160630. #define HAVE_PROTOTYPES
  160631. #define HAVE_UNSIGNED_CHAR
  160632. #define HAVE_UNSIGNED_SHORT
  160633. /* #define void char */
  160634. /* #define const */
  160635. #undef CHAR_IS_UNSIGNED
  160636. #define HAVE_STDDEF_H
  160637. #define HAVE_STDLIB_H
  160638. #undef NEED_BSD_STRINGS
  160639. #undef NEED_SYS_TYPES_H
  160640. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160641. #undef NEED_SHORT_EXTERNAL_NAMES
  160642. #undef INCOMPLETE_TYPES_BROKEN
  160643. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160644. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160645. typedef unsigned char boolean;
  160646. #endif
  160647. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160648. #ifdef JPEG_INTERNALS
  160649. #undef RIGHT_SHIFT_IS_UNSIGNED
  160650. #endif /* JPEG_INTERNALS */
  160651. #ifdef JPEG_CJPEG_DJPEG
  160652. #define BMP_SUPPORTED /* BMP image file format */
  160653. #define GIF_SUPPORTED /* GIF image file format */
  160654. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160655. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160656. #define TARGA_SUPPORTED /* Targa image file format */
  160657. #define TWO_FILE_COMMANDLINE /* optional */
  160658. #define USE_SETMODE /* Microsoft has setmode() */
  160659. #undef NEED_SIGNAL_CATCHER
  160660. #undef DONT_USE_B_MODE
  160661. #undef PROGRESS_REPORT /* optional */
  160662. #endif /* JPEG_CJPEG_DJPEG */
  160663. /*** End of inlined file: jconfig.h ***/
  160664. /* auto configuration options */
  160665. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160666. /*
  160667. * We need the NULL macro and size_t typedef.
  160668. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160669. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160670. * pull in <sys/types.h> as well.
  160671. * Note that the core JPEG library does not require <stdio.h>;
  160672. * only the default error handler and data source/destination modules do.
  160673. * But we must pull it in because of the references to FILE in jpeglib.h.
  160674. * You can remove those references if you want to compile without <stdio.h>.
  160675. */
  160676. #ifdef HAVE_STDDEF_H
  160677. #include <stddef.h>
  160678. #endif
  160679. #ifdef HAVE_STDLIB_H
  160680. #include <stdlib.h>
  160681. #endif
  160682. #ifdef NEED_SYS_TYPES_H
  160683. #include <sys/types.h>
  160684. #endif
  160685. #include <stdio.h>
  160686. /*
  160687. * We need memory copying and zeroing functions, plus strncpy().
  160688. * ANSI and System V implementations declare these in <string.h>.
  160689. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160690. * Some systems may declare memset and memcpy in <memory.h>.
  160691. *
  160692. * NOTE: we assume the size parameters to these functions are of type size_t.
  160693. * Change the casts in these macros if not!
  160694. */
  160695. #ifdef NEED_BSD_STRINGS
  160696. #include <strings.h>
  160697. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160698. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160699. #else /* not BSD, assume ANSI/SysV string lib */
  160700. #include <string.h>
  160701. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160702. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160703. #endif
  160704. /*
  160705. * In ANSI C, and indeed any rational implementation, size_t is also the
  160706. * type returned by sizeof(). However, it seems there are some irrational
  160707. * implementations out there, in which sizeof() returns an int even though
  160708. * size_t is defined as long or unsigned long. To ensure consistent results
  160709. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160710. */
  160711. #define SIZEOF(object) ((size_t) sizeof(object))
  160712. /*
  160713. * The modules that use fread() and fwrite() always invoke them through
  160714. * these macros. On some systems you may need to twiddle the argument casts.
  160715. * CAUTION: argument order is different from underlying functions!
  160716. */
  160717. #define JFREAD(file,buf,sizeofbuf) \
  160718. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160719. #define JFWRITE(file,buf,sizeofbuf) \
  160720. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160721. typedef enum { /* JPEG marker codes */
  160722. M_SOF0 = 0xc0,
  160723. M_SOF1 = 0xc1,
  160724. M_SOF2 = 0xc2,
  160725. M_SOF3 = 0xc3,
  160726. M_SOF5 = 0xc5,
  160727. M_SOF6 = 0xc6,
  160728. M_SOF7 = 0xc7,
  160729. M_JPG = 0xc8,
  160730. M_SOF9 = 0xc9,
  160731. M_SOF10 = 0xca,
  160732. M_SOF11 = 0xcb,
  160733. M_SOF13 = 0xcd,
  160734. M_SOF14 = 0xce,
  160735. M_SOF15 = 0xcf,
  160736. M_DHT = 0xc4,
  160737. M_DAC = 0xcc,
  160738. M_RST0 = 0xd0,
  160739. M_RST1 = 0xd1,
  160740. M_RST2 = 0xd2,
  160741. M_RST3 = 0xd3,
  160742. M_RST4 = 0xd4,
  160743. M_RST5 = 0xd5,
  160744. M_RST6 = 0xd6,
  160745. M_RST7 = 0xd7,
  160746. M_SOI = 0xd8,
  160747. M_EOI = 0xd9,
  160748. M_SOS = 0xda,
  160749. M_DQT = 0xdb,
  160750. M_DNL = 0xdc,
  160751. M_DRI = 0xdd,
  160752. M_DHP = 0xde,
  160753. M_EXP = 0xdf,
  160754. M_APP0 = 0xe0,
  160755. M_APP1 = 0xe1,
  160756. M_APP2 = 0xe2,
  160757. M_APP3 = 0xe3,
  160758. M_APP4 = 0xe4,
  160759. M_APP5 = 0xe5,
  160760. M_APP6 = 0xe6,
  160761. M_APP7 = 0xe7,
  160762. M_APP8 = 0xe8,
  160763. M_APP9 = 0xe9,
  160764. M_APP10 = 0xea,
  160765. M_APP11 = 0xeb,
  160766. M_APP12 = 0xec,
  160767. M_APP13 = 0xed,
  160768. M_APP14 = 0xee,
  160769. M_APP15 = 0xef,
  160770. M_JPG0 = 0xf0,
  160771. M_JPG13 = 0xfd,
  160772. M_COM = 0xfe,
  160773. M_TEM = 0x01,
  160774. M_ERROR = 0x100
  160775. } JPEG_MARKER;
  160776. /*
  160777. * Figure F.12: extend sign bit.
  160778. * On some machines, a shift and add will be faster than a table lookup.
  160779. */
  160780. #ifdef AVOID_TABLES
  160781. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160782. #else
  160783. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160784. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160785. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160786. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160787. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160788. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160789. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160790. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160791. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160792. #endif /* AVOID_TABLES */
  160793. #endif
  160794. /*** End of inlined file: jinclude.h ***/
  160795. /*
  160796. * Initialization of a JPEG compression object.
  160797. * The error manager must already be set up (in case memory manager fails).
  160798. */
  160799. GLOBAL(void)
  160800. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160801. {
  160802. int i;
  160803. /* Guard against version mismatches between library and caller. */
  160804. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160805. if (version != JPEG_LIB_VERSION)
  160806. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160807. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160808. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160809. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160810. /* For debugging purposes, we zero the whole master structure.
  160811. * But the application has already set the err pointer, and may have set
  160812. * client_data, so we have to save and restore those fields.
  160813. * Note: if application hasn't set client_data, tools like Purify may
  160814. * complain here.
  160815. */
  160816. {
  160817. struct jpeg_error_mgr * err = cinfo->err;
  160818. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160819. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  160820. cinfo->err = err;
  160821. cinfo->client_data = client_data;
  160822. }
  160823. cinfo->is_decompressor = FALSE;
  160824. /* Initialize a memory manager instance for this object */
  160825. jinit_memory_mgr((j_common_ptr) cinfo);
  160826. /* Zero out pointers to permanent structures. */
  160827. cinfo->progress = NULL;
  160828. cinfo->dest = NULL;
  160829. cinfo->comp_info = NULL;
  160830. for (i = 0; i < NUM_QUANT_TBLS; i++)
  160831. cinfo->quant_tbl_ptrs[i] = NULL;
  160832. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160833. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  160834. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  160835. }
  160836. cinfo->script_space = NULL;
  160837. cinfo->input_gamma = 1.0; /* in case application forgets */
  160838. /* OK, I'm ready */
  160839. cinfo->global_state = CSTATE_START;
  160840. }
  160841. /*
  160842. * Destruction of a JPEG compression object
  160843. */
  160844. GLOBAL(void)
  160845. jpeg_destroy_compress (j_compress_ptr cinfo)
  160846. {
  160847. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  160848. }
  160849. /*
  160850. * Abort processing of a JPEG compression operation,
  160851. * but don't destroy the object itself.
  160852. */
  160853. GLOBAL(void)
  160854. jpeg_abort_compress (j_compress_ptr cinfo)
  160855. {
  160856. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  160857. }
  160858. /*
  160859. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  160860. * Marks all currently defined tables as already written (if suppress)
  160861. * or not written (if !suppress). This will control whether they get emitted
  160862. * by a subsequent jpeg_start_compress call.
  160863. *
  160864. * This routine is exported for use by applications that want to produce
  160865. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  160866. * since it is called by jpeg_start_compress, we put it here --- otherwise
  160867. * jcparam.o would be linked whether the application used it or not.
  160868. */
  160869. GLOBAL(void)
  160870. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  160871. {
  160872. int i;
  160873. JQUANT_TBL * qtbl;
  160874. JHUFF_TBL * htbl;
  160875. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160876. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  160877. qtbl->sent_table = suppress;
  160878. }
  160879. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160880. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  160881. htbl->sent_table = suppress;
  160882. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  160883. htbl->sent_table = suppress;
  160884. }
  160885. }
  160886. /*
  160887. * Finish JPEG compression.
  160888. *
  160889. * If a multipass operating mode was selected, this may do a great deal of
  160890. * work including most of the actual output.
  160891. */
  160892. GLOBAL(void)
  160893. jpeg_finish_compress (j_compress_ptr cinfo)
  160894. {
  160895. JDIMENSION iMCU_row;
  160896. if (cinfo->global_state == CSTATE_SCANNING ||
  160897. cinfo->global_state == CSTATE_RAW_OK) {
  160898. /* Terminate first pass */
  160899. if (cinfo->next_scanline < cinfo->image_height)
  160900. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  160901. (*cinfo->master->finish_pass) (cinfo);
  160902. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  160903. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160904. /* Perform any remaining passes */
  160905. while (! cinfo->master->is_last_pass) {
  160906. (*cinfo->master->prepare_for_pass) (cinfo);
  160907. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  160908. if (cinfo->progress != NULL) {
  160909. cinfo->progress->pass_counter = (long) iMCU_row;
  160910. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  160911. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160912. }
  160913. /* We bypass the main controller and invoke coef controller directly;
  160914. * all work is being done from the coefficient buffer.
  160915. */
  160916. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  160917. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160918. }
  160919. (*cinfo->master->finish_pass) (cinfo);
  160920. }
  160921. /* Write EOI, do final cleanup */
  160922. (*cinfo->marker->write_file_trailer) (cinfo);
  160923. (*cinfo->dest->term_destination) (cinfo);
  160924. /* We can use jpeg_abort to release memory and reset global_state */
  160925. jpeg_abort((j_common_ptr) cinfo);
  160926. }
  160927. /*
  160928. * Write a special marker.
  160929. * This is only recommended for writing COM or APPn markers.
  160930. * Must be called after jpeg_start_compress() and before
  160931. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  160932. */
  160933. GLOBAL(void)
  160934. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  160935. const JOCTET *dataptr, unsigned int datalen)
  160936. {
  160937. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  160938. if (cinfo->next_scanline != 0 ||
  160939. (cinfo->global_state != CSTATE_SCANNING &&
  160940. cinfo->global_state != CSTATE_RAW_OK &&
  160941. cinfo->global_state != CSTATE_WRCOEFS))
  160942. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160943. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160944. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  160945. while (datalen--) {
  160946. (*write_marker_byte) (cinfo, *dataptr);
  160947. dataptr++;
  160948. }
  160949. }
  160950. /* Same, but piecemeal. */
  160951. GLOBAL(void)
  160952. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160953. {
  160954. if (cinfo->next_scanline != 0 ||
  160955. (cinfo->global_state != CSTATE_SCANNING &&
  160956. cinfo->global_state != CSTATE_RAW_OK &&
  160957. cinfo->global_state != CSTATE_WRCOEFS))
  160958. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160959. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160960. }
  160961. GLOBAL(void)
  160962. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  160963. {
  160964. (*cinfo->marker->write_marker_byte) (cinfo, val);
  160965. }
  160966. /*
  160967. * Alternate compression function: just write an abbreviated table file.
  160968. * Before calling this, all parameters and a data destination must be set up.
  160969. *
  160970. * To produce a pair of files containing abbreviated tables and abbreviated
  160971. * image data, one would proceed as follows:
  160972. *
  160973. * initialize JPEG object
  160974. * set JPEG parameters
  160975. * set destination to table file
  160976. * jpeg_write_tables(cinfo);
  160977. * set destination to image file
  160978. * jpeg_start_compress(cinfo, FALSE);
  160979. * write data...
  160980. * jpeg_finish_compress(cinfo);
  160981. *
  160982. * jpeg_write_tables has the side effect of marking all tables written
  160983. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  160984. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  160985. */
  160986. GLOBAL(void)
  160987. jpeg_write_tables (j_compress_ptr cinfo)
  160988. {
  160989. if (cinfo->global_state != CSTATE_START)
  160990. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160991. /* (Re)initialize error mgr and destination modules */
  160992. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160993. (*cinfo->dest->init_destination) (cinfo);
  160994. /* Initialize the marker writer ... bit of a crock to do it here. */
  160995. jinit_marker_writer(cinfo);
  160996. /* Write them tables! */
  160997. (*cinfo->marker->write_tables_only) (cinfo);
  160998. /* And clean up. */
  160999. (*cinfo->dest->term_destination) (cinfo);
  161000. /*
  161001. * In library releases up through v6a, we called jpeg_abort() here to free
  161002. * any working memory allocated by the destination manager and marker
  161003. * writer. Some applications had a problem with that: they allocated space
  161004. * of their own from the library memory manager, and didn't want it to go
  161005. * away during write_tables. So now we do nothing. This will cause a
  161006. * memory leak if an app calls write_tables repeatedly without doing a full
  161007. * compression cycle or otherwise resetting the JPEG object. However, that
  161008. * seems less bad than unexpectedly freeing memory in the normal case.
  161009. * An app that prefers the old behavior can call jpeg_abort for itself after
  161010. * each call to jpeg_write_tables().
  161011. */
  161012. }
  161013. /*** End of inlined file: jcapimin.c ***/
  161014. /*** Start of inlined file: jcapistd.c ***/
  161015. #define JPEG_INTERNALS
  161016. /*
  161017. * Compression initialization.
  161018. * Before calling this, all parameters and a data destination must be set up.
  161019. *
  161020. * We require a write_all_tables parameter as a failsafe check when writing
  161021. * multiple datastreams from the same compression object. Since prior runs
  161022. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161023. * would emit an abbreviated stream (no tables) by default. This may be what
  161024. * is wanted, but for safety's sake it should not be the default behavior:
  161025. * programmers should have to make a deliberate choice to emit abbreviated
  161026. * images. Therefore the documentation and examples should encourage people
  161027. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161028. * wrong thing.
  161029. */
  161030. GLOBAL(void)
  161031. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161032. {
  161033. if (cinfo->global_state != CSTATE_START)
  161034. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161035. if (write_all_tables)
  161036. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161037. /* (Re)initialize error mgr and destination modules */
  161038. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161039. (*cinfo->dest->init_destination) (cinfo);
  161040. /* Perform master selection of active modules */
  161041. jinit_compress_master(cinfo);
  161042. /* Set up for the first pass */
  161043. (*cinfo->master->prepare_for_pass) (cinfo);
  161044. /* Ready for application to drive first pass through jpeg_write_scanlines
  161045. * or jpeg_write_raw_data.
  161046. */
  161047. cinfo->next_scanline = 0;
  161048. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161049. }
  161050. /*
  161051. * Write some scanlines of data to the JPEG compressor.
  161052. *
  161053. * The return value will be the number of lines actually written.
  161054. * This should be less than the supplied num_lines only in case that
  161055. * the data destination module has requested suspension of the compressor,
  161056. * or if more than image_height scanlines are passed in.
  161057. *
  161058. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161059. * this likely signals an application programmer error. However,
  161060. * excess scanlines passed in the last valid call are *silently* ignored,
  161061. * so that the application need not adjust num_lines for end-of-image
  161062. * when using a multiple-scanline buffer.
  161063. */
  161064. GLOBAL(JDIMENSION)
  161065. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161066. JDIMENSION num_lines)
  161067. {
  161068. JDIMENSION row_ctr, rows_left;
  161069. if (cinfo->global_state != CSTATE_SCANNING)
  161070. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161071. if (cinfo->next_scanline >= cinfo->image_height)
  161072. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161073. /* Call progress monitor hook if present */
  161074. if (cinfo->progress != NULL) {
  161075. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161076. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161077. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161078. }
  161079. /* Give master control module another chance if this is first call to
  161080. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161081. * delayed so that application can write COM, etc, markers between
  161082. * jpeg_start_compress and jpeg_write_scanlines.
  161083. */
  161084. if (cinfo->master->call_pass_startup)
  161085. (*cinfo->master->pass_startup) (cinfo);
  161086. /* Ignore any extra scanlines at bottom of image. */
  161087. rows_left = cinfo->image_height - cinfo->next_scanline;
  161088. if (num_lines > rows_left)
  161089. num_lines = rows_left;
  161090. row_ctr = 0;
  161091. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161092. cinfo->next_scanline += row_ctr;
  161093. return row_ctr;
  161094. }
  161095. /*
  161096. * Alternate entry point to write raw data.
  161097. * Processes exactly one iMCU row per call, unless suspended.
  161098. */
  161099. GLOBAL(JDIMENSION)
  161100. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161101. JDIMENSION num_lines)
  161102. {
  161103. JDIMENSION lines_per_iMCU_row;
  161104. if (cinfo->global_state != CSTATE_RAW_OK)
  161105. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161106. if (cinfo->next_scanline >= cinfo->image_height) {
  161107. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161108. return 0;
  161109. }
  161110. /* Call progress monitor hook if present */
  161111. if (cinfo->progress != NULL) {
  161112. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161113. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161114. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161115. }
  161116. /* Give master control module another chance if this is first call to
  161117. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161118. * delayed so that application can write COM, etc, markers between
  161119. * jpeg_start_compress and jpeg_write_raw_data.
  161120. */
  161121. if (cinfo->master->call_pass_startup)
  161122. (*cinfo->master->pass_startup) (cinfo);
  161123. /* Verify that at least one iMCU row has been passed. */
  161124. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161125. if (num_lines < lines_per_iMCU_row)
  161126. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161127. /* Directly compress the row. */
  161128. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161129. /* If compressor did not consume the whole row, suspend processing. */
  161130. return 0;
  161131. }
  161132. /* OK, we processed one iMCU row. */
  161133. cinfo->next_scanline += lines_per_iMCU_row;
  161134. return lines_per_iMCU_row;
  161135. }
  161136. /*** End of inlined file: jcapistd.c ***/
  161137. /*** Start of inlined file: jccoefct.c ***/
  161138. #define JPEG_INTERNALS
  161139. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161140. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161141. * step is run during the first pass, and subsequent passes need only read
  161142. * the buffered coefficients.
  161143. */
  161144. #ifdef ENTROPY_OPT_SUPPORTED
  161145. #define FULL_COEF_BUFFER_SUPPORTED
  161146. #else
  161147. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161148. #define FULL_COEF_BUFFER_SUPPORTED
  161149. #endif
  161150. #endif
  161151. /* Private buffer controller object */
  161152. typedef struct {
  161153. struct jpeg_c_coef_controller pub; /* public fields */
  161154. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161155. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161156. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161157. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161158. /* For single-pass compression, it's sufficient to buffer just one MCU
  161159. * (although this may prove a bit slow in practice). We allocate a
  161160. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161161. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161162. * it's not really very big; this is to keep the module interfaces unchanged
  161163. * when a large coefficient buffer is necessary.)
  161164. * In multi-pass modes, this array points to the current MCU's blocks
  161165. * within the virtual arrays.
  161166. */
  161167. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161168. /* In multi-pass modes, we need a virtual block array for each component. */
  161169. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161170. } my_coef_controller;
  161171. typedef my_coef_controller * my_coef_ptr;
  161172. /* Forward declarations */
  161173. METHODDEF(boolean) compress_data
  161174. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161175. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161176. METHODDEF(boolean) compress_first_pass
  161177. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161178. METHODDEF(boolean) compress_output
  161179. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161180. #endif
  161181. LOCAL(void)
  161182. start_iMCU_row (j_compress_ptr cinfo)
  161183. /* Reset within-iMCU-row counters for a new row */
  161184. {
  161185. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161186. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161187. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161188. * But at the bottom of the image, process only what's left.
  161189. */
  161190. if (cinfo->comps_in_scan > 1) {
  161191. coef->MCU_rows_per_iMCU_row = 1;
  161192. } else {
  161193. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161194. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161195. else
  161196. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161197. }
  161198. coef->mcu_ctr = 0;
  161199. coef->MCU_vert_offset = 0;
  161200. }
  161201. /*
  161202. * Initialize for a processing pass.
  161203. */
  161204. METHODDEF(void)
  161205. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161206. {
  161207. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161208. coef->iMCU_row_num = 0;
  161209. start_iMCU_row(cinfo);
  161210. switch (pass_mode) {
  161211. case JBUF_PASS_THRU:
  161212. if (coef->whole_image[0] != NULL)
  161213. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161214. coef->pub.compress_data = compress_data;
  161215. break;
  161216. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161217. case JBUF_SAVE_AND_PASS:
  161218. if (coef->whole_image[0] == NULL)
  161219. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161220. coef->pub.compress_data = compress_first_pass;
  161221. break;
  161222. case JBUF_CRANK_DEST:
  161223. if (coef->whole_image[0] == NULL)
  161224. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161225. coef->pub.compress_data = compress_output;
  161226. break;
  161227. #endif
  161228. default:
  161229. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161230. break;
  161231. }
  161232. }
  161233. /*
  161234. * Process some data in the single-pass case.
  161235. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161236. * per call, ie, v_samp_factor block rows for each component in the image.
  161237. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161238. *
  161239. * NB: input_buf contains a plane for each component in image,
  161240. * which we index according to the component's SOF position.
  161241. */
  161242. METHODDEF(boolean)
  161243. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161244. {
  161245. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161246. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161247. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161248. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161249. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161250. JDIMENSION ypos, xpos;
  161251. jpeg_component_info *compptr;
  161252. /* Loop to write as much as one whole iMCU row */
  161253. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161254. yoffset++) {
  161255. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161256. MCU_col_num++) {
  161257. /* Determine where data comes from in input_buf and do the DCT thing.
  161258. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161259. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161260. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161261. * specially. The data in them does not matter for image reconstruction,
  161262. * so we fill them with values that will encode to the smallest amount of
  161263. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161264. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161265. */
  161266. blkn = 0;
  161267. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161268. compptr = cinfo->cur_comp_info[ci];
  161269. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161270. : compptr->last_col_width;
  161271. xpos = MCU_col_num * compptr->MCU_sample_width;
  161272. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161273. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161274. if (coef->iMCU_row_num < last_iMCU_row ||
  161275. yoffset+yindex < compptr->last_row_height) {
  161276. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161277. input_buf[compptr->component_index],
  161278. coef->MCU_buffer[blkn],
  161279. ypos, xpos, (JDIMENSION) blockcnt);
  161280. if (blockcnt < compptr->MCU_width) {
  161281. /* Create some dummy blocks at the right edge of the image. */
  161282. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161283. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161284. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161285. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161286. }
  161287. }
  161288. } else {
  161289. /* Create a row of dummy blocks at the bottom of the image. */
  161290. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161291. compptr->MCU_width * SIZEOF(JBLOCK));
  161292. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161293. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161294. }
  161295. }
  161296. blkn += compptr->MCU_width;
  161297. ypos += DCTSIZE;
  161298. }
  161299. }
  161300. /* Try to write the MCU. In event of a suspension failure, we will
  161301. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161302. */
  161303. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161304. /* Suspension forced; update state counters and exit */
  161305. coef->MCU_vert_offset = yoffset;
  161306. coef->mcu_ctr = MCU_col_num;
  161307. return FALSE;
  161308. }
  161309. }
  161310. /* Completed an MCU row, but perhaps not an iMCU row */
  161311. coef->mcu_ctr = 0;
  161312. }
  161313. /* Completed the iMCU row, advance counters for next one */
  161314. coef->iMCU_row_num++;
  161315. start_iMCU_row(cinfo);
  161316. return TRUE;
  161317. }
  161318. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161319. /*
  161320. * Process some data in the first pass of a multi-pass case.
  161321. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161322. * per call, ie, v_samp_factor block rows for each component in the image.
  161323. * This amount of data is read from the source buffer, DCT'd and quantized,
  161324. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161325. * as needed at the right and lower edges. (The dummy blocks are constructed
  161326. * in the virtual arrays, which have been padded appropriately.) This makes
  161327. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161328. *
  161329. * We must also emit the data to the entropy encoder. This is conveniently
  161330. * done by calling compress_output() after we've loaded the current strip
  161331. * of the virtual arrays.
  161332. *
  161333. * NB: input_buf contains a plane for each component in image. All
  161334. * components are DCT'd and loaded into the virtual arrays in this pass.
  161335. * However, it may be that only a subset of the components are emitted to
  161336. * the entropy encoder during this first pass; be careful about looking
  161337. * at the scan-dependent variables (MCU dimensions, etc).
  161338. */
  161339. METHODDEF(boolean)
  161340. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161341. {
  161342. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161343. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161344. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161345. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161346. JCOEF lastDC;
  161347. jpeg_component_info *compptr;
  161348. JBLOCKARRAY buffer;
  161349. JBLOCKROW thisblockrow, lastblockrow;
  161350. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161351. ci++, compptr++) {
  161352. /* Align the virtual buffer for this component. */
  161353. buffer = (*cinfo->mem->access_virt_barray)
  161354. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161355. coef->iMCU_row_num * compptr->v_samp_factor,
  161356. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161357. /* Count non-dummy DCT block rows in this iMCU row. */
  161358. if (coef->iMCU_row_num < last_iMCU_row)
  161359. block_rows = compptr->v_samp_factor;
  161360. else {
  161361. /* NB: can't use last_row_height here, since may not be set! */
  161362. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161363. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161364. }
  161365. blocks_across = compptr->width_in_blocks;
  161366. h_samp_factor = compptr->h_samp_factor;
  161367. /* Count number of dummy blocks to be added at the right margin. */
  161368. ndummy = (int) (blocks_across % h_samp_factor);
  161369. if (ndummy > 0)
  161370. ndummy = h_samp_factor - ndummy;
  161371. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161372. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161373. */
  161374. for (block_row = 0; block_row < block_rows; block_row++) {
  161375. thisblockrow = buffer[block_row];
  161376. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161377. input_buf[ci], thisblockrow,
  161378. (JDIMENSION) (block_row * DCTSIZE),
  161379. (JDIMENSION) 0, blocks_across);
  161380. if (ndummy > 0) {
  161381. /* Create dummy blocks at the right edge of the image. */
  161382. thisblockrow += blocks_across; /* => first dummy block */
  161383. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161384. lastDC = thisblockrow[-1][0];
  161385. for (bi = 0; bi < ndummy; bi++) {
  161386. thisblockrow[bi][0] = lastDC;
  161387. }
  161388. }
  161389. }
  161390. /* If at end of image, create dummy block rows as needed.
  161391. * The tricky part here is that within each MCU, we want the DC values
  161392. * of the dummy blocks to match the last real block's DC value.
  161393. * This squeezes a few more bytes out of the resulting file...
  161394. */
  161395. if (coef->iMCU_row_num == last_iMCU_row) {
  161396. blocks_across += ndummy; /* include lower right corner */
  161397. MCUs_across = blocks_across / h_samp_factor;
  161398. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161399. block_row++) {
  161400. thisblockrow = buffer[block_row];
  161401. lastblockrow = buffer[block_row-1];
  161402. jzero_far((void FAR *) thisblockrow,
  161403. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161404. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161405. lastDC = lastblockrow[h_samp_factor-1][0];
  161406. for (bi = 0; bi < h_samp_factor; bi++) {
  161407. thisblockrow[bi][0] = lastDC;
  161408. }
  161409. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161410. lastblockrow += h_samp_factor;
  161411. }
  161412. }
  161413. }
  161414. }
  161415. /* NB: compress_output will increment iMCU_row_num if successful.
  161416. * A suspension return will result in redoing all the work above next time.
  161417. */
  161418. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161419. return compress_output(cinfo, input_buf);
  161420. }
  161421. /*
  161422. * Process some data in subsequent passes of a multi-pass case.
  161423. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161424. * per call, ie, v_samp_factor block rows for each component in the scan.
  161425. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161426. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161427. *
  161428. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161429. */
  161430. METHODDEF(boolean)
  161431. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161432. {
  161433. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161434. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161435. int blkn, ci, xindex, yindex, yoffset;
  161436. JDIMENSION start_col;
  161437. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161438. JBLOCKROW buffer_ptr;
  161439. jpeg_component_info *compptr;
  161440. /* Align the virtual buffers for the components used in this scan.
  161441. * NB: during first pass, this is safe only because the buffers will
  161442. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161443. */
  161444. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161445. compptr = cinfo->cur_comp_info[ci];
  161446. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161447. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161448. coef->iMCU_row_num * compptr->v_samp_factor,
  161449. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161450. }
  161451. /* Loop to process one whole iMCU row */
  161452. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161453. yoffset++) {
  161454. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161455. MCU_col_num++) {
  161456. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161457. blkn = 0; /* index of current DCT block within MCU */
  161458. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161459. compptr = cinfo->cur_comp_info[ci];
  161460. start_col = MCU_col_num * compptr->MCU_width;
  161461. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161462. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161463. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161464. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161465. }
  161466. }
  161467. }
  161468. /* Try to write the MCU. */
  161469. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161470. /* Suspension forced; update state counters and exit */
  161471. coef->MCU_vert_offset = yoffset;
  161472. coef->mcu_ctr = MCU_col_num;
  161473. return FALSE;
  161474. }
  161475. }
  161476. /* Completed an MCU row, but perhaps not an iMCU row */
  161477. coef->mcu_ctr = 0;
  161478. }
  161479. /* Completed the iMCU row, advance counters for next one */
  161480. coef->iMCU_row_num++;
  161481. start_iMCU_row(cinfo);
  161482. return TRUE;
  161483. }
  161484. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161485. /*
  161486. * Initialize coefficient buffer controller.
  161487. */
  161488. GLOBAL(void)
  161489. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161490. {
  161491. my_coef_ptr coef;
  161492. coef = (my_coef_ptr)
  161493. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161494. SIZEOF(my_coef_controller));
  161495. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161496. coef->pub.start_pass = start_pass_coef;
  161497. /* Create the coefficient buffer. */
  161498. if (need_full_buffer) {
  161499. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161500. /* Allocate a full-image virtual array for each component, */
  161501. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161502. int ci;
  161503. jpeg_component_info *compptr;
  161504. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161505. ci++, compptr++) {
  161506. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161507. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161508. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161509. (long) compptr->h_samp_factor),
  161510. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161511. (long) compptr->v_samp_factor),
  161512. (JDIMENSION) compptr->v_samp_factor);
  161513. }
  161514. #else
  161515. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161516. #endif
  161517. } else {
  161518. /* We only need a single-MCU buffer. */
  161519. JBLOCKROW buffer;
  161520. int i;
  161521. buffer = (JBLOCKROW)
  161522. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161523. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161524. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161525. coef->MCU_buffer[i] = buffer + i;
  161526. }
  161527. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161528. }
  161529. }
  161530. /*** End of inlined file: jccoefct.c ***/
  161531. /*** Start of inlined file: jccolor.c ***/
  161532. #define JPEG_INTERNALS
  161533. /* Private subobject */
  161534. typedef struct {
  161535. struct jpeg_color_converter pub; /* public fields */
  161536. /* Private state for RGB->YCC conversion */
  161537. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161538. } my_color_converter;
  161539. typedef my_color_converter * my_cconvert_ptr;
  161540. /**************** RGB -> YCbCr conversion: most common case **************/
  161541. /*
  161542. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161543. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161544. * The conversion equations to be implemented are therefore
  161545. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161546. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161547. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161548. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161549. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161550. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161551. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161552. * were not represented exactly. Now we sacrifice exact representation of
  161553. * maximum red and maximum blue in order to get exact grayscales.
  161554. *
  161555. * To avoid floating-point arithmetic, we represent the fractional constants
  161556. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161557. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161558. *
  161559. * For even more speed, we avoid doing any multiplications in the inner loop
  161560. * by precalculating the constants times R,G,B for all possible values.
  161561. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161562. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161563. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161564. * colorspace anyway.
  161565. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161566. * in the tables to save adding them separately in the inner loop.
  161567. */
  161568. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161569. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161570. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161571. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161572. /* We allocate one big table and divide it up into eight parts, instead of
  161573. * doing eight alloc_small requests. This lets us use a single table base
  161574. * address, which can be held in a register in the inner loops on many
  161575. * machines (more than can hold all eight addresses, anyway).
  161576. */
  161577. #define R_Y_OFF 0 /* offset to R => Y section */
  161578. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161579. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161580. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161581. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161582. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161583. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161584. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161585. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161586. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161587. /*
  161588. * Initialize for RGB->YCC colorspace conversion.
  161589. */
  161590. METHODDEF(void)
  161591. rgb_ycc_start (j_compress_ptr cinfo)
  161592. {
  161593. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161594. INT32 * rgb_ycc_tab;
  161595. INT32 i;
  161596. /* Allocate and fill in the conversion tables. */
  161597. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161598. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161599. (TABLE_SIZE * SIZEOF(INT32)));
  161600. for (i = 0; i <= MAXJSAMPLE; i++) {
  161601. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161602. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161603. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161604. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161605. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161606. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161607. * This ensures that the maximum output will round to MAXJSAMPLE
  161608. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161609. */
  161610. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161611. /* B=>Cb and R=>Cr tables are the same
  161612. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161613. */
  161614. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161615. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161616. }
  161617. }
  161618. /*
  161619. * Convert some rows of samples to the JPEG colorspace.
  161620. *
  161621. * Note that we change from the application's interleaved-pixel format
  161622. * to our internal noninterleaved, one-plane-per-component format.
  161623. * The input buffer is therefore three times as wide as the output buffer.
  161624. *
  161625. * A starting row offset is provided only for the output buffer. The caller
  161626. * can easily adjust the passed input_buf value to accommodate any row
  161627. * offset required on that side.
  161628. */
  161629. METHODDEF(void)
  161630. rgb_ycc_convert (j_compress_ptr cinfo,
  161631. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161632. JDIMENSION output_row, int num_rows)
  161633. {
  161634. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161635. register int r, g, b;
  161636. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161637. register JSAMPROW inptr;
  161638. register JSAMPROW outptr0, outptr1, outptr2;
  161639. register JDIMENSION col;
  161640. JDIMENSION num_cols = cinfo->image_width;
  161641. while (--num_rows >= 0) {
  161642. inptr = *input_buf++;
  161643. outptr0 = output_buf[0][output_row];
  161644. outptr1 = output_buf[1][output_row];
  161645. outptr2 = output_buf[2][output_row];
  161646. output_row++;
  161647. for (col = 0; col < num_cols; col++) {
  161648. r = GETJSAMPLE(inptr[RGB_RED]);
  161649. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161650. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161651. inptr += RGB_PIXELSIZE;
  161652. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161653. * must be too; we do not need an explicit range-limiting operation.
  161654. * Hence the value being shifted is never negative, and we don't
  161655. * need the general RIGHT_SHIFT macro.
  161656. */
  161657. /* Y */
  161658. outptr0[col] = (JSAMPLE)
  161659. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161660. >> SCALEBITS);
  161661. /* Cb */
  161662. outptr1[col] = (JSAMPLE)
  161663. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161664. >> SCALEBITS);
  161665. /* Cr */
  161666. outptr2[col] = (JSAMPLE)
  161667. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161668. >> SCALEBITS);
  161669. }
  161670. }
  161671. }
  161672. /**************** Cases other than RGB -> YCbCr **************/
  161673. /*
  161674. * Convert some rows of samples to the JPEG colorspace.
  161675. * This version handles RGB->grayscale conversion, which is the same
  161676. * as the RGB->Y portion of RGB->YCbCr.
  161677. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161678. */
  161679. METHODDEF(void)
  161680. rgb_gray_convert (j_compress_ptr cinfo,
  161681. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161682. JDIMENSION output_row, int num_rows)
  161683. {
  161684. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161685. register int r, g, b;
  161686. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161687. register JSAMPROW inptr;
  161688. register JSAMPROW outptr;
  161689. register JDIMENSION col;
  161690. JDIMENSION num_cols = cinfo->image_width;
  161691. while (--num_rows >= 0) {
  161692. inptr = *input_buf++;
  161693. outptr = output_buf[0][output_row];
  161694. output_row++;
  161695. for (col = 0; col < num_cols; col++) {
  161696. r = GETJSAMPLE(inptr[RGB_RED]);
  161697. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161698. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161699. inptr += RGB_PIXELSIZE;
  161700. /* Y */
  161701. outptr[col] = (JSAMPLE)
  161702. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161703. >> SCALEBITS);
  161704. }
  161705. }
  161706. }
  161707. /*
  161708. * Convert some rows of samples to the JPEG colorspace.
  161709. * This version handles Adobe-style CMYK->YCCK conversion,
  161710. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161711. * conversion as above, while passing K (black) unchanged.
  161712. * We assume rgb_ycc_start has been called.
  161713. */
  161714. METHODDEF(void)
  161715. cmyk_ycck_convert (j_compress_ptr cinfo,
  161716. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161717. JDIMENSION output_row, int num_rows)
  161718. {
  161719. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161720. register int r, g, b;
  161721. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161722. register JSAMPROW inptr;
  161723. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161724. register JDIMENSION col;
  161725. JDIMENSION num_cols = cinfo->image_width;
  161726. while (--num_rows >= 0) {
  161727. inptr = *input_buf++;
  161728. outptr0 = output_buf[0][output_row];
  161729. outptr1 = output_buf[1][output_row];
  161730. outptr2 = output_buf[2][output_row];
  161731. outptr3 = output_buf[3][output_row];
  161732. output_row++;
  161733. for (col = 0; col < num_cols; col++) {
  161734. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161735. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161736. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161737. /* K passes through as-is */
  161738. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161739. inptr += 4;
  161740. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161741. * must be too; we do not need an explicit range-limiting operation.
  161742. * Hence the value being shifted is never negative, and we don't
  161743. * need the general RIGHT_SHIFT macro.
  161744. */
  161745. /* Y */
  161746. outptr0[col] = (JSAMPLE)
  161747. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161748. >> SCALEBITS);
  161749. /* Cb */
  161750. outptr1[col] = (JSAMPLE)
  161751. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161752. >> SCALEBITS);
  161753. /* Cr */
  161754. outptr2[col] = (JSAMPLE)
  161755. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161756. >> SCALEBITS);
  161757. }
  161758. }
  161759. }
  161760. /*
  161761. * Convert some rows of samples to the JPEG colorspace.
  161762. * This version handles grayscale output with no conversion.
  161763. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161764. */
  161765. METHODDEF(void)
  161766. grayscale_convert (j_compress_ptr cinfo,
  161767. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161768. JDIMENSION output_row, int num_rows)
  161769. {
  161770. register JSAMPROW inptr;
  161771. register JSAMPROW outptr;
  161772. register JDIMENSION col;
  161773. JDIMENSION num_cols = cinfo->image_width;
  161774. int instride = cinfo->input_components;
  161775. while (--num_rows >= 0) {
  161776. inptr = *input_buf++;
  161777. outptr = output_buf[0][output_row];
  161778. output_row++;
  161779. for (col = 0; col < num_cols; col++) {
  161780. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161781. inptr += instride;
  161782. }
  161783. }
  161784. }
  161785. /*
  161786. * Convert some rows of samples to the JPEG colorspace.
  161787. * This version handles multi-component colorspaces without conversion.
  161788. * We assume input_components == num_components.
  161789. */
  161790. METHODDEF(void)
  161791. null_convert (j_compress_ptr cinfo,
  161792. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161793. JDIMENSION output_row, int num_rows)
  161794. {
  161795. register JSAMPROW inptr;
  161796. register JSAMPROW outptr;
  161797. register JDIMENSION col;
  161798. register int ci;
  161799. int nc = cinfo->num_components;
  161800. JDIMENSION num_cols = cinfo->image_width;
  161801. while (--num_rows >= 0) {
  161802. /* It seems fastest to make a separate pass for each component. */
  161803. for (ci = 0; ci < nc; ci++) {
  161804. inptr = *input_buf;
  161805. outptr = output_buf[ci][output_row];
  161806. for (col = 0; col < num_cols; col++) {
  161807. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161808. inptr += nc;
  161809. }
  161810. }
  161811. input_buf++;
  161812. output_row++;
  161813. }
  161814. }
  161815. /*
  161816. * Empty method for start_pass.
  161817. */
  161818. METHODDEF(void)
  161819. null_method (j_compress_ptr)
  161820. {
  161821. /* no work needed */
  161822. }
  161823. /*
  161824. * Module initialization routine for input colorspace conversion.
  161825. */
  161826. GLOBAL(void)
  161827. jinit_color_converter (j_compress_ptr cinfo)
  161828. {
  161829. my_cconvert_ptr cconvert;
  161830. cconvert = (my_cconvert_ptr)
  161831. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161832. SIZEOF(my_color_converter));
  161833. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  161834. /* set start_pass to null method until we find out differently */
  161835. cconvert->pub.start_pass = null_method;
  161836. /* Make sure input_components agrees with in_color_space */
  161837. switch (cinfo->in_color_space) {
  161838. case JCS_GRAYSCALE:
  161839. if (cinfo->input_components != 1)
  161840. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161841. break;
  161842. case JCS_RGB:
  161843. #if RGB_PIXELSIZE != 3
  161844. if (cinfo->input_components != RGB_PIXELSIZE)
  161845. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161846. break;
  161847. #endif /* else share code with YCbCr */
  161848. case JCS_YCbCr:
  161849. if (cinfo->input_components != 3)
  161850. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161851. break;
  161852. case JCS_CMYK:
  161853. case JCS_YCCK:
  161854. if (cinfo->input_components != 4)
  161855. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161856. break;
  161857. default: /* JCS_UNKNOWN can be anything */
  161858. if (cinfo->input_components < 1)
  161859. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161860. break;
  161861. }
  161862. /* Check num_components, set conversion method based on requested space */
  161863. switch (cinfo->jpeg_color_space) {
  161864. case JCS_GRAYSCALE:
  161865. if (cinfo->num_components != 1)
  161866. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161867. if (cinfo->in_color_space == JCS_GRAYSCALE)
  161868. cconvert->pub.color_convert = grayscale_convert;
  161869. else if (cinfo->in_color_space == JCS_RGB) {
  161870. cconvert->pub.start_pass = rgb_ycc_start;
  161871. cconvert->pub.color_convert = rgb_gray_convert;
  161872. } else if (cinfo->in_color_space == JCS_YCbCr)
  161873. cconvert->pub.color_convert = grayscale_convert;
  161874. else
  161875. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161876. break;
  161877. case JCS_RGB:
  161878. if (cinfo->num_components != 3)
  161879. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161880. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  161881. cconvert->pub.color_convert = null_convert;
  161882. else
  161883. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161884. break;
  161885. case JCS_YCbCr:
  161886. if (cinfo->num_components != 3)
  161887. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161888. if (cinfo->in_color_space == JCS_RGB) {
  161889. cconvert->pub.start_pass = rgb_ycc_start;
  161890. cconvert->pub.color_convert = rgb_ycc_convert;
  161891. } else if (cinfo->in_color_space == JCS_YCbCr)
  161892. cconvert->pub.color_convert = null_convert;
  161893. else
  161894. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161895. break;
  161896. case JCS_CMYK:
  161897. if (cinfo->num_components != 4)
  161898. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161899. if (cinfo->in_color_space == JCS_CMYK)
  161900. cconvert->pub.color_convert = null_convert;
  161901. else
  161902. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161903. break;
  161904. case JCS_YCCK:
  161905. if (cinfo->num_components != 4)
  161906. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161907. if (cinfo->in_color_space == JCS_CMYK) {
  161908. cconvert->pub.start_pass = rgb_ycc_start;
  161909. cconvert->pub.color_convert = cmyk_ycck_convert;
  161910. } else if (cinfo->in_color_space == JCS_YCCK)
  161911. cconvert->pub.color_convert = null_convert;
  161912. else
  161913. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161914. break;
  161915. default: /* allow null conversion of JCS_UNKNOWN */
  161916. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  161917. cinfo->num_components != cinfo->input_components)
  161918. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161919. cconvert->pub.color_convert = null_convert;
  161920. break;
  161921. }
  161922. }
  161923. /*** End of inlined file: jccolor.c ***/
  161924. #undef FIX
  161925. /*** Start of inlined file: jcdctmgr.c ***/
  161926. #define JPEG_INTERNALS
  161927. /*** Start of inlined file: jdct.h ***/
  161928. /*
  161929. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  161930. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  161931. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  161932. * implementations use an array of type FAST_FLOAT, instead.)
  161933. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  161934. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  161935. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  161936. * convention improves accuracy in integer implementations and saves some
  161937. * work in floating-point ones.
  161938. * Quantization of the output coefficients is done by jcdctmgr.c.
  161939. */
  161940. #ifndef __jdct_h__
  161941. #define __jdct_h__
  161942. #if BITS_IN_JSAMPLE == 8
  161943. typedef int DCTELEM; /* 16 or 32 bits is fine */
  161944. #else
  161945. typedef INT32 DCTELEM; /* must have 32 bits */
  161946. #endif
  161947. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  161948. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  161949. /*
  161950. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  161951. * to an output sample array. The routine must dequantize the input data as
  161952. * well as perform the IDCT; for dequantization, it uses the multiplier table
  161953. * pointed to by compptr->dct_table. The output data is to be placed into the
  161954. * sample array starting at a specified column. (Any row offset needed will
  161955. * be applied to the array pointer before it is passed to the IDCT code.)
  161956. * Note that the number of samples emitted by the IDCT routine is
  161957. * DCT_scaled_size * DCT_scaled_size.
  161958. */
  161959. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  161960. /*
  161961. * Each IDCT routine has its own ideas about the best dct_table element type.
  161962. */
  161963. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  161964. #if BITS_IN_JSAMPLE == 8
  161965. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  161966. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  161967. #else
  161968. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  161969. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  161970. #endif
  161971. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  161972. /*
  161973. * Each IDCT routine is responsible for range-limiting its results and
  161974. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  161975. * be quite far out of range if the input data is corrupt, so a bulletproof
  161976. * range-limiting step is required. We use a mask-and-table-lookup method
  161977. * to do the combined operations quickly. See the comments with
  161978. * prepare_range_limit_table (in jdmaster.c) for more info.
  161979. */
  161980. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  161981. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  161982. /* Short forms of external names for systems with brain-damaged linkers. */
  161983. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161984. #define jpeg_fdct_islow jFDislow
  161985. #define jpeg_fdct_ifast jFDifast
  161986. #define jpeg_fdct_float jFDfloat
  161987. #define jpeg_idct_islow jRDislow
  161988. #define jpeg_idct_ifast jRDifast
  161989. #define jpeg_idct_float jRDfloat
  161990. #define jpeg_idct_4x4 jRD4x4
  161991. #define jpeg_idct_2x2 jRD2x2
  161992. #define jpeg_idct_1x1 jRD1x1
  161993. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161994. /* Extern declarations for the forward and inverse DCT routines. */
  161995. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  161996. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  161997. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  161998. EXTERN(void) jpeg_idct_islow
  161999. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162000. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162001. EXTERN(void) jpeg_idct_ifast
  162002. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162003. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162004. EXTERN(void) jpeg_idct_float
  162005. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162006. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162007. EXTERN(void) jpeg_idct_4x4
  162008. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162009. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162010. EXTERN(void) jpeg_idct_2x2
  162011. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162012. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162013. EXTERN(void) jpeg_idct_1x1
  162014. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162015. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162016. /*
  162017. * Macros for handling fixed-point arithmetic; these are used by many
  162018. * but not all of the DCT/IDCT modules.
  162019. *
  162020. * All values are expected to be of type INT32.
  162021. * Fractional constants are scaled left by CONST_BITS bits.
  162022. * CONST_BITS is defined within each module using these macros,
  162023. * and may differ from one module to the next.
  162024. */
  162025. #define ONE ((INT32) 1)
  162026. #define CONST_SCALE (ONE << CONST_BITS)
  162027. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162028. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162029. * thus causing a lot of useless floating-point operations at run time.
  162030. */
  162031. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162032. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162033. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162034. * the fudge factor is correct for either sign of X.
  162035. */
  162036. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162037. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162038. * This macro is used only when the two inputs will actually be no more than
  162039. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162040. * full 32x32 multiply. This provides a useful speedup on many machines.
  162041. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162042. * in C, but some C compilers will do the right thing if you provide the
  162043. * correct combination of casts.
  162044. */
  162045. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162046. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162047. #endif
  162048. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162049. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162050. #endif
  162051. #ifndef MULTIPLY16C16 /* default definition */
  162052. #define MULTIPLY16C16(var,const) ((var) * (const))
  162053. #endif
  162054. /* Same except both inputs are variables. */
  162055. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162056. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162057. #endif
  162058. #ifndef MULTIPLY16V16 /* default definition */
  162059. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162060. #endif
  162061. #endif
  162062. /*** End of inlined file: jdct.h ***/
  162063. /* Private declarations for DCT subsystem */
  162064. /* Private subobject for this module */
  162065. typedef struct {
  162066. struct jpeg_forward_dct pub; /* public fields */
  162067. /* Pointer to the DCT routine actually in use */
  162068. forward_DCT_method_ptr do_dct;
  162069. /* The actual post-DCT divisors --- not identical to the quant table
  162070. * entries, because of scaling (especially for an unnormalized DCT).
  162071. * Each table is given in normal array order.
  162072. */
  162073. DCTELEM * divisors[NUM_QUANT_TBLS];
  162074. #ifdef DCT_FLOAT_SUPPORTED
  162075. /* Same as above for the floating-point case. */
  162076. float_DCT_method_ptr do_float_dct;
  162077. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162078. #endif
  162079. } my_fdct_controller;
  162080. typedef my_fdct_controller * my_fdct_ptr;
  162081. /*
  162082. * Initialize for a processing pass.
  162083. * Verify that all referenced Q-tables are present, and set up
  162084. * the divisor table for each one.
  162085. * In the current implementation, DCT of all components is done during
  162086. * the first pass, even if only some components will be output in the
  162087. * first scan. Hence all components should be examined here.
  162088. */
  162089. METHODDEF(void)
  162090. start_pass_fdctmgr (j_compress_ptr cinfo)
  162091. {
  162092. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162093. int ci, qtblno, i;
  162094. jpeg_component_info *compptr;
  162095. JQUANT_TBL * qtbl;
  162096. DCTELEM * dtbl;
  162097. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162098. ci++, compptr++) {
  162099. qtblno = compptr->quant_tbl_no;
  162100. /* Make sure specified quantization table is present */
  162101. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162102. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162103. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162104. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162105. /* Compute divisors for this quant table */
  162106. /* We may do this more than once for same table, but it's not a big deal */
  162107. switch (cinfo->dct_method) {
  162108. #ifdef DCT_ISLOW_SUPPORTED
  162109. case JDCT_ISLOW:
  162110. /* For LL&M IDCT method, divisors are equal to raw quantization
  162111. * coefficients multiplied by 8 (to counteract scaling).
  162112. */
  162113. if (fdct->divisors[qtblno] == NULL) {
  162114. fdct->divisors[qtblno] = (DCTELEM *)
  162115. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162116. DCTSIZE2 * SIZEOF(DCTELEM));
  162117. }
  162118. dtbl = fdct->divisors[qtblno];
  162119. for (i = 0; i < DCTSIZE2; i++) {
  162120. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162121. }
  162122. break;
  162123. #endif
  162124. #ifdef DCT_IFAST_SUPPORTED
  162125. case JDCT_IFAST:
  162126. {
  162127. /* For AA&N IDCT method, divisors are equal to quantization
  162128. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162129. * scalefactor[0] = 1
  162130. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162131. * We apply a further scale factor of 8.
  162132. */
  162133. #define CONST_BITS 14
  162134. static const INT16 aanscales[DCTSIZE2] = {
  162135. /* precomputed values scaled up by 14 bits */
  162136. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162137. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162138. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162139. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162140. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162141. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162142. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162143. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162144. };
  162145. SHIFT_TEMPS
  162146. if (fdct->divisors[qtblno] == NULL) {
  162147. fdct->divisors[qtblno] = (DCTELEM *)
  162148. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162149. DCTSIZE2 * SIZEOF(DCTELEM));
  162150. }
  162151. dtbl = fdct->divisors[qtblno];
  162152. for (i = 0; i < DCTSIZE2; i++) {
  162153. dtbl[i] = (DCTELEM)
  162154. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162155. (INT32) aanscales[i]),
  162156. CONST_BITS-3);
  162157. }
  162158. }
  162159. break;
  162160. #endif
  162161. #ifdef DCT_FLOAT_SUPPORTED
  162162. case JDCT_FLOAT:
  162163. {
  162164. /* For float AA&N IDCT method, divisors are equal to quantization
  162165. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162166. * scalefactor[0] = 1
  162167. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162168. * We apply a further scale factor of 8.
  162169. * What's actually stored is 1/divisor so that the inner loop can
  162170. * use a multiplication rather than a division.
  162171. */
  162172. FAST_FLOAT * fdtbl;
  162173. int row, col;
  162174. static const double aanscalefactor[DCTSIZE] = {
  162175. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162176. 1.0, 0.785694958, 0.541196100, 0.275899379
  162177. };
  162178. if (fdct->float_divisors[qtblno] == NULL) {
  162179. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162180. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162181. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162182. }
  162183. fdtbl = fdct->float_divisors[qtblno];
  162184. i = 0;
  162185. for (row = 0; row < DCTSIZE; row++) {
  162186. for (col = 0; col < DCTSIZE; col++) {
  162187. fdtbl[i] = (FAST_FLOAT)
  162188. (1.0 / (((double) qtbl->quantval[i] *
  162189. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162190. i++;
  162191. }
  162192. }
  162193. }
  162194. break;
  162195. #endif
  162196. default:
  162197. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162198. break;
  162199. }
  162200. }
  162201. }
  162202. /*
  162203. * Perform forward DCT on one or more blocks of a component.
  162204. *
  162205. * The input samples are taken from the sample_data[] array starting at
  162206. * position start_row/start_col, and moving to the right for any additional
  162207. * blocks. The quantized coefficients are returned in coef_blocks[].
  162208. */
  162209. METHODDEF(void)
  162210. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162211. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162212. JDIMENSION start_row, JDIMENSION start_col,
  162213. JDIMENSION num_blocks)
  162214. /* This version is used for integer DCT implementations. */
  162215. {
  162216. /* This routine is heavily used, so it's worth coding it tightly. */
  162217. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162218. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162219. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162220. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162221. JDIMENSION bi;
  162222. sample_data += start_row; /* fold in the vertical offset once */
  162223. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162224. /* Load data into workspace, applying unsigned->signed conversion */
  162225. { register DCTELEM *workspaceptr;
  162226. register JSAMPROW elemptr;
  162227. register int elemr;
  162228. workspaceptr = workspace;
  162229. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162230. elemptr = sample_data[elemr] + start_col;
  162231. #if DCTSIZE == 8 /* unroll the inner loop */
  162232. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162233. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162234. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162235. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162236. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162237. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162238. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162239. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162240. #else
  162241. { register int elemc;
  162242. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162243. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162244. }
  162245. }
  162246. #endif
  162247. }
  162248. }
  162249. /* Perform the DCT */
  162250. (*do_dct) (workspace);
  162251. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162252. { register DCTELEM temp, qval;
  162253. register int i;
  162254. register JCOEFPTR output_ptr = coef_blocks[bi];
  162255. for (i = 0; i < DCTSIZE2; i++) {
  162256. qval = divisors[i];
  162257. temp = workspace[i];
  162258. /* Divide the coefficient value by qval, ensuring proper rounding.
  162259. * Since C does not specify the direction of rounding for negative
  162260. * quotients, we have to force the dividend positive for portability.
  162261. *
  162262. * In most files, at least half of the output values will be zero
  162263. * (at default quantization settings, more like three-quarters...)
  162264. * so we should ensure that this case is fast. On many machines,
  162265. * a comparison is enough cheaper than a divide to make a special test
  162266. * a win. Since both inputs will be nonnegative, we need only test
  162267. * for a < b to discover whether a/b is 0.
  162268. * If your machine's division is fast enough, define FAST_DIVIDE.
  162269. */
  162270. #ifdef FAST_DIVIDE
  162271. #define DIVIDE_BY(a,b) a /= b
  162272. #else
  162273. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162274. #endif
  162275. if (temp < 0) {
  162276. temp = -temp;
  162277. temp += qval>>1; /* for rounding */
  162278. DIVIDE_BY(temp, qval);
  162279. temp = -temp;
  162280. } else {
  162281. temp += qval>>1; /* for rounding */
  162282. DIVIDE_BY(temp, qval);
  162283. }
  162284. output_ptr[i] = (JCOEF) temp;
  162285. }
  162286. }
  162287. }
  162288. }
  162289. #ifdef DCT_FLOAT_SUPPORTED
  162290. METHODDEF(void)
  162291. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162292. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162293. JDIMENSION start_row, JDIMENSION start_col,
  162294. JDIMENSION num_blocks)
  162295. /* This version is used for floating-point DCT implementations. */
  162296. {
  162297. /* This routine is heavily used, so it's worth coding it tightly. */
  162298. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162299. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162300. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162301. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162302. JDIMENSION bi;
  162303. sample_data += start_row; /* fold in the vertical offset once */
  162304. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162305. /* Load data into workspace, applying unsigned->signed conversion */
  162306. { register FAST_FLOAT *workspaceptr;
  162307. register JSAMPROW elemptr;
  162308. register int elemr;
  162309. workspaceptr = workspace;
  162310. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162311. elemptr = sample_data[elemr] + start_col;
  162312. #if DCTSIZE == 8 /* unroll the inner loop */
  162313. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162314. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162315. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162316. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162317. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162318. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162319. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162320. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162321. #else
  162322. { register int elemc;
  162323. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162324. *workspaceptr++ = (FAST_FLOAT)
  162325. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162326. }
  162327. }
  162328. #endif
  162329. }
  162330. }
  162331. /* Perform the DCT */
  162332. (*do_dct) (workspace);
  162333. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162334. { register FAST_FLOAT temp;
  162335. register int i;
  162336. register JCOEFPTR output_ptr = coef_blocks[bi];
  162337. for (i = 0; i < DCTSIZE2; i++) {
  162338. /* Apply the quantization and scaling factor */
  162339. temp = workspace[i] * divisors[i];
  162340. /* Round to nearest integer.
  162341. * Since C does not specify the direction of rounding for negative
  162342. * quotients, we have to force the dividend positive for portability.
  162343. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162344. * code should work for either 16-bit or 32-bit ints.
  162345. */
  162346. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162347. }
  162348. }
  162349. }
  162350. }
  162351. #endif /* DCT_FLOAT_SUPPORTED */
  162352. /*
  162353. * Initialize FDCT manager.
  162354. */
  162355. GLOBAL(void)
  162356. jinit_forward_dct (j_compress_ptr cinfo)
  162357. {
  162358. my_fdct_ptr fdct;
  162359. int i;
  162360. fdct = (my_fdct_ptr)
  162361. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162362. SIZEOF(my_fdct_controller));
  162363. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162364. fdct->pub.start_pass = start_pass_fdctmgr;
  162365. switch (cinfo->dct_method) {
  162366. #ifdef DCT_ISLOW_SUPPORTED
  162367. case JDCT_ISLOW:
  162368. fdct->pub.forward_DCT = forward_DCT;
  162369. fdct->do_dct = jpeg_fdct_islow;
  162370. break;
  162371. #endif
  162372. #ifdef DCT_IFAST_SUPPORTED
  162373. case JDCT_IFAST:
  162374. fdct->pub.forward_DCT = forward_DCT;
  162375. fdct->do_dct = jpeg_fdct_ifast;
  162376. break;
  162377. #endif
  162378. #ifdef DCT_FLOAT_SUPPORTED
  162379. case JDCT_FLOAT:
  162380. fdct->pub.forward_DCT = forward_DCT_float;
  162381. fdct->do_float_dct = jpeg_fdct_float;
  162382. break;
  162383. #endif
  162384. default:
  162385. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162386. break;
  162387. }
  162388. /* Mark divisor tables unallocated */
  162389. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162390. fdct->divisors[i] = NULL;
  162391. #ifdef DCT_FLOAT_SUPPORTED
  162392. fdct->float_divisors[i] = NULL;
  162393. #endif
  162394. }
  162395. }
  162396. /*** End of inlined file: jcdctmgr.c ***/
  162397. #undef CONST_BITS
  162398. /*** Start of inlined file: jchuff.c ***/
  162399. #define JPEG_INTERNALS
  162400. /*** Start of inlined file: jchuff.h ***/
  162401. /* The legal range of a DCT coefficient is
  162402. * -1024 .. +1023 for 8-bit data;
  162403. * -16384 .. +16383 for 12-bit data.
  162404. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162405. */
  162406. #ifndef _jchuff_h_
  162407. #define _jchuff_h_
  162408. #if BITS_IN_JSAMPLE == 8
  162409. #define MAX_COEF_BITS 10
  162410. #else
  162411. #define MAX_COEF_BITS 14
  162412. #endif
  162413. /* Derived data constructed for each Huffman table */
  162414. typedef struct {
  162415. unsigned int ehufco[256]; /* code for each symbol */
  162416. char ehufsi[256]; /* length of code for each symbol */
  162417. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162418. } c_derived_tbl;
  162419. /* Short forms of external names for systems with brain-damaged linkers. */
  162420. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162421. #define jpeg_make_c_derived_tbl jMkCDerived
  162422. #define jpeg_gen_optimal_table jGenOptTbl
  162423. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162424. /* Expand a Huffman table definition into the derived format */
  162425. EXTERN(void) jpeg_make_c_derived_tbl
  162426. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162427. c_derived_tbl ** pdtbl));
  162428. /* Generate an optimal table definition given the specified counts */
  162429. EXTERN(void) jpeg_gen_optimal_table
  162430. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162431. #endif
  162432. /*** End of inlined file: jchuff.h ***/
  162433. /* Declarations shared with jcphuff.c */
  162434. /* Expanded entropy encoder object for Huffman encoding.
  162435. *
  162436. * The savable_state subrecord contains fields that change within an MCU,
  162437. * but must not be updated permanently until we complete the MCU.
  162438. */
  162439. typedef struct {
  162440. INT32 put_buffer; /* current bit-accumulation buffer */
  162441. int put_bits; /* # of bits now in it */
  162442. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162443. } savable_state;
  162444. /* This macro is to work around compilers with missing or broken
  162445. * structure assignment. You'll need to fix this code if you have
  162446. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162447. */
  162448. #ifndef NO_STRUCT_ASSIGN
  162449. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162450. #else
  162451. #if MAX_COMPS_IN_SCAN == 4
  162452. #define ASSIGN_STATE(dest,src) \
  162453. ((dest).put_buffer = (src).put_buffer, \
  162454. (dest).put_bits = (src).put_bits, \
  162455. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162456. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162457. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162458. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162459. #endif
  162460. #endif
  162461. typedef struct {
  162462. struct jpeg_entropy_encoder pub; /* public fields */
  162463. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162464. /* These fields are NOT loaded into local working state. */
  162465. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162466. int next_restart_num; /* next restart number to write (0-7) */
  162467. /* Pointers to derived tables (these workspaces have image lifespan) */
  162468. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162469. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162470. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162471. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162472. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162473. #endif
  162474. } huff_entropy_encoder;
  162475. typedef huff_entropy_encoder * huff_entropy_ptr;
  162476. /* Working state while writing an MCU.
  162477. * This struct contains all the fields that are needed by subroutines.
  162478. */
  162479. typedef struct {
  162480. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162481. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162482. savable_state cur; /* Current bit buffer & DC state */
  162483. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162484. } working_state;
  162485. /* Forward declarations */
  162486. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162487. JBLOCKROW *MCU_data));
  162488. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162489. #ifdef ENTROPY_OPT_SUPPORTED
  162490. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162491. JBLOCKROW *MCU_data));
  162492. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162493. #endif
  162494. /*
  162495. * Initialize for a Huffman-compressed scan.
  162496. * If gather_statistics is TRUE, we do not output anything during the scan,
  162497. * just count the Huffman symbols used and generate Huffman code tables.
  162498. */
  162499. METHODDEF(void)
  162500. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162501. {
  162502. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162503. int ci, dctbl, actbl;
  162504. jpeg_component_info * compptr;
  162505. if (gather_statistics) {
  162506. #ifdef ENTROPY_OPT_SUPPORTED
  162507. entropy->pub.encode_mcu = encode_mcu_gather;
  162508. entropy->pub.finish_pass = finish_pass_gather;
  162509. #else
  162510. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162511. #endif
  162512. } else {
  162513. entropy->pub.encode_mcu = encode_mcu_huff;
  162514. entropy->pub.finish_pass = finish_pass_huff;
  162515. }
  162516. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162517. compptr = cinfo->cur_comp_info[ci];
  162518. dctbl = compptr->dc_tbl_no;
  162519. actbl = compptr->ac_tbl_no;
  162520. if (gather_statistics) {
  162521. #ifdef ENTROPY_OPT_SUPPORTED
  162522. /* Check for invalid table indexes */
  162523. /* (make_c_derived_tbl does this in the other path) */
  162524. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162525. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162526. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162527. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162528. /* Allocate and zero the statistics tables */
  162529. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162530. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162531. entropy->dc_count_ptrs[dctbl] = (long *)
  162532. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162533. 257 * SIZEOF(long));
  162534. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162535. if (entropy->ac_count_ptrs[actbl] == NULL)
  162536. entropy->ac_count_ptrs[actbl] = (long *)
  162537. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162538. 257 * SIZEOF(long));
  162539. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162540. #endif
  162541. } else {
  162542. /* Compute derived values for Huffman tables */
  162543. /* We may do this more than once for a table, but it's not expensive */
  162544. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162545. & entropy->dc_derived_tbls[dctbl]);
  162546. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162547. & entropy->ac_derived_tbls[actbl]);
  162548. }
  162549. /* Initialize DC predictions to 0 */
  162550. entropy->saved.last_dc_val[ci] = 0;
  162551. }
  162552. /* Initialize bit buffer to empty */
  162553. entropy->saved.put_buffer = 0;
  162554. entropy->saved.put_bits = 0;
  162555. /* Initialize restart stuff */
  162556. entropy->restarts_to_go = cinfo->restart_interval;
  162557. entropy->next_restart_num = 0;
  162558. }
  162559. /*
  162560. * Compute the derived values for a Huffman table.
  162561. * This routine also performs some validation checks on the table.
  162562. *
  162563. * Note this is also used by jcphuff.c.
  162564. */
  162565. GLOBAL(void)
  162566. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162567. c_derived_tbl ** pdtbl)
  162568. {
  162569. JHUFF_TBL *htbl;
  162570. c_derived_tbl *dtbl;
  162571. int p, i, l, lastp, si, maxsymbol;
  162572. char huffsize[257];
  162573. unsigned int huffcode[257];
  162574. unsigned int code;
  162575. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162576. * paralleling the order of the symbols themselves in htbl->huffval[].
  162577. */
  162578. /* Find the input Huffman table */
  162579. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162580. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162581. htbl =
  162582. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162583. if (htbl == NULL)
  162584. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162585. /* Allocate a workspace if we haven't already done so. */
  162586. if (*pdtbl == NULL)
  162587. *pdtbl = (c_derived_tbl *)
  162588. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162589. SIZEOF(c_derived_tbl));
  162590. dtbl = *pdtbl;
  162591. /* Figure C.1: make table of Huffman code length for each symbol */
  162592. p = 0;
  162593. for (l = 1; l <= 16; l++) {
  162594. i = (int) htbl->bits[l];
  162595. if (i < 0 || p + i > 256) /* protect against table overrun */
  162596. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162597. while (i--)
  162598. huffsize[p++] = (char) l;
  162599. }
  162600. huffsize[p] = 0;
  162601. lastp = p;
  162602. /* Figure C.2: generate the codes themselves */
  162603. /* We also validate that the counts represent a legal Huffman code tree. */
  162604. code = 0;
  162605. si = huffsize[0];
  162606. p = 0;
  162607. while (huffsize[p]) {
  162608. while (((int) huffsize[p]) == si) {
  162609. huffcode[p++] = code;
  162610. code++;
  162611. }
  162612. /* code is now 1 more than the last code used for codelength si; but
  162613. * it must still fit in si bits, since no code is allowed to be all ones.
  162614. */
  162615. if (((INT32) code) >= (((INT32) 1) << si))
  162616. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162617. code <<= 1;
  162618. si++;
  162619. }
  162620. /* Figure C.3: generate encoding tables */
  162621. /* These are code and size indexed by symbol value */
  162622. /* Set all codeless symbols to have code length 0;
  162623. * this lets us detect duplicate VAL entries here, and later
  162624. * allows emit_bits to detect any attempt to emit such symbols.
  162625. */
  162626. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162627. /* This is also a convenient place to check for out-of-range
  162628. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162629. * but only 0..15 for DC. (We could constrain them further
  162630. * based on data depth and mode, but this seems enough.)
  162631. */
  162632. maxsymbol = isDC ? 15 : 255;
  162633. for (p = 0; p < lastp; p++) {
  162634. i = htbl->huffval[p];
  162635. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162636. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162637. dtbl->ehufco[i] = huffcode[p];
  162638. dtbl->ehufsi[i] = huffsize[p];
  162639. }
  162640. }
  162641. /* Outputting bytes to the file */
  162642. /* Emit a byte, taking 'action' if must suspend. */
  162643. #define emit_byte(state,val,action) \
  162644. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162645. if (--(state)->free_in_buffer == 0) \
  162646. if (! dump_buffer(state)) \
  162647. { action; } }
  162648. LOCAL(boolean)
  162649. dump_buffer (working_state * state)
  162650. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162651. {
  162652. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162653. if (! (*dest->empty_output_buffer) (state->cinfo))
  162654. return FALSE;
  162655. /* After a successful buffer dump, must reset buffer pointers */
  162656. state->next_output_byte = dest->next_output_byte;
  162657. state->free_in_buffer = dest->free_in_buffer;
  162658. return TRUE;
  162659. }
  162660. /* Outputting bits to the file */
  162661. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162662. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162663. * in one call, and we never retain more than 7 bits in put_buffer
  162664. * between calls, so 24 bits are sufficient.
  162665. */
  162666. INLINE
  162667. LOCAL(boolean)
  162668. emit_bits (working_state * state, unsigned int code, int size)
  162669. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162670. {
  162671. /* This routine is heavily used, so it's worth coding tightly. */
  162672. register INT32 put_buffer = (INT32) code;
  162673. register int put_bits = state->cur.put_bits;
  162674. /* if size is 0, caller used an invalid Huffman table entry */
  162675. if (size == 0)
  162676. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162677. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162678. put_bits += size; /* new number of bits in buffer */
  162679. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162680. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162681. while (put_bits >= 8) {
  162682. int c = (int) ((put_buffer >> 16) & 0xFF);
  162683. emit_byte(state, c, return FALSE);
  162684. if (c == 0xFF) { /* need to stuff a zero byte? */
  162685. emit_byte(state, 0, return FALSE);
  162686. }
  162687. put_buffer <<= 8;
  162688. put_bits -= 8;
  162689. }
  162690. state->cur.put_buffer = put_buffer; /* update state variables */
  162691. state->cur.put_bits = put_bits;
  162692. return TRUE;
  162693. }
  162694. LOCAL(boolean)
  162695. flush_bits (working_state * state)
  162696. {
  162697. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162698. return FALSE;
  162699. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162700. state->cur.put_bits = 0;
  162701. return TRUE;
  162702. }
  162703. /* Encode a single block's worth of coefficients */
  162704. LOCAL(boolean)
  162705. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162706. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162707. {
  162708. register int temp, temp2;
  162709. register int nbits;
  162710. register int k, r, i;
  162711. /* Encode the DC coefficient difference per section F.1.2.1 */
  162712. temp = temp2 = block[0] - last_dc_val;
  162713. if (temp < 0) {
  162714. temp = -temp; /* temp is abs value of input */
  162715. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162716. /* This code assumes we are on a two's complement machine */
  162717. temp2--;
  162718. }
  162719. /* Find the number of bits needed for the magnitude of the coefficient */
  162720. nbits = 0;
  162721. while (temp) {
  162722. nbits++;
  162723. temp >>= 1;
  162724. }
  162725. /* Check for out-of-range coefficient values.
  162726. * Since we're encoding a difference, the range limit is twice as much.
  162727. */
  162728. if (nbits > MAX_COEF_BITS+1)
  162729. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162730. /* Emit the Huffman-coded symbol for the number of bits */
  162731. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162732. return FALSE;
  162733. /* Emit that number of bits of the value, if positive, */
  162734. /* or the complement of its magnitude, if negative. */
  162735. if (nbits) /* emit_bits rejects calls with size 0 */
  162736. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162737. return FALSE;
  162738. /* Encode the AC coefficients per section F.1.2.2 */
  162739. r = 0; /* r = run length of zeros */
  162740. for (k = 1; k < DCTSIZE2; k++) {
  162741. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162742. r++;
  162743. } else {
  162744. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162745. while (r > 15) {
  162746. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162747. return FALSE;
  162748. r -= 16;
  162749. }
  162750. temp2 = temp;
  162751. if (temp < 0) {
  162752. temp = -temp; /* temp is abs value of input */
  162753. /* This code assumes we are on a two's complement machine */
  162754. temp2--;
  162755. }
  162756. /* Find the number of bits needed for the magnitude of the coefficient */
  162757. nbits = 1; /* there must be at least one 1 bit */
  162758. while ((temp >>= 1))
  162759. nbits++;
  162760. /* Check for out-of-range coefficient values */
  162761. if (nbits > MAX_COEF_BITS)
  162762. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162763. /* Emit Huffman symbol for run length / number of bits */
  162764. i = (r << 4) + nbits;
  162765. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162766. return FALSE;
  162767. /* Emit that number of bits of the value, if positive, */
  162768. /* or the complement of its magnitude, if negative. */
  162769. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162770. return FALSE;
  162771. r = 0;
  162772. }
  162773. }
  162774. /* If the last coef(s) were zero, emit an end-of-block code */
  162775. if (r > 0)
  162776. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162777. return FALSE;
  162778. return TRUE;
  162779. }
  162780. /*
  162781. * Emit a restart marker & resynchronize predictions.
  162782. */
  162783. LOCAL(boolean)
  162784. emit_restart (working_state * state, int restart_num)
  162785. {
  162786. int ci;
  162787. if (! flush_bits(state))
  162788. return FALSE;
  162789. emit_byte(state, 0xFF, return FALSE);
  162790. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162791. /* Re-initialize DC predictions to 0 */
  162792. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162793. state->cur.last_dc_val[ci] = 0;
  162794. /* The restart counter is not updated until we successfully write the MCU. */
  162795. return TRUE;
  162796. }
  162797. /*
  162798. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162799. */
  162800. METHODDEF(boolean)
  162801. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162802. {
  162803. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162804. working_state state;
  162805. int blkn, ci;
  162806. jpeg_component_info * compptr;
  162807. /* Load up working state */
  162808. state.next_output_byte = cinfo->dest->next_output_byte;
  162809. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162810. ASSIGN_STATE(state.cur, entropy->saved);
  162811. state.cinfo = cinfo;
  162812. /* Emit restart marker if needed */
  162813. if (cinfo->restart_interval) {
  162814. if (entropy->restarts_to_go == 0)
  162815. if (! emit_restart(&state, entropy->next_restart_num))
  162816. return FALSE;
  162817. }
  162818. /* Encode the MCU data blocks */
  162819. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162820. ci = cinfo->MCU_membership[blkn];
  162821. compptr = cinfo->cur_comp_info[ci];
  162822. if (! encode_one_block(&state,
  162823. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  162824. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  162825. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  162826. return FALSE;
  162827. /* Update last_dc_val */
  162828. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  162829. }
  162830. /* Completed MCU, so update state */
  162831. cinfo->dest->next_output_byte = state.next_output_byte;
  162832. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162833. ASSIGN_STATE(entropy->saved, state.cur);
  162834. /* Update restart-interval state too */
  162835. if (cinfo->restart_interval) {
  162836. if (entropy->restarts_to_go == 0) {
  162837. entropy->restarts_to_go = cinfo->restart_interval;
  162838. entropy->next_restart_num++;
  162839. entropy->next_restart_num &= 7;
  162840. }
  162841. entropy->restarts_to_go--;
  162842. }
  162843. return TRUE;
  162844. }
  162845. /*
  162846. * Finish up at the end of a Huffman-compressed scan.
  162847. */
  162848. METHODDEF(void)
  162849. finish_pass_huff (j_compress_ptr cinfo)
  162850. {
  162851. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162852. working_state state;
  162853. /* Load up working state ... flush_bits needs it */
  162854. state.next_output_byte = cinfo->dest->next_output_byte;
  162855. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162856. ASSIGN_STATE(state.cur, entropy->saved);
  162857. state.cinfo = cinfo;
  162858. /* Flush out the last data */
  162859. if (! flush_bits(&state))
  162860. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  162861. /* Update state */
  162862. cinfo->dest->next_output_byte = state.next_output_byte;
  162863. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162864. ASSIGN_STATE(entropy->saved, state.cur);
  162865. }
  162866. /*
  162867. * Huffman coding optimization.
  162868. *
  162869. * We first scan the supplied data and count the number of uses of each symbol
  162870. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  162871. * Then we build a Huffman coding tree for the observed counts.
  162872. * Symbols which are not needed at all for the particular image are not
  162873. * assigned any code, which saves space in the DHT marker as well as in
  162874. * the compressed data.
  162875. */
  162876. #ifdef ENTROPY_OPT_SUPPORTED
  162877. /* Process a single block's worth of coefficients */
  162878. LOCAL(void)
  162879. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  162880. long dc_counts[], long ac_counts[])
  162881. {
  162882. register int temp;
  162883. register int nbits;
  162884. register int k, r;
  162885. /* Encode the DC coefficient difference per section F.1.2.1 */
  162886. temp = block[0] - last_dc_val;
  162887. if (temp < 0)
  162888. temp = -temp;
  162889. /* Find the number of bits needed for the magnitude of the coefficient */
  162890. nbits = 0;
  162891. while (temp) {
  162892. nbits++;
  162893. temp >>= 1;
  162894. }
  162895. /* Check for out-of-range coefficient values.
  162896. * Since we're encoding a difference, the range limit is twice as much.
  162897. */
  162898. if (nbits > MAX_COEF_BITS+1)
  162899. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162900. /* Count the Huffman symbol for the number of bits */
  162901. dc_counts[nbits]++;
  162902. /* Encode the AC coefficients per section F.1.2.2 */
  162903. r = 0; /* r = run length of zeros */
  162904. for (k = 1; k < DCTSIZE2; k++) {
  162905. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162906. r++;
  162907. } else {
  162908. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162909. while (r > 15) {
  162910. ac_counts[0xF0]++;
  162911. r -= 16;
  162912. }
  162913. /* Find the number of bits needed for the magnitude of the coefficient */
  162914. if (temp < 0)
  162915. temp = -temp;
  162916. /* Find the number of bits needed for the magnitude of the coefficient */
  162917. nbits = 1; /* there must be at least one 1 bit */
  162918. while ((temp >>= 1))
  162919. nbits++;
  162920. /* Check for out-of-range coefficient values */
  162921. if (nbits > MAX_COEF_BITS)
  162922. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162923. /* Count Huffman symbol for run length / number of bits */
  162924. ac_counts[(r << 4) + nbits]++;
  162925. r = 0;
  162926. }
  162927. }
  162928. /* If the last coef(s) were zero, emit an end-of-block code */
  162929. if (r > 0)
  162930. ac_counts[0]++;
  162931. }
  162932. /*
  162933. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  162934. * No data is actually output, so no suspension return is possible.
  162935. */
  162936. METHODDEF(boolean)
  162937. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162938. {
  162939. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162940. int blkn, ci;
  162941. jpeg_component_info * compptr;
  162942. /* Take care of restart intervals if needed */
  162943. if (cinfo->restart_interval) {
  162944. if (entropy->restarts_to_go == 0) {
  162945. /* Re-initialize DC predictions to 0 */
  162946. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  162947. entropy->saved.last_dc_val[ci] = 0;
  162948. /* Update restart state */
  162949. entropy->restarts_to_go = cinfo->restart_interval;
  162950. }
  162951. entropy->restarts_to_go--;
  162952. }
  162953. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162954. ci = cinfo->MCU_membership[blkn];
  162955. compptr = cinfo->cur_comp_info[ci];
  162956. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  162957. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  162958. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  162959. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  162960. }
  162961. return TRUE;
  162962. }
  162963. /*
  162964. * Generate the best Huffman code table for the given counts, fill htbl.
  162965. * Note this is also used by jcphuff.c.
  162966. *
  162967. * The JPEG standard requires that no symbol be assigned a codeword of all
  162968. * one bits (so that padding bits added at the end of a compressed segment
  162969. * can't look like a valid code). Because of the canonical ordering of
  162970. * codewords, this just means that there must be an unused slot in the
  162971. * longest codeword length category. Section K.2 of the JPEG spec suggests
  162972. * reserving such a slot by pretending that symbol 256 is a valid symbol
  162973. * with count 1. In theory that's not optimal; giving it count zero but
  162974. * including it in the symbol set anyway should give a better Huffman code.
  162975. * But the theoretically better code actually seems to come out worse in
  162976. * practice, because it produces more all-ones bytes (which incur stuffed
  162977. * zero bytes in the final file). In any case the difference is tiny.
  162978. *
  162979. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  162980. * If some symbols have a very small but nonzero probability, the Huffman tree
  162981. * must be adjusted to meet the code length restriction. We currently use
  162982. * the adjustment method suggested in JPEG section K.2. This method is *not*
  162983. * optimal; it may not choose the best possible limited-length code. But
  162984. * typically only very-low-frequency symbols will be given less-than-optimal
  162985. * lengths, so the code is almost optimal. Experimental comparisons against
  162986. * an optimal limited-length-code algorithm indicate that the difference is
  162987. * microscopic --- usually less than a hundredth of a percent of total size.
  162988. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  162989. */
  162990. GLOBAL(void)
  162991. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  162992. {
  162993. #define MAX_CLEN 32 /* assumed maximum initial code length */
  162994. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  162995. int codesize[257]; /* codesize[k] = code length of symbol k */
  162996. int others[257]; /* next symbol in current branch of tree */
  162997. int c1, c2;
  162998. int p, i, j;
  162999. long v;
  163000. /* This algorithm is explained in section K.2 of the JPEG standard */
  163001. MEMZERO(bits, SIZEOF(bits));
  163002. MEMZERO(codesize, SIZEOF(codesize));
  163003. for (i = 0; i < 257; i++)
  163004. others[i] = -1; /* init links to empty */
  163005. freq[256] = 1; /* make sure 256 has a nonzero count */
  163006. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163007. * that no real symbol is given code-value of all ones, because 256
  163008. * will be placed last in the largest codeword category.
  163009. */
  163010. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163011. for (;;) {
  163012. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163013. /* In case of ties, take the larger symbol number */
  163014. c1 = -1;
  163015. v = 1000000000L;
  163016. for (i = 0; i <= 256; i++) {
  163017. if (freq[i] && freq[i] <= v) {
  163018. v = freq[i];
  163019. c1 = i;
  163020. }
  163021. }
  163022. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163023. /* In case of ties, take the larger symbol number */
  163024. c2 = -1;
  163025. v = 1000000000L;
  163026. for (i = 0; i <= 256; i++) {
  163027. if (freq[i] && freq[i] <= v && i != c1) {
  163028. v = freq[i];
  163029. c2 = i;
  163030. }
  163031. }
  163032. /* Done if we've merged everything into one frequency */
  163033. if (c2 < 0)
  163034. break;
  163035. /* Else merge the two counts/trees */
  163036. freq[c1] += freq[c2];
  163037. freq[c2] = 0;
  163038. /* Increment the codesize of everything in c1's tree branch */
  163039. codesize[c1]++;
  163040. while (others[c1] >= 0) {
  163041. c1 = others[c1];
  163042. codesize[c1]++;
  163043. }
  163044. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163045. /* Increment the codesize of everything in c2's tree branch */
  163046. codesize[c2]++;
  163047. while (others[c2] >= 0) {
  163048. c2 = others[c2];
  163049. codesize[c2]++;
  163050. }
  163051. }
  163052. /* Now count the number of symbols of each code length */
  163053. for (i = 0; i <= 256; i++) {
  163054. if (codesize[i]) {
  163055. /* The JPEG standard seems to think that this can't happen, */
  163056. /* but I'm paranoid... */
  163057. if (codesize[i] > MAX_CLEN)
  163058. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163059. bits[codesize[i]]++;
  163060. }
  163061. }
  163062. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163063. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163064. * Here is what the JPEG spec says about how this next bit works:
  163065. * Since symbols are paired for the longest Huffman code, the symbols are
  163066. * removed from this length category two at a time. The prefix for the pair
  163067. * (which is one bit shorter) is allocated to one of the pair; then,
  163068. * skipping the BITS entry for that prefix length, a code word from the next
  163069. * shortest nonzero BITS entry is converted into a prefix for two code words
  163070. * one bit longer.
  163071. */
  163072. for (i = MAX_CLEN; i > 16; i--) {
  163073. while (bits[i] > 0) {
  163074. j = i - 2; /* find length of new prefix to be used */
  163075. while (bits[j] == 0)
  163076. j--;
  163077. bits[i] -= 2; /* remove two symbols */
  163078. bits[i-1]++; /* one goes in this length */
  163079. bits[j+1] += 2; /* two new symbols in this length */
  163080. bits[j]--; /* symbol of this length is now a prefix */
  163081. }
  163082. }
  163083. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163084. while (bits[i] == 0) /* find largest codelength still in use */
  163085. i--;
  163086. bits[i]--;
  163087. /* Return final symbol counts (only for lengths 0..16) */
  163088. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163089. /* Return a list of the symbols sorted by code length */
  163090. /* It's not real clear to me why we don't need to consider the codelength
  163091. * changes made above, but the JPEG spec seems to think this works.
  163092. */
  163093. p = 0;
  163094. for (i = 1; i <= MAX_CLEN; i++) {
  163095. for (j = 0; j <= 255; j++) {
  163096. if (codesize[j] == i) {
  163097. htbl->huffval[p] = (UINT8) j;
  163098. p++;
  163099. }
  163100. }
  163101. }
  163102. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163103. htbl->sent_table = FALSE;
  163104. }
  163105. /*
  163106. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163107. */
  163108. METHODDEF(void)
  163109. finish_pass_gather (j_compress_ptr cinfo)
  163110. {
  163111. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163112. int ci, dctbl, actbl;
  163113. jpeg_component_info * compptr;
  163114. JHUFF_TBL **htblptr;
  163115. boolean did_dc[NUM_HUFF_TBLS];
  163116. boolean did_ac[NUM_HUFF_TBLS];
  163117. /* It's important not to apply jpeg_gen_optimal_table more than once
  163118. * per table, because it clobbers the input frequency counts!
  163119. */
  163120. MEMZERO(did_dc, SIZEOF(did_dc));
  163121. MEMZERO(did_ac, SIZEOF(did_ac));
  163122. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163123. compptr = cinfo->cur_comp_info[ci];
  163124. dctbl = compptr->dc_tbl_no;
  163125. actbl = compptr->ac_tbl_no;
  163126. if (! did_dc[dctbl]) {
  163127. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163128. if (*htblptr == NULL)
  163129. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163130. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163131. did_dc[dctbl] = TRUE;
  163132. }
  163133. if (! did_ac[actbl]) {
  163134. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163135. if (*htblptr == NULL)
  163136. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163137. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163138. did_ac[actbl] = TRUE;
  163139. }
  163140. }
  163141. }
  163142. #endif /* ENTROPY_OPT_SUPPORTED */
  163143. /*
  163144. * Module initialization routine for Huffman entropy encoding.
  163145. */
  163146. GLOBAL(void)
  163147. jinit_huff_encoder (j_compress_ptr cinfo)
  163148. {
  163149. huff_entropy_ptr entropy;
  163150. int i;
  163151. entropy = (huff_entropy_ptr)
  163152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163153. SIZEOF(huff_entropy_encoder));
  163154. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163155. entropy->pub.start_pass = start_pass_huff;
  163156. /* Mark tables unallocated */
  163157. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163158. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163159. #ifdef ENTROPY_OPT_SUPPORTED
  163160. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163161. #endif
  163162. }
  163163. }
  163164. /*** End of inlined file: jchuff.c ***/
  163165. #undef emit_byte
  163166. /*** Start of inlined file: jcinit.c ***/
  163167. #define JPEG_INTERNALS
  163168. /*
  163169. * Master selection of compression modules.
  163170. * This is done once at the start of processing an image. We determine
  163171. * which modules will be used and give them appropriate initialization calls.
  163172. */
  163173. GLOBAL(void)
  163174. jinit_compress_master (j_compress_ptr cinfo)
  163175. {
  163176. /* Initialize master control (includes parameter checking/processing) */
  163177. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163178. /* Preprocessing */
  163179. if (! cinfo->raw_data_in) {
  163180. jinit_color_converter(cinfo);
  163181. jinit_downsampler(cinfo);
  163182. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163183. }
  163184. /* Forward DCT */
  163185. jinit_forward_dct(cinfo);
  163186. /* Entropy encoding: either Huffman or arithmetic coding. */
  163187. if (cinfo->arith_code) {
  163188. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163189. } else {
  163190. if (cinfo->progressive_mode) {
  163191. #ifdef C_PROGRESSIVE_SUPPORTED
  163192. jinit_phuff_encoder(cinfo);
  163193. #else
  163194. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163195. #endif
  163196. } else
  163197. jinit_huff_encoder(cinfo);
  163198. }
  163199. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163200. jinit_c_coef_controller(cinfo,
  163201. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163202. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163203. jinit_marker_writer(cinfo);
  163204. /* We can now tell the memory manager to allocate virtual arrays. */
  163205. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163206. /* Write the datastream header (SOI) immediately.
  163207. * Frame and scan headers are postponed till later.
  163208. * This lets application insert special markers after the SOI.
  163209. */
  163210. (*cinfo->marker->write_file_header) (cinfo);
  163211. }
  163212. /*** End of inlined file: jcinit.c ***/
  163213. /*** Start of inlined file: jcmainct.c ***/
  163214. #define JPEG_INTERNALS
  163215. /* Note: currently, there is no operating mode in which a full-image buffer
  163216. * is needed at this step. If there were, that mode could not be used with
  163217. * "raw data" input, since this module is bypassed in that case. However,
  163218. * we've left the code here for possible use in special applications.
  163219. */
  163220. #undef FULL_MAIN_BUFFER_SUPPORTED
  163221. /* Private buffer controller object */
  163222. typedef struct {
  163223. struct jpeg_c_main_controller pub; /* public fields */
  163224. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163225. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163226. boolean suspended; /* remember if we suspended output */
  163227. J_BUF_MODE pass_mode; /* current operating mode */
  163228. /* If using just a strip buffer, this points to the entire set of buffers
  163229. * (we allocate one for each component). In the full-image case, this
  163230. * points to the currently accessible strips of the virtual arrays.
  163231. */
  163232. JSAMPARRAY buffer[MAX_COMPONENTS];
  163233. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163234. /* If using full-image storage, this array holds pointers to virtual-array
  163235. * control blocks for each component. Unused if not full-image storage.
  163236. */
  163237. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163238. #endif
  163239. } my_main_controller;
  163240. typedef my_main_controller * my_main_ptr;
  163241. /* Forward declarations */
  163242. METHODDEF(void) process_data_simple_main
  163243. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163244. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163245. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163246. METHODDEF(void) process_data_buffer_main
  163247. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163248. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163249. #endif
  163250. /*
  163251. * Initialize for a processing pass.
  163252. */
  163253. METHODDEF(void)
  163254. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163255. {
  163256. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163257. /* Do nothing in raw-data mode. */
  163258. if (cinfo->raw_data_in)
  163259. return;
  163260. main_->cur_iMCU_row = 0; /* initialize counters */
  163261. main_->rowgroup_ctr = 0;
  163262. main_->suspended = FALSE;
  163263. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163264. switch (pass_mode) {
  163265. case JBUF_PASS_THRU:
  163266. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163267. if (main_->whole_image[0] != NULL)
  163268. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163269. #endif
  163270. main_->pub.process_data = process_data_simple_main;
  163271. break;
  163272. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163273. case JBUF_SAVE_SOURCE:
  163274. case JBUF_CRANK_DEST:
  163275. case JBUF_SAVE_AND_PASS:
  163276. if (main_->whole_image[0] == NULL)
  163277. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163278. main_->pub.process_data = process_data_buffer_main;
  163279. break;
  163280. #endif
  163281. default:
  163282. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163283. break;
  163284. }
  163285. }
  163286. /*
  163287. * Process some data.
  163288. * This routine handles the simple pass-through mode,
  163289. * where we have only a strip buffer.
  163290. */
  163291. METHODDEF(void)
  163292. process_data_simple_main (j_compress_ptr cinfo,
  163293. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163294. JDIMENSION in_rows_avail)
  163295. {
  163296. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163297. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163298. /* Read input data if we haven't filled the main buffer yet */
  163299. if (main_->rowgroup_ctr < DCTSIZE)
  163300. (*cinfo->prep->pre_process_data) (cinfo,
  163301. input_buf, in_row_ctr, in_rows_avail,
  163302. main_->buffer, &main_->rowgroup_ctr,
  163303. (JDIMENSION) DCTSIZE);
  163304. /* If we don't have a full iMCU row buffered, return to application for
  163305. * more data. Note that preprocessor will always pad to fill the iMCU row
  163306. * at the bottom of the image.
  163307. */
  163308. if (main_->rowgroup_ctr != DCTSIZE)
  163309. return;
  163310. /* Send the completed row to the compressor */
  163311. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163312. /* If compressor did not consume the whole row, then we must need to
  163313. * suspend processing and return to the application. In this situation
  163314. * we pretend we didn't yet consume the last input row; otherwise, if
  163315. * it happened to be the last row of the image, the application would
  163316. * think we were done.
  163317. */
  163318. if (! main_->suspended) {
  163319. (*in_row_ctr)--;
  163320. main_->suspended = TRUE;
  163321. }
  163322. return;
  163323. }
  163324. /* We did finish the row. Undo our little suspension hack if a previous
  163325. * call suspended; then mark the main buffer empty.
  163326. */
  163327. if (main_->suspended) {
  163328. (*in_row_ctr)++;
  163329. main_->suspended = FALSE;
  163330. }
  163331. main_->rowgroup_ctr = 0;
  163332. main_->cur_iMCU_row++;
  163333. }
  163334. }
  163335. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163336. /*
  163337. * Process some data.
  163338. * This routine handles all of the modes that use a full-size buffer.
  163339. */
  163340. METHODDEF(void)
  163341. process_data_buffer_main (j_compress_ptr cinfo,
  163342. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163343. JDIMENSION in_rows_avail)
  163344. {
  163345. my_main_ptr main = (my_main_ptr) cinfo->main;
  163346. int ci;
  163347. jpeg_component_info *compptr;
  163348. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163349. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163350. /* Realign the virtual buffers if at the start of an iMCU row. */
  163351. if (main->rowgroup_ctr == 0) {
  163352. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163353. ci++, compptr++) {
  163354. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163355. ((j_common_ptr) cinfo, main->whole_image[ci],
  163356. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163357. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163358. }
  163359. /* In a read pass, pretend we just read some source data. */
  163360. if (! writing) {
  163361. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163362. main->rowgroup_ctr = DCTSIZE;
  163363. }
  163364. }
  163365. /* If a write pass, read input data until the current iMCU row is full. */
  163366. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163367. if (writing) {
  163368. (*cinfo->prep->pre_process_data) (cinfo,
  163369. input_buf, in_row_ctr, in_rows_avail,
  163370. main->buffer, &main->rowgroup_ctr,
  163371. (JDIMENSION) DCTSIZE);
  163372. /* Return to application if we need more data to fill the iMCU row. */
  163373. if (main->rowgroup_ctr < DCTSIZE)
  163374. return;
  163375. }
  163376. /* Emit data, unless this is a sink-only pass. */
  163377. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163378. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163379. /* If compressor did not consume the whole row, then we must need to
  163380. * suspend processing and return to the application. In this situation
  163381. * we pretend we didn't yet consume the last input row; otherwise, if
  163382. * it happened to be the last row of the image, the application would
  163383. * think we were done.
  163384. */
  163385. if (! main->suspended) {
  163386. (*in_row_ctr)--;
  163387. main->suspended = TRUE;
  163388. }
  163389. return;
  163390. }
  163391. /* We did finish the row. Undo our little suspension hack if a previous
  163392. * call suspended; then mark the main buffer empty.
  163393. */
  163394. if (main->suspended) {
  163395. (*in_row_ctr)++;
  163396. main->suspended = FALSE;
  163397. }
  163398. }
  163399. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163400. main->rowgroup_ctr = 0;
  163401. main->cur_iMCU_row++;
  163402. }
  163403. }
  163404. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163405. /*
  163406. * Initialize main buffer controller.
  163407. */
  163408. GLOBAL(void)
  163409. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163410. {
  163411. my_main_ptr main_;
  163412. int ci;
  163413. jpeg_component_info *compptr;
  163414. main_ = (my_main_ptr)
  163415. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163416. SIZEOF(my_main_controller));
  163417. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163418. main_->pub.start_pass = start_pass_main;
  163419. /* We don't need to create a buffer in raw-data mode. */
  163420. if (cinfo->raw_data_in)
  163421. return;
  163422. /* Create the buffer. It holds downsampled data, so each component
  163423. * may be of a different size.
  163424. */
  163425. if (need_full_buffer) {
  163426. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163427. /* Allocate a full-image virtual array for each component */
  163428. /* Note we pad the bottom to a multiple of the iMCU height */
  163429. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163430. ci++, compptr++) {
  163431. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163432. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163433. compptr->width_in_blocks * DCTSIZE,
  163434. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163435. (long) compptr->v_samp_factor) * DCTSIZE,
  163436. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163437. }
  163438. #else
  163439. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163440. #endif
  163441. } else {
  163442. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163443. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163444. #endif
  163445. /* Allocate a strip buffer for each component */
  163446. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163447. ci++, compptr++) {
  163448. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163449. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163450. compptr->width_in_blocks * DCTSIZE,
  163451. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163452. }
  163453. }
  163454. }
  163455. /*** End of inlined file: jcmainct.c ***/
  163456. /*** Start of inlined file: jcmarker.c ***/
  163457. #define JPEG_INTERNALS
  163458. /* Private state */
  163459. typedef struct {
  163460. struct jpeg_marker_writer pub; /* public fields */
  163461. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163462. } my_marker_writer;
  163463. typedef my_marker_writer * my_marker_ptr;
  163464. /*
  163465. * Basic output routines.
  163466. *
  163467. * Note that we do not support suspension while writing a marker.
  163468. * Therefore, an application using suspension must ensure that there is
  163469. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163470. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163471. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163472. * modes are not supported at all with suspension, so those two are the only
  163473. * points where markers will be written.
  163474. */
  163475. LOCAL(void)
  163476. emit_byte (j_compress_ptr cinfo, int val)
  163477. /* Emit a byte */
  163478. {
  163479. struct jpeg_destination_mgr * dest = cinfo->dest;
  163480. *(dest->next_output_byte)++ = (JOCTET) val;
  163481. if (--dest->free_in_buffer == 0) {
  163482. if (! (*dest->empty_output_buffer) (cinfo))
  163483. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163484. }
  163485. }
  163486. LOCAL(void)
  163487. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163488. /* Emit a marker code */
  163489. {
  163490. emit_byte(cinfo, 0xFF);
  163491. emit_byte(cinfo, (int) mark);
  163492. }
  163493. LOCAL(void)
  163494. emit_2bytes (j_compress_ptr cinfo, int value)
  163495. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163496. {
  163497. emit_byte(cinfo, (value >> 8) & 0xFF);
  163498. emit_byte(cinfo, value & 0xFF);
  163499. }
  163500. /*
  163501. * Routines to write specific marker types.
  163502. */
  163503. LOCAL(int)
  163504. emit_dqt (j_compress_ptr cinfo, int index)
  163505. /* Emit a DQT marker */
  163506. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163507. {
  163508. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163509. int prec;
  163510. int i;
  163511. if (qtbl == NULL)
  163512. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163513. prec = 0;
  163514. for (i = 0; i < DCTSIZE2; i++) {
  163515. if (qtbl->quantval[i] > 255)
  163516. prec = 1;
  163517. }
  163518. if (! qtbl->sent_table) {
  163519. emit_marker(cinfo, M_DQT);
  163520. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163521. emit_byte(cinfo, index + (prec<<4));
  163522. for (i = 0; i < DCTSIZE2; i++) {
  163523. /* The table entries must be emitted in zigzag order. */
  163524. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163525. if (prec)
  163526. emit_byte(cinfo, (int) (qval >> 8));
  163527. emit_byte(cinfo, (int) (qval & 0xFF));
  163528. }
  163529. qtbl->sent_table = TRUE;
  163530. }
  163531. return prec;
  163532. }
  163533. LOCAL(void)
  163534. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163535. /* Emit a DHT marker */
  163536. {
  163537. JHUFF_TBL * htbl;
  163538. int length, i;
  163539. if (is_ac) {
  163540. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163541. index += 0x10; /* output index has AC bit set */
  163542. } else {
  163543. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163544. }
  163545. if (htbl == NULL)
  163546. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163547. if (! htbl->sent_table) {
  163548. emit_marker(cinfo, M_DHT);
  163549. length = 0;
  163550. for (i = 1; i <= 16; i++)
  163551. length += htbl->bits[i];
  163552. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163553. emit_byte(cinfo, index);
  163554. for (i = 1; i <= 16; i++)
  163555. emit_byte(cinfo, htbl->bits[i]);
  163556. for (i = 0; i < length; i++)
  163557. emit_byte(cinfo, htbl->huffval[i]);
  163558. htbl->sent_table = TRUE;
  163559. }
  163560. }
  163561. LOCAL(void)
  163562. emit_dac (j_compress_ptr)
  163563. /* Emit a DAC marker */
  163564. /* Since the useful info is so small, we want to emit all the tables in */
  163565. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163566. {
  163567. #ifdef C_ARITH_CODING_SUPPORTED
  163568. char dc_in_use[NUM_ARITH_TBLS];
  163569. char ac_in_use[NUM_ARITH_TBLS];
  163570. int length, i;
  163571. jpeg_component_info *compptr;
  163572. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163573. dc_in_use[i] = ac_in_use[i] = 0;
  163574. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163575. compptr = cinfo->cur_comp_info[i];
  163576. dc_in_use[compptr->dc_tbl_no] = 1;
  163577. ac_in_use[compptr->ac_tbl_no] = 1;
  163578. }
  163579. length = 0;
  163580. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163581. length += dc_in_use[i] + ac_in_use[i];
  163582. emit_marker(cinfo, M_DAC);
  163583. emit_2bytes(cinfo, length*2 + 2);
  163584. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163585. if (dc_in_use[i]) {
  163586. emit_byte(cinfo, i);
  163587. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163588. }
  163589. if (ac_in_use[i]) {
  163590. emit_byte(cinfo, i + 0x10);
  163591. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163592. }
  163593. }
  163594. #endif /* C_ARITH_CODING_SUPPORTED */
  163595. }
  163596. LOCAL(void)
  163597. emit_dri (j_compress_ptr cinfo)
  163598. /* Emit a DRI marker */
  163599. {
  163600. emit_marker(cinfo, M_DRI);
  163601. emit_2bytes(cinfo, 4); /* fixed length */
  163602. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163603. }
  163604. LOCAL(void)
  163605. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163606. /* Emit a SOF marker */
  163607. {
  163608. int ci;
  163609. jpeg_component_info *compptr;
  163610. emit_marker(cinfo, code);
  163611. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163612. /* Make sure image isn't bigger than SOF field can handle */
  163613. if ((long) cinfo->image_height > 65535L ||
  163614. (long) cinfo->image_width > 65535L)
  163615. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163616. emit_byte(cinfo, cinfo->data_precision);
  163617. emit_2bytes(cinfo, (int) cinfo->image_height);
  163618. emit_2bytes(cinfo, (int) cinfo->image_width);
  163619. emit_byte(cinfo, cinfo->num_components);
  163620. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163621. ci++, compptr++) {
  163622. emit_byte(cinfo, compptr->component_id);
  163623. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163624. emit_byte(cinfo, compptr->quant_tbl_no);
  163625. }
  163626. }
  163627. LOCAL(void)
  163628. emit_sos (j_compress_ptr cinfo)
  163629. /* Emit a SOS marker */
  163630. {
  163631. int i, td, ta;
  163632. jpeg_component_info *compptr;
  163633. emit_marker(cinfo, M_SOS);
  163634. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163635. emit_byte(cinfo, cinfo->comps_in_scan);
  163636. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163637. compptr = cinfo->cur_comp_info[i];
  163638. emit_byte(cinfo, compptr->component_id);
  163639. td = compptr->dc_tbl_no;
  163640. ta = compptr->ac_tbl_no;
  163641. if (cinfo->progressive_mode) {
  163642. /* Progressive mode: only DC or only AC tables are used in one scan;
  163643. * furthermore, Huffman coding of DC refinement uses no table at all.
  163644. * We emit 0 for unused field(s); this is recommended by the P&M text
  163645. * but does not seem to be specified in the standard.
  163646. */
  163647. if (cinfo->Ss == 0) {
  163648. ta = 0; /* DC scan */
  163649. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163650. td = 0; /* no DC table either */
  163651. } else {
  163652. td = 0; /* AC scan */
  163653. }
  163654. }
  163655. emit_byte(cinfo, (td << 4) + ta);
  163656. }
  163657. emit_byte(cinfo, cinfo->Ss);
  163658. emit_byte(cinfo, cinfo->Se);
  163659. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163660. }
  163661. LOCAL(void)
  163662. emit_jfif_app0 (j_compress_ptr cinfo)
  163663. /* Emit a JFIF-compliant APP0 marker */
  163664. {
  163665. /*
  163666. * Length of APP0 block (2 bytes)
  163667. * Block ID (4 bytes - ASCII "JFIF")
  163668. * Zero byte (1 byte to terminate the ID string)
  163669. * Version Major, Minor (2 bytes - major first)
  163670. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163671. * Xdpu (2 bytes - dots per unit horizontal)
  163672. * Ydpu (2 bytes - dots per unit vertical)
  163673. * Thumbnail X size (1 byte)
  163674. * Thumbnail Y size (1 byte)
  163675. */
  163676. emit_marker(cinfo, M_APP0);
  163677. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163678. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163679. emit_byte(cinfo, 0x46);
  163680. emit_byte(cinfo, 0x49);
  163681. emit_byte(cinfo, 0x46);
  163682. emit_byte(cinfo, 0);
  163683. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163684. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163685. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163686. emit_2bytes(cinfo, (int) cinfo->X_density);
  163687. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163688. emit_byte(cinfo, 0); /* No thumbnail image */
  163689. emit_byte(cinfo, 0);
  163690. }
  163691. LOCAL(void)
  163692. emit_adobe_app14 (j_compress_ptr cinfo)
  163693. /* Emit an Adobe APP14 marker */
  163694. {
  163695. /*
  163696. * Length of APP14 block (2 bytes)
  163697. * Block ID (5 bytes - ASCII "Adobe")
  163698. * Version Number (2 bytes - currently 100)
  163699. * Flags0 (2 bytes - currently 0)
  163700. * Flags1 (2 bytes - currently 0)
  163701. * Color transform (1 byte)
  163702. *
  163703. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163704. * now in circulation seem to use Version = 100, so that's what we write.
  163705. *
  163706. * We write the color transform byte as 1 if the JPEG color space is
  163707. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163708. * whether the encoder performed a transformation, which is pretty useless.
  163709. */
  163710. emit_marker(cinfo, M_APP14);
  163711. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163712. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163713. emit_byte(cinfo, 0x64);
  163714. emit_byte(cinfo, 0x6F);
  163715. emit_byte(cinfo, 0x62);
  163716. emit_byte(cinfo, 0x65);
  163717. emit_2bytes(cinfo, 100); /* Version */
  163718. emit_2bytes(cinfo, 0); /* Flags0 */
  163719. emit_2bytes(cinfo, 0); /* Flags1 */
  163720. switch (cinfo->jpeg_color_space) {
  163721. case JCS_YCbCr:
  163722. emit_byte(cinfo, 1); /* Color transform = 1 */
  163723. break;
  163724. case JCS_YCCK:
  163725. emit_byte(cinfo, 2); /* Color transform = 2 */
  163726. break;
  163727. default:
  163728. emit_byte(cinfo, 0); /* Color transform = 0 */
  163729. break;
  163730. }
  163731. }
  163732. /*
  163733. * These routines allow writing an arbitrary marker with parameters.
  163734. * The only intended use is to emit COM or APPn markers after calling
  163735. * write_file_header and before calling write_frame_header.
  163736. * Other uses are not guaranteed to produce desirable results.
  163737. * Counting the parameter bytes properly is the caller's responsibility.
  163738. */
  163739. METHODDEF(void)
  163740. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163741. /* Emit an arbitrary marker header */
  163742. {
  163743. if (datalen > (unsigned int) 65533) /* safety check */
  163744. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163745. emit_marker(cinfo, (JPEG_MARKER) marker);
  163746. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163747. }
  163748. METHODDEF(void)
  163749. write_marker_byte (j_compress_ptr cinfo, int val)
  163750. /* Emit one byte of marker parameters following write_marker_header */
  163751. {
  163752. emit_byte(cinfo, val);
  163753. }
  163754. /*
  163755. * Write datastream header.
  163756. * This consists of an SOI and optional APPn markers.
  163757. * We recommend use of the JFIF marker, but not the Adobe marker,
  163758. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163759. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163760. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163761. * Note that an application can write additional header markers after
  163762. * jpeg_start_compress returns.
  163763. */
  163764. METHODDEF(void)
  163765. write_file_header (j_compress_ptr cinfo)
  163766. {
  163767. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163768. emit_marker(cinfo, M_SOI); /* first the SOI */
  163769. /* SOI is defined to reset restart interval to 0 */
  163770. marker->last_restart_interval = 0;
  163771. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163772. emit_jfif_app0(cinfo);
  163773. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163774. emit_adobe_app14(cinfo);
  163775. }
  163776. /*
  163777. * Write frame header.
  163778. * This consists of DQT and SOFn markers.
  163779. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163780. * This avoids compatibility problems with incorrect implementations that
  163781. * try to error-check the quant table numbers as soon as they see the SOF.
  163782. */
  163783. METHODDEF(void)
  163784. write_frame_header (j_compress_ptr cinfo)
  163785. {
  163786. int ci, prec;
  163787. boolean is_baseline;
  163788. jpeg_component_info *compptr;
  163789. /* Emit DQT for each quantization table.
  163790. * Note that emit_dqt() suppresses any duplicate tables.
  163791. */
  163792. prec = 0;
  163793. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163794. ci++, compptr++) {
  163795. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163796. }
  163797. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163798. /* Check for a non-baseline specification.
  163799. * Note we assume that Huffman table numbers won't be changed later.
  163800. */
  163801. if (cinfo->arith_code || cinfo->progressive_mode ||
  163802. cinfo->data_precision != 8) {
  163803. is_baseline = FALSE;
  163804. } else {
  163805. is_baseline = TRUE;
  163806. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163807. ci++, compptr++) {
  163808. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163809. is_baseline = FALSE;
  163810. }
  163811. if (prec && is_baseline) {
  163812. is_baseline = FALSE;
  163813. /* If it's baseline except for quantizer size, warn the user */
  163814. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163815. }
  163816. }
  163817. /* Emit the proper SOF marker */
  163818. if (cinfo->arith_code) {
  163819. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  163820. } else {
  163821. if (cinfo->progressive_mode)
  163822. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  163823. else if (is_baseline)
  163824. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  163825. else
  163826. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  163827. }
  163828. }
  163829. /*
  163830. * Write scan header.
  163831. * This consists of DHT or DAC markers, optional DRI, and SOS.
  163832. * Compressed data will be written following the SOS.
  163833. */
  163834. METHODDEF(void)
  163835. write_scan_header (j_compress_ptr cinfo)
  163836. {
  163837. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163838. int i;
  163839. jpeg_component_info *compptr;
  163840. if (cinfo->arith_code) {
  163841. /* Emit arith conditioning info. We may have some duplication
  163842. * if the file has multiple scans, but it's so small it's hardly
  163843. * worth worrying about.
  163844. */
  163845. emit_dac(cinfo);
  163846. } else {
  163847. /* Emit Huffman tables.
  163848. * Note that emit_dht() suppresses any duplicate tables.
  163849. */
  163850. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163851. compptr = cinfo->cur_comp_info[i];
  163852. if (cinfo->progressive_mode) {
  163853. /* Progressive mode: only DC or only AC tables are used in one scan */
  163854. if (cinfo->Ss == 0) {
  163855. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  163856. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163857. } else {
  163858. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163859. }
  163860. } else {
  163861. /* Sequential mode: need both DC and AC tables */
  163862. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163863. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163864. }
  163865. }
  163866. }
  163867. /* Emit DRI if required --- note that DRI value could change for each scan.
  163868. * We avoid wasting space with unnecessary DRIs, however.
  163869. */
  163870. if (cinfo->restart_interval != marker->last_restart_interval) {
  163871. emit_dri(cinfo);
  163872. marker->last_restart_interval = cinfo->restart_interval;
  163873. }
  163874. emit_sos(cinfo);
  163875. }
  163876. /*
  163877. * Write datastream trailer.
  163878. */
  163879. METHODDEF(void)
  163880. write_file_trailer (j_compress_ptr cinfo)
  163881. {
  163882. emit_marker(cinfo, M_EOI);
  163883. }
  163884. /*
  163885. * Write an abbreviated table-specification datastream.
  163886. * This consists of SOI, DQT and DHT tables, and EOI.
  163887. * Any table that is defined and not marked sent_table = TRUE will be
  163888. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  163889. */
  163890. METHODDEF(void)
  163891. write_tables_only (j_compress_ptr cinfo)
  163892. {
  163893. int i;
  163894. emit_marker(cinfo, M_SOI);
  163895. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163896. if (cinfo->quant_tbl_ptrs[i] != NULL)
  163897. (void) emit_dqt(cinfo, i);
  163898. }
  163899. if (! cinfo->arith_code) {
  163900. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163901. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  163902. emit_dht(cinfo, i, FALSE);
  163903. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  163904. emit_dht(cinfo, i, TRUE);
  163905. }
  163906. }
  163907. emit_marker(cinfo, M_EOI);
  163908. }
  163909. /*
  163910. * Initialize the marker writer module.
  163911. */
  163912. GLOBAL(void)
  163913. jinit_marker_writer (j_compress_ptr cinfo)
  163914. {
  163915. my_marker_ptr marker;
  163916. /* Create the subobject */
  163917. marker = (my_marker_ptr)
  163918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163919. SIZEOF(my_marker_writer));
  163920. cinfo->marker = (struct jpeg_marker_writer *) marker;
  163921. /* Initialize method pointers */
  163922. marker->pub.write_file_header = write_file_header;
  163923. marker->pub.write_frame_header = write_frame_header;
  163924. marker->pub.write_scan_header = write_scan_header;
  163925. marker->pub.write_file_trailer = write_file_trailer;
  163926. marker->pub.write_tables_only = write_tables_only;
  163927. marker->pub.write_marker_header = write_marker_header;
  163928. marker->pub.write_marker_byte = write_marker_byte;
  163929. /* Initialize private state */
  163930. marker->last_restart_interval = 0;
  163931. }
  163932. /*** End of inlined file: jcmarker.c ***/
  163933. /*** Start of inlined file: jcmaster.c ***/
  163934. #define JPEG_INTERNALS
  163935. /* Private state */
  163936. typedef enum {
  163937. main_pass, /* input data, also do first output step */
  163938. huff_opt_pass, /* Huffman code optimization pass */
  163939. output_pass /* data output pass */
  163940. } c_pass_type;
  163941. typedef struct {
  163942. struct jpeg_comp_master pub; /* public fields */
  163943. c_pass_type pass_type; /* the type of the current pass */
  163944. int pass_number; /* # of passes completed */
  163945. int total_passes; /* total # of passes needed */
  163946. int scan_number; /* current index in scan_info[] */
  163947. } my_comp_master;
  163948. typedef my_comp_master * my_master_ptr;
  163949. /*
  163950. * Support routines that do various essential calculations.
  163951. */
  163952. LOCAL(void)
  163953. initial_setup (j_compress_ptr cinfo)
  163954. /* Do computations that are needed before master selection phase */
  163955. {
  163956. int ci;
  163957. jpeg_component_info *compptr;
  163958. long samplesperrow;
  163959. JDIMENSION jd_samplesperrow;
  163960. /* Sanity check on image dimensions */
  163961. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  163962. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  163963. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  163964. /* Make sure image isn't bigger than I can handle */
  163965. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163966. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163967. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163968. /* Width of an input scanline must be representable as JDIMENSION. */
  163969. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  163970. jd_samplesperrow = (JDIMENSION) samplesperrow;
  163971. if ((long) jd_samplesperrow != samplesperrow)
  163972. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  163973. /* For now, precision must match compiled-in value... */
  163974. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163975. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163976. /* Check that number of components won't exceed internal array sizes */
  163977. if (cinfo->num_components > MAX_COMPONENTS)
  163978. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163979. MAX_COMPONENTS);
  163980. /* Compute maximum sampling factors; check factor validity */
  163981. cinfo->max_h_samp_factor = 1;
  163982. cinfo->max_v_samp_factor = 1;
  163983. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163984. ci++, compptr++) {
  163985. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163986. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163987. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163988. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163989. compptr->h_samp_factor);
  163990. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163991. compptr->v_samp_factor);
  163992. }
  163993. /* Compute dimensions of components */
  163994. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163995. ci++, compptr++) {
  163996. /* Fill in the correct component_index value; don't rely on application */
  163997. compptr->component_index = ci;
  163998. /* For compression, we never do DCT scaling. */
  163999. compptr->DCT_scaled_size = DCTSIZE;
  164000. /* Size in DCT blocks */
  164001. compptr->width_in_blocks = (JDIMENSION)
  164002. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164003. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164004. compptr->height_in_blocks = (JDIMENSION)
  164005. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164006. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164007. /* Size in samples */
  164008. compptr->downsampled_width = (JDIMENSION)
  164009. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164010. (long) cinfo->max_h_samp_factor);
  164011. compptr->downsampled_height = (JDIMENSION)
  164012. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164013. (long) cinfo->max_v_samp_factor);
  164014. /* Mark component needed (this flag isn't actually used for compression) */
  164015. compptr->component_needed = TRUE;
  164016. }
  164017. /* Compute number of fully interleaved MCU rows (number of times that
  164018. * main controller will call coefficient controller).
  164019. */
  164020. cinfo->total_iMCU_rows = (JDIMENSION)
  164021. jdiv_round_up((long) cinfo->image_height,
  164022. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164023. }
  164024. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164025. LOCAL(void)
  164026. validate_script (j_compress_ptr cinfo)
  164027. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164028. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164029. */
  164030. {
  164031. const jpeg_scan_info * scanptr;
  164032. int scanno, ncomps, ci, coefi, thisi;
  164033. int Ss, Se, Ah, Al;
  164034. boolean component_sent[MAX_COMPONENTS];
  164035. #ifdef C_PROGRESSIVE_SUPPORTED
  164036. int * last_bitpos_ptr;
  164037. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164038. /* -1 until that coefficient has been seen; then last Al for it */
  164039. #endif
  164040. if (cinfo->num_scans <= 0)
  164041. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164042. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164043. * for progressive JPEG, no scan can have this.
  164044. */
  164045. scanptr = cinfo->scan_info;
  164046. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164047. #ifdef C_PROGRESSIVE_SUPPORTED
  164048. cinfo->progressive_mode = TRUE;
  164049. last_bitpos_ptr = & last_bitpos[0][0];
  164050. for (ci = 0; ci < cinfo->num_components; ci++)
  164051. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164052. *last_bitpos_ptr++ = -1;
  164053. #else
  164054. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164055. #endif
  164056. } else {
  164057. cinfo->progressive_mode = FALSE;
  164058. for (ci = 0; ci < cinfo->num_components; ci++)
  164059. component_sent[ci] = FALSE;
  164060. }
  164061. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164062. /* Validate component indexes */
  164063. ncomps = scanptr->comps_in_scan;
  164064. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164065. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164066. for (ci = 0; ci < ncomps; ci++) {
  164067. thisi = scanptr->component_index[ci];
  164068. if (thisi < 0 || thisi >= cinfo->num_components)
  164069. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164070. /* Components must appear in SOF order within each scan */
  164071. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164072. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164073. }
  164074. /* Validate progression parameters */
  164075. Ss = scanptr->Ss;
  164076. Se = scanptr->Se;
  164077. Ah = scanptr->Ah;
  164078. Al = scanptr->Al;
  164079. if (cinfo->progressive_mode) {
  164080. #ifdef C_PROGRESSIVE_SUPPORTED
  164081. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164082. * seems wrong: the upper bound ought to depend on data precision.
  164083. * Perhaps they really meant 0..N+1 for N-bit precision.
  164084. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164085. * out-of-range reconstructed DC values during the first DC scan,
  164086. * which might cause problems for some decoders.
  164087. */
  164088. #if BITS_IN_JSAMPLE == 8
  164089. #define MAX_AH_AL 10
  164090. #else
  164091. #define MAX_AH_AL 13
  164092. #endif
  164093. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164094. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164095. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164096. if (Ss == 0) {
  164097. if (Se != 0) /* DC and AC together not OK */
  164098. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164099. } else {
  164100. if (ncomps != 1) /* AC scans must be for only one component */
  164101. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164102. }
  164103. for (ci = 0; ci < ncomps; ci++) {
  164104. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164105. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164106. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164107. for (coefi = Ss; coefi <= Se; coefi++) {
  164108. if (last_bitpos_ptr[coefi] < 0) {
  164109. /* first scan of this coefficient */
  164110. if (Ah != 0)
  164111. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164112. } else {
  164113. /* not first scan */
  164114. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164115. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164116. }
  164117. last_bitpos_ptr[coefi] = Al;
  164118. }
  164119. }
  164120. #endif
  164121. } else {
  164122. /* For sequential JPEG, all progression parameters must be these: */
  164123. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164124. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164125. /* Make sure components are not sent twice */
  164126. for (ci = 0; ci < ncomps; ci++) {
  164127. thisi = scanptr->component_index[ci];
  164128. if (component_sent[thisi])
  164129. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164130. component_sent[thisi] = TRUE;
  164131. }
  164132. }
  164133. }
  164134. /* Now verify that everything got sent. */
  164135. if (cinfo->progressive_mode) {
  164136. #ifdef C_PROGRESSIVE_SUPPORTED
  164137. /* For progressive mode, we only check that at least some DC data
  164138. * got sent for each component; the spec does not require that all bits
  164139. * of all coefficients be transmitted. Would it be wiser to enforce
  164140. * transmission of all coefficient bits??
  164141. */
  164142. for (ci = 0; ci < cinfo->num_components; ci++) {
  164143. if (last_bitpos[ci][0] < 0)
  164144. ERREXIT(cinfo, JERR_MISSING_DATA);
  164145. }
  164146. #endif
  164147. } else {
  164148. for (ci = 0; ci < cinfo->num_components; ci++) {
  164149. if (! component_sent[ci])
  164150. ERREXIT(cinfo, JERR_MISSING_DATA);
  164151. }
  164152. }
  164153. }
  164154. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164155. LOCAL(void)
  164156. select_scan_parameters (j_compress_ptr cinfo)
  164157. /* Set up the scan parameters for the current scan */
  164158. {
  164159. int ci;
  164160. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164161. if (cinfo->scan_info != NULL) {
  164162. /* Prepare for current scan --- the script is already validated */
  164163. my_master_ptr master = (my_master_ptr) cinfo->master;
  164164. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164165. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164166. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164167. cinfo->cur_comp_info[ci] =
  164168. &cinfo->comp_info[scanptr->component_index[ci]];
  164169. }
  164170. cinfo->Ss = scanptr->Ss;
  164171. cinfo->Se = scanptr->Se;
  164172. cinfo->Ah = scanptr->Ah;
  164173. cinfo->Al = scanptr->Al;
  164174. }
  164175. else
  164176. #endif
  164177. {
  164178. /* Prepare for single sequential-JPEG scan containing all components */
  164179. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164180. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164181. MAX_COMPS_IN_SCAN);
  164182. cinfo->comps_in_scan = cinfo->num_components;
  164183. for (ci = 0; ci < cinfo->num_components; ci++) {
  164184. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164185. }
  164186. cinfo->Ss = 0;
  164187. cinfo->Se = DCTSIZE2-1;
  164188. cinfo->Ah = 0;
  164189. cinfo->Al = 0;
  164190. }
  164191. }
  164192. LOCAL(void)
  164193. per_scan_setup (j_compress_ptr cinfo)
  164194. /* Do computations that are needed before processing a JPEG scan */
  164195. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164196. {
  164197. int ci, mcublks, tmp;
  164198. jpeg_component_info *compptr;
  164199. if (cinfo->comps_in_scan == 1) {
  164200. /* Noninterleaved (single-component) scan */
  164201. compptr = cinfo->cur_comp_info[0];
  164202. /* Overall image size in MCUs */
  164203. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164204. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164205. /* For noninterleaved scan, always one block per MCU */
  164206. compptr->MCU_width = 1;
  164207. compptr->MCU_height = 1;
  164208. compptr->MCU_blocks = 1;
  164209. compptr->MCU_sample_width = DCTSIZE;
  164210. compptr->last_col_width = 1;
  164211. /* For noninterleaved scans, it is convenient to define last_row_height
  164212. * as the number of block rows present in the last iMCU row.
  164213. */
  164214. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164215. if (tmp == 0) tmp = compptr->v_samp_factor;
  164216. compptr->last_row_height = tmp;
  164217. /* Prepare array describing MCU composition */
  164218. cinfo->blocks_in_MCU = 1;
  164219. cinfo->MCU_membership[0] = 0;
  164220. } else {
  164221. /* Interleaved (multi-component) scan */
  164222. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164223. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164224. MAX_COMPS_IN_SCAN);
  164225. /* Overall image size in MCUs */
  164226. cinfo->MCUs_per_row = (JDIMENSION)
  164227. jdiv_round_up((long) cinfo->image_width,
  164228. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164229. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164230. jdiv_round_up((long) cinfo->image_height,
  164231. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164232. cinfo->blocks_in_MCU = 0;
  164233. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164234. compptr = cinfo->cur_comp_info[ci];
  164235. /* Sampling factors give # of blocks of component in each MCU */
  164236. compptr->MCU_width = compptr->h_samp_factor;
  164237. compptr->MCU_height = compptr->v_samp_factor;
  164238. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164239. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164240. /* Figure number of non-dummy blocks in last MCU column & row */
  164241. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164242. if (tmp == 0) tmp = compptr->MCU_width;
  164243. compptr->last_col_width = tmp;
  164244. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164245. if (tmp == 0) tmp = compptr->MCU_height;
  164246. compptr->last_row_height = tmp;
  164247. /* Prepare array describing MCU composition */
  164248. mcublks = compptr->MCU_blocks;
  164249. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164250. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164251. while (mcublks-- > 0) {
  164252. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164253. }
  164254. }
  164255. }
  164256. /* Convert restart specified in rows to actual MCU count. */
  164257. /* Note that count must fit in 16 bits, so we provide limiting. */
  164258. if (cinfo->restart_in_rows > 0) {
  164259. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164260. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164261. }
  164262. }
  164263. /*
  164264. * Per-pass setup.
  164265. * This is called at the beginning of each pass. We determine which modules
  164266. * will be active during this pass and give them appropriate start_pass calls.
  164267. * We also set is_last_pass to indicate whether any more passes will be
  164268. * required.
  164269. */
  164270. METHODDEF(void)
  164271. prepare_for_pass (j_compress_ptr cinfo)
  164272. {
  164273. my_master_ptr master = (my_master_ptr) cinfo->master;
  164274. switch (master->pass_type) {
  164275. case main_pass:
  164276. /* Initial pass: will collect input data, and do either Huffman
  164277. * optimization or data output for the first scan.
  164278. */
  164279. select_scan_parameters(cinfo);
  164280. per_scan_setup(cinfo);
  164281. if (! cinfo->raw_data_in) {
  164282. (*cinfo->cconvert->start_pass) (cinfo);
  164283. (*cinfo->downsample->start_pass) (cinfo);
  164284. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164285. }
  164286. (*cinfo->fdct->start_pass) (cinfo);
  164287. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164288. (*cinfo->coef->start_pass) (cinfo,
  164289. (master->total_passes > 1 ?
  164290. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164291. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164292. if (cinfo->optimize_coding) {
  164293. /* No immediate data output; postpone writing frame/scan headers */
  164294. master->pub.call_pass_startup = FALSE;
  164295. } else {
  164296. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164297. master->pub.call_pass_startup = TRUE;
  164298. }
  164299. break;
  164300. #ifdef ENTROPY_OPT_SUPPORTED
  164301. case huff_opt_pass:
  164302. /* Do Huffman optimization for a scan after the first one. */
  164303. select_scan_parameters(cinfo);
  164304. per_scan_setup(cinfo);
  164305. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164306. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164307. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164308. master->pub.call_pass_startup = FALSE;
  164309. break;
  164310. }
  164311. /* Special case: Huffman DC refinement scans need no Huffman table
  164312. * and therefore we can skip the optimization pass for them.
  164313. */
  164314. master->pass_type = output_pass;
  164315. master->pass_number++;
  164316. /*FALLTHROUGH*/
  164317. #endif
  164318. case output_pass:
  164319. /* Do a data-output pass. */
  164320. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164321. if (! cinfo->optimize_coding) {
  164322. select_scan_parameters(cinfo);
  164323. per_scan_setup(cinfo);
  164324. }
  164325. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164326. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164327. /* We emit frame/scan headers now */
  164328. if (master->scan_number == 0)
  164329. (*cinfo->marker->write_frame_header) (cinfo);
  164330. (*cinfo->marker->write_scan_header) (cinfo);
  164331. master->pub.call_pass_startup = FALSE;
  164332. break;
  164333. default:
  164334. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164335. }
  164336. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164337. /* Set up progress monitor's pass info if present */
  164338. if (cinfo->progress != NULL) {
  164339. cinfo->progress->completed_passes = master->pass_number;
  164340. cinfo->progress->total_passes = master->total_passes;
  164341. }
  164342. }
  164343. /*
  164344. * Special start-of-pass hook.
  164345. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164346. * In single-pass processing, we need this hook because we don't want to
  164347. * write frame/scan headers during jpeg_start_compress; we want to let the
  164348. * application write COM markers etc. between jpeg_start_compress and the
  164349. * jpeg_write_scanlines loop.
  164350. * In multi-pass processing, this routine is not used.
  164351. */
  164352. METHODDEF(void)
  164353. pass_startup (j_compress_ptr cinfo)
  164354. {
  164355. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164356. (*cinfo->marker->write_frame_header) (cinfo);
  164357. (*cinfo->marker->write_scan_header) (cinfo);
  164358. }
  164359. /*
  164360. * Finish up at end of pass.
  164361. */
  164362. METHODDEF(void)
  164363. finish_pass_master (j_compress_ptr cinfo)
  164364. {
  164365. my_master_ptr master = (my_master_ptr) cinfo->master;
  164366. /* The entropy coder always needs an end-of-pass call,
  164367. * either to analyze statistics or to flush its output buffer.
  164368. */
  164369. (*cinfo->entropy->finish_pass) (cinfo);
  164370. /* Update state for next pass */
  164371. switch (master->pass_type) {
  164372. case main_pass:
  164373. /* next pass is either output of scan 0 (after optimization)
  164374. * or output of scan 1 (if no optimization).
  164375. */
  164376. master->pass_type = output_pass;
  164377. if (! cinfo->optimize_coding)
  164378. master->scan_number++;
  164379. break;
  164380. case huff_opt_pass:
  164381. /* next pass is always output of current scan */
  164382. master->pass_type = output_pass;
  164383. break;
  164384. case output_pass:
  164385. /* next pass is either optimization or output of next scan */
  164386. if (cinfo->optimize_coding)
  164387. master->pass_type = huff_opt_pass;
  164388. master->scan_number++;
  164389. break;
  164390. }
  164391. master->pass_number++;
  164392. }
  164393. /*
  164394. * Initialize master compression control.
  164395. */
  164396. GLOBAL(void)
  164397. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164398. {
  164399. my_master_ptr master;
  164400. master = (my_master_ptr)
  164401. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164402. SIZEOF(my_comp_master));
  164403. cinfo->master = (struct jpeg_comp_master *) master;
  164404. master->pub.prepare_for_pass = prepare_for_pass;
  164405. master->pub.pass_startup = pass_startup;
  164406. master->pub.finish_pass = finish_pass_master;
  164407. master->pub.is_last_pass = FALSE;
  164408. /* Validate parameters, determine derived values */
  164409. initial_setup(cinfo);
  164410. if (cinfo->scan_info != NULL) {
  164411. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164412. validate_script(cinfo);
  164413. #else
  164414. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164415. #endif
  164416. } else {
  164417. cinfo->progressive_mode = FALSE;
  164418. cinfo->num_scans = 1;
  164419. }
  164420. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164421. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164422. /* Initialize my private state */
  164423. if (transcode_only) {
  164424. /* no main pass in transcoding */
  164425. if (cinfo->optimize_coding)
  164426. master->pass_type = huff_opt_pass;
  164427. else
  164428. master->pass_type = output_pass;
  164429. } else {
  164430. /* for normal compression, first pass is always this type: */
  164431. master->pass_type = main_pass;
  164432. }
  164433. master->scan_number = 0;
  164434. master->pass_number = 0;
  164435. if (cinfo->optimize_coding)
  164436. master->total_passes = cinfo->num_scans * 2;
  164437. else
  164438. master->total_passes = cinfo->num_scans;
  164439. }
  164440. /*** End of inlined file: jcmaster.c ***/
  164441. /*** Start of inlined file: jcomapi.c ***/
  164442. #define JPEG_INTERNALS
  164443. /*
  164444. * Abort processing of a JPEG compression or decompression operation,
  164445. * but don't destroy the object itself.
  164446. *
  164447. * For this, we merely clean up all the nonpermanent memory pools.
  164448. * Note that temp files (virtual arrays) are not allowed to belong to
  164449. * the permanent pool, so we will be able to close all temp files here.
  164450. * Closing a data source or destination, if necessary, is the application's
  164451. * responsibility.
  164452. */
  164453. GLOBAL(void)
  164454. jpeg_abort (j_common_ptr cinfo)
  164455. {
  164456. int pool;
  164457. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164458. if (cinfo->mem == NULL)
  164459. return;
  164460. /* Releasing pools in reverse order might help avoid fragmentation
  164461. * with some (brain-damaged) malloc libraries.
  164462. */
  164463. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164464. (*cinfo->mem->free_pool) (cinfo, pool);
  164465. }
  164466. /* Reset overall state for possible reuse of object */
  164467. if (cinfo->is_decompressor) {
  164468. cinfo->global_state = DSTATE_START;
  164469. /* Try to keep application from accessing now-deleted marker list.
  164470. * A bit kludgy to do it here, but this is the most central place.
  164471. */
  164472. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164473. } else {
  164474. cinfo->global_state = CSTATE_START;
  164475. }
  164476. }
  164477. /*
  164478. * Destruction of a JPEG object.
  164479. *
  164480. * Everything gets deallocated except the master jpeg_compress_struct itself
  164481. * and the error manager struct. Both of these are supplied by the application
  164482. * and must be freed, if necessary, by the application. (Often they are on
  164483. * the stack and so don't need to be freed anyway.)
  164484. * Closing a data source or destination, if necessary, is the application's
  164485. * responsibility.
  164486. */
  164487. GLOBAL(void)
  164488. jpeg_destroy (j_common_ptr cinfo)
  164489. {
  164490. /* We need only tell the memory manager to release everything. */
  164491. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164492. if (cinfo->mem != NULL)
  164493. (*cinfo->mem->self_destruct) (cinfo);
  164494. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164495. cinfo->global_state = 0; /* mark it destroyed */
  164496. }
  164497. /*
  164498. * Convenience routines for allocating quantization and Huffman tables.
  164499. * (Would jutils.c be a more reasonable place to put these?)
  164500. */
  164501. GLOBAL(JQUANT_TBL *)
  164502. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164503. {
  164504. JQUANT_TBL *tbl;
  164505. tbl = (JQUANT_TBL *)
  164506. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164507. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164508. return tbl;
  164509. }
  164510. GLOBAL(JHUFF_TBL *)
  164511. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164512. {
  164513. JHUFF_TBL *tbl;
  164514. tbl = (JHUFF_TBL *)
  164515. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164516. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164517. return tbl;
  164518. }
  164519. /*** End of inlined file: jcomapi.c ***/
  164520. /*** Start of inlined file: jcparam.c ***/
  164521. #define JPEG_INTERNALS
  164522. /*
  164523. * Quantization table setup routines
  164524. */
  164525. GLOBAL(void)
  164526. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164527. const unsigned int *basic_table,
  164528. int scale_factor, boolean force_baseline)
  164529. /* Define a quantization table equal to the basic_table times
  164530. * a scale factor (given as a percentage).
  164531. * If force_baseline is TRUE, the computed quantization table entries
  164532. * are limited to 1..255 for JPEG baseline compatibility.
  164533. */
  164534. {
  164535. JQUANT_TBL ** qtblptr;
  164536. int i;
  164537. long temp;
  164538. /* Safety check to ensure start_compress not called yet. */
  164539. if (cinfo->global_state != CSTATE_START)
  164540. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164541. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164542. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164543. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164544. if (*qtblptr == NULL)
  164545. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164546. for (i = 0; i < DCTSIZE2; i++) {
  164547. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164548. /* limit the values to the valid range */
  164549. if (temp <= 0L) temp = 1L;
  164550. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164551. if (force_baseline && temp > 255L)
  164552. temp = 255L; /* limit to baseline range if requested */
  164553. (*qtblptr)->quantval[i] = (UINT16) temp;
  164554. }
  164555. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164556. (*qtblptr)->sent_table = FALSE;
  164557. }
  164558. GLOBAL(void)
  164559. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164560. boolean force_baseline)
  164561. /* Set or change the 'quality' (quantization) setting, using default tables
  164562. * and a straight percentage-scaling quality scale. In most cases it's better
  164563. * to use jpeg_set_quality (below); this entry point is provided for
  164564. * applications that insist on a linear percentage scaling.
  164565. */
  164566. {
  164567. /* These are the sample quantization tables given in JPEG spec section K.1.
  164568. * The spec says that the values given produce "good" quality, and
  164569. * when divided by 2, "very good" quality.
  164570. */
  164571. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164572. 16, 11, 10, 16, 24, 40, 51, 61,
  164573. 12, 12, 14, 19, 26, 58, 60, 55,
  164574. 14, 13, 16, 24, 40, 57, 69, 56,
  164575. 14, 17, 22, 29, 51, 87, 80, 62,
  164576. 18, 22, 37, 56, 68, 109, 103, 77,
  164577. 24, 35, 55, 64, 81, 104, 113, 92,
  164578. 49, 64, 78, 87, 103, 121, 120, 101,
  164579. 72, 92, 95, 98, 112, 100, 103, 99
  164580. };
  164581. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164582. 17, 18, 24, 47, 99, 99, 99, 99,
  164583. 18, 21, 26, 66, 99, 99, 99, 99,
  164584. 24, 26, 56, 99, 99, 99, 99, 99,
  164585. 47, 66, 99, 99, 99, 99, 99, 99,
  164586. 99, 99, 99, 99, 99, 99, 99, 99,
  164587. 99, 99, 99, 99, 99, 99, 99, 99,
  164588. 99, 99, 99, 99, 99, 99, 99, 99,
  164589. 99, 99, 99, 99, 99, 99, 99, 99
  164590. };
  164591. /* Set up two quantization tables using the specified scaling */
  164592. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164593. scale_factor, force_baseline);
  164594. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164595. scale_factor, force_baseline);
  164596. }
  164597. GLOBAL(int)
  164598. jpeg_quality_scaling (int quality)
  164599. /* Convert a user-specified quality rating to a percentage scaling factor
  164600. * for an underlying quantization table, using our recommended scaling curve.
  164601. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164602. */
  164603. {
  164604. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164605. if (quality <= 0) quality = 1;
  164606. if (quality > 100) quality = 100;
  164607. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164608. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164609. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164610. * to make all the table entries 1 (hence, minimum quantization loss).
  164611. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164612. */
  164613. if (quality < 50)
  164614. quality = 5000 / quality;
  164615. else
  164616. quality = 200 - quality*2;
  164617. return quality;
  164618. }
  164619. GLOBAL(void)
  164620. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164621. /* Set or change the 'quality' (quantization) setting, using default tables.
  164622. * This is the standard quality-adjusting entry point for typical user
  164623. * interfaces; only those who want detailed control over quantization tables
  164624. * would use the preceding three routines directly.
  164625. */
  164626. {
  164627. /* Convert user 0-100 rating to percentage scaling */
  164628. quality = jpeg_quality_scaling(quality);
  164629. /* Set up standard quality tables */
  164630. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164631. }
  164632. /*
  164633. * Huffman table setup routines
  164634. */
  164635. LOCAL(void)
  164636. add_huff_table (j_compress_ptr cinfo,
  164637. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164638. /* Define a Huffman table */
  164639. {
  164640. int nsymbols, len;
  164641. if (*htblptr == NULL)
  164642. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164643. /* Copy the number-of-symbols-of-each-code-length counts */
  164644. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164645. /* Validate the counts. We do this here mainly so we can copy the right
  164646. * number of symbols from the val[] array, without risking marching off
  164647. * the end of memory. jchuff.c will do a more thorough test later.
  164648. */
  164649. nsymbols = 0;
  164650. for (len = 1; len <= 16; len++)
  164651. nsymbols += bits[len];
  164652. if (nsymbols < 1 || nsymbols > 256)
  164653. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164654. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164655. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164656. (*htblptr)->sent_table = FALSE;
  164657. }
  164658. LOCAL(void)
  164659. std_huff_tables (j_compress_ptr cinfo)
  164660. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164661. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164662. {
  164663. static const UINT8 bits_dc_luminance[17] =
  164664. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164665. static const UINT8 val_dc_luminance[] =
  164666. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164667. static const UINT8 bits_dc_chrominance[17] =
  164668. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164669. static const UINT8 val_dc_chrominance[] =
  164670. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164671. static const UINT8 bits_ac_luminance[17] =
  164672. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164673. static const UINT8 val_ac_luminance[] =
  164674. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164675. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164676. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164677. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164678. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164679. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164680. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164681. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164682. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164683. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164684. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164685. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164686. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164687. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164688. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164689. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164690. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164691. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164692. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164693. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164694. 0xf9, 0xfa };
  164695. static const UINT8 bits_ac_chrominance[17] =
  164696. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164697. static const UINT8 val_ac_chrominance[] =
  164698. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164699. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164700. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164701. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164702. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164703. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164704. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164705. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164706. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164707. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164708. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164709. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164710. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164711. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164712. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164713. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164714. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164715. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164716. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164717. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164718. 0xf9, 0xfa };
  164719. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164720. bits_dc_luminance, val_dc_luminance);
  164721. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164722. bits_ac_luminance, val_ac_luminance);
  164723. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164724. bits_dc_chrominance, val_dc_chrominance);
  164725. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164726. bits_ac_chrominance, val_ac_chrominance);
  164727. }
  164728. /*
  164729. * Default parameter setup for compression.
  164730. *
  164731. * Applications that don't choose to use this routine must do their
  164732. * own setup of all these parameters. Alternately, you can call this
  164733. * to establish defaults and then alter parameters selectively. This
  164734. * is the recommended approach since, if we add any new parameters,
  164735. * your code will still work (they'll be set to reasonable defaults).
  164736. */
  164737. GLOBAL(void)
  164738. jpeg_set_defaults (j_compress_ptr cinfo)
  164739. {
  164740. int i;
  164741. /* Safety check to ensure start_compress not called yet. */
  164742. if (cinfo->global_state != CSTATE_START)
  164743. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164744. /* Allocate comp_info array large enough for maximum component count.
  164745. * Array is made permanent in case application wants to compress
  164746. * multiple images at same param settings.
  164747. */
  164748. if (cinfo->comp_info == NULL)
  164749. cinfo->comp_info = (jpeg_component_info *)
  164750. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164751. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164752. /* Initialize everything not dependent on the color space */
  164753. cinfo->data_precision = BITS_IN_JSAMPLE;
  164754. /* Set up two quantization tables using default quality of 75 */
  164755. jpeg_set_quality(cinfo, 75, TRUE);
  164756. /* Set up two Huffman tables */
  164757. std_huff_tables(cinfo);
  164758. /* Initialize default arithmetic coding conditioning */
  164759. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164760. cinfo->arith_dc_L[i] = 0;
  164761. cinfo->arith_dc_U[i] = 1;
  164762. cinfo->arith_ac_K[i] = 5;
  164763. }
  164764. /* Default is no multiple-scan output */
  164765. cinfo->scan_info = NULL;
  164766. cinfo->num_scans = 0;
  164767. /* Expect normal source image, not raw downsampled data */
  164768. cinfo->raw_data_in = FALSE;
  164769. /* Use Huffman coding, not arithmetic coding, by default */
  164770. cinfo->arith_code = FALSE;
  164771. /* By default, don't do extra passes to optimize entropy coding */
  164772. cinfo->optimize_coding = FALSE;
  164773. /* The standard Huffman tables are only valid for 8-bit data precision.
  164774. * If the precision is higher, force optimization on so that usable
  164775. * tables will be computed. This test can be removed if default tables
  164776. * are supplied that are valid for the desired precision.
  164777. */
  164778. if (cinfo->data_precision > 8)
  164779. cinfo->optimize_coding = TRUE;
  164780. /* By default, use the simpler non-cosited sampling alignment */
  164781. cinfo->CCIR601_sampling = FALSE;
  164782. /* No input smoothing */
  164783. cinfo->smoothing_factor = 0;
  164784. /* DCT algorithm preference */
  164785. cinfo->dct_method = JDCT_DEFAULT;
  164786. /* No restart markers */
  164787. cinfo->restart_interval = 0;
  164788. cinfo->restart_in_rows = 0;
  164789. /* Fill in default JFIF marker parameters. Note that whether the marker
  164790. * will actually be written is determined by jpeg_set_colorspace.
  164791. *
  164792. * By default, the library emits JFIF version code 1.01.
  164793. * An application that wants to emit JFIF 1.02 extension markers should set
  164794. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164795. * to 1.02, but there may still be some decoders in use that will complain
  164796. * about that; saying 1.01 should minimize compatibility problems.
  164797. */
  164798. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164799. cinfo->JFIF_minor_version = 1;
  164800. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164801. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164802. cinfo->Y_density = 1;
  164803. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164804. jpeg_default_colorspace(cinfo);
  164805. }
  164806. /*
  164807. * Select an appropriate JPEG colorspace for in_color_space.
  164808. */
  164809. GLOBAL(void)
  164810. jpeg_default_colorspace (j_compress_ptr cinfo)
  164811. {
  164812. switch (cinfo->in_color_space) {
  164813. case JCS_GRAYSCALE:
  164814. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164815. break;
  164816. case JCS_RGB:
  164817. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164818. break;
  164819. case JCS_YCbCr:
  164820. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164821. break;
  164822. case JCS_CMYK:
  164823. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  164824. break;
  164825. case JCS_YCCK:
  164826. jpeg_set_colorspace(cinfo, JCS_YCCK);
  164827. break;
  164828. case JCS_UNKNOWN:
  164829. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  164830. break;
  164831. default:
  164832. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  164833. }
  164834. }
  164835. /*
  164836. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  164837. */
  164838. GLOBAL(void)
  164839. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  164840. {
  164841. jpeg_component_info * compptr;
  164842. int ci;
  164843. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  164844. (compptr = &cinfo->comp_info[index], \
  164845. compptr->component_id = (id), \
  164846. compptr->h_samp_factor = (hsamp), \
  164847. compptr->v_samp_factor = (vsamp), \
  164848. compptr->quant_tbl_no = (quant), \
  164849. compptr->dc_tbl_no = (dctbl), \
  164850. compptr->ac_tbl_no = (actbl) )
  164851. /* Safety check to ensure start_compress not called yet. */
  164852. if (cinfo->global_state != CSTATE_START)
  164853. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164854. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  164855. * tables 1 for chrominance components.
  164856. */
  164857. cinfo->jpeg_color_space = colorspace;
  164858. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  164859. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  164860. switch (colorspace) {
  164861. case JCS_GRAYSCALE:
  164862. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164863. cinfo->num_components = 1;
  164864. /* JFIF specifies component ID 1 */
  164865. SET_COMP(0, 1, 1,1, 0, 0,0);
  164866. break;
  164867. case JCS_RGB:
  164868. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  164869. cinfo->num_components = 3;
  164870. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  164871. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  164872. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  164873. break;
  164874. case JCS_YCbCr:
  164875. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164876. cinfo->num_components = 3;
  164877. /* JFIF specifies component IDs 1,2,3 */
  164878. /* We default to 2x2 subsamples of chrominance */
  164879. SET_COMP(0, 1, 2,2, 0, 0,0);
  164880. SET_COMP(1, 2, 1,1, 1, 1,1);
  164881. SET_COMP(2, 3, 1,1, 1, 1,1);
  164882. break;
  164883. case JCS_CMYK:
  164884. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  164885. cinfo->num_components = 4;
  164886. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  164887. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  164888. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  164889. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  164890. break;
  164891. case JCS_YCCK:
  164892. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  164893. cinfo->num_components = 4;
  164894. SET_COMP(0, 1, 2,2, 0, 0,0);
  164895. SET_COMP(1, 2, 1,1, 1, 1,1);
  164896. SET_COMP(2, 3, 1,1, 1, 1,1);
  164897. SET_COMP(3, 4, 2,2, 0, 0,0);
  164898. break;
  164899. case JCS_UNKNOWN:
  164900. cinfo->num_components = cinfo->input_components;
  164901. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  164902. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164903. MAX_COMPONENTS);
  164904. for (ci = 0; ci < cinfo->num_components; ci++) {
  164905. SET_COMP(ci, ci, 1,1, 0, 0,0);
  164906. }
  164907. break;
  164908. default:
  164909. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164910. }
  164911. }
  164912. #ifdef C_PROGRESSIVE_SUPPORTED
  164913. LOCAL(jpeg_scan_info *)
  164914. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  164915. int Ss, int Se, int Ah, int Al)
  164916. /* Support routine: generate one scan for specified component */
  164917. {
  164918. scanptr->comps_in_scan = 1;
  164919. scanptr->component_index[0] = ci;
  164920. scanptr->Ss = Ss;
  164921. scanptr->Se = Se;
  164922. scanptr->Ah = Ah;
  164923. scanptr->Al = Al;
  164924. scanptr++;
  164925. return scanptr;
  164926. }
  164927. LOCAL(jpeg_scan_info *)
  164928. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  164929. int Ss, int Se, int Ah, int Al)
  164930. /* Support routine: generate one scan for each component */
  164931. {
  164932. int ci;
  164933. for (ci = 0; ci < ncomps; ci++) {
  164934. scanptr->comps_in_scan = 1;
  164935. scanptr->component_index[0] = ci;
  164936. scanptr->Ss = Ss;
  164937. scanptr->Se = Se;
  164938. scanptr->Ah = Ah;
  164939. scanptr->Al = Al;
  164940. scanptr++;
  164941. }
  164942. return scanptr;
  164943. }
  164944. LOCAL(jpeg_scan_info *)
  164945. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  164946. /* Support routine: generate interleaved DC scan if possible, else N scans */
  164947. {
  164948. int ci;
  164949. if (ncomps <= MAX_COMPS_IN_SCAN) {
  164950. /* Single interleaved DC scan */
  164951. scanptr->comps_in_scan = ncomps;
  164952. for (ci = 0; ci < ncomps; ci++)
  164953. scanptr->component_index[ci] = ci;
  164954. scanptr->Ss = scanptr->Se = 0;
  164955. scanptr->Ah = Ah;
  164956. scanptr->Al = Al;
  164957. scanptr++;
  164958. } else {
  164959. /* Noninterleaved DC scan for each component */
  164960. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  164961. }
  164962. return scanptr;
  164963. }
  164964. /*
  164965. * Create a recommended progressive-JPEG script.
  164966. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  164967. */
  164968. GLOBAL(void)
  164969. jpeg_simple_progression (j_compress_ptr cinfo)
  164970. {
  164971. int ncomps = cinfo->num_components;
  164972. int nscans;
  164973. jpeg_scan_info * scanptr;
  164974. /* Safety check to ensure start_compress not called yet. */
  164975. if (cinfo->global_state != CSTATE_START)
  164976. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164977. /* Figure space needed for script. Calculation must match code below! */
  164978. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164979. /* Custom script for YCbCr color images. */
  164980. nscans = 10;
  164981. } else {
  164982. /* All-purpose script for other color spaces. */
  164983. if (ncomps > MAX_COMPS_IN_SCAN)
  164984. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  164985. else
  164986. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  164987. }
  164988. /* Allocate space for script.
  164989. * We need to put it in the permanent pool in case the application performs
  164990. * multiple compressions without changing the settings. To avoid a memory
  164991. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  164992. * object, we try to re-use previously allocated space, and we allocate
  164993. * enough space to handle YCbCr even if initially asked for grayscale.
  164994. */
  164995. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  164996. cinfo->script_space_size = MAX(nscans, 10);
  164997. cinfo->script_space = (jpeg_scan_info *)
  164998. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164999. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165000. }
  165001. scanptr = cinfo->script_space;
  165002. cinfo->scan_info = scanptr;
  165003. cinfo->num_scans = nscans;
  165004. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165005. /* Custom script for YCbCr color images. */
  165006. /* Initial DC scan */
  165007. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165008. /* Initial AC scan: get some luma data out in a hurry */
  165009. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165010. /* Chroma data is too small to be worth expending many scans on */
  165011. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165012. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165013. /* Complete spectral selection for luma AC */
  165014. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165015. /* Refine next bit of luma AC */
  165016. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165017. /* Finish DC successive approximation */
  165018. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165019. /* Finish AC successive approximation */
  165020. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165021. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165022. /* Luma bottom bit comes last since it's usually largest scan */
  165023. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165024. } else {
  165025. /* All-purpose script for other color spaces. */
  165026. /* Successive approximation first pass */
  165027. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165028. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165029. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165030. /* Successive approximation second pass */
  165031. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165032. /* Successive approximation final pass */
  165033. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165034. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165035. }
  165036. }
  165037. #endif /* C_PROGRESSIVE_SUPPORTED */
  165038. /*** End of inlined file: jcparam.c ***/
  165039. /*** Start of inlined file: jcphuff.c ***/
  165040. #define JPEG_INTERNALS
  165041. #ifdef C_PROGRESSIVE_SUPPORTED
  165042. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165043. typedef struct {
  165044. struct jpeg_entropy_encoder pub; /* public fields */
  165045. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165046. boolean gather_statistics;
  165047. /* Bit-level coding status.
  165048. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165049. */
  165050. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165051. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165052. INT32 put_buffer; /* current bit-accumulation buffer */
  165053. int put_bits; /* # of bits now in it */
  165054. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165055. /* Coding status for DC components */
  165056. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165057. /* Coding status for AC components */
  165058. int ac_tbl_no; /* the table number of the single component */
  165059. unsigned int EOBRUN; /* run length of EOBs */
  165060. unsigned int BE; /* # of buffered correction bits before MCU */
  165061. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165062. /* packing correction bits tightly would save some space but cost time... */
  165063. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165064. int next_restart_num; /* next restart number to write (0-7) */
  165065. /* Pointers to derived tables (these workspaces have image lifespan).
  165066. * Since any one scan codes only DC or only AC, we only need one set
  165067. * of tables, not one for DC and one for AC.
  165068. */
  165069. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165070. /* Statistics tables for optimization; again, one set is enough */
  165071. long * count_ptrs[NUM_HUFF_TBLS];
  165072. } phuff_entropy_encoder;
  165073. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165074. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165075. * buffer can hold. Larger sizes may slightly improve compression, but
  165076. * 1000 is already well into the realm of overkill.
  165077. * The minimum safe size is 64 bits.
  165078. */
  165079. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165080. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165081. * We assume that int right shift is unsigned if INT32 right shift is,
  165082. * which should be safe.
  165083. */
  165084. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165085. #define ISHIFT_TEMPS int ishift_temp;
  165086. #define IRIGHT_SHIFT(x,shft) \
  165087. ((ishift_temp = (x)) < 0 ? \
  165088. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165089. (ishift_temp >> (shft)))
  165090. #else
  165091. #define ISHIFT_TEMPS
  165092. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165093. #endif
  165094. /* Forward declarations */
  165095. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165096. JBLOCKROW *MCU_data));
  165097. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165098. JBLOCKROW *MCU_data));
  165099. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165100. JBLOCKROW *MCU_data));
  165101. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165102. JBLOCKROW *MCU_data));
  165103. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165104. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165105. /*
  165106. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165107. */
  165108. METHODDEF(void)
  165109. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165110. {
  165111. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165112. boolean is_DC_band;
  165113. int ci, tbl;
  165114. jpeg_component_info * compptr;
  165115. entropy->cinfo = cinfo;
  165116. entropy->gather_statistics = gather_statistics;
  165117. is_DC_band = (cinfo->Ss == 0);
  165118. /* We assume jcmaster.c already validated the scan parameters. */
  165119. /* Select execution routines */
  165120. if (cinfo->Ah == 0) {
  165121. if (is_DC_band)
  165122. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165123. else
  165124. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165125. } else {
  165126. if (is_DC_band)
  165127. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165128. else {
  165129. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165130. /* AC refinement needs a correction bit buffer */
  165131. if (entropy->bit_buffer == NULL)
  165132. entropy->bit_buffer = (char *)
  165133. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165134. MAX_CORR_BITS * SIZEOF(char));
  165135. }
  165136. }
  165137. if (gather_statistics)
  165138. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165139. else
  165140. entropy->pub.finish_pass = finish_pass_phuff;
  165141. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165142. * for AC coefficients.
  165143. */
  165144. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165145. compptr = cinfo->cur_comp_info[ci];
  165146. /* Initialize DC predictions to 0 */
  165147. entropy->last_dc_val[ci] = 0;
  165148. /* Get table index */
  165149. if (is_DC_band) {
  165150. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165151. continue;
  165152. tbl = compptr->dc_tbl_no;
  165153. } else {
  165154. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165155. }
  165156. if (gather_statistics) {
  165157. /* Check for invalid table index */
  165158. /* (make_c_derived_tbl does this in the other path) */
  165159. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165160. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165161. /* Allocate and zero the statistics tables */
  165162. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165163. if (entropy->count_ptrs[tbl] == NULL)
  165164. entropy->count_ptrs[tbl] = (long *)
  165165. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165166. 257 * SIZEOF(long));
  165167. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165168. } else {
  165169. /* Compute derived values for Huffman table */
  165170. /* We may do this more than once for a table, but it's not expensive */
  165171. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165172. & entropy->derived_tbls[tbl]);
  165173. }
  165174. }
  165175. /* Initialize AC stuff */
  165176. entropy->EOBRUN = 0;
  165177. entropy->BE = 0;
  165178. /* Initialize bit buffer to empty */
  165179. entropy->put_buffer = 0;
  165180. entropy->put_bits = 0;
  165181. /* Initialize restart stuff */
  165182. entropy->restarts_to_go = cinfo->restart_interval;
  165183. entropy->next_restart_num = 0;
  165184. }
  165185. /* Outputting bytes to the file.
  165186. * NB: these must be called only when actually outputting,
  165187. * that is, entropy->gather_statistics == FALSE.
  165188. */
  165189. /* Emit a byte */
  165190. #define emit_byte(entropy,val) \
  165191. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165192. if (--(entropy)->free_in_buffer == 0) \
  165193. dump_buffer_p(entropy); }
  165194. LOCAL(void)
  165195. dump_buffer_p (phuff_entropy_ptr entropy)
  165196. /* Empty the output buffer; we do not support suspension in this module. */
  165197. {
  165198. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165199. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165200. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165201. /* After a successful buffer dump, must reset buffer pointers */
  165202. entropy->next_output_byte = dest->next_output_byte;
  165203. entropy->free_in_buffer = dest->free_in_buffer;
  165204. }
  165205. /* Outputting bits to the file */
  165206. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165207. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165208. * in one call, and we never retain more than 7 bits in put_buffer
  165209. * between calls, so 24 bits are sufficient.
  165210. */
  165211. INLINE
  165212. LOCAL(void)
  165213. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165214. /* Emit some bits, unless we are in gather mode */
  165215. {
  165216. /* This routine is heavily used, so it's worth coding tightly. */
  165217. register INT32 put_buffer = (INT32) code;
  165218. register int put_bits = entropy->put_bits;
  165219. /* if size is 0, caller used an invalid Huffman table entry */
  165220. if (size == 0)
  165221. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165222. if (entropy->gather_statistics)
  165223. return; /* do nothing if we're only getting stats */
  165224. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165225. put_bits += size; /* new number of bits in buffer */
  165226. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165227. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165228. while (put_bits >= 8) {
  165229. int c = (int) ((put_buffer >> 16) & 0xFF);
  165230. emit_byte(entropy, c);
  165231. if (c == 0xFF) { /* need to stuff a zero byte? */
  165232. emit_byte(entropy, 0);
  165233. }
  165234. put_buffer <<= 8;
  165235. put_bits -= 8;
  165236. }
  165237. entropy->put_buffer = put_buffer; /* update variables */
  165238. entropy->put_bits = put_bits;
  165239. }
  165240. LOCAL(void)
  165241. flush_bits_p (phuff_entropy_ptr entropy)
  165242. {
  165243. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165244. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165245. entropy->put_bits = 0;
  165246. }
  165247. /*
  165248. * Emit (or just count) a Huffman symbol.
  165249. */
  165250. INLINE
  165251. LOCAL(void)
  165252. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165253. {
  165254. if (entropy->gather_statistics)
  165255. entropy->count_ptrs[tbl_no][symbol]++;
  165256. else {
  165257. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165258. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165259. }
  165260. }
  165261. /*
  165262. * Emit bits from a correction bit buffer.
  165263. */
  165264. LOCAL(void)
  165265. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165266. unsigned int nbits)
  165267. {
  165268. if (entropy->gather_statistics)
  165269. return; /* no real work */
  165270. while (nbits > 0) {
  165271. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165272. bufstart++;
  165273. nbits--;
  165274. }
  165275. }
  165276. /*
  165277. * Emit any pending EOBRUN symbol.
  165278. */
  165279. LOCAL(void)
  165280. emit_eobrun (phuff_entropy_ptr entropy)
  165281. {
  165282. register int temp, nbits;
  165283. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165284. temp = entropy->EOBRUN;
  165285. nbits = 0;
  165286. while ((temp >>= 1))
  165287. nbits++;
  165288. /* safety check: shouldn't happen given limited correction-bit buffer */
  165289. if (nbits > 14)
  165290. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165291. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165292. if (nbits)
  165293. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165294. entropy->EOBRUN = 0;
  165295. /* Emit any buffered correction bits */
  165296. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165297. entropy->BE = 0;
  165298. }
  165299. }
  165300. /*
  165301. * Emit a restart marker & resynchronize predictions.
  165302. */
  165303. LOCAL(void)
  165304. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165305. {
  165306. int ci;
  165307. emit_eobrun(entropy);
  165308. if (! entropy->gather_statistics) {
  165309. flush_bits_p(entropy);
  165310. emit_byte(entropy, 0xFF);
  165311. emit_byte(entropy, JPEG_RST0 + restart_num);
  165312. }
  165313. if (entropy->cinfo->Ss == 0) {
  165314. /* Re-initialize DC predictions to 0 */
  165315. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165316. entropy->last_dc_val[ci] = 0;
  165317. } else {
  165318. /* Re-initialize all AC-related fields to 0 */
  165319. entropy->EOBRUN = 0;
  165320. entropy->BE = 0;
  165321. }
  165322. }
  165323. /*
  165324. * MCU encoding for DC initial scan (either spectral selection,
  165325. * or first pass of successive approximation).
  165326. */
  165327. METHODDEF(boolean)
  165328. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165329. {
  165330. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165331. register int temp, temp2;
  165332. register int nbits;
  165333. int blkn, ci;
  165334. int Al = cinfo->Al;
  165335. JBLOCKROW block;
  165336. jpeg_component_info * compptr;
  165337. ISHIFT_TEMPS
  165338. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165339. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165340. /* Emit restart marker if needed */
  165341. if (cinfo->restart_interval)
  165342. if (entropy->restarts_to_go == 0)
  165343. emit_restart_p(entropy, entropy->next_restart_num);
  165344. /* Encode the MCU data blocks */
  165345. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165346. block = MCU_data[blkn];
  165347. ci = cinfo->MCU_membership[blkn];
  165348. compptr = cinfo->cur_comp_info[ci];
  165349. /* Compute the DC value after the required point transform by Al.
  165350. * This is simply an arithmetic right shift.
  165351. */
  165352. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165353. /* DC differences are figured on the point-transformed values. */
  165354. temp = temp2 - entropy->last_dc_val[ci];
  165355. entropy->last_dc_val[ci] = temp2;
  165356. /* Encode the DC coefficient difference per section G.1.2.1 */
  165357. temp2 = temp;
  165358. if (temp < 0) {
  165359. temp = -temp; /* temp is abs value of input */
  165360. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165361. /* This code assumes we are on a two's complement machine */
  165362. temp2--;
  165363. }
  165364. /* Find the number of bits needed for the magnitude of the coefficient */
  165365. nbits = 0;
  165366. while (temp) {
  165367. nbits++;
  165368. temp >>= 1;
  165369. }
  165370. /* Check for out-of-range coefficient values.
  165371. * Since we're encoding a difference, the range limit is twice as much.
  165372. */
  165373. if (nbits > MAX_COEF_BITS+1)
  165374. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165375. /* Count/emit the Huffman-coded symbol for the number of bits */
  165376. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165377. /* Emit that number of bits of the value, if positive, */
  165378. /* or the complement of its magnitude, if negative. */
  165379. if (nbits) /* emit_bits rejects calls with size 0 */
  165380. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165381. }
  165382. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165383. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165384. /* Update restart-interval state too */
  165385. if (cinfo->restart_interval) {
  165386. if (entropy->restarts_to_go == 0) {
  165387. entropy->restarts_to_go = cinfo->restart_interval;
  165388. entropy->next_restart_num++;
  165389. entropy->next_restart_num &= 7;
  165390. }
  165391. entropy->restarts_to_go--;
  165392. }
  165393. return TRUE;
  165394. }
  165395. /*
  165396. * MCU encoding for AC initial scan (either spectral selection,
  165397. * or first pass of successive approximation).
  165398. */
  165399. METHODDEF(boolean)
  165400. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165401. {
  165402. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165403. register int temp, temp2;
  165404. register int nbits;
  165405. register int r, k;
  165406. int Se = cinfo->Se;
  165407. int Al = cinfo->Al;
  165408. JBLOCKROW block;
  165409. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165410. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165411. /* Emit restart marker if needed */
  165412. if (cinfo->restart_interval)
  165413. if (entropy->restarts_to_go == 0)
  165414. emit_restart_p(entropy, entropy->next_restart_num);
  165415. /* Encode the MCU data block */
  165416. block = MCU_data[0];
  165417. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165418. r = 0; /* r = run length of zeros */
  165419. for (k = cinfo->Ss; k <= Se; k++) {
  165420. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165421. r++;
  165422. continue;
  165423. }
  165424. /* We must apply the point transform by Al. For AC coefficients this
  165425. * is an integer division with rounding towards 0. To do this portably
  165426. * in C, we shift after obtaining the absolute value; so the code is
  165427. * interwoven with finding the abs value (temp) and output bits (temp2).
  165428. */
  165429. if (temp < 0) {
  165430. temp = -temp; /* temp is abs value of input */
  165431. temp >>= Al; /* apply the point transform */
  165432. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165433. temp2 = ~temp;
  165434. } else {
  165435. temp >>= Al; /* apply the point transform */
  165436. temp2 = temp;
  165437. }
  165438. /* Watch out for case that nonzero coef is zero after point transform */
  165439. if (temp == 0) {
  165440. r++;
  165441. continue;
  165442. }
  165443. /* Emit any pending EOBRUN */
  165444. if (entropy->EOBRUN > 0)
  165445. emit_eobrun(entropy);
  165446. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165447. while (r > 15) {
  165448. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165449. r -= 16;
  165450. }
  165451. /* Find the number of bits needed for the magnitude of the coefficient */
  165452. nbits = 1; /* there must be at least one 1 bit */
  165453. while ((temp >>= 1))
  165454. nbits++;
  165455. /* Check for out-of-range coefficient values */
  165456. if (nbits > MAX_COEF_BITS)
  165457. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165458. /* Count/emit Huffman symbol for run length / number of bits */
  165459. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165460. /* Emit that number of bits of the value, if positive, */
  165461. /* or the complement of its magnitude, if negative. */
  165462. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165463. r = 0; /* reset zero run length */
  165464. }
  165465. if (r > 0) { /* If there are trailing zeroes, */
  165466. entropy->EOBRUN++; /* count an EOB */
  165467. if (entropy->EOBRUN == 0x7FFF)
  165468. emit_eobrun(entropy); /* force it out to avoid overflow */
  165469. }
  165470. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165471. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165472. /* Update restart-interval state too */
  165473. if (cinfo->restart_interval) {
  165474. if (entropy->restarts_to_go == 0) {
  165475. entropy->restarts_to_go = cinfo->restart_interval;
  165476. entropy->next_restart_num++;
  165477. entropy->next_restart_num &= 7;
  165478. }
  165479. entropy->restarts_to_go--;
  165480. }
  165481. return TRUE;
  165482. }
  165483. /*
  165484. * MCU encoding for DC successive approximation refinement scan.
  165485. * Note: we assume such scans can be multi-component, although the spec
  165486. * is not very clear on the point.
  165487. */
  165488. METHODDEF(boolean)
  165489. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165490. {
  165491. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165492. register int temp;
  165493. int blkn;
  165494. int Al = cinfo->Al;
  165495. JBLOCKROW block;
  165496. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165497. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165498. /* Emit restart marker if needed */
  165499. if (cinfo->restart_interval)
  165500. if (entropy->restarts_to_go == 0)
  165501. emit_restart_p(entropy, entropy->next_restart_num);
  165502. /* Encode the MCU data blocks */
  165503. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165504. block = MCU_data[blkn];
  165505. /* We simply emit the Al'th bit of the DC coefficient value. */
  165506. temp = (*block)[0];
  165507. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165508. }
  165509. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165510. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165511. /* Update restart-interval state too */
  165512. if (cinfo->restart_interval) {
  165513. if (entropy->restarts_to_go == 0) {
  165514. entropy->restarts_to_go = cinfo->restart_interval;
  165515. entropy->next_restart_num++;
  165516. entropy->next_restart_num &= 7;
  165517. }
  165518. entropy->restarts_to_go--;
  165519. }
  165520. return TRUE;
  165521. }
  165522. /*
  165523. * MCU encoding for AC successive approximation refinement scan.
  165524. */
  165525. METHODDEF(boolean)
  165526. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165527. {
  165528. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165529. register int temp;
  165530. register int r, k;
  165531. int EOB;
  165532. char *BR_buffer;
  165533. unsigned int BR;
  165534. int Se = cinfo->Se;
  165535. int Al = cinfo->Al;
  165536. JBLOCKROW block;
  165537. int absvalues[DCTSIZE2];
  165538. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165539. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165540. /* Emit restart marker if needed */
  165541. if (cinfo->restart_interval)
  165542. if (entropy->restarts_to_go == 0)
  165543. emit_restart_p(entropy, entropy->next_restart_num);
  165544. /* Encode the MCU data block */
  165545. block = MCU_data[0];
  165546. /* It is convenient to make a pre-pass to determine the transformed
  165547. * coefficients' absolute values and the EOB position.
  165548. */
  165549. EOB = 0;
  165550. for (k = cinfo->Ss; k <= Se; k++) {
  165551. temp = (*block)[jpeg_natural_order[k]];
  165552. /* We must apply the point transform by Al. For AC coefficients this
  165553. * is an integer division with rounding towards 0. To do this portably
  165554. * in C, we shift after obtaining the absolute value.
  165555. */
  165556. if (temp < 0)
  165557. temp = -temp; /* temp is abs value of input */
  165558. temp >>= Al; /* apply the point transform */
  165559. absvalues[k] = temp; /* save abs value for main pass */
  165560. if (temp == 1)
  165561. EOB = k; /* EOB = index of last newly-nonzero coef */
  165562. }
  165563. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165564. r = 0; /* r = run length of zeros */
  165565. BR = 0; /* BR = count of buffered bits added now */
  165566. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165567. for (k = cinfo->Ss; k <= Se; k++) {
  165568. if ((temp = absvalues[k]) == 0) {
  165569. r++;
  165570. continue;
  165571. }
  165572. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165573. while (r > 15 && k <= EOB) {
  165574. /* emit any pending EOBRUN and the BE correction bits */
  165575. emit_eobrun(entropy);
  165576. /* Emit ZRL */
  165577. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165578. r -= 16;
  165579. /* Emit buffered correction bits that must be associated with ZRL */
  165580. emit_buffered_bits(entropy, BR_buffer, BR);
  165581. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165582. BR = 0;
  165583. }
  165584. /* If the coef was previously nonzero, it only needs a correction bit.
  165585. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165586. * that we also need to test r > 15. But if r > 15, we can only get here
  165587. * if k > EOB, which implies that this coefficient is not 1.
  165588. */
  165589. if (temp > 1) {
  165590. /* The correction bit is the next bit of the absolute value. */
  165591. BR_buffer[BR++] = (char) (temp & 1);
  165592. continue;
  165593. }
  165594. /* Emit any pending EOBRUN and the BE correction bits */
  165595. emit_eobrun(entropy);
  165596. /* Count/emit Huffman symbol for run length / number of bits */
  165597. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165598. /* Emit output bit for newly-nonzero coef */
  165599. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165600. emit_bits_p(entropy, (unsigned int) temp, 1);
  165601. /* Emit buffered correction bits that must be associated with this code */
  165602. emit_buffered_bits(entropy, BR_buffer, BR);
  165603. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165604. BR = 0;
  165605. r = 0; /* reset zero run length */
  165606. }
  165607. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165608. entropy->EOBRUN++; /* count an EOB */
  165609. entropy->BE += BR; /* concat my correction bits to older ones */
  165610. /* We force out the EOB if we risk either:
  165611. * 1. overflow of the EOB counter;
  165612. * 2. overflow of the correction bit buffer during the next MCU.
  165613. */
  165614. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165615. emit_eobrun(entropy);
  165616. }
  165617. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165618. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165619. /* Update restart-interval state too */
  165620. if (cinfo->restart_interval) {
  165621. if (entropy->restarts_to_go == 0) {
  165622. entropy->restarts_to_go = cinfo->restart_interval;
  165623. entropy->next_restart_num++;
  165624. entropy->next_restart_num &= 7;
  165625. }
  165626. entropy->restarts_to_go--;
  165627. }
  165628. return TRUE;
  165629. }
  165630. /*
  165631. * Finish up at the end of a Huffman-compressed progressive scan.
  165632. */
  165633. METHODDEF(void)
  165634. finish_pass_phuff (j_compress_ptr cinfo)
  165635. {
  165636. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165637. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165638. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165639. /* Flush out any buffered data */
  165640. emit_eobrun(entropy);
  165641. flush_bits_p(entropy);
  165642. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165643. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165644. }
  165645. /*
  165646. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165647. */
  165648. METHODDEF(void)
  165649. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165650. {
  165651. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165652. boolean is_DC_band;
  165653. int ci, tbl;
  165654. jpeg_component_info * compptr;
  165655. JHUFF_TBL **htblptr;
  165656. boolean did[NUM_HUFF_TBLS];
  165657. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165658. emit_eobrun(entropy);
  165659. is_DC_band = (cinfo->Ss == 0);
  165660. /* It's important not to apply jpeg_gen_optimal_table more than once
  165661. * per table, because it clobbers the input frequency counts!
  165662. */
  165663. MEMZERO(did, SIZEOF(did));
  165664. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165665. compptr = cinfo->cur_comp_info[ci];
  165666. if (is_DC_band) {
  165667. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165668. continue;
  165669. tbl = compptr->dc_tbl_no;
  165670. } else {
  165671. tbl = compptr->ac_tbl_no;
  165672. }
  165673. if (! did[tbl]) {
  165674. if (is_DC_band)
  165675. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165676. else
  165677. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165678. if (*htblptr == NULL)
  165679. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165680. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165681. did[tbl] = TRUE;
  165682. }
  165683. }
  165684. }
  165685. /*
  165686. * Module initialization routine for progressive Huffman entropy encoding.
  165687. */
  165688. GLOBAL(void)
  165689. jinit_phuff_encoder (j_compress_ptr cinfo)
  165690. {
  165691. phuff_entropy_ptr entropy;
  165692. int i;
  165693. entropy = (phuff_entropy_ptr)
  165694. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165695. SIZEOF(phuff_entropy_encoder));
  165696. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165697. entropy->pub.start_pass = start_pass_phuff;
  165698. /* Mark tables unallocated */
  165699. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165700. entropy->derived_tbls[i] = NULL;
  165701. entropy->count_ptrs[i] = NULL;
  165702. }
  165703. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165704. }
  165705. #endif /* C_PROGRESSIVE_SUPPORTED */
  165706. /*** End of inlined file: jcphuff.c ***/
  165707. /*** Start of inlined file: jcprepct.c ***/
  165708. #define JPEG_INTERNALS
  165709. /* At present, jcsample.c can request context rows only for smoothing.
  165710. * In the future, we might also need context rows for CCIR601 sampling
  165711. * or other more-complex downsampling procedures. The code to support
  165712. * context rows should be compiled only if needed.
  165713. */
  165714. #ifdef INPUT_SMOOTHING_SUPPORTED
  165715. #define CONTEXT_ROWS_SUPPORTED
  165716. #endif
  165717. /*
  165718. * For the simple (no-context-row) case, we just need to buffer one
  165719. * row group's worth of pixels for the downsampling step. At the bottom of
  165720. * the image, we pad to a full row group by replicating the last pixel row.
  165721. * The downsampler's last output row is then replicated if needed to pad
  165722. * out to a full iMCU row.
  165723. *
  165724. * When providing context rows, we must buffer three row groups' worth of
  165725. * pixels. Three row groups are physically allocated, but the row pointer
  165726. * arrays are made five row groups high, with the extra pointers above and
  165727. * below "wrapping around" to point to the last and first real row groups.
  165728. * This allows the downsampler to access the proper context rows.
  165729. * At the top and bottom of the image, we create dummy context rows by
  165730. * copying the first or last real pixel row. This copying could be avoided
  165731. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165732. * trouble on the compression side.
  165733. */
  165734. /* Private buffer controller object */
  165735. typedef struct {
  165736. struct jpeg_c_prep_controller pub; /* public fields */
  165737. /* Downsampling input buffer. This buffer holds color-converted data
  165738. * until we have enough to do a downsample step.
  165739. */
  165740. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165741. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165742. int next_buf_row; /* index of next row to store in color_buf */
  165743. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165744. int this_row_group; /* starting row index of group to process */
  165745. int next_buf_stop; /* downsample when we reach this index */
  165746. #endif
  165747. } my_prep_controller;
  165748. typedef my_prep_controller * my_prep_ptr;
  165749. /*
  165750. * Initialize for a processing pass.
  165751. */
  165752. METHODDEF(void)
  165753. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165754. {
  165755. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165756. if (pass_mode != JBUF_PASS_THRU)
  165757. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165758. /* Initialize total-height counter for detecting bottom of image */
  165759. prep->rows_to_go = cinfo->image_height;
  165760. /* Mark the conversion buffer empty */
  165761. prep->next_buf_row = 0;
  165762. #ifdef CONTEXT_ROWS_SUPPORTED
  165763. /* Preset additional state variables for context mode.
  165764. * These aren't used in non-context mode, so we needn't test which mode.
  165765. */
  165766. prep->this_row_group = 0;
  165767. /* Set next_buf_stop to stop after two row groups have been read in. */
  165768. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165769. #endif
  165770. }
  165771. /*
  165772. * Expand an image vertically from height input_rows to height output_rows,
  165773. * by duplicating the bottom row.
  165774. */
  165775. LOCAL(void)
  165776. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165777. int input_rows, int output_rows)
  165778. {
  165779. register int row;
  165780. for (row = input_rows; row < output_rows; row++) {
  165781. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165782. 1, num_cols);
  165783. }
  165784. }
  165785. /*
  165786. * Process some data in the simple no-context case.
  165787. *
  165788. * Preprocessor output data is counted in "row groups". A row group
  165789. * is defined to be v_samp_factor sample rows of each component.
  165790. * Downsampling will produce this much data from each max_v_samp_factor
  165791. * input rows.
  165792. */
  165793. METHODDEF(void)
  165794. pre_process_data (j_compress_ptr cinfo,
  165795. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165796. JDIMENSION in_rows_avail,
  165797. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165798. JDIMENSION out_row_groups_avail)
  165799. {
  165800. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165801. int numrows, ci;
  165802. JDIMENSION inrows;
  165803. jpeg_component_info * compptr;
  165804. while (*in_row_ctr < in_rows_avail &&
  165805. *out_row_group_ctr < out_row_groups_avail) {
  165806. /* Do color conversion to fill the conversion buffer. */
  165807. inrows = in_rows_avail - *in_row_ctr;
  165808. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165809. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165810. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165811. prep->color_buf,
  165812. (JDIMENSION) prep->next_buf_row,
  165813. numrows);
  165814. *in_row_ctr += numrows;
  165815. prep->next_buf_row += numrows;
  165816. prep->rows_to_go -= numrows;
  165817. /* If at bottom of image, pad to fill the conversion buffer. */
  165818. if (prep->rows_to_go == 0 &&
  165819. prep->next_buf_row < cinfo->max_v_samp_factor) {
  165820. for (ci = 0; ci < cinfo->num_components; ci++) {
  165821. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165822. prep->next_buf_row, cinfo->max_v_samp_factor);
  165823. }
  165824. prep->next_buf_row = cinfo->max_v_samp_factor;
  165825. }
  165826. /* If we've filled the conversion buffer, empty it. */
  165827. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  165828. (*cinfo->downsample->downsample) (cinfo,
  165829. prep->color_buf, (JDIMENSION) 0,
  165830. output_buf, *out_row_group_ctr);
  165831. prep->next_buf_row = 0;
  165832. (*out_row_group_ctr)++;
  165833. }
  165834. /* If at bottom of image, pad the output to a full iMCU height.
  165835. * Note we assume the caller is providing a one-iMCU-height output buffer!
  165836. */
  165837. if (prep->rows_to_go == 0 &&
  165838. *out_row_group_ctr < out_row_groups_avail) {
  165839. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165840. ci++, compptr++) {
  165841. expand_bottom_edge(output_buf[ci],
  165842. compptr->width_in_blocks * DCTSIZE,
  165843. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  165844. (int) (out_row_groups_avail * compptr->v_samp_factor));
  165845. }
  165846. *out_row_group_ctr = out_row_groups_avail;
  165847. break; /* can exit outer loop without test */
  165848. }
  165849. }
  165850. }
  165851. #ifdef CONTEXT_ROWS_SUPPORTED
  165852. /*
  165853. * Process some data in the context case.
  165854. */
  165855. METHODDEF(void)
  165856. pre_process_context (j_compress_ptr cinfo,
  165857. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165858. JDIMENSION in_rows_avail,
  165859. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165860. JDIMENSION out_row_groups_avail)
  165861. {
  165862. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165863. int numrows, ci;
  165864. int buf_height = cinfo->max_v_samp_factor * 3;
  165865. JDIMENSION inrows;
  165866. while (*out_row_group_ctr < out_row_groups_avail) {
  165867. if (*in_row_ctr < in_rows_avail) {
  165868. /* Do color conversion to fill the conversion buffer. */
  165869. inrows = in_rows_avail - *in_row_ctr;
  165870. numrows = prep->next_buf_stop - prep->next_buf_row;
  165871. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165872. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165873. prep->color_buf,
  165874. (JDIMENSION) prep->next_buf_row,
  165875. numrows);
  165876. /* Pad at top of image, if first time through */
  165877. if (prep->rows_to_go == cinfo->image_height) {
  165878. for (ci = 0; ci < cinfo->num_components; ci++) {
  165879. int row;
  165880. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  165881. jcopy_sample_rows(prep->color_buf[ci], 0,
  165882. prep->color_buf[ci], -row,
  165883. 1, cinfo->image_width);
  165884. }
  165885. }
  165886. }
  165887. *in_row_ctr += numrows;
  165888. prep->next_buf_row += numrows;
  165889. prep->rows_to_go -= numrows;
  165890. } else {
  165891. /* Return for more data, unless we are at the bottom of the image. */
  165892. if (prep->rows_to_go != 0)
  165893. break;
  165894. /* When at bottom of image, pad to fill the conversion buffer. */
  165895. if (prep->next_buf_row < prep->next_buf_stop) {
  165896. for (ci = 0; ci < cinfo->num_components; ci++) {
  165897. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165898. prep->next_buf_row, prep->next_buf_stop);
  165899. }
  165900. prep->next_buf_row = prep->next_buf_stop;
  165901. }
  165902. }
  165903. /* If we've gotten enough data, downsample a row group. */
  165904. if (prep->next_buf_row == prep->next_buf_stop) {
  165905. (*cinfo->downsample->downsample) (cinfo,
  165906. prep->color_buf,
  165907. (JDIMENSION) prep->this_row_group,
  165908. output_buf, *out_row_group_ctr);
  165909. (*out_row_group_ctr)++;
  165910. /* Advance pointers with wraparound as necessary. */
  165911. prep->this_row_group += cinfo->max_v_samp_factor;
  165912. if (prep->this_row_group >= buf_height)
  165913. prep->this_row_group = 0;
  165914. if (prep->next_buf_row >= buf_height)
  165915. prep->next_buf_row = 0;
  165916. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  165917. }
  165918. }
  165919. }
  165920. /*
  165921. * Create the wrapped-around downsampling input buffer needed for context mode.
  165922. */
  165923. LOCAL(void)
  165924. create_context_buffer (j_compress_ptr cinfo)
  165925. {
  165926. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165927. int rgroup_height = cinfo->max_v_samp_factor;
  165928. int ci, i;
  165929. jpeg_component_info * compptr;
  165930. JSAMPARRAY true_buffer, fake_buffer;
  165931. /* Grab enough space for fake row pointers for all the components;
  165932. * we need five row groups' worth of pointers for each component.
  165933. */
  165934. fake_buffer = (JSAMPARRAY)
  165935. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165936. (cinfo->num_components * 5 * rgroup_height) *
  165937. SIZEOF(JSAMPROW));
  165938. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165939. ci++, compptr++) {
  165940. /* Allocate the actual buffer space (3 row groups) for this component.
  165941. * We make the buffer wide enough to allow the downsampler to edge-expand
  165942. * horizontally within the buffer, if it so chooses.
  165943. */
  165944. true_buffer = (*cinfo->mem->alloc_sarray)
  165945. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165946. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165947. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165948. (JDIMENSION) (3 * rgroup_height));
  165949. /* Copy true buffer row pointers into the middle of the fake row array */
  165950. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  165951. 3 * rgroup_height * SIZEOF(JSAMPROW));
  165952. /* Fill in the above and below wraparound pointers */
  165953. for (i = 0; i < rgroup_height; i++) {
  165954. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  165955. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  165956. }
  165957. prep->color_buf[ci] = fake_buffer + rgroup_height;
  165958. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  165959. }
  165960. }
  165961. #endif /* CONTEXT_ROWS_SUPPORTED */
  165962. /*
  165963. * Initialize preprocessing controller.
  165964. */
  165965. GLOBAL(void)
  165966. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  165967. {
  165968. my_prep_ptr prep;
  165969. int ci;
  165970. jpeg_component_info * compptr;
  165971. if (need_full_buffer) /* safety check */
  165972. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165973. prep = (my_prep_ptr)
  165974. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165975. SIZEOF(my_prep_controller));
  165976. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  165977. prep->pub.start_pass = start_pass_prep;
  165978. /* Allocate the color conversion buffer.
  165979. * We make the buffer wide enough to allow the downsampler to edge-expand
  165980. * horizontally within the buffer, if it so chooses.
  165981. */
  165982. if (cinfo->downsample->need_context_rows) {
  165983. /* Set up to provide context rows */
  165984. #ifdef CONTEXT_ROWS_SUPPORTED
  165985. prep->pub.pre_process_data = pre_process_context;
  165986. create_context_buffer(cinfo);
  165987. #else
  165988. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165989. #endif
  165990. } else {
  165991. /* No context, just make it tall enough for one row group */
  165992. prep->pub.pre_process_data = pre_process_data;
  165993. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165994. ci++, compptr++) {
  165995. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  165996. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165997. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165998. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165999. (JDIMENSION) cinfo->max_v_samp_factor);
  166000. }
  166001. }
  166002. }
  166003. /*** End of inlined file: jcprepct.c ***/
  166004. /*** Start of inlined file: jcsample.c ***/
  166005. #define JPEG_INTERNALS
  166006. /* Pointer to routine to downsample a single component */
  166007. typedef JMETHOD(void, downsample1_ptr,
  166008. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166009. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166010. /* Private subobject */
  166011. typedef struct {
  166012. struct jpeg_downsampler pub; /* public fields */
  166013. /* Downsampling method pointers, one per component */
  166014. downsample1_ptr methods[MAX_COMPONENTS];
  166015. } my_downsampler;
  166016. typedef my_downsampler * my_downsample_ptr;
  166017. /*
  166018. * Initialize for a downsampling pass.
  166019. */
  166020. METHODDEF(void)
  166021. start_pass_downsample (j_compress_ptr)
  166022. {
  166023. /* no work for now */
  166024. }
  166025. /*
  166026. * Expand a component horizontally from width input_cols to width output_cols,
  166027. * by duplicating the rightmost samples.
  166028. */
  166029. LOCAL(void)
  166030. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166031. JDIMENSION input_cols, JDIMENSION output_cols)
  166032. {
  166033. register JSAMPROW ptr;
  166034. register JSAMPLE pixval;
  166035. register int count;
  166036. int row;
  166037. int numcols = (int) (output_cols - input_cols);
  166038. if (numcols > 0) {
  166039. for (row = 0; row < num_rows; row++) {
  166040. ptr = image_data[row] + input_cols;
  166041. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166042. for (count = numcols; count > 0; count--)
  166043. *ptr++ = pixval;
  166044. }
  166045. }
  166046. }
  166047. /*
  166048. * Do downsampling for a whole row group (all components).
  166049. *
  166050. * In this version we simply downsample each component independently.
  166051. */
  166052. METHODDEF(void)
  166053. sep_downsample (j_compress_ptr cinfo,
  166054. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166055. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166056. {
  166057. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166058. int ci;
  166059. jpeg_component_info * compptr;
  166060. JSAMPARRAY in_ptr, out_ptr;
  166061. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166062. ci++, compptr++) {
  166063. in_ptr = input_buf[ci] + in_row_index;
  166064. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166065. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166066. }
  166067. }
  166068. /*
  166069. * Downsample pixel values of a single component.
  166070. * One row group is processed per call.
  166071. * This version handles arbitrary integral sampling ratios, without smoothing.
  166072. * Note that this version is not actually used for customary sampling ratios.
  166073. */
  166074. METHODDEF(void)
  166075. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166076. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166077. {
  166078. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166079. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166080. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166081. JSAMPROW inptr, outptr;
  166082. INT32 outvalue;
  166083. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166084. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166085. numpix = h_expand * v_expand;
  166086. numpix2 = numpix/2;
  166087. /* Expand input data enough to let all the output samples be generated
  166088. * by the standard loop. Special-casing padded output would be more
  166089. * efficient.
  166090. */
  166091. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166092. cinfo->image_width, output_cols * h_expand);
  166093. inrow = 0;
  166094. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166095. outptr = output_data[outrow];
  166096. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166097. outcol++, outcol_h += h_expand) {
  166098. outvalue = 0;
  166099. for (v = 0; v < v_expand; v++) {
  166100. inptr = input_data[inrow+v] + outcol_h;
  166101. for (h = 0; h < h_expand; h++) {
  166102. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166103. }
  166104. }
  166105. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166106. }
  166107. inrow += v_expand;
  166108. }
  166109. }
  166110. /*
  166111. * Downsample pixel values of a single component.
  166112. * This version handles the special case of a full-size component,
  166113. * without smoothing.
  166114. */
  166115. METHODDEF(void)
  166116. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166117. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166118. {
  166119. /* Copy the data */
  166120. jcopy_sample_rows(input_data, 0, output_data, 0,
  166121. cinfo->max_v_samp_factor, cinfo->image_width);
  166122. /* Edge-expand */
  166123. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166124. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166125. }
  166126. /*
  166127. * Downsample pixel values of a single component.
  166128. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166129. * without smoothing.
  166130. *
  166131. * A note about the "bias" calculations: when rounding fractional values to
  166132. * integer, we do not want to always round 0.5 up to the next integer.
  166133. * If we did that, we'd introduce a noticeable bias towards larger values.
  166134. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166135. * alternate pixel locations (a simple ordered dither pattern).
  166136. */
  166137. METHODDEF(void)
  166138. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166139. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166140. {
  166141. int outrow;
  166142. JDIMENSION outcol;
  166143. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166144. register JSAMPROW inptr, outptr;
  166145. register int bias;
  166146. /* Expand input data enough to let all the output samples be generated
  166147. * by the standard loop. Special-casing padded output would be more
  166148. * efficient.
  166149. */
  166150. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166151. cinfo->image_width, output_cols * 2);
  166152. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166153. outptr = output_data[outrow];
  166154. inptr = input_data[outrow];
  166155. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166156. for (outcol = 0; outcol < output_cols; outcol++) {
  166157. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166158. + bias) >> 1);
  166159. bias ^= 1; /* 0=>1, 1=>0 */
  166160. inptr += 2;
  166161. }
  166162. }
  166163. }
  166164. /*
  166165. * Downsample pixel values of a single component.
  166166. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166167. * without smoothing.
  166168. */
  166169. METHODDEF(void)
  166170. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166171. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166172. {
  166173. int inrow, outrow;
  166174. JDIMENSION outcol;
  166175. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166176. register JSAMPROW inptr0, inptr1, outptr;
  166177. register int bias;
  166178. /* Expand input data enough to let all the output samples be generated
  166179. * by the standard loop. Special-casing padded output would be more
  166180. * efficient.
  166181. */
  166182. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166183. cinfo->image_width, output_cols * 2);
  166184. inrow = 0;
  166185. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166186. outptr = output_data[outrow];
  166187. inptr0 = input_data[inrow];
  166188. inptr1 = input_data[inrow+1];
  166189. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166190. for (outcol = 0; outcol < output_cols; outcol++) {
  166191. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166192. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166193. + bias) >> 2);
  166194. bias ^= 3; /* 1=>2, 2=>1 */
  166195. inptr0 += 2; inptr1 += 2;
  166196. }
  166197. inrow += 2;
  166198. }
  166199. }
  166200. #ifdef INPUT_SMOOTHING_SUPPORTED
  166201. /*
  166202. * Downsample pixel values of a single component.
  166203. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166204. * with smoothing. One row of context is required.
  166205. */
  166206. METHODDEF(void)
  166207. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166208. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166209. {
  166210. int inrow, outrow;
  166211. JDIMENSION colctr;
  166212. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166213. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166214. INT32 membersum, neighsum, memberscale, neighscale;
  166215. /* Expand input data enough to let all the output samples be generated
  166216. * by the standard loop. Special-casing padded output would be more
  166217. * efficient.
  166218. */
  166219. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166220. cinfo->image_width, output_cols * 2);
  166221. /* We don't bother to form the individual "smoothed" input pixel values;
  166222. * we can directly compute the output which is the average of the four
  166223. * smoothed values. Each of the four member pixels contributes a fraction
  166224. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166225. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166226. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166227. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166228. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166229. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166230. * factors are scaled by 2^16 = 65536.
  166231. * Also recall that SF = smoothing_factor / 1024.
  166232. */
  166233. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166234. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166235. inrow = 0;
  166236. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166237. outptr = output_data[outrow];
  166238. inptr0 = input_data[inrow];
  166239. inptr1 = input_data[inrow+1];
  166240. above_ptr = input_data[inrow-1];
  166241. below_ptr = input_data[inrow+2];
  166242. /* Special case for first column: pretend column -1 is same as column 0 */
  166243. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166244. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166245. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166246. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166247. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166248. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166249. neighsum += neighsum;
  166250. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166251. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166252. membersum = membersum * memberscale + neighsum * neighscale;
  166253. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166254. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166255. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166256. /* sum of pixels directly mapped to this output element */
  166257. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166258. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166259. /* sum of edge-neighbor pixels */
  166260. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166261. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166262. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166263. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166264. /* The edge-neighbors count twice as much as corner-neighbors */
  166265. neighsum += neighsum;
  166266. /* Add in the corner-neighbors */
  166267. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166268. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166269. /* form final output scaled up by 2^16 */
  166270. membersum = membersum * memberscale + neighsum * neighscale;
  166271. /* round, descale and output it */
  166272. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166273. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166274. }
  166275. /* Special case for last column */
  166276. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166277. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166278. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166279. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166280. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166281. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166282. neighsum += neighsum;
  166283. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166284. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166285. membersum = membersum * memberscale + neighsum * neighscale;
  166286. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166287. inrow += 2;
  166288. }
  166289. }
  166290. /*
  166291. * Downsample pixel values of a single component.
  166292. * This version handles the special case of a full-size component,
  166293. * with smoothing. One row of context is required.
  166294. */
  166295. METHODDEF(void)
  166296. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166297. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166298. {
  166299. int outrow;
  166300. JDIMENSION colctr;
  166301. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166302. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166303. INT32 membersum, neighsum, memberscale, neighscale;
  166304. int colsum, lastcolsum, nextcolsum;
  166305. /* Expand input data enough to let all the output samples be generated
  166306. * by the standard loop. Special-casing padded output would be more
  166307. * efficient.
  166308. */
  166309. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166310. cinfo->image_width, output_cols);
  166311. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166312. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166313. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166314. * Also recall that SF = smoothing_factor / 1024.
  166315. */
  166316. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166317. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166318. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166319. outptr = output_data[outrow];
  166320. inptr = input_data[outrow];
  166321. above_ptr = input_data[outrow-1];
  166322. below_ptr = input_data[outrow+1];
  166323. /* Special case for first column */
  166324. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166325. GETJSAMPLE(*inptr);
  166326. membersum = GETJSAMPLE(*inptr++);
  166327. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166328. GETJSAMPLE(*inptr);
  166329. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166330. membersum = membersum * memberscale + neighsum * neighscale;
  166331. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166332. lastcolsum = colsum; colsum = nextcolsum;
  166333. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166334. membersum = GETJSAMPLE(*inptr++);
  166335. above_ptr++; below_ptr++;
  166336. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166337. GETJSAMPLE(*inptr);
  166338. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166339. membersum = membersum * memberscale + neighsum * neighscale;
  166340. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166341. lastcolsum = colsum; colsum = nextcolsum;
  166342. }
  166343. /* Special case for last column */
  166344. membersum = GETJSAMPLE(*inptr);
  166345. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166346. membersum = membersum * memberscale + neighsum * neighscale;
  166347. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166348. }
  166349. }
  166350. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166351. /*
  166352. * Module initialization routine for downsampling.
  166353. * Note that we must select a routine for each component.
  166354. */
  166355. GLOBAL(void)
  166356. jinit_downsampler (j_compress_ptr cinfo)
  166357. {
  166358. my_downsample_ptr downsample;
  166359. int ci;
  166360. jpeg_component_info * compptr;
  166361. boolean smoothok = TRUE;
  166362. downsample = (my_downsample_ptr)
  166363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166364. SIZEOF(my_downsampler));
  166365. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166366. downsample->pub.start_pass = start_pass_downsample;
  166367. downsample->pub.downsample = sep_downsample;
  166368. downsample->pub.need_context_rows = FALSE;
  166369. if (cinfo->CCIR601_sampling)
  166370. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166371. /* Verify we can handle the sampling factors, and set up method pointers */
  166372. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166373. ci++, compptr++) {
  166374. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166375. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166376. #ifdef INPUT_SMOOTHING_SUPPORTED
  166377. if (cinfo->smoothing_factor) {
  166378. downsample->methods[ci] = fullsize_smooth_downsample;
  166379. downsample->pub.need_context_rows = TRUE;
  166380. } else
  166381. #endif
  166382. downsample->methods[ci] = fullsize_downsample;
  166383. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166384. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166385. smoothok = FALSE;
  166386. downsample->methods[ci] = h2v1_downsample;
  166387. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166388. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166389. #ifdef INPUT_SMOOTHING_SUPPORTED
  166390. if (cinfo->smoothing_factor) {
  166391. downsample->methods[ci] = h2v2_smooth_downsample;
  166392. downsample->pub.need_context_rows = TRUE;
  166393. } else
  166394. #endif
  166395. downsample->methods[ci] = h2v2_downsample;
  166396. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166397. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166398. smoothok = FALSE;
  166399. downsample->methods[ci] = int_downsample;
  166400. } else
  166401. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166402. }
  166403. #ifdef INPUT_SMOOTHING_SUPPORTED
  166404. if (cinfo->smoothing_factor && !smoothok)
  166405. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166406. #endif
  166407. }
  166408. /*** End of inlined file: jcsample.c ***/
  166409. /*** Start of inlined file: jctrans.c ***/
  166410. #define JPEG_INTERNALS
  166411. /* Forward declarations */
  166412. LOCAL(void) transencode_master_selection
  166413. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166414. LOCAL(void) transencode_coef_controller
  166415. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166416. /*
  166417. * Compression initialization for writing raw-coefficient data.
  166418. * Before calling this, all parameters and a data destination must be set up.
  166419. * Call jpeg_finish_compress() to actually write the data.
  166420. *
  166421. * The number of passed virtual arrays must match cinfo->num_components.
  166422. * Note that the virtual arrays need not be filled or even realized at
  166423. * the time write_coefficients is called; indeed, if the virtual arrays
  166424. * were requested from this compression object's memory manager, they
  166425. * typically will be realized during this routine and filled afterwards.
  166426. */
  166427. GLOBAL(void)
  166428. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166429. {
  166430. if (cinfo->global_state != CSTATE_START)
  166431. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166432. /* Mark all tables to be written */
  166433. jpeg_suppress_tables(cinfo, FALSE);
  166434. /* (Re)initialize error mgr and destination modules */
  166435. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166436. (*cinfo->dest->init_destination) (cinfo);
  166437. /* Perform master selection of active modules */
  166438. transencode_master_selection(cinfo, coef_arrays);
  166439. /* Wait for jpeg_finish_compress() call */
  166440. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166441. cinfo->global_state = CSTATE_WRCOEFS;
  166442. }
  166443. /*
  166444. * Initialize the compression object with default parameters,
  166445. * then copy from the source object all parameters needed for lossless
  166446. * transcoding. Parameters that can be varied without loss (such as
  166447. * scan script and Huffman optimization) are left in their default states.
  166448. */
  166449. GLOBAL(void)
  166450. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166451. j_compress_ptr dstinfo)
  166452. {
  166453. JQUANT_TBL ** qtblptr;
  166454. jpeg_component_info *incomp, *outcomp;
  166455. JQUANT_TBL *c_quant, *slot_quant;
  166456. int tblno, ci, coefi;
  166457. /* Safety check to ensure start_compress not called yet. */
  166458. if (dstinfo->global_state != CSTATE_START)
  166459. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166460. /* Copy fundamental image dimensions */
  166461. dstinfo->image_width = srcinfo->image_width;
  166462. dstinfo->image_height = srcinfo->image_height;
  166463. dstinfo->input_components = srcinfo->num_components;
  166464. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166465. /* Initialize all parameters to default values */
  166466. jpeg_set_defaults(dstinfo);
  166467. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166468. * Fix it to get the right header markers for the image colorspace.
  166469. */
  166470. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166471. dstinfo->data_precision = srcinfo->data_precision;
  166472. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166473. /* Copy the source's quantization tables. */
  166474. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166475. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166476. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166477. if (*qtblptr == NULL)
  166478. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166479. MEMCOPY((*qtblptr)->quantval,
  166480. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166481. SIZEOF((*qtblptr)->quantval));
  166482. (*qtblptr)->sent_table = FALSE;
  166483. }
  166484. }
  166485. /* Copy the source's per-component info.
  166486. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166487. */
  166488. dstinfo->num_components = srcinfo->num_components;
  166489. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166490. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166491. MAX_COMPONENTS);
  166492. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166493. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166494. outcomp->component_id = incomp->component_id;
  166495. outcomp->h_samp_factor = incomp->h_samp_factor;
  166496. outcomp->v_samp_factor = incomp->v_samp_factor;
  166497. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166498. /* Make sure saved quantization table for component matches the qtable
  166499. * slot. If not, the input file re-used this qtable slot.
  166500. * IJG encoder currently cannot duplicate this.
  166501. */
  166502. tblno = outcomp->quant_tbl_no;
  166503. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166504. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166505. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166506. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166507. c_quant = incomp->quant_table;
  166508. if (c_quant != NULL) {
  166509. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166510. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166511. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166512. }
  166513. }
  166514. /* Note: we do not copy the source's Huffman table assignments;
  166515. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166516. */
  166517. }
  166518. /* Also copy JFIF version and resolution information, if available.
  166519. * Strictly speaking this isn't "critical" info, but it's nearly
  166520. * always appropriate to copy it if available. In particular,
  166521. * if the application chooses to copy JFIF 1.02 extension markers from
  166522. * the source file, we need to copy the version to make sure we don't
  166523. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166524. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166525. */
  166526. if (srcinfo->saw_JFIF_marker) {
  166527. if (srcinfo->JFIF_major_version == 1) {
  166528. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166529. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166530. }
  166531. dstinfo->density_unit = srcinfo->density_unit;
  166532. dstinfo->X_density = srcinfo->X_density;
  166533. dstinfo->Y_density = srcinfo->Y_density;
  166534. }
  166535. }
  166536. /*
  166537. * Master selection of compression modules for transcoding.
  166538. * This substitutes for jcinit.c's initialization of the full compressor.
  166539. */
  166540. LOCAL(void)
  166541. transencode_master_selection (j_compress_ptr cinfo,
  166542. jvirt_barray_ptr * coef_arrays)
  166543. {
  166544. /* Although we don't actually use input_components for transcoding,
  166545. * jcmaster.c's initial_setup will complain if input_components is 0.
  166546. */
  166547. cinfo->input_components = 1;
  166548. /* Initialize master control (includes parameter checking/processing) */
  166549. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166550. /* Entropy encoding: either Huffman or arithmetic coding. */
  166551. if (cinfo->arith_code) {
  166552. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166553. } else {
  166554. if (cinfo->progressive_mode) {
  166555. #ifdef C_PROGRESSIVE_SUPPORTED
  166556. jinit_phuff_encoder(cinfo);
  166557. #else
  166558. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166559. #endif
  166560. } else
  166561. jinit_huff_encoder(cinfo);
  166562. }
  166563. /* We need a special coefficient buffer controller. */
  166564. transencode_coef_controller(cinfo, coef_arrays);
  166565. jinit_marker_writer(cinfo);
  166566. /* We can now tell the memory manager to allocate virtual arrays. */
  166567. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166568. /* Write the datastream header (SOI, JFIF) immediately.
  166569. * Frame and scan headers are postponed till later.
  166570. * This lets application insert special markers after the SOI.
  166571. */
  166572. (*cinfo->marker->write_file_header) (cinfo);
  166573. }
  166574. /*
  166575. * The rest of this file is a special implementation of the coefficient
  166576. * buffer controller. This is similar to jccoefct.c, but it handles only
  166577. * output from presupplied virtual arrays. Furthermore, we generate any
  166578. * dummy padding blocks on-the-fly rather than expecting them to be present
  166579. * in the arrays.
  166580. */
  166581. /* Private buffer controller object */
  166582. typedef struct {
  166583. struct jpeg_c_coef_controller pub; /* public fields */
  166584. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166585. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166586. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166587. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166588. /* Virtual block array for each component. */
  166589. jvirt_barray_ptr * whole_image;
  166590. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166591. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166592. } my_coef_controller2;
  166593. typedef my_coef_controller2 * my_coef_ptr2;
  166594. LOCAL(void)
  166595. start_iMCU_row2 (j_compress_ptr cinfo)
  166596. /* Reset within-iMCU-row counters for a new row */
  166597. {
  166598. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166599. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166600. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166601. * But at the bottom of the image, process only what's left.
  166602. */
  166603. if (cinfo->comps_in_scan > 1) {
  166604. coef->MCU_rows_per_iMCU_row = 1;
  166605. } else {
  166606. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166607. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166608. else
  166609. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166610. }
  166611. coef->mcu_ctr = 0;
  166612. coef->MCU_vert_offset = 0;
  166613. }
  166614. /*
  166615. * Initialize for a processing pass.
  166616. */
  166617. METHODDEF(void)
  166618. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166619. {
  166620. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166621. if (pass_mode != JBUF_CRANK_DEST)
  166622. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166623. coef->iMCU_row_num = 0;
  166624. start_iMCU_row2(cinfo);
  166625. }
  166626. /*
  166627. * Process some data.
  166628. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166629. * per call, ie, v_samp_factor block rows for each component in the scan.
  166630. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166631. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166632. *
  166633. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166634. */
  166635. METHODDEF(boolean)
  166636. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166637. {
  166638. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166639. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166640. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166641. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166642. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166643. JDIMENSION start_col;
  166644. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166645. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166646. JBLOCKROW buffer_ptr;
  166647. jpeg_component_info *compptr;
  166648. /* Align the virtual buffers for the components used in this scan. */
  166649. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166650. compptr = cinfo->cur_comp_info[ci];
  166651. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166652. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166653. coef->iMCU_row_num * compptr->v_samp_factor,
  166654. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166655. }
  166656. /* Loop to process one whole iMCU row */
  166657. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166658. yoffset++) {
  166659. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166660. MCU_col_num++) {
  166661. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166662. blkn = 0; /* index of current DCT block within MCU */
  166663. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166664. compptr = cinfo->cur_comp_info[ci];
  166665. start_col = MCU_col_num * compptr->MCU_width;
  166666. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166667. : compptr->last_col_width;
  166668. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166669. if (coef->iMCU_row_num < last_iMCU_row ||
  166670. yindex+yoffset < compptr->last_row_height) {
  166671. /* Fill in pointers to real blocks in this row */
  166672. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166673. for (xindex = 0; xindex < blockcnt; xindex++)
  166674. MCU_buffer[blkn++] = buffer_ptr++;
  166675. } else {
  166676. /* At bottom of image, need a whole row of dummy blocks */
  166677. xindex = 0;
  166678. }
  166679. /* Fill in any dummy blocks needed in this row.
  166680. * Dummy blocks are filled in the same way as in jccoefct.c:
  166681. * all zeroes in the AC entries, DC entries equal to previous
  166682. * block's DC value. The init routine has already zeroed the
  166683. * AC entries, so we need only set the DC entries correctly.
  166684. */
  166685. for (; xindex < compptr->MCU_width; xindex++) {
  166686. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166687. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166688. blkn++;
  166689. }
  166690. }
  166691. }
  166692. /* Try to write the MCU. */
  166693. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166694. /* Suspension forced; update state counters and exit */
  166695. coef->MCU_vert_offset = yoffset;
  166696. coef->mcu_ctr = MCU_col_num;
  166697. return FALSE;
  166698. }
  166699. }
  166700. /* Completed an MCU row, but perhaps not an iMCU row */
  166701. coef->mcu_ctr = 0;
  166702. }
  166703. /* Completed the iMCU row, advance counters for next one */
  166704. coef->iMCU_row_num++;
  166705. start_iMCU_row2(cinfo);
  166706. return TRUE;
  166707. }
  166708. /*
  166709. * Initialize coefficient buffer controller.
  166710. *
  166711. * Each passed coefficient array must be the right size for that
  166712. * coefficient: width_in_blocks wide and height_in_blocks high,
  166713. * with unitheight at least v_samp_factor.
  166714. */
  166715. LOCAL(void)
  166716. transencode_coef_controller (j_compress_ptr cinfo,
  166717. jvirt_barray_ptr * coef_arrays)
  166718. {
  166719. my_coef_ptr2 coef;
  166720. JBLOCKROW buffer;
  166721. int i;
  166722. coef = (my_coef_ptr2)
  166723. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166724. SIZEOF(my_coef_controller2));
  166725. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166726. coef->pub.start_pass = start_pass_coef2;
  166727. coef->pub.compress_data = compress_output2;
  166728. /* Save pointer to virtual arrays */
  166729. coef->whole_image = coef_arrays;
  166730. /* Allocate and pre-zero space for dummy DCT blocks. */
  166731. buffer = (JBLOCKROW)
  166732. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166733. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166734. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166735. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166736. coef->dummy_buffer[i] = buffer + i;
  166737. }
  166738. }
  166739. /*** End of inlined file: jctrans.c ***/
  166740. /*** Start of inlined file: jdapistd.c ***/
  166741. #define JPEG_INTERNALS
  166742. /* Forward declarations */
  166743. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166744. /*
  166745. * Decompression initialization.
  166746. * jpeg_read_header must be completed before calling this.
  166747. *
  166748. * If a multipass operating mode was selected, this will do all but the
  166749. * last pass, and thus may take a great deal of time.
  166750. *
  166751. * Returns FALSE if suspended. The return value need be inspected only if
  166752. * a suspending data source is used.
  166753. */
  166754. GLOBAL(boolean)
  166755. jpeg_start_decompress (j_decompress_ptr cinfo)
  166756. {
  166757. if (cinfo->global_state == DSTATE_READY) {
  166758. /* First call: initialize master control, select active modules */
  166759. jinit_master_decompress(cinfo);
  166760. if (cinfo->buffered_image) {
  166761. /* No more work here; expecting jpeg_start_output next */
  166762. cinfo->global_state = DSTATE_BUFIMAGE;
  166763. return TRUE;
  166764. }
  166765. cinfo->global_state = DSTATE_PRELOAD;
  166766. }
  166767. if (cinfo->global_state == DSTATE_PRELOAD) {
  166768. /* If file has multiple scans, absorb them all into the coef buffer */
  166769. if (cinfo->inputctl->has_multiple_scans) {
  166770. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166771. for (;;) {
  166772. int retcode;
  166773. /* Call progress monitor hook if present */
  166774. if (cinfo->progress != NULL)
  166775. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166776. /* Absorb some more input */
  166777. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166778. if (retcode == JPEG_SUSPENDED)
  166779. return FALSE;
  166780. if (retcode == JPEG_REACHED_EOI)
  166781. break;
  166782. /* Advance progress counter if appropriate */
  166783. if (cinfo->progress != NULL &&
  166784. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166785. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166786. /* jdmaster underestimated number of scans; ratchet up one scan */
  166787. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166788. }
  166789. }
  166790. }
  166791. #else
  166792. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166793. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166794. }
  166795. cinfo->output_scan_number = cinfo->input_scan_number;
  166796. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166797. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166798. /* Perform any dummy output passes, and set up for the final pass */
  166799. return output_pass_setup(cinfo);
  166800. }
  166801. /*
  166802. * Set up for an output pass, and perform any dummy pass(es) needed.
  166803. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166804. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166805. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166806. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166807. */
  166808. LOCAL(boolean)
  166809. output_pass_setup (j_decompress_ptr cinfo)
  166810. {
  166811. if (cinfo->global_state != DSTATE_PRESCAN) {
  166812. /* First call: do pass setup */
  166813. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166814. cinfo->output_scanline = 0;
  166815. cinfo->global_state = DSTATE_PRESCAN;
  166816. }
  166817. /* Loop over any required dummy passes */
  166818. while (cinfo->master->is_dummy_pass) {
  166819. #ifdef QUANT_2PASS_SUPPORTED
  166820. /* Crank through the dummy pass */
  166821. while (cinfo->output_scanline < cinfo->output_height) {
  166822. JDIMENSION last_scanline;
  166823. /* Call progress monitor hook if present */
  166824. if (cinfo->progress != NULL) {
  166825. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166826. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166827. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166828. }
  166829. /* Process some data */
  166830. last_scanline = cinfo->output_scanline;
  166831. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  166832. &cinfo->output_scanline, (JDIMENSION) 0);
  166833. if (cinfo->output_scanline == last_scanline)
  166834. return FALSE; /* No progress made, must suspend */
  166835. }
  166836. /* Finish up dummy pass, and set up for another one */
  166837. (*cinfo->master->finish_output_pass) (cinfo);
  166838. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166839. cinfo->output_scanline = 0;
  166840. #else
  166841. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166842. #endif /* QUANT_2PASS_SUPPORTED */
  166843. }
  166844. /* Ready for application to drive output pass through
  166845. * jpeg_read_scanlines or jpeg_read_raw_data.
  166846. */
  166847. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  166848. return TRUE;
  166849. }
  166850. /*
  166851. * Read some scanlines of data from the JPEG decompressor.
  166852. *
  166853. * The return value will be the number of lines actually read.
  166854. * This may be less than the number requested in several cases,
  166855. * including bottom of image, data source suspension, and operating
  166856. * modes that emit multiple scanlines at a time.
  166857. *
  166858. * Note: we warn about excess calls to jpeg_read_scanlines() since
  166859. * this likely signals an application programmer error. However,
  166860. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  166861. */
  166862. GLOBAL(JDIMENSION)
  166863. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  166864. JDIMENSION max_lines)
  166865. {
  166866. JDIMENSION row_ctr;
  166867. if (cinfo->global_state != DSTATE_SCANNING)
  166868. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166869. if (cinfo->output_scanline >= cinfo->output_height) {
  166870. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166871. return 0;
  166872. }
  166873. /* Call progress monitor hook if present */
  166874. if (cinfo->progress != NULL) {
  166875. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166876. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166877. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166878. }
  166879. /* Process some data */
  166880. row_ctr = 0;
  166881. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  166882. cinfo->output_scanline += row_ctr;
  166883. return row_ctr;
  166884. }
  166885. /*
  166886. * Alternate entry point to read raw data.
  166887. * Processes exactly one iMCU row per call, unless suspended.
  166888. */
  166889. GLOBAL(JDIMENSION)
  166890. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  166891. JDIMENSION max_lines)
  166892. {
  166893. JDIMENSION lines_per_iMCU_row;
  166894. if (cinfo->global_state != DSTATE_RAW_OK)
  166895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166896. if (cinfo->output_scanline >= cinfo->output_height) {
  166897. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166898. return 0;
  166899. }
  166900. /* Call progress monitor hook if present */
  166901. if (cinfo->progress != NULL) {
  166902. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166903. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166904. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166905. }
  166906. /* Verify that at least one iMCU row can be returned. */
  166907. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  166908. if (max_lines < lines_per_iMCU_row)
  166909. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  166910. /* Decompress directly into user's buffer. */
  166911. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  166912. return 0; /* suspension forced, can do nothing more */
  166913. /* OK, we processed one iMCU row. */
  166914. cinfo->output_scanline += lines_per_iMCU_row;
  166915. return lines_per_iMCU_row;
  166916. }
  166917. /* Additional entry points for buffered-image mode. */
  166918. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166919. /*
  166920. * Initialize for an output pass in buffered-image mode.
  166921. */
  166922. GLOBAL(boolean)
  166923. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  166924. {
  166925. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  166926. cinfo->global_state != DSTATE_PRESCAN)
  166927. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166928. /* Limit scan number to valid range */
  166929. if (scan_number <= 0)
  166930. scan_number = 1;
  166931. if (cinfo->inputctl->eoi_reached &&
  166932. scan_number > cinfo->input_scan_number)
  166933. scan_number = cinfo->input_scan_number;
  166934. cinfo->output_scan_number = scan_number;
  166935. /* Perform any dummy output passes, and set up for the real pass */
  166936. return output_pass_setup(cinfo);
  166937. }
  166938. /*
  166939. * Finish up after an output pass in buffered-image mode.
  166940. *
  166941. * Returns FALSE if suspended. The return value need be inspected only if
  166942. * a suspending data source is used.
  166943. */
  166944. GLOBAL(boolean)
  166945. jpeg_finish_output (j_decompress_ptr cinfo)
  166946. {
  166947. if ((cinfo->global_state == DSTATE_SCANNING ||
  166948. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  166949. /* Terminate this pass. */
  166950. /* We do not require the whole pass to have been completed. */
  166951. (*cinfo->master->finish_output_pass) (cinfo);
  166952. cinfo->global_state = DSTATE_BUFPOST;
  166953. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  166954. /* BUFPOST = repeat call after a suspension, anything else is error */
  166955. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166956. }
  166957. /* Read markers looking for SOS or EOI */
  166958. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  166959. ! cinfo->inputctl->eoi_reached) {
  166960. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166961. return FALSE; /* Suspend, come back later */
  166962. }
  166963. cinfo->global_state = DSTATE_BUFIMAGE;
  166964. return TRUE;
  166965. }
  166966. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166967. /*** End of inlined file: jdapistd.c ***/
  166968. /*** Start of inlined file: jdapimin.c ***/
  166969. #define JPEG_INTERNALS
  166970. /*
  166971. * Initialization of a JPEG decompression object.
  166972. * The error manager must already be set up (in case memory manager fails).
  166973. */
  166974. GLOBAL(void)
  166975. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  166976. {
  166977. int i;
  166978. /* Guard against version mismatches between library and caller. */
  166979. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  166980. if (version != JPEG_LIB_VERSION)
  166981. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  166982. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  166983. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  166984. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  166985. /* For debugging purposes, we zero the whole master structure.
  166986. * But the application has already set the err pointer, and may have set
  166987. * client_data, so we have to save and restore those fields.
  166988. * Note: if application hasn't set client_data, tools like Purify may
  166989. * complain here.
  166990. */
  166991. {
  166992. struct jpeg_error_mgr * err = cinfo->err;
  166993. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  166994. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  166995. cinfo->err = err;
  166996. cinfo->client_data = client_data;
  166997. }
  166998. cinfo->is_decompressor = TRUE;
  166999. /* Initialize a memory manager instance for this object */
  167000. jinit_memory_mgr((j_common_ptr) cinfo);
  167001. /* Zero out pointers to permanent structures. */
  167002. cinfo->progress = NULL;
  167003. cinfo->src = NULL;
  167004. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167005. cinfo->quant_tbl_ptrs[i] = NULL;
  167006. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167007. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167008. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167009. }
  167010. /* Initialize marker processor so application can override methods
  167011. * for COM, APPn markers before calling jpeg_read_header.
  167012. */
  167013. cinfo->marker_list = NULL;
  167014. jinit_marker_reader(cinfo);
  167015. /* And initialize the overall input controller. */
  167016. jinit_input_controller(cinfo);
  167017. /* OK, I'm ready */
  167018. cinfo->global_state = DSTATE_START;
  167019. }
  167020. /*
  167021. * Destruction of a JPEG decompression object
  167022. */
  167023. GLOBAL(void)
  167024. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167025. {
  167026. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167027. }
  167028. /*
  167029. * Abort processing of a JPEG decompression operation,
  167030. * but don't destroy the object itself.
  167031. */
  167032. GLOBAL(void)
  167033. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167034. {
  167035. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167036. }
  167037. /*
  167038. * Set default decompression parameters.
  167039. */
  167040. LOCAL(void)
  167041. default_decompress_parms (j_decompress_ptr cinfo)
  167042. {
  167043. /* Guess the input colorspace, and set output colorspace accordingly. */
  167044. /* (Wish JPEG committee had provided a real way to specify this...) */
  167045. /* Note application may override our guesses. */
  167046. switch (cinfo->num_components) {
  167047. case 1:
  167048. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167049. cinfo->out_color_space = JCS_GRAYSCALE;
  167050. break;
  167051. case 3:
  167052. if (cinfo->saw_JFIF_marker) {
  167053. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167054. } else if (cinfo->saw_Adobe_marker) {
  167055. switch (cinfo->Adobe_transform) {
  167056. case 0:
  167057. cinfo->jpeg_color_space = JCS_RGB;
  167058. break;
  167059. case 1:
  167060. cinfo->jpeg_color_space = JCS_YCbCr;
  167061. break;
  167062. default:
  167063. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167064. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167065. break;
  167066. }
  167067. } else {
  167068. /* Saw no special markers, try to guess from the component IDs */
  167069. int cid0 = cinfo->comp_info[0].component_id;
  167070. int cid1 = cinfo->comp_info[1].component_id;
  167071. int cid2 = cinfo->comp_info[2].component_id;
  167072. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167073. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167074. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167075. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167076. else {
  167077. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167078. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167079. }
  167080. }
  167081. /* Always guess RGB is proper output colorspace. */
  167082. cinfo->out_color_space = JCS_RGB;
  167083. break;
  167084. case 4:
  167085. if (cinfo->saw_Adobe_marker) {
  167086. switch (cinfo->Adobe_transform) {
  167087. case 0:
  167088. cinfo->jpeg_color_space = JCS_CMYK;
  167089. break;
  167090. case 2:
  167091. cinfo->jpeg_color_space = JCS_YCCK;
  167092. break;
  167093. default:
  167094. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167095. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167096. break;
  167097. }
  167098. } else {
  167099. /* No special markers, assume straight CMYK. */
  167100. cinfo->jpeg_color_space = JCS_CMYK;
  167101. }
  167102. cinfo->out_color_space = JCS_CMYK;
  167103. break;
  167104. default:
  167105. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167106. cinfo->out_color_space = JCS_UNKNOWN;
  167107. break;
  167108. }
  167109. /* Set defaults for other decompression parameters. */
  167110. cinfo->scale_num = 1; /* 1:1 scaling */
  167111. cinfo->scale_denom = 1;
  167112. cinfo->output_gamma = 1.0;
  167113. cinfo->buffered_image = FALSE;
  167114. cinfo->raw_data_out = FALSE;
  167115. cinfo->dct_method = JDCT_DEFAULT;
  167116. cinfo->do_fancy_upsampling = TRUE;
  167117. cinfo->do_block_smoothing = TRUE;
  167118. cinfo->quantize_colors = FALSE;
  167119. /* We set these in case application only sets quantize_colors. */
  167120. cinfo->dither_mode = JDITHER_FS;
  167121. #ifdef QUANT_2PASS_SUPPORTED
  167122. cinfo->two_pass_quantize = TRUE;
  167123. #else
  167124. cinfo->two_pass_quantize = FALSE;
  167125. #endif
  167126. cinfo->desired_number_of_colors = 256;
  167127. cinfo->colormap = NULL;
  167128. /* Initialize for no mode change in buffered-image mode. */
  167129. cinfo->enable_1pass_quant = FALSE;
  167130. cinfo->enable_external_quant = FALSE;
  167131. cinfo->enable_2pass_quant = FALSE;
  167132. }
  167133. /*
  167134. * Decompression startup: read start of JPEG datastream to see what's there.
  167135. * Need only initialize JPEG object and supply a data source before calling.
  167136. *
  167137. * This routine will read as far as the first SOS marker (ie, actual start of
  167138. * compressed data), and will save all tables and parameters in the JPEG
  167139. * object. It will also initialize the decompression parameters to default
  167140. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167141. * adjust the decompression parameters and then call jpeg_start_decompress.
  167142. * (Or, if the application only wanted to determine the image parameters,
  167143. * the data need not be decompressed. In that case, call jpeg_abort or
  167144. * jpeg_destroy to release any temporary space.)
  167145. * If an abbreviated (tables only) datastream is presented, the routine will
  167146. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167147. * re-use the JPEG object to read the abbreviated image datastream(s).
  167148. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167149. * The JPEG_SUSPENDED return code only occurs if the data source module
  167150. * requests suspension of the decompressor. In this case the application
  167151. * should load more source data and then re-call jpeg_read_header to resume
  167152. * processing.
  167153. * If a non-suspending data source is used and require_image is TRUE, then the
  167154. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167155. *
  167156. * This routine is now just a front end to jpeg_consume_input, with some
  167157. * extra error checking.
  167158. */
  167159. GLOBAL(int)
  167160. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167161. {
  167162. int retcode;
  167163. if (cinfo->global_state != DSTATE_START &&
  167164. cinfo->global_state != DSTATE_INHEADER)
  167165. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167166. retcode = jpeg_consume_input(cinfo);
  167167. switch (retcode) {
  167168. case JPEG_REACHED_SOS:
  167169. retcode = JPEG_HEADER_OK;
  167170. break;
  167171. case JPEG_REACHED_EOI:
  167172. if (require_image) /* Complain if application wanted an image */
  167173. ERREXIT(cinfo, JERR_NO_IMAGE);
  167174. /* Reset to start state; it would be safer to require the application to
  167175. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167176. * A side effect is to free any temporary memory (there shouldn't be any).
  167177. */
  167178. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167179. retcode = JPEG_HEADER_TABLES_ONLY;
  167180. break;
  167181. case JPEG_SUSPENDED:
  167182. /* no work */
  167183. break;
  167184. }
  167185. return retcode;
  167186. }
  167187. /*
  167188. * Consume data in advance of what the decompressor requires.
  167189. * This can be called at any time once the decompressor object has
  167190. * been created and a data source has been set up.
  167191. *
  167192. * This routine is essentially a state machine that handles a couple
  167193. * of critical state-transition actions, namely initial setup and
  167194. * transition from header scanning to ready-for-start_decompress.
  167195. * All the actual input is done via the input controller's consume_input
  167196. * method.
  167197. */
  167198. GLOBAL(int)
  167199. jpeg_consume_input (j_decompress_ptr cinfo)
  167200. {
  167201. int retcode = JPEG_SUSPENDED;
  167202. /* NB: every possible DSTATE value should be listed in this switch */
  167203. switch (cinfo->global_state) {
  167204. case DSTATE_START:
  167205. /* Start-of-datastream actions: reset appropriate modules */
  167206. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167207. /* Initialize application's data source module */
  167208. (*cinfo->src->init_source) (cinfo);
  167209. cinfo->global_state = DSTATE_INHEADER;
  167210. /*FALLTHROUGH*/
  167211. case DSTATE_INHEADER:
  167212. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167213. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167214. /* Set up default parameters based on header data */
  167215. default_decompress_parms(cinfo);
  167216. /* Set global state: ready for start_decompress */
  167217. cinfo->global_state = DSTATE_READY;
  167218. }
  167219. break;
  167220. case DSTATE_READY:
  167221. /* Can't advance past first SOS until start_decompress is called */
  167222. retcode = JPEG_REACHED_SOS;
  167223. break;
  167224. case DSTATE_PRELOAD:
  167225. case DSTATE_PRESCAN:
  167226. case DSTATE_SCANNING:
  167227. case DSTATE_RAW_OK:
  167228. case DSTATE_BUFIMAGE:
  167229. case DSTATE_BUFPOST:
  167230. case DSTATE_STOPPING:
  167231. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167232. break;
  167233. default:
  167234. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167235. }
  167236. return retcode;
  167237. }
  167238. /*
  167239. * Have we finished reading the input file?
  167240. */
  167241. GLOBAL(boolean)
  167242. jpeg_input_complete (j_decompress_ptr cinfo)
  167243. {
  167244. /* Check for valid jpeg object */
  167245. if (cinfo->global_state < DSTATE_START ||
  167246. cinfo->global_state > DSTATE_STOPPING)
  167247. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167248. return cinfo->inputctl->eoi_reached;
  167249. }
  167250. /*
  167251. * Is there more than one scan?
  167252. */
  167253. GLOBAL(boolean)
  167254. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167255. {
  167256. /* Only valid after jpeg_read_header completes */
  167257. if (cinfo->global_state < DSTATE_READY ||
  167258. cinfo->global_state > DSTATE_STOPPING)
  167259. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167260. return cinfo->inputctl->has_multiple_scans;
  167261. }
  167262. /*
  167263. * Finish JPEG decompression.
  167264. *
  167265. * This will normally just verify the file trailer and release temp storage.
  167266. *
  167267. * Returns FALSE if suspended. The return value need be inspected only if
  167268. * a suspending data source is used.
  167269. */
  167270. GLOBAL(boolean)
  167271. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167272. {
  167273. if ((cinfo->global_state == DSTATE_SCANNING ||
  167274. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167275. /* Terminate final pass of non-buffered mode */
  167276. if (cinfo->output_scanline < cinfo->output_height)
  167277. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167278. (*cinfo->master->finish_output_pass) (cinfo);
  167279. cinfo->global_state = DSTATE_STOPPING;
  167280. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167281. /* Finishing after a buffered-image operation */
  167282. cinfo->global_state = DSTATE_STOPPING;
  167283. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167284. /* STOPPING = repeat call after a suspension, anything else is error */
  167285. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167286. }
  167287. /* Read until EOI */
  167288. while (! cinfo->inputctl->eoi_reached) {
  167289. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167290. return FALSE; /* Suspend, come back later */
  167291. }
  167292. /* Do final cleanup */
  167293. (*cinfo->src->term_source) (cinfo);
  167294. /* We can use jpeg_abort to release memory and reset global_state */
  167295. jpeg_abort((j_common_ptr) cinfo);
  167296. return TRUE;
  167297. }
  167298. /*** End of inlined file: jdapimin.c ***/
  167299. /*** Start of inlined file: jdatasrc.c ***/
  167300. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167301. /*** Start of inlined file: jerror.h ***/
  167302. /*
  167303. * To define the enum list of message codes, include this file without
  167304. * defining macro JMESSAGE. To create a message string table, include it
  167305. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167306. */
  167307. #ifndef JMESSAGE
  167308. #ifndef JERROR_H
  167309. /* First time through, define the enum list */
  167310. #define JMAKE_ENUM_LIST
  167311. #else
  167312. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167313. #define JMESSAGE(code,string)
  167314. #endif /* JERROR_H */
  167315. #endif /* JMESSAGE */
  167316. #ifdef JMAKE_ENUM_LIST
  167317. typedef enum {
  167318. #define JMESSAGE(code,string) code ,
  167319. #endif /* JMAKE_ENUM_LIST */
  167320. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167321. /* For maintenance convenience, list is alphabetical by message code name */
  167322. JMESSAGE(JERR_ARITH_NOTIMPL,
  167323. "Sorry, there are legal restrictions on arithmetic coding")
  167324. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167325. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167326. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167327. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167328. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167329. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167330. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167331. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167332. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167333. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167334. JMESSAGE(JERR_BAD_LIB_VERSION,
  167335. "Wrong JPEG library version: library is %d, caller expects %d")
  167336. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167337. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167338. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167339. JMESSAGE(JERR_BAD_PROGRESSION,
  167340. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167341. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167342. "Invalid progressive parameters at scan script entry %d")
  167343. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167344. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167345. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167346. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167347. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167348. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167349. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167350. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167351. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167352. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167353. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167354. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167355. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167356. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167357. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167358. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167359. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167360. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167361. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167362. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167363. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167364. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167365. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167366. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167367. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167368. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167369. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167370. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167371. "Cannot transcode due to multiple use of quantization table %d")
  167372. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167373. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167374. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167375. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167376. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167377. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167378. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167379. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167380. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167381. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167382. JMESSAGE(JERR_QUANT_COMPONENTS,
  167383. "Cannot quantize more than %d color components")
  167384. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167385. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167386. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167387. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167388. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167389. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167390. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167391. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167392. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167393. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167394. JMESSAGE(JERR_TFILE_WRITE,
  167395. "Write failed on temporary file --- out of disk space?")
  167396. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167397. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167398. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167399. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167400. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167401. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167402. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167403. JMESSAGE(JMSG_VERSION, JVERSION)
  167404. JMESSAGE(JTRC_16BIT_TABLES,
  167405. "Caution: quantization tables are too coarse for baseline JPEG")
  167406. JMESSAGE(JTRC_ADOBE,
  167407. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167408. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167409. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167410. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167411. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167412. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167413. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167414. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167415. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167416. JMESSAGE(JTRC_EOI, "End Of Image")
  167417. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167418. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167419. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167420. "Warning: thumbnail image size does not match data length %u")
  167421. JMESSAGE(JTRC_JFIF_EXTENSION,
  167422. "JFIF extension marker: type 0x%02x, length %u")
  167423. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167424. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167425. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167426. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167427. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167428. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167429. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167430. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167431. JMESSAGE(JTRC_RST, "RST%d")
  167432. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167433. "Smoothing not supported with nonstandard sampling ratios")
  167434. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167435. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167436. JMESSAGE(JTRC_SOI, "Start of Image")
  167437. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167438. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167439. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167440. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167441. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167442. JMESSAGE(JTRC_THUMB_JPEG,
  167443. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167444. JMESSAGE(JTRC_THUMB_PALETTE,
  167445. "JFIF extension marker: palette thumbnail image, length %u")
  167446. JMESSAGE(JTRC_THUMB_RGB,
  167447. "JFIF extension marker: RGB thumbnail image, length %u")
  167448. JMESSAGE(JTRC_UNKNOWN_IDS,
  167449. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167450. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167451. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167452. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167453. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167454. "Inconsistent progression sequence for component %d coefficient %d")
  167455. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167456. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167457. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167458. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167459. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167460. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167461. JMESSAGE(JWRN_MUST_RESYNC,
  167462. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167463. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167464. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167465. #ifdef JMAKE_ENUM_LIST
  167466. JMSG_LASTMSGCODE
  167467. } J_MESSAGE_CODE;
  167468. #undef JMAKE_ENUM_LIST
  167469. #endif /* JMAKE_ENUM_LIST */
  167470. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167471. #undef JMESSAGE
  167472. #ifndef JERROR_H
  167473. #define JERROR_H
  167474. /* Macros to simplify using the error and trace message stuff */
  167475. /* The first parameter is either type of cinfo pointer */
  167476. /* Fatal errors (print message and exit) */
  167477. #define ERREXIT(cinfo,code) \
  167478. ((cinfo)->err->msg_code = (code), \
  167479. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167480. #define ERREXIT1(cinfo,code,p1) \
  167481. ((cinfo)->err->msg_code = (code), \
  167482. (cinfo)->err->msg_parm.i[0] = (p1), \
  167483. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167484. #define ERREXIT2(cinfo,code,p1,p2) \
  167485. ((cinfo)->err->msg_code = (code), \
  167486. (cinfo)->err->msg_parm.i[0] = (p1), \
  167487. (cinfo)->err->msg_parm.i[1] = (p2), \
  167488. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167489. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167490. ((cinfo)->err->msg_code = (code), \
  167491. (cinfo)->err->msg_parm.i[0] = (p1), \
  167492. (cinfo)->err->msg_parm.i[1] = (p2), \
  167493. (cinfo)->err->msg_parm.i[2] = (p3), \
  167494. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167495. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167496. ((cinfo)->err->msg_code = (code), \
  167497. (cinfo)->err->msg_parm.i[0] = (p1), \
  167498. (cinfo)->err->msg_parm.i[1] = (p2), \
  167499. (cinfo)->err->msg_parm.i[2] = (p3), \
  167500. (cinfo)->err->msg_parm.i[3] = (p4), \
  167501. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167502. #define ERREXITS(cinfo,code,str) \
  167503. ((cinfo)->err->msg_code = (code), \
  167504. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167505. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167506. #define MAKESTMT(stuff) do { stuff } while (0)
  167507. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167508. #define WARNMS(cinfo,code) \
  167509. ((cinfo)->err->msg_code = (code), \
  167510. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167511. #define WARNMS1(cinfo,code,p1) \
  167512. ((cinfo)->err->msg_code = (code), \
  167513. (cinfo)->err->msg_parm.i[0] = (p1), \
  167514. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167515. #define WARNMS2(cinfo,code,p1,p2) \
  167516. ((cinfo)->err->msg_code = (code), \
  167517. (cinfo)->err->msg_parm.i[0] = (p1), \
  167518. (cinfo)->err->msg_parm.i[1] = (p2), \
  167519. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167520. /* Informational/debugging messages */
  167521. #define TRACEMS(cinfo,lvl,code) \
  167522. ((cinfo)->err->msg_code = (code), \
  167523. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167524. #define TRACEMS1(cinfo,lvl,code,p1) \
  167525. ((cinfo)->err->msg_code = (code), \
  167526. (cinfo)->err->msg_parm.i[0] = (p1), \
  167527. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167528. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167529. ((cinfo)->err->msg_code = (code), \
  167530. (cinfo)->err->msg_parm.i[0] = (p1), \
  167531. (cinfo)->err->msg_parm.i[1] = (p2), \
  167532. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167533. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167534. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167535. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167536. (cinfo)->err->msg_code = (code); \
  167537. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167538. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167539. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167540. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167541. (cinfo)->err->msg_code = (code); \
  167542. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167543. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167544. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167545. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167546. _mp[4] = (p5); \
  167547. (cinfo)->err->msg_code = (code); \
  167548. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167549. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167550. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167551. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167552. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167553. (cinfo)->err->msg_code = (code); \
  167554. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167555. #define TRACEMSS(cinfo,lvl,code,str) \
  167556. ((cinfo)->err->msg_code = (code), \
  167557. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167558. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167559. #endif /* JERROR_H */
  167560. /*** End of inlined file: jerror.h ***/
  167561. /* Expanded data source object for stdio input */
  167562. typedef struct {
  167563. struct jpeg_source_mgr pub; /* public fields */
  167564. FILE * infile; /* source stream */
  167565. JOCTET * buffer; /* start of buffer */
  167566. boolean start_of_file; /* have we gotten any data yet? */
  167567. } my_source_mgr;
  167568. typedef my_source_mgr * my_src_ptr;
  167569. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167570. /*
  167571. * Initialize source --- called by jpeg_read_header
  167572. * before any data is actually read.
  167573. */
  167574. METHODDEF(void)
  167575. init_source (j_decompress_ptr cinfo)
  167576. {
  167577. my_src_ptr src = (my_src_ptr) cinfo->src;
  167578. /* We reset the empty-input-file flag for each image,
  167579. * but we don't clear the input buffer.
  167580. * This is correct behavior for reading a series of images from one source.
  167581. */
  167582. src->start_of_file = TRUE;
  167583. }
  167584. /*
  167585. * Fill the input buffer --- called whenever buffer is emptied.
  167586. *
  167587. * In typical applications, this should read fresh data into the buffer
  167588. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167589. * reset the pointer & count to the start of the buffer, and return TRUE
  167590. * indicating that the buffer has been reloaded. It is not necessary to
  167591. * fill the buffer entirely, only to obtain at least one more byte.
  167592. *
  167593. * There is no such thing as an EOF return. If the end of the file has been
  167594. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167595. * the buffer. In most cases, generating a warning message and inserting a
  167596. * fake EOI marker is the best course of action --- this will allow the
  167597. * decompressor to output however much of the image is there. However,
  167598. * the resulting error message is misleading if the real problem is an empty
  167599. * input file, so we handle that case specially.
  167600. *
  167601. * In applications that need to be able to suspend compression due to input
  167602. * not being available yet, a FALSE return indicates that no more data can be
  167603. * obtained right now, but more may be forthcoming later. In this situation,
  167604. * the decompressor will return to its caller (with an indication of the
  167605. * number of scanlines it has read, if any). The application should resume
  167606. * decompression after it has loaded more data into the input buffer. Note
  167607. * that there are substantial restrictions on the use of suspension --- see
  167608. * the documentation.
  167609. *
  167610. * When suspending, the decompressor will back up to a convenient restart point
  167611. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167612. * indicate where the restart point will be if the current call returns FALSE.
  167613. * Data beyond this point must be rescanned after resumption, so move it to
  167614. * the front of the buffer rather than discarding it.
  167615. */
  167616. METHODDEF(boolean)
  167617. fill_input_buffer (j_decompress_ptr cinfo)
  167618. {
  167619. my_src_ptr src = (my_src_ptr) cinfo->src;
  167620. size_t nbytes;
  167621. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167622. if (nbytes <= 0) {
  167623. if (src->start_of_file) /* Treat empty input file as fatal error */
  167624. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167625. WARNMS(cinfo, JWRN_JPEG_EOF);
  167626. /* Insert a fake EOI marker */
  167627. src->buffer[0] = (JOCTET) 0xFF;
  167628. src->buffer[1] = (JOCTET) JPEG_EOI;
  167629. nbytes = 2;
  167630. }
  167631. src->pub.next_input_byte = src->buffer;
  167632. src->pub.bytes_in_buffer = nbytes;
  167633. src->start_of_file = FALSE;
  167634. return TRUE;
  167635. }
  167636. /*
  167637. * Skip data --- used to skip over a potentially large amount of
  167638. * uninteresting data (such as an APPn marker).
  167639. *
  167640. * Writers of suspendable-input applications must note that skip_input_data
  167641. * is not granted the right to give a suspension return. If the skip extends
  167642. * beyond the data currently in the buffer, the buffer can be marked empty so
  167643. * that the next read will cause a fill_input_buffer call that can suspend.
  167644. * Arranging for additional bytes to be discarded before reloading the input
  167645. * buffer is the application writer's problem.
  167646. */
  167647. METHODDEF(void)
  167648. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167649. {
  167650. my_src_ptr src = (my_src_ptr) cinfo->src;
  167651. /* Just a dumb implementation for now. Could use fseek() except
  167652. * it doesn't work on pipes. Not clear that being smart is worth
  167653. * any trouble anyway --- large skips are infrequent.
  167654. */
  167655. if (num_bytes > 0) {
  167656. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167657. num_bytes -= (long) src->pub.bytes_in_buffer;
  167658. (void) fill_input_buffer(cinfo);
  167659. /* note we assume that fill_input_buffer will never return FALSE,
  167660. * so suspension need not be handled.
  167661. */
  167662. }
  167663. src->pub.next_input_byte += (size_t) num_bytes;
  167664. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167665. }
  167666. }
  167667. /*
  167668. * An additional method that can be provided by data source modules is the
  167669. * resync_to_restart method for error recovery in the presence of RST markers.
  167670. * For the moment, this source module just uses the default resync method
  167671. * provided by the JPEG library. That method assumes that no backtracking
  167672. * is possible.
  167673. */
  167674. /*
  167675. * Terminate source --- called by jpeg_finish_decompress
  167676. * after all data has been read. Often a no-op.
  167677. *
  167678. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167679. * application must deal with any cleanup that should happen even
  167680. * for error exit.
  167681. */
  167682. METHODDEF(void)
  167683. term_source (j_decompress_ptr)
  167684. {
  167685. /* no work necessary here */
  167686. }
  167687. /*
  167688. * Prepare for input from a stdio stream.
  167689. * The caller must have already opened the stream, and is responsible
  167690. * for closing it after finishing decompression.
  167691. */
  167692. GLOBAL(void)
  167693. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167694. {
  167695. my_src_ptr src;
  167696. /* The source object and input buffer are made permanent so that a series
  167697. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167698. * only before the first one. (If we discarded the buffer at the end of
  167699. * one image, we'd likely lose the start of the next one.)
  167700. * This makes it unsafe to use this manager and a different source
  167701. * manager serially with the same JPEG object. Caveat programmer.
  167702. */
  167703. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167704. cinfo->src = (struct jpeg_source_mgr *)
  167705. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167706. SIZEOF(my_source_mgr));
  167707. src = (my_src_ptr) cinfo->src;
  167708. src->buffer = (JOCTET *)
  167709. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167710. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167711. }
  167712. src = (my_src_ptr) cinfo->src;
  167713. src->pub.init_source = init_source;
  167714. src->pub.fill_input_buffer = fill_input_buffer;
  167715. src->pub.skip_input_data = skip_input_data;
  167716. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167717. src->pub.term_source = term_source;
  167718. src->infile = infile;
  167719. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167720. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167721. }
  167722. /*** End of inlined file: jdatasrc.c ***/
  167723. /*** Start of inlined file: jdcoefct.c ***/
  167724. #define JPEG_INTERNALS
  167725. /* Block smoothing is only applicable for progressive JPEG, so: */
  167726. #ifndef D_PROGRESSIVE_SUPPORTED
  167727. #undef BLOCK_SMOOTHING_SUPPORTED
  167728. #endif
  167729. /* Private buffer controller object */
  167730. typedef struct {
  167731. struct jpeg_d_coef_controller pub; /* public fields */
  167732. /* These variables keep track of the current location of the input side. */
  167733. /* cinfo->input_iMCU_row is also used for this. */
  167734. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167735. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167736. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167737. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167738. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167739. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167740. * and let the entropy decoder write into that workspace each time.
  167741. * (On 80x86, the workspace is FAR even though it's not really very big;
  167742. * this is to keep the module interfaces unchanged when a large coefficient
  167743. * buffer is necessary.)
  167744. * In multi-pass modes, this array points to the current MCU's blocks
  167745. * within the virtual arrays; it is used only by the input side.
  167746. */
  167747. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167748. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167749. /* In multi-pass modes, we need a virtual block array for each component. */
  167750. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167751. #endif
  167752. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167753. /* When doing block smoothing, we latch coefficient Al values here */
  167754. int * coef_bits_latch;
  167755. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167756. #endif
  167757. } my_coef_controller3;
  167758. typedef my_coef_controller3 * my_coef_ptr3;
  167759. /* Forward declarations */
  167760. METHODDEF(int) decompress_onepass
  167761. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167762. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167763. METHODDEF(int) decompress_data
  167764. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167765. #endif
  167766. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167767. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167768. METHODDEF(int) decompress_smooth_data
  167769. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167770. #endif
  167771. LOCAL(void)
  167772. start_iMCU_row3 (j_decompress_ptr cinfo)
  167773. /* Reset within-iMCU-row counters for a new row (input side) */
  167774. {
  167775. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167776. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167777. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167778. * But at the bottom of the image, process only what's left.
  167779. */
  167780. if (cinfo->comps_in_scan > 1) {
  167781. coef->MCU_rows_per_iMCU_row = 1;
  167782. } else {
  167783. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167784. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167785. else
  167786. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167787. }
  167788. coef->MCU_ctr = 0;
  167789. coef->MCU_vert_offset = 0;
  167790. }
  167791. /*
  167792. * Initialize for an input processing pass.
  167793. */
  167794. METHODDEF(void)
  167795. start_input_pass (j_decompress_ptr cinfo)
  167796. {
  167797. cinfo->input_iMCU_row = 0;
  167798. start_iMCU_row3(cinfo);
  167799. }
  167800. /*
  167801. * Initialize for an output processing pass.
  167802. */
  167803. METHODDEF(void)
  167804. start_output_pass (j_decompress_ptr cinfo)
  167805. {
  167806. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167807. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167808. /* If multipass, check to see whether to use block smoothing on this pass */
  167809. if (coef->pub.coef_arrays != NULL) {
  167810. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167811. coef->pub.decompress_data = decompress_smooth_data;
  167812. else
  167813. coef->pub.decompress_data = decompress_data;
  167814. }
  167815. #endif
  167816. cinfo->output_iMCU_row = 0;
  167817. }
  167818. /*
  167819. * Decompress and return some data in the single-pass case.
  167820. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167821. * Input and output must run in lockstep since we have only a one-MCU buffer.
  167822. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167823. *
  167824. * NB: output_buf contains a plane for each component in image,
  167825. * which we index according to the component's SOF position.
  167826. */
  167827. METHODDEF(int)
  167828. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167829. {
  167830. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167831. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167832. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167833. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167834. int blkn, ci, xindex, yindex, yoffset, useful_width;
  167835. JSAMPARRAY output_ptr;
  167836. JDIMENSION start_col, output_col;
  167837. jpeg_component_info *compptr;
  167838. inverse_DCT_method_ptr inverse_DCT;
  167839. /* Loop to process as much as one whole iMCU row */
  167840. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167841. yoffset++) {
  167842. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  167843. MCU_col_num++) {
  167844. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  167845. jzero_far((void FAR *) coef->MCU_buffer[0],
  167846. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  167847. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167848. /* Suspension forced; update state counters and exit */
  167849. coef->MCU_vert_offset = yoffset;
  167850. coef->MCU_ctr = MCU_col_num;
  167851. return JPEG_SUSPENDED;
  167852. }
  167853. /* Determine where data should go in output_buf and do the IDCT thing.
  167854. * We skip dummy blocks at the right and bottom edges (but blkn gets
  167855. * incremented past them!). Note the inner loop relies on having
  167856. * allocated the MCU_buffer[] blocks sequentially.
  167857. */
  167858. blkn = 0; /* index of current DCT block within MCU */
  167859. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167860. compptr = cinfo->cur_comp_info[ci];
  167861. /* Don't bother to IDCT an uninteresting component. */
  167862. if (! compptr->component_needed) {
  167863. blkn += compptr->MCU_blocks;
  167864. continue;
  167865. }
  167866. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  167867. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167868. : compptr->last_col_width;
  167869. output_ptr = output_buf[compptr->component_index] +
  167870. yoffset * compptr->DCT_scaled_size;
  167871. start_col = MCU_col_num * compptr->MCU_sample_width;
  167872. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167873. if (cinfo->input_iMCU_row < last_iMCU_row ||
  167874. yoffset+yindex < compptr->last_row_height) {
  167875. output_col = start_col;
  167876. for (xindex = 0; xindex < useful_width; xindex++) {
  167877. (*inverse_DCT) (cinfo, compptr,
  167878. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  167879. output_ptr, output_col);
  167880. output_col += compptr->DCT_scaled_size;
  167881. }
  167882. }
  167883. blkn += compptr->MCU_width;
  167884. output_ptr += compptr->DCT_scaled_size;
  167885. }
  167886. }
  167887. }
  167888. /* Completed an MCU row, but perhaps not an iMCU row */
  167889. coef->MCU_ctr = 0;
  167890. }
  167891. /* Completed the iMCU row, advance counters for next one */
  167892. cinfo->output_iMCU_row++;
  167893. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167894. start_iMCU_row3(cinfo);
  167895. return JPEG_ROW_COMPLETED;
  167896. }
  167897. /* Completed the scan */
  167898. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167899. return JPEG_SCAN_COMPLETED;
  167900. }
  167901. /*
  167902. * Dummy consume-input routine for single-pass operation.
  167903. */
  167904. METHODDEF(int)
  167905. dummy_consume_data (j_decompress_ptr)
  167906. {
  167907. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  167908. }
  167909. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167910. /*
  167911. * Consume input data and store it in the full-image coefficient buffer.
  167912. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  167913. * ie, v_samp_factor block rows for each component in the scan.
  167914. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167915. */
  167916. METHODDEF(int)
  167917. consume_data (j_decompress_ptr cinfo)
  167918. {
  167919. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167920. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167921. int blkn, ci, xindex, yindex, yoffset;
  167922. JDIMENSION start_col;
  167923. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167924. JBLOCKROW buffer_ptr;
  167925. jpeg_component_info *compptr;
  167926. /* Align the virtual buffers for the components used in this scan. */
  167927. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167928. compptr = cinfo->cur_comp_info[ci];
  167929. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167930. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167931. cinfo->input_iMCU_row * compptr->v_samp_factor,
  167932. (JDIMENSION) compptr->v_samp_factor, TRUE);
  167933. /* Note: entropy decoder expects buffer to be zeroed,
  167934. * but this is handled automatically by the memory manager
  167935. * because we requested a pre-zeroed array.
  167936. */
  167937. }
  167938. /* Loop to process one whole iMCU row */
  167939. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167940. yoffset++) {
  167941. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167942. MCU_col_num++) {
  167943. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167944. blkn = 0; /* index of current DCT block within MCU */
  167945. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167946. compptr = cinfo->cur_comp_info[ci];
  167947. start_col = MCU_col_num * compptr->MCU_width;
  167948. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167949. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167950. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  167951. coef->MCU_buffer[blkn++] = buffer_ptr++;
  167952. }
  167953. }
  167954. }
  167955. /* Try to fetch the MCU. */
  167956. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167957. /* Suspension forced; update state counters and exit */
  167958. coef->MCU_vert_offset = yoffset;
  167959. coef->MCU_ctr = MCU_col_num;
  167960. return JPEG_SUSPENDED;
  167961. }
  167962. }
  167963. /* Completed an MCU row, but perhaps not an iMCU row */
  167964. coef->MCU_ctr = 0;
  167965. }
  167966. /* Completed the iMCU row, advance counters for next one */
  167967. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167968. start_iMCU_row3(cinfo);
  167969. return JPEG_ROW_COMPLETED;
  167970. }
  167971. /* Completed the scan */
  167972. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167973. return JPEG_SCAN_COMPLETED;
  167974. }
  167975. /*
  167976. * Decompress and return some data in the multi-pass case.
  167977. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167978. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167979. *
  167980. * NB: output_buf contains a plane for each component in image.
  167981. */
  167982. METHODDEF(int)
  167983. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167984. {
  167985. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167986. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167987. JDIMENSION block_num;
  167988. int ci, block_row, block_rows;
  167989. JBLOCKARRAY buffer;
  167990. JBLOCKROW buffer_ptr;
  167991. JSAMPARRAY output_ptr;
  167992. JDIMENSION output_col;
  167993. jpeg_component_info *compptr;
  167994. inverse_DCT_method_ptr inverse_DCT;
  167995. /* Force some input to be done if we are getting ahead of the input. */
  167996. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  167997. (cinfo->input_scan_number == cinfo->output_scan_number &&
  167998. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  167999. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168000. return JPEG_SUSPENDED;
  168001. }
  168002. /* OK, output from the virtual arrays. */
  168003. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168004. ci++, compptr++) {
  168005. /* Don't bother to IDCT an uninteresting component. */
  168006. if (! compptr->component_needed)
  168007. continue;
  168008. /* Align the virtual buffer for this component. */
  168009. buffer = (*cinfo->mem->access_virt_barray)
  168010. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168011. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168012. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168013. /* Count non-dummy DCT block rows in this iMCU row. */
  168014. if (cinfo->output_iMCU_row < last_iMCU_row)
  168015. block_rows = compptr->v_samp_factor;
  168016. else {
  168017. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168018. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168019. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168020. }
  168021. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168022. output_ptr = output_buf[ci];
  168023. /* Loop over all DCT blocks to be processed. */
  168024. for (block_row = 0; block_row < block_rows; block_row++) {
  168025. buffer_ptr = buffer[block_row];
  168026. output_col = 0;
  168027. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168028. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168029. output_ptr, output_col);
  168030. buffer_ptr++;
  168031. output_col += compptr->DCT_scaled_size;
  168032. }
  168033. output_ptr += compptr->DCT_scaled_size;
  168034. }
  168035. }
  168036. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168037. return JPEG_ROW_COMPLETED;
  168038. return JPEG_SCAN_COMPLETED;
  168039. }
  168040. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168041. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168042. /*
  168043. * This code applies interblock smoothing as described by section K.8
  168044. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168045. * the DC values of a DCT block and its 8 neighboring blocks.
  168046. * We apply smoothing only for progressive JPEG decoding, and only if
  168047. * the coefficients it can estimate are not yet known to full precision.
  168048. */
  168049. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168050. #define Q01_POS 1
  168051. #define Q10_POS 8
  168052. #define Q20_POS 16
  168053. #define Q11_POS 9
  168054. #define Q02_POS 2
  168055. /*
  168056. * Determine whether block smoothing is applicable and safe.
  168057. * We also latch the current states of the coef_bits[] entries for the
  168058. * AC coefficients; otherwise, if the input side of the decompressor
  168059. * advances into a new scan, we might think the coefficients are known
  168060. * more accurately than they really are.
  168061. */
  168062. LOCAL(boolean)
  168063. smoothing_ok (j_decompress_ptr cinfo)
  168064. {
  168065. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168066. boolean smoothing_useful = FALSE;
  168067. int ci, coefi;
  168068. jpeg_component_info *compptr;
  168069. JQUANT_TBL * qtable;
  168070. int * coef_bits;
  168071. int * coef_bits_latch;
  168072. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168073. return FALSE;
  168074. /* Allocate latch area if not already done */
  168075. if (coef->coef_bits_latch == NULL)
  168076. coef->coef_bits_latch = (int *)
  168077. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168078. cinfo->num_components *
  168079. (SAVED_COEFS * SIZEOF(int)));
  168080. coef_bits_latch = coef->coef_bits_latch;
  168081. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168082. ci++, compptr++) {
  168083. /* All components' quantization values must already be latched. */
  168084. if ((qtable = compptr->quant_table) == NULL)
  168085. return FALSE;
  168086. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168087. if (qtable->quantval[0] == 0 ||
  168088. qtable->quantval[Q01_POS] == 0 ||
  168089. qtable->quantval[Q10_POS] == 0 ||
  168090. qtable->quantval[Q20_POS] == 0 ||
  168091. qtable->quantval[Q11_POS] == 0 ||
  168092. qtable->quantval[Q02_POS] == 0)
  168093. return FALSE;
  168094. /* DC values must be at least partly known for all components. */
  168095. coef_bits = cinfo->coef_bits[ci];
  168096. if (coef_bits[0] < 0)
  168097. return FALSE;
  168098. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168099. for (coefi = 1; coefi <= 5; coefi++) {
  168100. coef_bits_latch[coefi] = coef_bits[coefi];
  168101. if (coef_bits[coefi] != 0)
  168102. smoothing_useful = TRUE;
  168103. }
  168104. coef_bits_latch += SAVED_COEFS;
  168105. }
  168106. return smoothing_useful;
  168107. }
  168108. /*
  168109. * Variant of decompress_data for use when doing block smoothing.
  168110. */
  168111. METHODDEF(int)
  168112. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168113. {
  168114. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168115. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168116. JDIMENSION block_num, last_block_column;
  168117. int ci, block_row, block_rows, access_rows;
  168118. JBLOCKARRAY buffer;
  168119. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168120. JSAMPARRAY output_ptr;
  168121. JDIMENSION output_col;
  168122. jpeg_component_info *compptr;
  168123. inverse_DCT_method_ptr inverse_DCT;
  168124. boolean first_row, last_row;
  168125. JBLOCK workspace;
  168126. int *coef_bits;
  168127. JQUANT_TBL *quanttbl;
  168128. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168129. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168130. int Al, pred;
  168131. /* Force some input to be done if we are getting ahead of the input. */
  168132. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168133. ! cinfo->inputctl->eoi_reached) {
  168134. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168135. /* If input is working on current scan, we ordinarily want it to
  168136. * have completed the current row. But if input scan is DC,
  168137. * we want it to keep one row ahead so that next block row's DC
  168138. * values are up to date.
  168139. */
  168140. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168141. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168142. break;
  168143. }
  168144. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168145. return JPEG_SUSPENDED;
  168146. }
  168147. /* OK, output from the virtual arrays. */
  168148. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168149. ci++, compptr++) {
  168150. /* Don't bother to IDCT an uninteresting component. */
  168151. if (! compptr->component_needed)
  168152. continue;
  168153. /* Count non-dummy DCT block rows in this iMCU row. */
  168154. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168155. block_rows = compptr->v_samp_factor;
  168156. access_rows = block_rows * 2; /* this and next iMCU row */
  168157. last_row = FALSE;
  168158. } else {
  168159. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168160. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168161. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168162. access_rows = block_rows; /* this iMCU row only */
  168163. last_row = TRUE;
  168164. }
  168165. /* Align the virtual buffer for this component. */
  168166. if (cinfo->output_iMCU_row > 0) {
  168167. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168168. buffer = (*cinfo->mem->access_virt_barray)
  168169. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168170. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168171. (JDIMENSION) access_rows, FALSE);
  168172. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168173. first_row = FALSE;
  168174. } else {
  168175. buffer = (*cinfo->mem->access_virt_barray)
  168176. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168177. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168178. first_row = TRUE;
  168179. }
  168180. /* Fetch component-dependent info */
  168181. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168182. quanttbl = compptr->quant_table;
  168183. Q00 = quanttbl->quantval[0];
  168184. Q01 = quanttbl->quantval[Q01_POS];
  168185. Q10 = quanttbl->quantval[Q10_POS];
  168186. Q20 = quanttbl->quantval[Q20_POS];
  168187. Q11 = quanttbl->quantval[Q11_POS];
  168188. Q02 = quanttbl->quantval[Q02_POS];
  168189. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168190. output_ptr = output_buf[ci];
  168191. /* Loop over all DCT blocks to be processed. */
  168192. for (block_row = 0; block_row < block_rows; block_row++) {
  168193. buffer_ptr = buffer[block_row];
  168194. if (first_row && block_row == 0)
  168195. prev_block_row = buffer_ptr;
  168196. else
  168197. prev_block_row = buffer[block_row-1];
  168198. if (last_row && block_row == block_rows-1)
  168199. next_block_row = buffer_ptr;
  168200. else
  168201. next_block_row = buffer[block_row+1];
  168202. /* We fetch the surrounding DC values using a sliding-register approach.
  168203. * Initialize all nine here so as to do the right thing on narrow pics.
  168204. */
  168205. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168206. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168207. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168208. output_col = 0;
  168209. last_block_column = compptr->width_in_blocks - 1;
  168210. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168211. /* Fetch current DCT block into workspace so we can modify it. */
  168212. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168213. /* Update DC values */
  168214. if (block_num < last_block_column) {
  168215. DC3 = (int) prev_block_row[1][0];
  168216. DC6 = (int) buffer_ptr[1][0];
  168217. DC9 = (int) next_block_row[1][0];
  168218. }
  168219. /* Compute coefficient estimates per K.8.
  168220. * An estimate is applied only if coefficient is still zero,
  168221. * and is not known to be fully accurate.
  168222. */
  168223. /* AC01 */
  168224. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168225. num = 36 * Q00 * (DC4 - DC6);
  168226. if (num >= 0) {
  168227. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168228. if (Al > 0 && pred >= (1<<Al))
  168229. pred = (1<<Al)-1;
  168230. } else {
  168231. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168232. if (Al > 0 && pred >= (1<<Al))
  168233. pred = (1<<Al)-1;
  168234. pred = -pred;
  168235. }
  168236. workspace[1] = (JCOEF) pred;
  168237. }
  168238. /* AC10 */
  168239. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168240. num = 36 * Q00 * (DC2 - DC8);
  168241. if (num >= 0) {
  168242. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168243. if (Al > 0 && pred >= (1<<Al))
  168244. pred = (1<<Al)-1;
  168245. } else {
  168246. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168247. if (Al > 0 && pred >= (1<<Al))
  168248. pred = (1<<Al)-1;
  168249. pred = -pred;
  168250. }
  168251. workspace[8] = (JCOEF) pred;
  168252. }
  168253. /* AC20 */
  168254. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168255. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168256. if (num >= 0) {
  168257. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168258. if (Al > 0 && pred >= (1<<Al))
  168259. pred = (1<<Al)-1;
  168260. } else {
  168261. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168262. if (Al > 0 && pred >= (1<<Al))
  168263. pred = (1<<Al)-1;
  168264. pred = -pred;
  168265. }
  168266. workspace[16] = (JCOEF) pred;
  168267. }
  168268. /* AC11 */
  168269. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168270. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168271. if (num >= 0) {
  168272. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168273. if (Al > 0 && pred >= (1<<Al))
  168274. pred = (1<<Al)-1;
  168275. } else {
  168276. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168277. if (Al > 0 && pred >= (1<<Al))
  168278. pred = (1<<Al)-1;
  168279. pred = -pred;
  168280. }
  168281. workspace[9] = (JCOEF) pred;
  168282. }
  168283. /* AC02 */
  168284. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168285. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168286. if (num >= 0) {
  168287. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168288. if (Al > 0 && pred >= (1<<Al))
  168289. pred = (1<<Al)-1;
  168290. } else {
  168291. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168292. if (Al > 0 && pred >= (1<<Al))
  168293. pred = (1<<Al)-1;
  168294. pred = -pred;
  168295. }
  168296. workspace[2] = (JCOEF) pred;
  168297. }
  168298. /* OK, do the IDCT */
  168299. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168300. output_ptr, output_col);
  168301. /* Advance for next column */
  168302. DC1 = DC2; DC2 = DC3;
  168303. DC4 = DC5; DC5 = DC6;
  168304. DC7 = DC8; DC8 = DC9;
  168305. buffer_ptr++, prev_block_row++, next_block_row++;
  168306. output_col += compptr->DCT_scaled_size;
  168307. }
  168308. output_ptr += compptr->DCT_scaled_size;
  168309. }
  168310. }
  168311. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168312. return JPEG_ROW_COMPLETED;
  168313. return JPEG_SCAN_COMPLETED;
  168314. }
  168315. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168316. /*
  168317. * Initialize coefficient buffer controller.
  168318. */
  168319. GLOBAL(void)
  168320. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168321. {
  168322. my_coef_ptr3 coef;
  168323. coef = (my_coef_ptr3)
  168324. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168325. SIZEOF(my_coef_controller3));
  168326. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168327. coef->pub.start_input_pass = start_input_pass;
  168328. coef->pub.start_output_pass = start_output_pass;
  168329. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168330. coef->coef_bits_latch = NULL;
  168331. #endif
  168332. /* Create the coefficient buffer. */
  168333. if (need_full_buffer) {
  168334. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168335. /* Allocate a full-image virtual array for each component, */
  168336. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168337. /* Note we ask for a pre-zeroed array. */
  168338. int ci, access_rows;
  168339. jpeg_component_info *compptr;
  168340. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168341. ci++, compptr++) {
  168342. access_rows = compptr->v_samp_factor;
  168343. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168344. /* If block smoothing could be used, need a bigger window */
  168345. if (cinfo->progressive_mode)
  168346. access_rows *= 3;
  168347. #endif
  168348. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168349. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168350. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168351. (long) compptr->h_samp_factor),
  168352. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168353. (long) compptr->v_samp_factor),
  168354. (JDIMENSION) access_rows);
  168355. }
  168356. coef->pub.consume_data = consume_data;
  168357. coef->pub.decompress_data = decompress_data;
  168358. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168359. #else
  168360. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168361. #endif
  168362. } else {
  168363. /* We only need a single-MCU buffer. */
  168364. JBLOCKROW buffer;
  168365. int i;
  168366. buffer = (JBLOCKROW)
  168367. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168368. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168369. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168370. coef->MCU_buffer[i] = buffer + i;
  168371. }
  168372. coef->pub.consume_data = dummy_consume_data;
  168373. coef->pub.decompress_data = decompress_onepass;
  168374. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168375. }
  168376. }
  168377. /*** End of inlined file: jdcoefct.c ***/
  168378. #undef FIX
  168379. /*** Start of inlined file: jdcolor.c ***/
  168380. #define JPEG_INTERNALS
  168381. /* Private subobject */
  168382. typedef struct {
  168383. struct jpeg_color_deconverter pub; /* public fields */
  168384. /* Private state for YCC->RGB conversion */
  168385. int * Cr_r_tab; /* => table for Cr to R conversion */
  168386. int * Cb_b_tab; /* => table for Cb to B conversion */
  168387. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168388. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168389. } my_color_deconverter2;
  168390. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168391. /**************** YCbCr -> RGB conversion: most common case **************/
  168392. /*
  168393. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168394. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168395. * The conversion equations to be implemented are therefore
  168396. * R = Y + 1.40200 * Cr
  168397. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168398. * B = Y + 1.77200 * Cb
  168399. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168400. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168401. *
  168402. * To avoid floating-point arithmetic, we represent the fractional constants
  168403. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168404. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168405. * Notice that Y, being an integral input, does not contribute any fraction
  168406. * so it need not participate in the rounding.
  168407. *
  168408. * For even more speed, we avoid doing any multiplications in the inner loop
  168409. * by precalculating the constants times Cb and Cr for all possible values.
  168410. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168411. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168412. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168413. * colorspace anyway.
  168414. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168415. * values for the G calculation are left scaled up, since we must add them
  168416. * together before rounding.
  168417. */
  168418. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168419. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168420. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168421. /*
  168422. * Initialize tables for YCC->RGB colorspace conversion.
  168423. */
  168424. LOCAL(void)
  168425. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168426. {
  168427. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168428. int i;
  168429. INT32 x;
  168430. SHIFT_TEMPS
  168431. cconvert->Cr_r_tab = (int *)
  168432. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168433. (MAXJSAMPLE+1) * SIZEOF(int));
  168434. cconvert->Cb_b_tab = (int *)
  168435. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168436. (MAXJSAMPLE+1) * SIZEOF(int));
  168437. cconvert->Cr_g_tab = (INT32 *)
  168438. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168439. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168440. cconvert->Cb_g_tab = (INT32 *)
  168441. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168442. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168443. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168444. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168445. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168446. /* Cr=>R value is nearest int to 1.40200 * x */
  168447. cconvert->Cr_r_tab[i] = (int)
  168448. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168449. /* Cb=>B value is nearest int to 1.77200 * x */
  168450. cconvert->Cb_b_tab[i] = (int)
  168451. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168452. /* Cr=>G value is scaled-up -0.71414 * x */
  168453. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168454. /* Cb=>G value is scaled-up -0.34414 * x */
  168455. /* We also add in ONE_HALF so that need not do it in inner loop */
  168456. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168457. }
  168458. }
  168459. /*
  168460. * Convert some rows of samples to the output colorspace.
  168461. *
  168462. * Note that we change from noninterleaved, one-plane-per-component format
  168463. * to interleaved-pixel format. The output buffer is therefore three times
  168464. * as wide as the input buffer.
  168465. * A starting row offset is provided only for the input buffer. The caller
  168466. * can easily adjust the passed output_buf value to accommodate any row
  168467. * offset required on that side.
  168468. */
  168469. METHODDEF(void)
  168470. ycc_rgb_convert (j_decompress_ptr cinfo,
  168471. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168472. JSAMPARRAY output_buf, int num_rows)
  168473. {
  168474. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168475. register int y, cb, cr;
  168476. register JSAMPROW outptr;
  168477. register JSAMPROW inptr0, inptr1, inptr2;
  168478. register JDIMENSION col;
  168479. JDIMENSION num_cols = cinfo->output_width;
  168480. /* copy these pointers into registers if possible */
  168481. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168482. register int * Crrtab = cconvert->Cr_r_tab;
  168483. register int * Cbbtab = cconvert->Cb_b_tab;
  168484. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168485. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168486. SHIFT_TEMPS
  168487. while (--num_rows >= 0) {
  168488. inptr0 = input_buf[0][input_row];
  168489. inptr1 = input_buf[1][input_row];
  168490. inptr2 = input_buf[2][input_row];
  168491. input_row++;
  168492. outptr = *output_buf++;
  168493. for (col = 0; col < num_cols; col++) {
  168494. y = GETJSAMPLE(inptr0[col]);
  168495. cb = GETJSAMPLE(inptr1[col]);
  168496. cr = GETJSAMPLE(inptr2[col]);
  168497. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168498. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168499. outptr[RGB_GREEN] = range_limit[y +
  168500. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168501. SCALEBITS))];
  168502. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168503. outptr += RGB_PIXELSIZE;
  168504. }
  168505. }
  168506. }
  168507. /**************** Cases other than YCbCr -> RGB **************/
  168508. /*
  168509. * Color conversion for no colorspace change: just copy the data,
  168510. * converting from separate-planes to interleaved representation.
  168511. */
  168512. METHODDEF(void)
  168513. null_convert2 (j_decompress_ptr cinfo,
  168514. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168515. JSAMPARRAY output_buf, int num_rows)
  168516. {
  168517. register JSAMPROW inptr, outptr;
  168518. register JDIMENSION count;
  168519. register int num_components = cinfo->num_components;
  168520. JDIMENSION num_cols = cinfo->output_width;
  168521. int ci;
  168522. while (--num_rows >= 0) {
  168523. for (ci = 0; ci < num_components; ci++) {
  168524. inptr = input_buf[ci][input_row];
  168525. outptr = output_buf[0] + ci;
  168526. for (count = num_cols; count > 0; count--) {
  168527. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168528. outptr += num_components;
  168529. }
  168530. }
  168531. input_row++;
  168532. output_buf++;
  168533. }
  168534. }
  168535. /*
  168536. * Color conversion for grayscale: just copy the data.
  168537. * This also works for YCbCr -> grayscale conversion, in which
  168538. * we just copy the Y (luminance) component and ignore chrominance.
  168539. */
  168540. METHODDEF(void)
  168541. grayscale_convert2 (j_decompress_ptr cinfo,
  168542. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168543. JSAMPARRAY output_buf, int num_rows)
  168544. {
  168545. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168546. num_rows, cinfo->output_width);
  168547. }
  168548. /*
  168549. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168550. * This is provided to support applications that don't want to cope
  168551. * with grayscale as a separate case.
  168552. */
  168553. METHODDEF(void)
  168554. gray_rgb_convert (j_decompress_ptr cinfo,
  168555. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168556. JSAMPARRAY output_buf, int num_rows)
  168557. {
  168558. register JSAMPROW inptr, outptr;
  168559. register JDIMENSION col;
  168560. JDIMENSION num_cols = cinfo->output_width;
  168561. while (--num_rows >= 0) {
  168562. inptr = input_buf[0][input_row++];
  168563. outptr = *output_buf++;
  168564. for (col = 0; col < num_cols; col++) {
  168565. /* We can dispense with GETJSAMPLE() here */
  168566. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168567. outptr += RGB_PIXELSIZE;
  168568. }
  168569. }
  168570. }
  168571. /*
  168572. * Adobe-style YCCK->CMYK conversion.
  168573. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168574. * conversion as above, while passing K (black) unchanged.
  168575. * We assume build_ycc_rgb_table has been called.
  168576. */
  168577. METHODDEF(void)
  168578. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168579. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168580. JSAMPARRAY output_buf, int num_rows)
  168581. {
  168582. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168583. register int y, cb, cr;
  168584. register JSAMPROW outptr;
  168585. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168586. register JDIMENSION col;
  168587. JDIMENSION num_cols = cinfo->output_width;
  168588. /* copy these pointers into registers if possible */
  168589. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168590. register int * Crrtab = cconvert->Cr_r_tab;
  168591. register int * Cbbtab = cconvert->Cb_b_tab;
  168592. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168593. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168594. SHIFT_TEMPS
  168595. while (--num_rows >= 0) {
  168596. inptr0 = input_buf[0][input_row];
  168597. inptr1 = input_buf[1][input_row];
  168598. inptr2 = input_buf[2][input_row];
  168599. inptr3 = input_buf[3][input_row];
  168600. input_row++;
  168601. outptr = *output_buf++;
  168602. for (col = 0; col < num_cols; col++) {
  168603. y = GETJSAMPLE(inptr0[col]);
  168604. cb = GETJSAMPLE(inptr1[col]);
  168605. cr = GETJSAMPLE(inptr2[col]);
  168606. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168607. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168608. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168609. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168610. SCALEBITS)))];
  168611. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168612. /* K passes through unchanged */
  168613. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168614. outptr += 4;
  168615. }
  168616. }
  168617. }
  168618. /*
  168619. * Empty method for start_pass.
  168620. */
  168621. METHODDEF(void)
  168622. start_pass_dcolor (j_decompress_ptr)
  168623. {
  168624. /* no work needed */
  168625. }
  168626. /*
  168627. * Module initialization routine for output colorspace conversion.
  168628. */
  168629. GLOBAL(void)
  168630. jinit_color_deconverter (j_decompress_ptr cinfo)
  168631. {
  168632. my_cconvert_ptr2 cconvert;
  168633. int ci;
  168634. cconvert = (my_cconvert_ptr2)
  168635. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168636. SIZEOF(my_color_deconverter2));
  168637. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168638. cconvert->pub.start_pass = start_pass_dcolor;
  168639. /* Make sure num_components agrees with jpeg_color_space */
  168640. switch (cinfo->jpeg_color_space) {
  168641. case JCS_GRAYSCALE:
  168642. if (cinfo->num_components != 1)
  168643. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168644. break;
  168645. case JCS_RGB:
  168646. case JCS_YCbCr:
  168647. if (cinfo->num_components != 3)
  168648. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168649. break;
  168650. case JCS_CMYK:
  168651. case JCS_YCCK:
  168652. if (cinfo->num_components != 4)
  168653. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168654. break;
  168655. default: /* JCS_UNKNOWN can be anything */
  168656. if (cinfo->num_components < 1)
  168657. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168658. break;
  168659. }
  168660. /* Set out_color_components and conversion method based on requested space.
  168661. * Also clear the component_needed flags for any unused components,
  168662. * so that earlier pipeline stages can avoid useless computation.
  168663. */
  168664. switch (cinfo->out_color_space) {
  168665. case JCS_GRAYSCALE:
  168666. cinfo->out_color_components = 1;
  168667. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168668. cinfo->jpeg_color_space == JCS_YCbCr) {
  168669. cconvert->pub.color_convert = grayscale_convert2;
  168670. /* For color->grayscale conversion, only the Y (0) component is needed */
  168671. for (ci = 1; ci < cinfo->num_components; ci++)
  168672. cinfo->comp_info[ci].component_needed = FALSE;
  168673. } else
  168674. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168675. break;
  168676. case JCS_RGB:
  168677. cinfo->out_color_components = RGB_PIXELSIZE;
  168678. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168679. cconvert->pub.color_convert = ycc_rgb_convert;
  168680. build_ycc_rgb_table(cinfo);
  168681. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168682. cconvert->pub.color_convert = gray_rgb_convert;
  168683. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168684. cconvert->pub.color_convert = null_convert2;
  168685. } else
  168686. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168687. break;
  168688. case JCS_CMYK:
  168689. cinfo->out_color_components = 4;
  168690. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168691. cconvert->pub.color_convert = ycck_cmyk_convert;
  168692. build_ycc_rgb_table(cinfo);
  168693. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168694. cconvert->pub.color_convert = null_convert2;
  168695. } else
  168696. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168697. break;
  168698. default:
  168699. /* Permit null conversion to same output space */
  168700. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168701. cinfo->out_color_components = cinfo->num_components;
  168702. cconvert->pub.color_convert = null_convert2;
  168703. } else /* unsupported non-null conversion */
  168704. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168705. break;
  168706. }
  168707. if (cinfo->quantize_colors)
  168708. cinfo->output_components = 1; /* single colormapped output component */
  168709. else
  168710. cinfo->output_components = cinfo->out_color_components;
  168711. }
  168712. /*** End of inlined file: jdcolor.c ***/
  168713. #undef FIX
  168714. /*** Start of inlined file: jddctmgr.c ***/
  168715. #define JPEG_INTERNALS
  168716. /*
  168717. * The decompressor input side (jdinput.c) saves away the appropriate
  168718. * quantization table for each component at the start of the first scan
  168719. * involving that component. (This is necessary in order to correctly
  168720. * decode files that reuse Q-table slots.)
  168721. * When we are ready to make an output pass, the saved Q-table is converted
  168722. * to a multiplier table that will actually be used by the IDCT routine.
  168723. * The multiplier table contents are IDCT-method-dependent. To support
  168724. * application changes in IDCT method between scans, we can remake the
  168725. * multiplier tables if necessary.
  168726. * In buffered-image mode, the first output pass may occur before any data
  168727. * has been seen for some components, and thus before their Q-tables have
  168728. * been saved away. To handle this case, multiplier tables are preset
  168729. * to zeroes; the result of the IDCT will be a neutral gray level.
  168730. */
  168731. /* Private subobject for this module */
  168732. typedef struct {
  168733. struct jpeg_inverse_dct pub; /* public fields */
  168734. /* This array contains the IDCT method code that each multiplier table
  168735. * is currently set up for, or -1 if it's not yet set up.
  168736. * The actual multiplier tables are pointed to by dct_table in the
  168737. * per-component comp_info structures.
  168738. */
  168739. int cur_method[MAX_COMPONENTS];
  168740. } my_idct_controller;
  168741. typedef my_idct_controller * my_idct_ptr;
  168742. /* Allocated multiplier tables: big enough for any supported variant */
  168743. typedef union {
  168744. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168745. #ifdef DCT_IFAST_SUPPORTED
  168746. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168747. #endif
  168748. #ifdef DCT_FLOAT_SUPPORTED
  168749. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168750. #endif
  168751. } multiplier_table;
  168752. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168753. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168754. */
  168755. #ifdef DCT_ISLOW_SUPPORTED
  168756. #define PROVIDE_ISLOW_TABLES
  168757. #else
  168758. #ifdef IDCT_SCALING_SUPPORTED
  168759. #define PROVIDE_ISLOW_TABLES
  168760. #endif
  168761. #endif
  168762. /*
  168763. * Prepare for an output pass.
  168764. * Here we select the proper IDCT routine for each component and build
  168765. * a matching multiplier table.
  168766. */
  168767. METHODDEF(void)
  168768. start_pass (j_decompress_ptr cinfo)
  168769. {
  168770. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168771. int ci, i;
  168772. jpeg_component_info *compptr;
  168773. int method = 0;
  168774. inverse_DCT_method_ptr method_ptr = NULL;
  168775. JQUANT_TBL * qtbl;
  168776. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168777. ci++, compptr++) {
  168778. /* Select the proper IDCT routine for this component's scaling */
  168779. switch (compptr->DCT_scaled_size) {
  168780. #ifdef IDCT_SCALING_SUPPORTED
  168781. case 1:
  168782. method_ptr = jpeg_idct_1x1;
  168783. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168784. break;
  168785. case 2:
  168786. method_ptr = jpeg_idct_2x2;
  168787. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168788. break;
  168789. case 4:
  168790. method_ptr = jpeg_idct_4x4;
  168791. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168792. break;
  168793. #endif
  168794. case DCTSIZE:
  168795. switch (cinfo->dct_method) {
  168796. #ifdef DCT_ISLOW_SUPPORTED
  168797. case JDCT_ISLOW:
  168798. method_ptr = jpeg_idct_islow;
  168799. method = JDCT_ISLOW;
  168800. break;
  168801. #endif
  168802. #ifdef DCT_IFAST_SUPPORTED
  168803. case JDCT_IFAST:
  168804. method_ptr = jpeg_idct_ifast;
  168805. method = JDCT_IFAST;
  168806. break;
  168807. #endif
  168808. #ifdef DCT_FLOAT_SUPPORTED
  168809. case JDCT_FLOAT:
  168810. method_ptr = jpeg_idct_float;
  168811. method = JDCT_FLOAT;
  168812. break;
  168813. #endif
  168814. default:
  168815. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168816. break;
  168817. }
  168818. break;
  168819. default:
  168820. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  168821. break;
  168822. }
  168823. idct->pub.inverse_DCT[ci] = method_ptr;
  168824. /* Create multiplier table from quant table.
  168825. * However, we can skip this if the component is uninteresting
  168826. * or if we already built the table. Also, if no quant table
  168827. * has yet been saved for the component, we leave the
  168828. * multiplier table all-zero; we'll be reading zeroes from the
  168829. * coefficient controller's buffer anyway.
  168830. */
  168831. if (! compptr->component_needed || idct->cur_method[ci] == method)
  168832. continue;
  168833. qtbl = compptr->quant_table;
  168834. if (qtbl == NULL) /* happens if no data yet for component */
  168835. continue;
  168836. idct->cur_method[ci] = method;
  168837. switch (method) {
  168838. #ifdef PROVIDE_ISLOW_TABLES
  168839. case JDCT_ISLOW:
  168840. {
  168841. /* For LL&M IDCT method, multipliers are equal to raw quantization
  168842. * coefficients, but are stored as ints to ensure access efficiency.
  168843. */
  168844. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168845. for (i = 0; i < DCTSIZE2; i++) {
  168846. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  168847. }
  168848. }
  168849. break;
  168850. #endif
  168851. #ifdef DCT_IFAST_SUPPORTED
  168852. case JDCT_IFAST:
  168853. {
  168854. /* For AA&N IDCT method, multipliers are equal to quantization
  168855. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168856. * scalefactor[0] = 1
  168857. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168858. * For integer operation, the multiplier table is to be scaled by
  168859. * IFAST_SCALE_BITS.
  168860. */
  168861. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  168862. #define CONST_BITS 14
  168863. static const INT16 aanscales[DCTSIZE2] = {
  168864. /* precomputed values scaled up by 14 bits */
  168865. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168866. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  168867. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  168868. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  168869. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168870. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  168871. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  168872. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  168873. };
  168874. SHIFT_TEMPS
  168875. for (i = 0; i < DCTSIZE2; i++) {
  168876. ifmtbl[i] = (IFAST_MULT_TYPE)
  168877. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  168878. (INT32) aanscales[i]),
  168879. CONST_BITS-IFAST_SCALE_BITS);
  168880. }
  168881. }
  168882. break;
  168883. #endif
  168884. #ifdef DCT_FLOAT_SUPPORTED
  168885. case JDCT_FLOAT:
  168886. {
  168887. /* For float AA&N IDCT method, multipliers are equal to quantization
  168888. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168889. * scalefactor[0] = 1
  168890. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168891. */
  168892. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168893. int row, col;
  168894. static const double aanscalefactor[DCTSIZE] = {
  168895. 1.0, 1.387039845, 1.306562965, 1.175875602,
  168896. 1.0, 0.785694958, 0.541196100, 0.275899379
  168897. };
  168898. i = 0;
  168899. for (row = 0; row < DCTSIZE; row++) {
  168900. for (col = 0; col < DCTSIZE; col++) {
  168901. fmtbl[i] = (FLOAT_MULT_TYPE)
  168902. ((double) qtbl->quantval[i] *
  168903. aanscalefactor[row] * aanscalefactor[col]);
  168904. i++;
  168905. }
  168906. }
  168907. }
  168908. break;
  168909. #endif
  168910. default:
  168911. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168912. break;
  168913. }
  168914. }
  168915. }
  168916. /*
  168917. * Initialize IDCT manager.
  168918. */
  168919. GLOBAL(void)
  168920. jinit_inverse_dct (j_decompress_ptr cinfo)
  168921. {
  168922. my_idct_ptr idct;
  168923. int ci;
  168924. jpeg_component_info *compptr;
  168925. idct = (my_idct_ptr)
  168926. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168927. SIZEOF(my_idct_controller));
  168928. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  168929. idct->pub.start_pass = start_pass;
  168930. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168931. ci++, compptr++) {
  168932. /* Allocate and pre-zero a multiplier table for each component */
  168933. compptr->dct_table =
  168934. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168935. SIZEOF(multiplier_table));
  168936. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  168937. /* Mark multiplier table not yet set up for any method */
  168938. idct->cur_method[ci] = -1;
  168939. }
  168940. }
  168941. /*** End of inlined file: jddctmgr.c ***/
  168942. #undef CONST_BITS
  168943. #undef ASSIGN_STATE
  168944. /*** Start of inlined file: jdhuff.c ***/
  168945. #define JPEG_INTERNALS
  168946. /*** Start of inlined file: jdhuff.h ***/
  168947. /* Short forms of external names for systems with brain-damaged linkers. */
  168948. #ifndef __jdhuff_h__
  168949. #define __jdhuff_h__
  168950. #ifdef NEED_SHORT_EXTERNAL_NAMES
  168951. #define jpeg_make_d_derived_tbl jMkDDerived
  168952. #define jpeg_fill_bit_buffer jFilBitBuf
  168953. #define jpeg_huff_decode jHufDecode
  168954. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  168955. /* Derived data constructed for each Huffman table */
  168956. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  168957. typedef struct {
  168958. /* Basic tables: (element [0] of each array is unused) */
  168959. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  168960. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  168961. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  168962. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  168963. * the smallest code of length k; so given a code of length k, the
  168964. * corresponding symbol is huffval[code + valoffset[k]]
  168965. */
  168966. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  168967. JHUFF_TBL *pub;
  168968. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  168969. * the input data stream. If the next Huffman code is no more
  168970. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  168971. * the corresponding symbol directly from these tables.
  168972. */
  168973. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  168974. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  168975. } d_derived_tbl;
  168976. /* Expand a Huffman table definition into the derived format */
  168977. EXTERN(void) jpeg_make_d_derived_tbl
  168978. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  168979. d_derived_tbl ** pdtbl));
  168980. /*
  168981. * Fetching the next N bits from the input stream is a time-critical operation
  168982. * for the Huffman decoders. We implement it with a combination of inline
  168983. * macros and out-of-line subroutines. Note that N (the number of bits
  168984. * demanded at one time) never exceeds 15 for JPEG use.
  168985. *
  168986. * We read source bytes into get_buffer and dole out bits as needed.
  168987. * If get_buffer already contains enough bits, they are fetched in-line
  168988. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  168989. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  168990. * as full as possible (not just to the number of bits needed; this
  168991. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  168992. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  168993. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  168994. * at least the requested number of bits --- dummy zeroes are inserted if
  168995. * necessary.
  168996. */
  168997. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  168998. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  168999. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169000. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169001. * appropriately should be a win. Unfortunately we can't define the size
  169002. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169003. * because not all machines measure sizeof in 8-bit bytes.
  169004. */
  169005. typedef struct { /* Bitreading state saved across MCUs */
  169006. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169007. int bits_left; /* # of unused bits in it */
  169008. } bitread_perm_state;
  169009. typedef struct { /* Bitreading working state within an MCU */
  169010. /* Current data source location */
  169011. /* We need a copy, rather than munging the original, in case of suspension */
  169012. const JOCTET * next_input_byte; /* => next byte to read from source */
  169013. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169014. /* Bit input buffer --- note these values are kept in register variables,
  169015. * not in this struct, inside the inner loops.
  169016. */
  169017. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169018. int bits_left; /* # of unused bits in it */
  169019. /* Pointer needed by jpeg_fill_bit_buffer. */
  169020. j_decompress_ptr cinfo; /* back link to decompress master record */
  169021. } bitread_working_state;
  169022. /* Macros to declare and load/save bitread local variables. */
  169023. #define BITREAD_STATE_VARS \
  169024. register bit_buf_type get_buffer; \
  169025. register int bits_left; \
  169026. bitread_working_state br_state
  169027. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169028. br_state.cinfo = cinfop; \
  169029. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169030. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169031. get_buffer = permstate.get_buffer; \
  169032. bits_left = permstate.bits_left;
  169033. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169034. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169035. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169036. permstate.get_buffer = get_buffer; \
  169037. permstate.bits_left = bits_left
  169038. /*
  169039. * These macros provide the in-line portion of bit fetching.
  169040. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169041. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169042. * The variables get_buffer and bits_left are assumed to be locals,
  169043. * but the state struct might not be (jpeg_huff_decode needs this).
  169044. * CHECK_BIT_BUFFER(state,n,action);
  169045. * Ensure there are N bits in get_buffer; if suspend, take action.
  169046. * val = GET_BITS(n);
  169047. * Fetch next N bits.
  169048. * val = PEEK_BITS(n);
  169049. * Fetch next N bits without removing them from the buffer.
  169050. * DROP_BITS(n);
  169051. * Discard next N bits.
  169052. * The value N should be a simple variable, not an expression, because it
  169053. * is evaluated multiple times.
  169054. */
  169055. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169056. { if (bits_left < (nbits)) { \
  169057. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169058. { action; } \
  169059. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169060. #define GET_BITS(nbits) \
  169061. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169062. #define PEEK_BITS(nbits) \
  169063. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169064. #define DROP_BITS(nbits) \
  169065. (bits_left -= (nbits))
  169066. /* Load up the bit buffer to a depth of at least nbits */
  169067. EXTERN(boolean) jpeg_fill_bit_buffer
  169068. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169069. register int bits_left, int nbits));
  169070. /*
  169071. * Code for extracting next Huffman-coded symbol from input bit stream.
  169072. * Again, this is time-critical and we make the main paths be macros.
  169073. *
  169074. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169075. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169076. * or fewer bits long. The few overlength codes are handled with a loop,
  169077. * which need not be inline code.
  169078. *
  169079. * Notes about the HUFF_DECODE macro:
  169080. * 1. Near the end of the data segment, we may fail to get enough bits
  169081. * for a lookahead. In that case, we do it the hard way.
  169082. * 2. If the lookahead table contains no entry, the next code must be
  169083. * more than HUFF_LOOKAHEAD bits long.
  169084. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169085. */
  169086. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169087. { register int nb, look; \
  169088. if (bits_left < HUFF_LOOKAHEAD) { \
  169089. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169090. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169091. if (bits_left < HUFF_LOOKAHEAD) { \
  169092. nb = 1; goto slowlabel; \
  169093. } \
  169094. } \
  169095. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169096. if ((nb = htbl->look_nbits[look]) != 0) { \
  169097. DROP_BITS(nb); \
  169098. result = htbl->look_sym[look]; \
  169099. } else { \
  169100. nb = HUFF_LOOKAHEAD+1; \
  169101. slowlabel: \
  169102. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169103. { failaction; } \
  169104. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169105. } \
  169106. }
  169107. /* Out-of-line case for Huffman code fetching */
  169108. EXTERN(int) jpeg_huff_decode
  169109. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169110. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169111. #endif
  169112. /*** End of inlined file: jdhuff.h ***/
  169113. /* Declarations shared with jdphuff.c */
  169114. /*
  169115. * Expanded entropy decoder object for Huffman decoding.
  169116. *
  169117. * The savable_state subrecord contains fields that change within an MCU,
  169118. * but must not be updated permanently until we complete the MCU.
  169119. */
  169120. typedef struct {
  169121. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169122. } savable_state2;
  169123. /* This macro is to work around compilers with missing or broken
  169124. * structure assignment. You'll need to fix this code if you have
  169125. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169126. */
  169127. #ifndef NO_STRUCT_ASSIGN
  169128. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169129. #else
  169130. #if MAX_COMPS_IN_SCAN == 4
  169131. #define ASSIGN_STATE(dest,src) \
  169132. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169133. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169134. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169135. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169136. #endif
  169137. #endif
  169138. typedef struct {
  169139. struct jpeg_entropy_decoder pub; /* public fields */
  169140. /* These fields are loaded into local variables at start of each MCU.
  169141. * In case of suspension, we exit WITHOUT updating them.
  169142. */
  169143. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169144. savable_state2 saved; /* Other state at start of MCU */
  169145. /* These fields are NOT loaded into local working state. */
  169146. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169147. /* Pointers to derived tables (these workspaces have image lifespan) */
  169148. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169149. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169150. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169151. /* Pointers to derived tables to be used for each block within an MCU */
  169152. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169153. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169154. /* Whether we care about the DC and AC coefficient values for each block */
  169155. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169156. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169157. } huff_entropy_decoder2;
  169158. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169159. /*
  169160. * Initialize for a Huffman-compressed scan.
  169161. */
  169162. METHODDEF(void)
  169163. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169164. {
  169165. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169166. int ci, blkn, dctbl, actbl;
  169167. jpeg_component_info * compptr;
  169168. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169169. * This ought to be an error condition, but we make it a warning because
  169170. * there are some baseline files out there with all zeroes in these bytes.
  169171. */
  169172. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169173. cinfo->Ah != 0 || cinfo->Al != 0)
  169174. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169175. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169176. compptr = cinfo->cur_comp_info[ci];
  169177. dctbl = compptr->dc_tbl_no;
  169178. actbl = compptr->ac_tbl_no;
  169179. /* Compute derived values for Huffman tables */
  169180. /* We may do this more than once for a table, but it's not expensive */
  169181. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169182. & entropy->dc_derived_tbls[dctbl]);
  169183. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169184. & entropy->ac_derived_tbls[actbl]);
  169185. /* Initialize DC predictions to 0 */
  169186. entropy->saved.last_dc_val[ci] = 0;
  169187. }
  169188. /* Precalculate decoding info for each block in an MCU of this scan */
  169189. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169190. ci = cinfo->MCU_membership[blkn];
  169191. compptr = cinfo->cur_comp_info[ci];
  169192. /* Precalculate which table to use for each block */
  169193. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169194. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169195. /* Decide whether we really care about the coefficient values */
  169196. if (compptr->component_needed) {
  169197. entropy->dc_needed[blkn] = TRUE;
  169198. /* we don't need the ACs if producing a 1/8th-size image */
  169199. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169200. } else {
  169201. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169202. }
  169203. }
  169204. /* Initialize bitread state variables */
  169205. entropy->bitstate.bits_left = 0;
  169206. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169207. entropy->pub.insufficient_data = FALSE;
  169208. /* Initialize restart counter */
  169209. entropy->restarts_to_go = cinfo->restart_interval;
  169210. }
  169211. /*
  169212. * Compute the derived values for a Huffman table.
  169213. * This routine also performs some validation checks on the table.
  169214. *
  169215. * Note this is also used by jdphuff.c.
  169216. */
  169217. GLOBAL(void)
  169218. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169219. d_derived_tbl ** pdtbl)
  169220. {
  169221. JHUFF_TBL *htbl;
  169222. d_derived_tbl *dtbl;
  169223. int p, i, l, si, numsymbols;
  169224. int lookbits, ctr;
  169225. char huffsize[257];
  169226. unsigned int huffcode[257];
  169227. unsigned int code;
  169228. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169229. * paralleling the order of the symbols themselves in htbl->huffval[].
  169230. */
  169231. /* Find the input Huffman table */
  169232. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169233. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169234. htbl =
  169235. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169236. if (htbl == NULL)
  169237. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169238. /* Allocate a workspace if we haven't already done so. */
  169239. if (*pdtbl == NULL)
  169240. *pdtbl = (d_derived_tbl *)
  169241. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169242. SIZEOF(d_derived_tbl));
  169243. dtbl = *pdtbl;
  169244. dtbl->pub = htbl; /* fill in back link */
  169245. /* Figure C.1: make table of Huffman code length for each symbol */
  169246. p = 0;
  169247. for (l = 1; l <= 16; l++) {
  169248. i = (int) htbl->bits[l];
  169249. if (i < 0 || p + i > 256) /* protect against table overrun */
  169250. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169251. while (i--)
  169252. huffsize[p++] = (char) l;
  169253. }
  169254. huffsize[p] = 0;
  169255. numsymbols = p;
  169256. /* Figure C.2: generate the codes themselves */
  169257. /* We also validate that the counts represent a legal Huffman code tree. */
  169258. code = 0;
  169259. si = huffsize[0];
  169260. p = 0;
  169261. while (huffsize[p]) {
  169262. while (((int) huffsize[p]) == si) {
  169263. huffcode[p++] = code;
  169264. code++;
  169265. }
  169266. /* code is now 1 more than the last code used for codelength si; but
  169267. * it must still fit in si bits, since no code is allowed to be all ones.
  169268. */
  169269. if (((INT32) code) >= (((INT32) 1) << si))
  169270. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169271. code <<= 1;
  169272. si++;
  169273. }
  169274. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169275. p = 0;
  169276. for (l = 1; l <= 16; l++) {
  169277. if (htbl->bits[l]) {
  169278. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169279. * minus the minimum code of length l
  169280. */
  169281. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169282. p += htbl->bits[l];
  169283. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169284. } else {
  169285. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169286. }
  169287. }
  169288. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169289. /* Compute lookahead tables to speed up decoding.
  169290. * First we set all the table entries to 0, indicating "too long";
  169291. * then we iterate through the Huffman codes that are short enough and
  169292. * fill in all the entries that correspond to bit sequences starting
  169293. * with that code.
  169294. */
  169295. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169296. p = 0;
  169297. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169298. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169299. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169300. /* Generate left-justified code followed by all possible bit sequences */
  169301. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169302. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169303. dtbl->look_nbits[lookbits] = l;
  169304. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169305. lookbits++;
  169306. }
  169307. }
  169308. }
  169309. /* Validate symbols as being reasonable.
  169310. * For AC tables, we make no check, but accept all byte values 0..255.
  169311. * For DC tables, we require the symbols to be in range 0..15.
  169312. * (Tighter bounds could be applied depending on the data depth and mode,
  169313. * but this is sufficient to ensure safe decoding.)
  169314. */
  169315. if (isDC) {
  169316. for (i = 0; i < numsymbols; i++) {
  169317. int sym = htbl->huffval[i];
  169318. if (sym < 0 || sym > 15)
  169319. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169320. }
  169321. }
  169322. }
  169323. /*
  169324. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169325. * See jdhuff.h for info about usage.
  169326. * Note: current values of get_buffer and bits_left are passed as parameters,
  169327. * but are returned in the corresponding fields of the state struct.
  169328. *
  169329. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169330. * of get_buffer to be used. (On machines with wider words, an even larger
  169331. * buffer could be used.) However, on some machines 32-bit shifts are
  169332. * quite slow and take time proportional to the number of places shifted.
  169333. * (This is true with most PC compilers, for instance.) In this case it may
  169334. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169335. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169336. */
  169337. #ifdef SLOW_SHIFT_32
  169338. #define MIN_GET_BITS 15 /* minimum allowable value */
  169339. #else
  169340. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169341. #endif
  169342. GLOBAL(boolean)
  169343. jpeg_fill_bit_buffer (bitread_working_state * state,
  169344. register bit_buf_type get_buffer, register int bits_left,
  169345. int nbits)
  169346. /* Load up the bit buffer to a depth of at least nbits */
  169347. {
  169348. /* Copy heavily used state fields into locals (hopefully registers) */
  169349. register const JOCTET * next_input_byte = state->next_input_byte;
  169350. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169351. j_decompress_ptr cinfo = state->cinfo;
  169352. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169353. /* (It is assumed that no request will be for more than that many bits.) */
  169354. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169355. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169356. while (bits_left < MIN_GET_BITS) {
  169357. register int c;
  169358. /* Attempt to read a byte */
  169359. if (bytes_in_buffer == 0) {
  169360. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169361. return FALSE;
  169362. next_input_byte = cinfo->src->next_input_byte;
  169363. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169364. }
  169365. bytes_in_buffer--;
  169366. c = GETJOCTET(*next_input_byte++);
  169367. /* If it's 0xFF, check and discard stuffed zero byte */
  169368. if (c == 0xFF) {
  169369. /* Loop here to discard any padding FF's on terminating marker,
  169370. * so that we can save a valid unread_marker value. NOTE: we will
  169371. * accept multiple FF's followed by a 0 as meaning a single FF data
  169372. * byte. This data pattern is not valid according to the standard.
  169373. */
  169374. do {
  169375. if (bytes_in_buffer == 0) {
  169376. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169377. return FALSE;
  169378. next_input_byte = cinfo->src->next_input_byte;
  169379. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169380. }
  169381. bytes_in_buffer--;
  169382. c = GETJOCTET(*next_input_byte++);
  169383. } while (c == 0xFF);
  169384. if (c == 0) {
  169385. /* Found FF/00, which represents an FF data byte */
  169386. c = 0xFF;
  169387. } else {
  169388. /* Oops, it's actually a marker indicating end of compressed data.
  169389. * Save the marker code for later use.
  169390. * Fine point: it might appear that we should save the marker into
  169391. * bitread working state, not straight into permanent state. But
  169392. * once we have hit a marker, we cannot need to suspend within the
  169393. * current MCU, because we will read no more bytes from the data
  169394. * source. So it is OK to update permanent state right away.
  169395. */
  169396. cinfo->unread_marker = c;
  169397. /* See if we need to insert some fake zero bits. */
  169398. goto no_more_bytes;
  169399. }
  169400. }
  169401. /* OK, load c into get_buffer */
  169402. get_buffer = (get_buffer << 8) | c;
  169403. bits_left += 8;
  169404. } /* end while */
  169405. } else {
  169406. no_more_bytes:
  169407. /* We get here if we've read the marker that terminates the compressed
  169408. * data segment. There should be enough bits in the buffer register
  169409. * to satisfy the request; if so, no problem.
  169410. */
  169411. if (nbits > bits_left) {
  169412. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169413. * the data stream, so that we can produce some kind of image.
  169414. * We use a nonvolatile flag to ensure that only one warning message
  169415. * appears per data segment.
  169416. */
  169417. if (! cinfo->entropy->insufficient_data) {
  169418. WARNMS(cinfo, JWRN_HIT_MARKER);
  169419. cinfo->entropy->insufficient_data = TRUE;
  169420. }
  169421. /* Fill the buffer with zero bits */
  169422. get_buffer <<= MIN_GET_BITS - bits_left;
  169423. bits_left = MIN_GET_BITS;
  169424. }
  169425. }
  169426. /* Unload the local registers */
  169427. state->next_input_byte = next_input_byte;
  169428. state->bytes_in_buffer = bytes_in_buffer;
  169429. state->get_buffer = get_buffer;
  169430. state->bits_left = bits_left;
  169431. return TRUE;
  169432. }
  169433. /*
  169434. * Out-of-line code for Huffman code decoding.
  169435. * See jdhuff.h for info about usage.
  169436. */
  169437. GLOBAL(int)
  169438. jpeg_huff_decode (bitread_working_state * state,
  169439. register bit_buf_type get_buffer, register int bits_left,
  169440. d_derived_tbl * htbl, int min_bits)
  169441. {
  169442. register int l = min_bits;
  169443. register INT32 code;
  169444. /* HUFF_DECODE has determined that the code is at least min_bits */
  169445. /* bits long, so fetch that many bits in one swoop. */
  169446. CHECK_BIT_BUFFER(*state, l, return -1);
  169447. code = GET_BITS(l);
  169448. /* Collect the rest of the Huffman code one bit at a time. */
  169449. /* This is per Figure F.16 in the JPEG spec. */
  169450. while (code > htbl->maxcode[l]) {
  169451. code <<= 1;
  169452. CHECK_BIT_BUFFER(*state, 1, return -1);
  169453. code |= GET_BITS(1);
  169454. l++;
  169455. }
  169456. /* Unload the local registers */
  169457. state->get_buffer = get_buffer;
  169458. state->bits_left = bits_left;
  169459. /* With garbage input we may reach the sentinel value l = 17. */
  169460. if (l > 16) {
  169461. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169462. return 0; /* fake a zero as the safest result */
  169463. }
  169464. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169465. }
  169466. /*
  169467. * Check for a restart marker & resynchronize decoder.
  169468. * Returns FALSE if must suspend.
  169469. */
  169470. LOCAL(boolean)
  169471. process_restart (j_decompress_ptr cinfo)
  169472. {
  169473. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169474. int ci;
  169475. /* Throw away any unused bits remaining in bit buffer; */
  169476. /* include any full bytes in next_marker's count of discarded bytes */
  169477. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169478. entropy->bitstate.bits_left = 0;
  169479. /* Advance past the RSTn marker */
  169480. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169481. return FALSE;
  169482. /* Re-initialize DC predictions to 0 */
  169483. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169484. entropy->saved.last_dc_val[ci] = 0;
  169485. /* Reset restart counter */
  169486. entropy->restarts_to_go = cinfo->restart_interval;
  169487. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169488. * against a marker. In that case we will end up treating the next data
  169489. * segment as empty, and we can avoid producing bogus output pixels by
  169490. * leaving the flag set.
  169491. */
  169492. if (cinfo->unread_marker == 0)
  169493. entropy->pub.insufficient_data = FALSE;
  169494. return TRUE;
  169495. }
  169496. /*
  169497. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169498. * The coefficients are reordered from zigzag order into natural array order,
  169499. * but are not dequantized.
  169500. *
  169501. * The i'th block of the MCU is stored into the block pointed to by
  169502. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169503. * (Wholesale zeroing is usually a little faster than retail...)
  169504. *
  169505. * Returns FALSE if data source requested suspension. In that case no
  169506. * changes have been made to permanent state. (Exception: some output
  169507. * coefficients may already have been assigned. This is harmless for
  169508. * this module, since we'll just re-assign them on the next call.)
  169509. */
  169510. METHODDEF(boolean)
  169511. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169512. {
  169513. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169514. int blkn;
  169515. BITREAD_STATE_VARS;
  169516. savable_state2 state;
  169517. /* Process restart marker if needed; may have to suspend */
  169518. if (cinfo->restart_interval) {
  169519. if (entropy->restarts_to_go == 0)
  169520. if (! process_restart(cinfo))
  169521. return FALSE;
  169522. }
  169523. /* If we've run out of data, just leave the MCU set to zeroes.
  169524. * This way, we return uniform gray for the remainder of the segment.
  169525. */
  169526. if (! entropy->pub.insufficient_data) {
  169527. /* Load up working state */
  169528. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169529. ASSIGN_STATE(state, entropy->saved);
  169530. /* Outer loop handles each block in the MCU */
  169531. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169532. JBLOCKROW block = MCU_data[blkn];
  169533. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169534. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169535. register int s, k, r;
  169536. /* Decode a single block's worth of coefficients */
  169537. /* Section F.2.2.1: decode the DC coefficient difference */
  169538. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169539. if (s) {
  169540. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169541. r = GET_BITS(s);
  169542. s = HUFF_EXTEND(r, s);
  169543. }
  169544. if (entropy->dc_needed[blkn]) {
  169545. /* Convert DC difference to actual value, update last_dc_val */
  169546. int ci = cinfo->MCU_membership[blkn];
  169547. s += state.last_dc_val[ci];
  169548. state.last_dc_val[ci] = s;
  169549. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169550. (*block)[0] = (JCOEF) s;
  169551. }
  169552. if (entropy->ac_needed[blkn]) {
  169553. /* Section F.2.2.2: decode the AC coefficients */
  169554. /* Since zeroes are skipped, output area must be cleared beforehand */
  169555. for (k = 1; k < DCTSIZE2; k++) {
  169556. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169557. r = s >> 4;
  169558. s &= 15;
  169559. if (s) {
  169560. k += r;
  169561. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169562. r = GET_BITS(s);
  169563. s = HUFF_EXTEND(r, s);
  169564. /* Output coefficient in natural (dezigzagged) order.
  169565. * Note: the extra entries in jpeg_natural_order[] will save us
  169566. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169567. */
  169568. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169569. } else {
  169570. if (r != 15)
  169571. break;
  169572. k += 15;
  169573. }
  169574. }
  169575. } else {
  169576. /* Section F.2.2.2: decode the AC coefficients */
  169577. /* In this path we just discard the values */
  169578. for (k = 1; k < DCTSIZE2; k++) {
  169579. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169580. r = s >> 4;
  169581. s &= 15;
  169582. if (s) {
  169583. k += r;
  169584. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169585. DROP_BITS(s);
  169586. } else {
  169587. if (r != 15)
  169588. break;
  169589. k += 15;
  169590. }
  169591. }
  169592. }
  169593. }
  169594. /* Completed MCU, so update state */
  169595. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169596. ASSIGN_STATE(entropy->saved, state);
  169597. }
  169598. /* Account for restart interval (no-op if not using restarts) */
  169599. entropy->restarts_to_go--;
  169600. return TRUE;
  169601. }
  169602. /*
  169603. * Module initialization routine for Huffman entropy decoding.
  169604. */
  169605. GLOBAL(void)
  169606. jinit_huff_decoder (j_decompress_ptr cinfo)
  169607. {
  169608. huff_entropy_ptr2 entropy;
  169609. int i;
  169610. entropy = (huff_entropy_ptr2)
  169611. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169612. SIZEOF(huff_entropy_decoder2));
  169613. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169614. entropy->pub.start_pass = start_pass_huff_decoder;
  169615. entropy->pub.decode_mcu = decode_mcu;
  169616. /* Mark tables unallocated */
  169617. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169618. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169619. }
  169620. }
  169621. /*** End of inlined file: jdhuff.c ***/
  169622. /*** Start of inlined file: jdinput.c ***/
  169623. #define JPEG_INTERNALS
  169624. /* Private state */
  169625. typedef struct {
  169626. struct jpeg_input_controller pub; /* public fields */
  169627. boolean inheaders; /* TRUE until first SOS is reached */
  169628. } my_input_controller;
  169629. typedef my_input_controller * my_inputctl_ptr;
  169630. /* Forward declarations */
  169631. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169632. /*
  169633. * Routines to calculate various quantities related to the size of the image.
  169634. */
  169635. LOCAL(void)
  169636. initial_setup2 (j_decompress_ptr cinfo)
  169637. /* Called once, when first SOS marker is reached */
  169638. {
  169639. int ci;
  169640. jpeg_component_info *compptr;
  169641. /* Make sure image isn't bigger than I can handle */
  169642. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169643. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169644. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169645. /* For now, precision must match compiled-in value... */
  169646. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169647. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169648. /* Check that number of components won't exceed internal array sizes */
  169649. if (cinfo->num_components > MAX_COMPONENTS)
  169650. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169651. MAX_COMPONENTS);
  169652. /* Compute maximum sampling factors; check factor validity */
  169653. cinfo->max_h_samp_factor = 1;
  169654. cinfo->max_v_samp_factor = 1;
  169655. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169656. ci++, compptr++) {
  169657. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169658. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169659. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169660. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169661. compptr->h_samp_factor);
  169662. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169663. compptr->v_samp_factor);
  169664. }
  169665. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169666. * In the full decompressor, this will be overridden by jdmaster.c;
  169667. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169668. */
  169669. cinfo->min_DCT_scaled_size = DCTSIZE;
  169670. /* Compute dimensions of components */
  169671. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169672. ci++, compptr++) {
  169673. compptr->DCT_scaled_size = DCTSIZE;
  169674. /* Size in DCT blocks */
  169675. compptr->width_in_blocks = (JDIMENSION)
  169676. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169677. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169678. compptr->height_in_blocks = (JDIMENSION)
  169679. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169680. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169681. /* downsampled_width and downsampled_height will also be overridden by
  169682. * jdmaster.c if we are doing full decompression. The transcoder library
  169683. * doesn't use these values, but the calling application might.
  169684. */
  169685. /* Size in samples */
  169686. compptr->downsampled_width = (JDIMENSION)
  169687. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169688. (long) cinfo->max_h_samp_factor);
  169689. compptr->downsampled_height = (JDIMENSION)
  169690. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169691. (long) cinfo->max_v_samp_factor);
  169692. /* Mark component needed, until color conversion says otherwise */
  169693. compptr->component_needed = TRUE;
  169694. /* Mark no quantization table yet saved for component */
  169695. compptr->quant_table = NULL;
  169696. }
  169697. /* Compute number of fully interleaved MCU rows. */
  169698. cinfo->total_iMCU_rows = (JDIMENSION)
  169699. jdiv_round_up((long) cinfo->image_height,
  169700. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169701. /* Decide whether file contains multiple scans */
  169702. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169703. cinfo->inputctl->has_multiple_scans = TRUE;
  169704. else
  169705. cinfo->inputctl->has_multiple_scans = FALSE;
  169706. }
  169707. LOCAL(void)
  169708. per_scan_setup2 (j_decompress_ptr cinfo)
  169709. /* Do computations that are needed before processing a JPEG scan */
  169710. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169711. {
  169712. int ci, mcublks, tmp;
  169713. jpeg_component_info *compptr;
  169714. if (cinfo->comps_in_scan == 1) {
  169715. /* Noninterleaved (single-component) scan */
  169716. compptr = cinfo->cur_comp_info[0];
  169717. /* Overall image size in MCUs */
  169718. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169719. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169720. /* For noninterleaved scan, always one block per MCU */
  169721. compptr->MCU_width = 1;
  169722. compptr->MCU_height = 1;
  169723. compptr->MCU_blocks = 1;
  169724. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169725. compptr->last_col_width = 1;
  169726. /* For noninterleaved scans, it is convenient to define last_row_height
  169727. * as the number of block rows present in the last iMCU row.
  169728. */
  169729. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169730. if (tmp == 0) tmp = compptr->v_samp_factor;
  169731. compptr->last_row_height = tmp;
  169732. /* Prepare array describing MCU composition */
  169733. cinfo->blocks_in_MCU = 1;
  169734. cinfo->MCU_membership[0] = 0;
  169735. } else {
  169736. /* Interleaved (multi-component) scan */
  169737. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169738. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169739. MAX_COMPS_IN_SCAN);
  169740. /* Overall image size in MCUs */
  169741. cinfo->MCUs_per_row = (JDIMENSION)
  169742. jdiv_round_up((long) cinfo->image_width,
  169743. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169744. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169745. jdiv_round_up((long) cinfo->image_height,
  169746. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169747. cinfo->blocks_in_MCU = 0;
  169748. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169749. compptr = cinfo->cur_comp_info[ci];
  169750. /* Sampling factors give # of blocks of component in each MCU */
  169751. compptr->MCU_width = compptr->h_samp_factor;
  169752. compptr->MCU_height = compptr->v_samp_factor;
  169753. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169754. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169755. /* Figure number of non-dummy blocks in last MCU column & row */
  169756. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169757. if (tmp == 0) tmp = compptr->MCU_width;
  169758. compptr->last_col_width = tmp;
  169759. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169760. if (tmp == 0) tmp = compptr->MCU_height;
  169761. compptr->last_row_height = tmp;
  169762. /* Prepare array describing MCU composition */
  169763. mcublks = compptr->MCU_blocks;
  169764. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169765. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169766. while (mcublks-- > 0) {
  169767. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169768. }
  169769. }
  169770. }
  169771. }
  169772. /*
  169773. * Save away a copy of the Q-table referenced by each component present
  169774. * in the current scan, unless already saved during a prior scan.
  169775. *
  169776. * In a multiple-scan JPEG file, the encoder could assign different components
  169777. * the same Q-table slot number, but change table definitions between scans
  169778. * so that each component uses a different Q-table. (The IJG encoder is not
  169779. * currently capable of doing this, but other encoders might.) Since we want
  169780. * to be able to dequantize all the components at the end of the file, this
  169781. * means that we have to save away the table actually used for each component.
  169782. * We do this by copying the table at the start of the first scan containing
  169783. * the component.
  169784. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169785. * slot between scans of a component using that slot. If the encoder does so
  169786. * anyway, this decoder will simply use the Q-table values that were current
  169787. * at the start of the first scan for the component.
  169788. *
  169789. * The decompressor output side looks only at the saved quant tables,
  169790. * not at the current Q-table slots.
  169791. */
  169792. LOCAL(void)
  169793. latch_quant_tables (j_decompress_ptr cinfo)
  169794. {
  169795. int ci, qtblno;
  169796. jpeg_component_info *compptr;
  169797. JQUANT_TBL * qtbl;
  169798. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169799. compptr = cinfo->cur_comp_info[ci];
  169800. /* No work if we already saved Q-table for this component */
  169801. if (compptr->quant_table != NULL)
  169802. continue;
  169803. /* Make sure specified quantization table is present */
  169804. qtblno = compptr->quant_tbl_no;
  169805. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169806. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169807. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169808. /* OK, save away the quantization table */
  169809. qtbl = (JQUANT_TBL *)
  169810. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169811. SIZEOF(JQUANT_TBL));
  169812. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169813. compptr->quant_table = qtbl;
  169814. }
  169815. }
  169816. /*
  169817. * Initialize the input modules to read a scan of compressed data.
  169818. * The first call to this is done by jdmaster.c after initializing
  169819. * the entire decompressor (during jpeg_start_decompress).
  169820. * Subsequent calls come from consume_markers, below.
  169821. */
  169822. METHODDEF(void)
  169823. start_input_pass2 (j_decompress_ptr cinfo)
  169824. {
  169825. per_scan_setup2(cinfo);
  169826. latch_quant_tables(cinfo);
  169827. (*cinfo->entropy->start_pass) (cinfo);
  169828. (*cinfo->coef->start_input_pass) (cinfo);
  169829. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  169830. }
  169831. /*
  169832. * Finish up after inputting a compressed-data scan.
  169833. * This is called by the coefficient controller after it's read all
  169834. * the expected data of the scan.
  169835. */
  169836. METHODDEF(void)
  169837. finish_input_pass (j_decompress_ptr cinfo)
  169838. {
  169839. cinfo->inputctl->consume_input = consume_markers;
  169840. }
  169841. /*
  169842. * Read JPEG markers before, between, or after compressed-data scans.
  169843. * Change state as necessary when a new scan is reached.
  169844. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  169845. *
  169846. * The consume_input method pointer points either here or to the
  169847. * coefficient controller's consume_data routine, depending on whether
  169848. * we are reading a compressed data segment or inter-segment markers.
  169849. */
  169850. METHODDEF(int)
  169851. consume_markers (j_decompress_ptr cinfo)
  169852. {
  169853. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169854. int val;
  169855. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  169856. return JPEG_REACHED_EOI;
  169857. val = (*cinfo->marker->read_markers) (cinfo);
  169858. switch (val) {
  169859. case JPEG_REACHED_SOS: /* Found SOS */
  169860. if (inputctl->inheaders) { /* 1st SOS */
  169861. initial_setup2(cinfo);
  169862. inputctl->inheaders = FALSE;
  169863. /* Note: start_input_pass must be called by jdmaster.c
  169864. * before any more input can be consumed. jdapimin.c is
  169865. * responsible for enforcing this sequencing.
  169866. */
  169867. } else { /* 2nd or later SOS marker */
  169868. if (! inputctl->pub.has_multiple_scans)
  169869. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  169870. start_input_pass2(cinfo);
  169871. }
  169872. break;
  169873. case JPEG_REACHED_EOI: /* Found EOI */
  169874. inputctl->pub.eoi_reached = TRUE;
  169875. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  169876. if (cinfo->marker->saw_SOF)
  169877. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  169878. } else {
  169879. /* Prevent infinite loop in coef ctlr's decompress_data routine
  169880. * if user set output_scan_number larger than number of scans.
  169881. */
  169882. if (cinfo->output_scan_number > cinfo->input_scan_number)
  169883. cinfo->output_scan_number = cinfo->input_scan_number;
  169884. }
  169885. break;
  169886. case JPEG_SUSPENDED:
  169887. break;
  169888. }
  169889. return val;
  169890. }
  169891. /*
  169892. * Reset state to begin a fresh datastream.
  169893. */
  169894. METHODDEF(void)
  169895. reset_input_controller (j_decompress_ptr cinfo)
  169896. {
  169897. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169898. inputctl->pub.consume_input = consume_markers;
  169899. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169900. inputctl->pub.eoi_reached = FALSE;
  169901. inputctl->inheaders = TRUE;
  169902. /* Reset other modules */
  169903. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  169904. (*cinfo->marker->reset_marker_reader) (cinfo);
  169905. /* Reset progression state -- would be cleaner if entropy decoder did this */
  169906. cinfo->coef_bits = NULL;
  169907. }
  169908. /*
  169909. * Initialize the input controller module.
  169910. * This is called only once, when the decompression object is created.
  169911. */
  169912. GLOBAL(void)
  169913. jinit_input_controller (j_decompress_ptr cinfo)
  169914. {
  169915. my_inputctl_ptr inputctl;
  169916. /* Create subobject in permanent pool */
  169917. inputctl = (my_inputctl_ptr)
  169918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169919. SIZEOF(my_input_controller));
  169920. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  169921. /* Initialize method pointers */
  169922. inputctl->pub.consume_input = consume_markers;
  169923. inputctl->pub.reset_input_controller = reset_input_controller;
  169924. inputctl->pub.start_input_pass = start_input_pass2;
  169925. inputctl->pub.finish_input_pass = finish_input_pass;
  169926. /* Initialize state: can't use reset_input_controller since we don't
  169927. * want to try to reset other modules yet.
  169928. */
  169929. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169930. inputctl->pub.eoi_reached = FALSE;
  169931. inputctl->inheaders = TRUE;
  169932. }
  169933. /*** End of inlined file: jdinput.c ***/
  169934. /*** Start of inlined file: jdmainct.c ***/
  169935. #define JPEG_INTERNALS
  169936. /*
  169937. * In the current system design, the main buffer need never be a full-image
  169938. * buffer; any full-height buffers will be found inside the coefficient or
  169939. * postprocessing controllers. Nonetheless, the main controller is not
  169940. * trivial. Its responsibility is to provide context rows for upsampling/
  169941. * rescaling, and doing this in an efficient fashion is a bit tricky.
  169942. *
  169943. * Postprocessor input data is counted in "row groups". A row group
  169944. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  169945. * sample rows of each component. (We require DCT_scaled_size values to be
  169946. * chosen such that these numbers are integers. In practice DCT_scaled_size
  169947. * values will likely be powers of two, so we actually have the stronger
  169948. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  169949. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  169950. * row group (times any additional scale factor that the upsampler is
  169951. * applying).
  169952. *
  169953. * The coefficient controller will deliver data to us one iMCU row at a time;
  169954. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  169955. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  169956. * to one row of MCUs when the image is fully interleaved.) Note that the
  169957. * number of sample rows varies across components, but the number of row
  169958. * groups does not. Some garbage sample rows may be included in the last iMCU
  169959. * row at the bottom of the image.
  169960. *
  169961. * Depending on the vertical scaling algorithm used, the upsampler may need
  169962. * access to the sample row(s) above and below its current input row group.
  169963. * The upsampler is required to set need_context_rows TRUE at global selection
  169964. * time if so. When need_context_rows is FALSE, this controller can simply
  169965. * obtain one iMCU row at a time from the coefficient controller and dole it
  169966. * out as row groups to the postprocessor.
  169967. *
  169968. * When need_context_rows is TRUE, this controller guarantees that the buffer
  169969. * passed to postprocessing contains at least one row group's worth of samples
  169970. * above and below the row group(s) being processed. Note that the context
  169971. * rows "above" the first passed row group appear at negative row offsets in
  169972. * the passed buffer. At the top and bottom of the image, the required
  169973. * context rows are manufactured by duplicating the first or last real sample
  169974. * row; this avoids having special cases in the upsampling inner loops.
  169975. *
  169976. * The amount of context is fixed at one row group just because that's a
  169977. * convenient number for this controller to work with. The existing
  169978. * upsamplers really only need one sample row of context. An upsampler
  169979. * supporting arbitrary output rescaling might wish for more than one row
  169980. * group of context when shrinking the image; tough, we don't handle that.
  169981. * (This is justified by the assumption that downsizing will be handled mostly
  169982. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  169983. * the upsample step needn't be much less than one.)
  169984. *
  169985. * To provide the desired context, we have to retain the last two row groups
  169986. * of one iMCU row while reading in the next iMCU row. (The last row group
  169987. * can't be processed until we have another row group for its below-context,
  169988. * and so we have to save the next-to-last group too for its above-context.)
  169989. * We could do this most simply by copying data around in our buffer, but
  169990. * that'd be very slow. We can avoid copying any data by creating a rather
  169991. * strange pointer structure. Here's how it works. We allocate a workspace
  169992. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  169993. * of row groups per iMCU row). We create two sets of redundant pointers to
  169994. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  169995. * pointer lists look like this:
  169996. * M+1 M-1
  169997. * master pointer --> 0 master pointer --> 0
  169998. * 1 1
  169999. * ... ...
  170000. * M-3 M-3
  170001. * M-2 M
  170002. * M-1 M+1
  170003. * M M-2
  170004. * M+1 M-1
  170005. * 0 0
  170006. * We read alternate iMCU rows using each master pointer; thus the last two
  170007. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170008. * The pointer lists are set up so that the required context rows appear to
  170009. * be adjacent to the proper places when we pass the pointer lists to the
  170010. * upsampler.
  170011. *
  170012. * The above pictures describe the normal state of the pointer lists.
  170013. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170014. * the first or last sample row as necessary (this is cheaper than copying
  170015. * sample rows around).
  170016. *
  170017. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170018. * situation each iMCU row provides only one row group so the buffering logic
  170019. * must be different (eg, we must read two iMCU rows before we can emit the
  170020. * first row group). For now, we simply do not support providing context
  170021. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170022. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170023. * want it quick and dirty, so a context-free upsampler is sufficient.
  170024. */
  170025. /* Private buffer controller object */
  170026. typedef struct {
  170027. struct jpeg_d_main_controller pub; /* public fields */
  170028. /* Pointer to allocated workspace (M or M+2 row groups). */
  170029. JSAMPARRAY buffer[MAX_COMPONENTS];
  170030. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170031. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170032. /* Remaining fields are only used in the context case. */
  170033. /* These are the master pointers to the funny-order pointer lists. */
  170034. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170035. int whichptr; /* indicates which pointer set is now in use */
  170036. int context_state; /* process_data state machine status */
  170037. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170038. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170039. } my_main_controller4;
  170040. typedef my_main_controller4 * my_main_ptr4;
  170041. /* context_state values: */
  170042. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170043. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170044. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170045. /* Forward declarations */
  170046. METHODDEF(void) process_data_simple_main2
  170047. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170048. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170049. METHODDEF(void) process_data_context_main
  170050. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170051. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170052. #ifdef QUANT_2PASS_SUPPORTED
  170053. METHODDEF(void) process_data_crank_post
  170054. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170055. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170056. #endif
  170057. LOCAL(void)
  170058. alloc_funny_pointers (j_decompress_ptr cinfo)
  170059. /* Allocate space for the funny pointer lists.
  170060. * This is done only once, not once per pass.
  170061. */
  170062. {
  170063. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170064. int ci, rgroup;
  170065. int M = cinfo->min_DCT_scaled_size;
  170066. jpeg_component_info *compptr;
  170067. JSAMPARRAY xbuf;
  170068. /* Get top-level space for component array pointers.
  170069. * We alloc both arrays with one call to save a few cycles.
  170070. */
  170071. main_->xbuffer[0] = (JSAMPIMAGE)
  170072. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170073. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170074. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170075. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170076. ci++, compptr++) {
  170077. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170078. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170079. /* Get space for pointer lists --- M+4 row groups in each list.
  170080. * We alloc both pointer lists with one call to save a few cycles.
  170081. */
  170082. xbuf = (JSAMPARRAY)
  170083. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170084. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170085. xbuf += rgroup; /* want one row group at negative offsets */
  170086. main_->xbuffer[0][ci] = xbuf;
  170087. xbuf += rgroup * (M + 4);
  170088. main_->xbuffer[1][ci] = xbuf;
  170089. }
  170090. }
  170091. LOCAL(void)
  170092. make_funny_pointers (j_decompress_ptr cinfo)
  170093. /* Create the funny pointer lists discussed in the comments above.
  170094. * The actual workspace is already allocated (in main->buffer),
  170095. * and the space for the pointer lists is allocated too.
  170096. * This routine just fills in the curiously ordered lists.
  170097. * This will be repeated at the beginning of each pass.
  170098. */
  170099. {
  170100. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170101. int ci, i, rgroup;
  170102. int M = cinfo->min_DCT_scaled_size;
  170103. jpeg_component_info *compptr;
  170104. JSAMPARRAY buf, xbuf0, xbuf1;
  170105. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170106. ci++, compptr++) {
  170107. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170108. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170109. xbuf0 = main_->xbuffer[0][ci];
  170110. xbuf1 = main_->xbuffer[1][ci];
  170111. /* First copy the workspace pointers as-is */
  170112. buf = main_->buffer[ci];
  170113. for (i = 0; i < rgroup * (M + 2); i++) {
  170114. xbuf0[i] = xbuf1[i] = buf[i];
  170115. }
  170116. /* In the second list, put the last four row groups in swapped order */
  170117. for (i = 0; i < rgroup * 2; i++) {
  170118. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170119. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170120. }
  170121. /* The wraparound pointers at top and bottom will be filled later
  170122. * (see set_wraparound_pointers, below). Initially we want the "above"
  170123. * pointers to duplicate the first actual data line. This only needs
  170124. * to happen in xbuffer[0].
  170125. */
  170126. for (i = 0; i < rgroup; i++) {
  170127. xbuf0[i - rgroup] = xbuf0[0];
  170128. }
  170129. }
  170130. }
  170131. LOCAL(void)
  170132. set_wraparound_pointers (j_decompress_ptr cinfo)
  170133. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170134. * This changes the pointer list state from top-of-image to the normal state.
  170135. */
  170136. {
  170137. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170138. int ci, i, rgroup;
  170139. int M = cinfo->min_DCT_scaled_size;
  170140. jpeg_component_info *compptr;
  170141. JSAMPARRAY xbuf0, xbuf1;
  170142. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170143. ci++, compptr++) {
  170144. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170145. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170146. xbuf0 = main_->xbuffer[0][ci];
  170147. xbuf1 = main_->xbuffer[1][ci];
  170148. for (i = 0; i < rgroup; i++) {
  170149. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170150. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170151. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170152. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170153. }
  170154. }
  170155. }
  170156. LOCAL(void)
  170157. set_bottom_pointers (j_decompress_ptr cinfo)
  170158. /* Change the pointer lists to duplicate the last sample row at the bottom
  170159. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170160. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170161. */
  170162. {
  170163. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170164. int ci, i, rgroup, iMCUheight, rows_left;
  170165. jpeg_component_info *compptr;
  170166. JSAMPARRAY xbuf;
  170167. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170168. ci++, compptr++) {
  170169. /* Count sample rows in one iMCU row and in one row group */
  170170. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170171. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170172. /* Count nondummy sample rows remaining for this component */
  170173. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170174. if (rows_left == 0) rows_left = iMCUheight;
  170175. /* Count nondummy row groups. Should get same answer for each component,
  170176. * so we need only do it once.
  170177. */
  170178. if (ci == 0) {
  170179. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170180. }
  170181. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170182. * last partial rowgroup and ensures at least one full rowgroup of context.
  170183. */
  170184. xbuf = main_->xbuffer[main_->whichptr][ci];
  170185. for (i = 0; i < rgroup * 2; i++) {
  170186. xbuf[rows_left + i] = xbuf[rows_left-1];
  170187. }
  170188. }
  170189. }
  170190. /*
  170191. * Initialize for a processing pass.
  170192. */
  170193. METHODDEF(void)
  170194. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170195. {
  170196. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170197. switch (pass_mode) {
  170198. case JBUF_PASS_THRU:
  170199. if (cinfo->upsample->need_context_rows) {
  170200. main_->pub.process_data = process_data_context_main;
  170201. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170202. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170203. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170204. main_->iMCU_row_ctr = 0;
  170205. } else {
  170206. /* Simple case with no context needed */
  170207. main_->pub.process_data = process_data_simple_main2;
  170208. }
  170209. main_->buffer_full = FALSE; /* Mark buffer empty */
  170210. main_->rowgroup_ctr = 0;
  170211. break;
  170212. #ifdef QUANT_2PASS_SUPPORTED
  170213. case JBUF_CRANK_DEST:
  170214. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170215. main_->pub.process_data = process_data_crank_post;
  170216. break;
  170217. #endif
  170218. default:
  170219. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170220. break;
  170221. }
  170222. }
  170223. /*
  170224. * Process some data.
  170225. * This handles the simple case where no context is required.
  170226. */
  170227. METHODDEF(void)
  170228. process_data_simple_main2 (j_decompress_ptr cinfo,
  170229. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170230. JDIMENSION out_rows_avail)
  170231. {
  170232. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170233. JDIMENSION rowgroups_avail;
  170234. /* Read input data if we haven't filled the main buffer yet */
  170235. if (! main_->buffer_full) {
  170236. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170237. return; /* suspension forced, can do nothing more */
  170238. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170239. }
  170240. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170241. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170242. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170243. * to the postprocessor. The postprocessor has to check for bottom
  170244. * of image anyway (at row resolution), so no point in us doing it too.
  170245. */
  170246. /* Feed the postprocessor */
  170247. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170248. &main_->rowgroup_ctr, rowgroups_avail,
  170249. output_buf, out_row_ctr, out_rows_avail);
  170250. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170251. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170252. main_->buffer_full = FALSE;
  170253. main_->rowgroup_ctr = 0;
  170254. }
  170255. }
  170256. /*
  170257. * Process some data.
  170258. * This handles the case where context rows must be provided.
  170259. */
  170260. METHODDEF(void)
  170261. process_data_context_main (j_decompress_ptr cinfo,
  170262. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170263. JDIMENSION out_rows_avail)
  170264. {
  170265. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170266. /* Read input data if we haven't filled the main buffer yet */
  170267. if (! main_->buffer_full) {
  170268. if (! (*cinfo->coef->decompress_data) (cinfo,
  170269. main_->xbuffer[main_->whichptr]))
  170270. return; /* suspension forced, can do nothing more */
  170271. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170272. main_->iMCU_row_ctr++; /* count rows received */
  170273. }
  170274. /* Postprocessor typically will not swallow all the input data it is handed
  170275. * in one call (due to filling the output buffer first). Must be prepared
  170276. * to exit and restart. This switch lets us keep track of how far we got.
  170277. * Note that each case falls through to the next on successful completion.
  170278. */
  170279. switch (main_->context_state) {
  170280. case CTX_POSTPONED_ROW:
  170281. /* Call postprocessor using previously set pointers for postponed row */
  170282. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170283. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170284. output_buf, out_row_ctr, out_rows_avail);
  170285. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170286. return; /* Need to suspend */
  170287. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170288. if (*out_row_ctr >= out_rows_avail)
  170289. return; /* Postprocessor exactly filled output buf */
  170290. /*FALLTHROUGH*/
  170291. case CTX_PREPARE_FOR_IMCU:
  170292. /* Prepare to process first M-1 row groups of this iMCU row */
  170293. main_->rowgroup_ctr = 0;
  170294. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170295. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170296. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170297. */
  170298. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170299. set_bottom_pointers(cinfo);
  170300. main_->context_state = CTX_PROCESS_IMCU;
  170301. /*FALLTHROUGH*/
  170302. case CTX_PROCESS_IMCU:
  170303. /* Call postprocessor using previously set pointers */
  170304. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170305. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170306. output_buf, out_row_ctr, out_rows_avail);
  170307. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170308. return; /* Need to suspend */
  170309. /* After the first iMCU, change wraparound pointers to normal state */
  170310. if (main_->iMCU_row_ctr == 1)
  170311. set_wraparound_pointers(cinfo);
  170312. /* Prepare to load new iMCU row using other xbuffer list */
  170313. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170314. main_->buffer_full = FALSE;
  170315. /* Still need to process last row group of this iMCU row, */
  170316. /* which is saved at index M+1 of the other xbuffer */
  170317. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170318. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170319. main_->context_state = CTX_POSTPONED_ROW;
  170320. }
  170321. }
  170322. /*
  170323. * Process some data.
  170324. * Final pass of two-pass quantization: just call the postprocessor.
  170325. * Source data will be the postprocessor controller's internal buffer.
  170326. */
  170327. #ifdef QUANT_2PASS_SUPPORTED
  170328. METHODDEF(void)
  170329. process_data_crank_post (j_decompress_ptr cinfo,
  170330. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170331. JDIMENSION out_rows_avail)
  170332. {
  170333. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170334. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170335. output_buf, out_row_ctr, out_rows_avail);
  170336. }
  170337. #endif /* QUANT_2PASS_SUPPORTED */
  170338. /*
  170339. * Initialize main buffer controller.
  170340. */
  170341. GLOBAL(void)
  170342. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170343. {
  170344. my_main_ptr4 main_;
  170345. int ci, rgroup, ngroups;
  170346. jpeg_component_info *compptr;
  170347. main_ = (my_main_ptr4)
  170348. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170349. SIZEOF(my_main_controller4));
  170350. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170351. main_->pub.start_pass = start_pass_main2;
  170352. if (need_full_buffer) /* shouldn't happen */
  170353. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170354. /* Allocate the workspace.
  170355. * ngroups is the number of row groups we need.
  170356. */
  170357. if (cinfo->upsample->need_context_rows) {
  170358. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170359. ERREXIT(cinfo, JERR_NOTIMPL);
  170360. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170361. ngroups = cinfo->min_DCT_scaled_size + 2;
  170362. } else {
  170363. ngroups = cinfo->min_DCT_scaled_size;
  170364. }
  170365. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170366. ci++, compptr++) {
  170367. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170368. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170369. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170370. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170371. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170372. (JDIMENSION) (rgroup * ngroups));
  170373. }
  170374. }
  170375. /*** End of inlined file: jdmainct.c ***/
  170376. /*** Start of inlined file: jdmarker.c ***/
  170377. #define JPEG_INTERNALS
  170378. /* Private state */
  170379. typedef struct {
  170380. struct jpeg_marker_reader pub; /* public fields */
  170381. /* Application-overridable marker processing methods */
  170382. jpeg_marker_parser_method process_COM;
  170383. jpeg_marker_parser_method process_APPn[16];
  170384. /* Limit on marker data length to save for each marker type */
  170385. unsigned int length_limit_COM;
  170386. unsigned int length_limit_APPn[16];
  170387. /* Status of COM/APPn marker saving */
  170388. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170389. unsigned int bytes_read; /* data bytes read so far in marker */
  170390. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170391. } my_marker_reader;
  170392. typedef my_marker_reader * my_marker_ptr2;
  170393. /*
  170394. * Macros for fetching data from the data source module.
  170395. *
  170396. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170397. * the current restart point; we update them only when we have reached a
  170398. * suitable place to restart if a suspension occurs.
  170399. */
  170400. /* Declare and initialize local copies of input pointer/count */
  170401. #define INPUT_VARS(cinfo) \
  170402. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170403. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170404. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170405. /* Unload the local copies --- do this only at a restart boundary */
  170406. #define INPUT_SYNC(cinfo) \
  170407. ( datasrc->next_input_byte = next_input_byte, \
  170408. datasrc->bytes_in_buffer = bytes_in_buffer )
  170409. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170410. #define INPUT_RELOAD(cinfo) \
  170411. ( next_input_byte = datasrc->next_input_byte, \
  170412. bytes_in_buffer = datasrc->bytes_in_buffer )
  170413. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170414. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170415. * but we must reload the local copies after a successful fill.
  170416. */
  170417. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170418. if (bytes_in_buffer == 0) { \
  170419. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170420. { action; } \
  170421. INPUT_RELOAD(cinfo); \
  170422. }
  170423. /* Read a byte into variable V.
  170424. * If must suspend, take the specified action (typically "return FALSE").
  170425. */
  170426. #define INPUT_BYTE(cinfo,V,action) \
  170427. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170428. bytes_in_buffer--; \
  170429. V = GETJOCTET(*next_input_byte++); )
  170430. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170431. * V should be declared unsigned int or perhaps INT32.
  170432. */
  170433. #define INPUT_2BYTES(cinfo,V,action) \
  170434. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170435. bytes_in_buffer--; \
  170436. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170437. MAKE_BYTE_AVAIL(cinfo,action); \
  170438. bytes_in_buffer--; \
  170439. V += GETJOCTET(*next_input_byte++); )
  170440. /*
  170441. * Routines to process JPEG markers.
  170442. *
  170443. * Entry condition: JPEG marker itself has been read and its code saved
  170444. * in cinfo->unread_marker; input restart point is just after the marker.
  170445. *
  170446. * Exit: if return TRUE, have read and processed any parameters, and have
  170447. * updated the restart point to point after the parameters.
  170448. * If return FALSE, was forced to suspend before reaching end of
  170449. * marker parameters; restart point has not been moved. Same routine
  170450. * will be called again after application supplies more input data.
  170451. *
  170452. * This approach to suspension assumes that all of a marker's parameters
  170453. * can fit into a single input bufferload. This should hold for "normal"
  170454. * markers. Some COM/APPn markers might have large parameter segments
  170455. * that might not fit. If we are simply dropping such a marker, we use
  170456. * skip_input_data to get past it, and thereby put the problem on the
  170457. * source manager's shoulders. If we are saving the marker's contents
  170458. * into memory, we use a slightly different convention: when forced to
  170459. * suspend, the marker processor updates the restart point to the end of
  170460. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170461. * On resumption, cinfo->unread_marker still contains the marker code,
  170462. * but the data source will point to the next chunk of marker data.
  170463. * The marker processor must retain internal state to deal with this.
  170464. *
  170465. * Note that we don't bother to avoid duplicate trace messages if a
  170466. * suspension occurs within marker parameters. Other side effects
  170467. * require more care.
  170468. */
  170469. LOCAL(boolean)
  170470. get_soi (j_decompress_ptr cinfo)
  170471. /* Process an SOI marker */
  170472. {
  170473. int i;
  170474. TRACEMS(cinfo, 1, JTRC_SOI);
  170475. if (cinfo->marker->saw_SOI)
  170476. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170477. /* Reset all parameters that are defined to be reset by SOI */
  170478. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170479. cinfo->arith_dc_L[i] = 0;
  170480. cinfo->arith_dc_U[i] = 1;
  170481. cinfo->arith_ac_K[i] = 5;
  170482. }
  170483. cinfo->restart_interval = 0;
  170484. /* Set initial assumptions for colorspace etc */
  170485. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170486. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170487. cinfo->saw_JFIF_marker = FALSE;
  170488. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170489. cinfo->JFIF_minor_version = 1;
  170490. cinfo->density_unit = 0;
  170491. cinfo->X_density = 1;
  170492. cinfo->Y_density = 1;
  170493. cinfo->saw_Adobe_marker = FALSE;
  170494. cinfo->Adobe_transform = 0;
  170495. cinfo->marker->saw_SOI = TRUE;
  170496. return TRUE;
  170497. }
  170498. LOCAL(boolean)
  170499. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170500. /* Process a SOFn marker */
  170501. {
  170502. INT32 length;
  170503. int c, ci;
  170504. jpeg_component_info * compptr;
  170505. INPUT_VARS(cinfo);
  170506. cinfo->progressive_mode = is_prog;
  170507. cinfo->arith_code = is_arith;
  170508. INPUT_2BYTES(cinfo, length, return FALSE);
  170509. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170510. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170511. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170512. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170513. length -= 8;
  170514. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170515. (int) cinfo->image_width, (int) cinfo->image_height,
  170516. cinfo->num_components);
  170517. if (cinfo->marker->saw_SOF)
  170518. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170519. /* We don't support files in which the image height is initially specified */
  170520. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170521. /* might as well have a general sanity check. */
  170522. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170523. || cinfo->num_components <= 0)
  170524. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170525. if (length != (cinfo->num_components * 3))
  170526. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170527. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170528. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170529. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170530. cinfo->num_components * SIZEOF(jpeg_component_info));
  170531. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170532. ci++, compptr++) {
  170533. compptr->component_index = ci;
  170534. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170535. INPUT_BYTE(cinfo, c, return FALSE);
  170536. compptr->h_samp_factor = (c >> 4) & 15;
  170537. compptr->v_samp_factor = (c ) & 15;
  170538. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170539. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170540. compptr->component_id, compptr->h_samp_factor,
  170541. compptr->v_samp_factor, compptr->quant_tbl_no);
  170542. }
  170543. cinfo->marker->saw_SOF = TRUE;
  170544. INPUT_SYNC(cinfo);
  170545. return TRUE;
  170546. }
  170547. LOCAL(boolean)
  170548. get_sos (j_decompress_ptr cinfo)
  170549. /* Process a SOS marker */
  170550. {
  170551. INT32 length;
  170552. int i, ci, n, c, cc;
  170553. jpeg_component_info * compptr;
  170554. INPUT_VARS(cinfo);
  170555. if (! cinfo->marker->saw_SOF)
  170556. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170557. INPUT_2BYTES(cinfo, length, return FALSE);
  170558. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170559. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170560. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170561. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170562. cinfo->comps_in_scan = n;
  170563. /* Collect the component-spec parameters */
  170564. for (i = 0; i < n; i++) {
  170565. INPUT_BYTE(cinfo, cc, return FALSE);
  170566. INPUT_BYTE(cinfo, c, return FALSE);
  170567. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170568. ci++, compptr++) {
  170569. if (cc == compptr->component_id)
  170570. goto id_found;
  170571. }
  170572. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170573. id_found:
  170574. cinfo->cur_comp_info[i] = compptr;
  170575. compptr->dc_tbl_no = (c >> 4) & 15;
  170576. compptr->ac_tbl_no = (c ) & 15;
  170577. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170578. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170579. }
  170580. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170581. INPUT_BYTE(cinfo, c, return FALSE);
  170582. cinfo->Ss = c;
  170583. INPUT_BYTE(cinfo, c, return FALSE);
  170584. cinfo->Se = c;
  170585. INPUT_BYTE(cinfo, c, return FALSE);
  170586. cinfo->Ah = (c >> 4) & 15;
  170587. cinfo->Al = (c ) & 15;
  170588. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170589. cinfo->Ah, cinfo->Al);
  170590. /* Prepare to scan data & restart markers */
  170591. cinfo->marker->next_restart_num = 0;
  170592. /* Count another SOS marker */
  170593. cinfo->input_scan_number++;
  170594. INPUT_SYNC(cinfo);
  170595. return TRUE;
  170596. }
  170597. #ifdef D_ARITH_CODING_SUPPORTED
  170598. LOCAL(boolean)
  170599. get_dac (j_decompress_ptr cinfo)
  170600. /* Process a DAC marker */
  170601. {
  170602. INT32 length;
  170603. int index, val;
  170604. INPUT_VARS(cinfo);
  170605. INPUT_2BYTES(cinfo, length, return FALSE);
  170606. length -= 2;
  170607. while (length > 0) {
  170608. INPUT_BYTE(cinfo, index, return FALSE);
  170609. INPUT_BYTE(cinfo, val, return FALSE);
  170610. length -= 2;
  170611. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170612. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170613. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170614. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170615. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170616. } else { /* define DC table */
  170617. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170618. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170619. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170620. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170621. }
  170622. }
  170623. if (length != 0)
  170624. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170625. INPUT_SYNC(cinfo);
  170626. return TRUE;
  170627. }
  170628. #else /* ! D_ARITH_CODING_SUPPORTED */
  170629. #define get_dac(cinfo) skip_variable(cinfo)
  170630. #endif /* D_ARITH_CODING_SUPPORTED */
  170631. LOCAL(boolean)
  170632. get_dht (j_decompress_ptr cinfo)
  170633. /* Process a DHT marker */
  170634. {
  170635. INT32 length;
  170636. UINT8 bits[17];
  170637. UINT8 huffval[256];
  170638. int i, index, count;
  170639. JHUFF_TBL **htblptr;
  170640. INPUT_VARS(cinfo);
  170641. INPUT_2BYTES(cinfo, length, return FALSE);
  170642. length -= 2;
  170643. while (length > 16) {
  170644. INPUT_BYTE(cinfo, index, return FALSE);
  170645. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170646. bits[0] = 0;
  170647. count = 0;
  170648. for (i = 1; i <= 16; i++) {
  170649. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170650. count += bits[i];
  170651. }
  170652. length -= 1 + 16;
  170653. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170654. bits[1], bits[2], bits[3], bits[4],
  170655. bits[5], bits[6], bits[7], bits[8]);
  170656. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170657. bits[9], bits[10], bits[11], bits[12],
  170658. bits[13], bits[14], bits[15], bits[16]);
  170659. /* Here we just do minimal validation of the counts to avoid walking
  170660. * off the end of our table space. jdhuff.c will check more carefully.
  170661. */
  170662. if (count > 256 || ((INT32) count) > length)
  170663. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170664. for (i = 0; i < count; i++)
  170665. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170666. length -= count;
  170667. if (index & 0x10) { /* AC table definition */
  170668. index -= 0x10;
  170669. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170670. } else { /* DC table definition */
  170671. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170672. }
  170673. if (index < 0 || index >= NUM_HUFF_TBLS)
  170674. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170675. if (*htblptr == NULL)
  170676. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170677. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170678. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170679. }
  170680. if (length != 0)
  170681. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170682. INPUT_SYNC(cinfo);
  170683. return TRUE;
  170684. }
  170685. LOCAL(boolean)
  170686. get_dqt (j_decompress_ptr cinfo)
  170687. /* Process a DQT marker */
  170688. {
  170689. INT32 length;
  170690. int n, i, prec;
  170691. unsigned int tmp;
  170692. JQUANT_TBL *quant_ptr;
  170693. INPUT_VARS(cinfo);
  170694. INPUT_2BYTES(cinfo, length, return FALSE);
  170695. length -= 2;
  170696. while (length > 0) {
  170697. INPUT_BYTE(cinfo, n, return FALSE);
  170698. prec = n >> 4;
  170699. n &= 0x0F;
  170700. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170701. if (n >= NUM_QUANT_TBLS)
  170702. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170703. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170704. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170705. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170706. for (i = 0; i < DCTSIZE2; i++) {
  170707. if (prec)
  170708. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170709. else
  170710. INPUT_BYTE(cinfo, tmp, return FALSE);
  170711. /* We convert the zigzag-order table to natural array order. */
  170712. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170713. }
  170714. if (cinfo->err->trace_level >= 2) {
  170715. for (i = 0; i < DCTSIZE2; i += 8) {
  170716. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170717. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170718. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170719. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170720. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170721. }
  170722. }
  170723. length -= DCTSIZE2+1;
  170724. if (prec) length -= DCTSIZE2;
  170725. }
  170726. if (length != 0)
  170727. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170728. INPUT_SYNC(cinfo);
  170729. return TRUE;
  170730. }
  170731. LOCAL(boolean)
  170732. get_dri (j_decompress_ptr cinfo)
  170733. /* Process a DRI marker */
  170734. {
  170735. INT32 length;
  170736. unsigned int tmp;
  170737. INPUT_VARS(cinfo);
  170738. INPUT_2BYTES(cinfo, length, return FALSE);
  170739. if (length != 4)
  170740. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170741. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170742. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170743. cinfo->restart_interval = tmp;
  170744. INPUT_SYNC(cinfo);
  170745. return TRUE;
  170746. }
  170747. /*
  170748. * Routines for processing APPn and COM markers.
  170749. * These are either saved in memory or discarded, per application request.
  170750. * APP0 and APP14 are specially checked to see if they are
  170751. * JFIF and Adobe markers, respectively.
  170752. */
  170753. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170754. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170755. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170756. LOCAL(void)
  170757. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170758. unsigned int datalen, INT32 remaining)
  170759. /* Examine first few bytes from an APP0.
  170760. * Take appropriate action if it is a JFIF marker.
  170761. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170762. */
  170763. {
  170764. INT32 totallen = (INT32) datalen + remaining;
  170765. if (datalen >= APP0_DATA_LEN &&
  170766. GETJOCTET(data[0]) == 0x4A &&
  170767. GETJOCTET(data[1]) == 0x46 &&
  170768. GETJOCTET(data[2]) == 0x49 &&
  170769. GETJOCTET(data[3]) == 0x46 &&
  170770. GETJOCTET(data[4]) == 0) {
  170771. /* Found JFIF APP0 marker: save info */
  170772. cinfo->saw_JFIF_marker = TRUE;
  170773. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170774. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170775. cinfo->density_unit = GETJOCTET(data[7]);
  170776. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170777. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170778. /* Check version.
  170779. * Major version must be 1, anything else signals an incompatible change.
  170780. * (We used to treat this as an error, but now it's a nonfatal warning,
  170781. * because some bozo at Hijaak couldn't read the spec.)
  170782. * Minor version should be 0..2, but process anyway if newer.
  170783. */
  170784. if (cinfo->JFIF_major_version != 1)
  170785. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170786. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170787. /* Generate trace messages */
  170788. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170789. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170790. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170791. /* Validate thumbnail dimensions and issue appropriate messages */
  170792. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170793. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170794. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170795. totallen -= APP0_DATA_LEN;
  170796. if (totallen !=
  170797. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170798. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170799. } else if (datalen >= 6 &&
  170800. GETJOCTET(data[0]) == 0x4A &&
  170801. GETJOCTET(data[1]) == 0x46 &&
  170802. GETJOCTET(data[2]) == 0x58 &&
  170803. GETJOCTET(data[3]) == 0x58 &&
  170804. GETJOCTET(data[4]) == 0) {
  170805. /* Found JFIF "JFXX" extension APP0 marker */
  170806. /* The library doesn't actually do anything with these,
  170807. * but we try to produce a helpful trace message.
  170808. */
  170809. switch (GETJOCTET(data[5])) {
  170810. case 0x10:
  170811. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170812. break;
  170813. case 0x11:
  170814. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170815. break;
  170816. case 0x13:
  170817. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170818. break;
  170819. default:
  170820. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  170821. GETJOCTET(data[5]), (int) totallen);
  170822. break;
  170823. }
  170824. } else {
  170825. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  170826. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  170827. }
  170828. }
  170829. LOCAL(void)
  170830. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170831. unsigned int datalen, INT32 remaining)
  170832. /* Examine first few bytes from an APP14.
  170833. * Take appropriate action if it is an Adobe marker.
  170834. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170835. */
  170836. {
  170837. unsigned int version, flags0, flags1, transform;
  170838. if (datalen >= APP14_DATA_LEN &&
  170839. GETJOCTET(data[0]) == 0x41 &&
  170840. GETJOCTET(data[1]) == 0x64 &&
  170841. GETJOCTET(data[2]) == 0x6F &&
  170842. GETJOCTET(data[3]) == 0x62 &&
  170843. GETJOCTET(data[4]) == 0x65) {
  170844. /* Found Adobe APP14 marker */
  170845. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  170846. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  170847. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  170848. transform = GETJOCTET(data[11]);
  170849. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  170850. cinfo->saw_Adobe_marker = TRUE;
  170851. cinfo->Adobe_transform = (UINT8) transform;
  170852. } else {
  170853. /* Start of APP14 does not match "Adobe", or too short */
  170854. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  170855. }
  170856. }
  170857. METHODDEF(boolean)
  170858. get_interesting_appn (j_decompress_ptr cinfo)
  170859. /* Process an APP0 or APP14 marker without saving it */
  170860. {
  170861. INT32 length;
  170862. JOCTET b[APPN_DATA_LEN];
  170863. unsigned int i, numtoread;
  170864. INPUT_VARS(cinfo);
  170865. INPUT_2BYTES(cinfo, length, return FALSE);
  170866. length -= 2;
  170867. /* get the interesting part of the marker data */
  170868. if (length >= APPN_DATA_LEN)
  170869. numtoread = APPN_DATA_LEN;
  170870. else if (length > 0)
  170871. numtoread = (unsigned int) length;
  170872. else
  170873. numtoread = 0;
  170874. for (i = 0; i < numtoread; i++)
  170875. INPUT_BYTE(cinfo, b[i], return FALSE);
  170876. length -= numtoread;
  170877. /* process it */
  170878. switch (cinfo->unread_marker) {
  170879. case M_APP0:
  170880. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  170881. break;
  170882. case M_APP14:
  170883. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  170884. break;
  170885. default:
  170886. /* can't get here unless jpeg_save_markers chooses wrong processor */
  170887. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170888. break;
  170889. }
  170890. /* skip any remaining data -- could be lots */
  170891. INPUT_SYNC(cinfo);
  170892. if (length > 0)
  170893. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170894. return TRUE;
  170895. }
  170896. #ifdef SAVE_MARKERS_SUPPORTED
  170897. METHODDEF(boolean)
  170898. save_marker (j_decompress_ptr cinfo)
  170899. /* Save an APPn or COM marker into the marker list */
  170900. {
  170901. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170902. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  170903. unsigned int bytes_read, data_length;
  170904. JOCTET FAR * data;
  170905. INT32 length = 0;
  170906. INPUT_VARS(cinfo);
  170907. if (cur_marker == NULL) {
  170908. /* begin reading a marker */
  170909. INPUT_2BYTES(cinfo, length, return FALSE);
  170910. length -= 2;
  170911. if (length >= 0) { /* watch out for bogus length word */
  170912. /* figure out how much we want to save */
  170913. unsigned int limit;
  170914. if (cinfo->unread_marker == (int) M_COM)
  170915. limit = marker->length_limit_COM;
  170916. else
  170917. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  170918. if ((unsigned int) length < limit)
  170919. limit = (unsigned int) length;
  170920. /* allocate and initialize the marker item */
  170921. cur_marker = (jpeg_saved_marker_ptr)
  170922. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170923. SIZEOF(struct jpeg_marker_struct) + limit);
  170924. cur_marker->next = NULL;
  170925. cur_marker->marker = (UINT8) cinfo->unread_marker;
  170926. cur_marker->original_length = (unsigned int) length;
  170927. cur_marker->data_length = limit;
  170928. /* data area is just beyond the jpeg_marker_struct */
  170929. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  170930. marker->cur_marker = cur_marker;
  170931. marker->bytes_read = 0;
  170932. bytes_read = 0;
  170933. data_length = limit;
  170934. } else {
  170935. /* deal with bogus length word */
  170936. bytes_read = data_length = 0;
  170937. data = NULL;
  170938. }
  170939. } else {
  170940. /* resume reading a marker */
  170941. bytes_read = marker->bytes_read;
  170942. data_length = cur_marker->data_length;
  170943. data = cur_marker->data + bytes_read;
  170944. }
  170945. while (bytes_read < data_length) {
  170946. INPUT_SYNC(cinfo); /* move the restart point to here */
  170947. marker->bytes_read = bytes_read;
  170948. /* If there's not at least one byte in buffer, suspend */
  170949. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  170950. /* Copy bytes with reasonable rapidity */
  170951. while (bytes_read < data_length && bytes_in_buffer > 0) {
  170952. *data++ = *next_input_byte++;
  170953. bytes_in_buffer--;
  170954. bytes_read++;
  170955. }
  170956. }
  170957. /* Done reading what we want to read */
  170958. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  170959. /* Add new marker to end of list */
  170960. if (cinfo->marker_list == NULL) {
  170961. cinfo->marker_list = cur_marker;
  170962. } else {
  170963. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  170964. while (prev->next != NULL)
  170965. prev = prev->next;
  170966. prev->next = cur_marker;
  170967. }
  170968. /* Reset pointer & calc remaining data length */
  170969. data = cur_marker->data;
  170970. length = cur_marker->original_length - data_length;
  170971. }
  170972. /* Reset to initial state for next marker */
  170973. marker->cur_marker = NULL;
  170974. /* Process the marker if interesting; else just make a generic trace msg */
  170975. switch (cinfo->unread_marker) {
  170976. case M_APP0:
  170977. examine_app0(cinfo, data, data_length, length);
  170978. break;
  170979. case M_APP14:
  170980. examine_app14(cinfo, data, data_length, length);
  170981. break;
  170982. default:
  170983. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  170984. (int) (data_length + length));
  170985. break;
  170986. }
  170987. /* skip any remaining data -- could be lots */
  170988. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170989. if (length > 0)
  170990. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170991. return TRUE;
  170992. }
  170993. #endif /* SAVE_MARKERS_SUPPORTED */
  170994. METHODDEF(boolean)
  170995. skip_variable (j_decompress_ptr cinfo)
  170996. /* Skip over an unknown or uninteresting variable-length marker */
  170997. {
  170998. INT32 length;
  170999. INPUT_VARS(cinfo);
  171000. INPUT_2BYTES(cinfo, length, return FALSE);
  171001. length -= 2;
  171002. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171003. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171004. if (length > 0)
  171005. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171006. return TRUE;
  171007. }
  171008. /*
  171009. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171010. * Returns FALSE if had to suspend before reaching a marker;
  171011. * in that case cinfo->unread_marker is unchanged.
  171012. *
  171013. * Note that the result might not be a valid marker code,
  171014. * but it will never be 0 or FF.
  171015. */
  171016. LOCAL(boolean)
  171017. next_marker (j_decompress_ptr cinfo)
  171018. {
  171019. int c;
  171020. INPUT_VARS(cinfo);
  171021. for (;;) {
  171022. INPUT_BYTE(cinfo, c, return FALSE);
  171023. /* Skip any non-FF bytes.
  171024. * This may look a bit inefficient, but it will not occur in a valid file.
  171025. * We sync after each discarded byte so that a suspending data source
  171026. * can discard the byte from its buffer.
  171027. */
  171028. while (c != 0xFF) {
  171029. cinfo->marker->discarded_bytes++;
  171030. INPUT_SYNC(cinfo);
  171031. INPUT_BYTE(cinfo, c, return FALSE);
  171032. }
  171033. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171034. * pad bytes, so don't count them in discarded_bytes. We assume there
  171035. * will not be so many consecutive FF bytes as to overflow a suspending
  171036. * data source's input buffer.
  171037. */
  171038. do {
  171039. INPUT_BYTE(cinfo, c, return FALSE);
  171040. } while (c == 0xFF);
  171041. if (c != 0)
  171042. break; /* found a valid marker, exit loop */
  171043. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171044. * Discard it and loop back to try again.
  171045. */
  171046. cinfo->marker->discarded_bytes += 2;
  171047. INPUT_SYNC(cinfo);
  171048. }
  171049. if (cinfo->marker->discarded_bytes != 0) {
  171050. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171051. cinfo->marker->discarded_bytes = 0;
  171052. }
  171053. cinfo->unread_marker = c;
  171054. INPUT_SYNC(cinfo);
  171055. return TRUE;
  171056. }
  171057. LOCAL(boolean)
  171058. first_marker (j_decompress_ptr cinfo)
  171059. /* Like next_marker, but used to obtain the initial SOI marker. */
  171060. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171061. * we might well scan an entire input file before realizing it ain't JPEG.
  171062. * If an application wants to process non-JFIF files, it must seek to the
  171063. * SOI before calling the JPEG library.
  171064. */
  171065. {
  171066. int c, c2;
  171067. INPUT_VARS(cinfo);
  171068. INPUT_BYTE(cinfo, c, return FALSE);
  171069. INPUT_BYTE(cinfo, c2, return FALSE);
  171070. if (c != 0xFF || c2 != (int) M_SOI)
  171071. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171072. cinfo->unread_marker = c2;
  171073. INPUT_SYNC(cinfo);
  171074. return TRUE;
  171075. }
  171076. /*
  171077. * Read markers until SOS or EOI.
  171078. *
  171079. * Returns same codes as are defined for jpeg_consume_input:
  171080. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171081. */
  171082. METHODDEF(int)
  171083. read_markers (j_decompress_ptr cinfo)
  171084. {
  171085. /* Outer loop repeats once for each marker. */
  171086. for (;;) {
  171087. /* Collect the marker proper, unless we already did. */
  171088. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171089. if (cinfo->unread_marker == 0) {
  171090. if (! cinfo->marker->saw_SOI) {
  171091. if (! first_marker(cinfo))
  171092. return JPEG_SUSPENDED;
  171093. } else {
  171094. if (! next_marker(cinfo))
  171095. return JPEG_SUSPENDED;
  171096. }
  171097. }
  171098. /* At this point cinfo->unread_marker contains the marker code and the
  171099. * input point is just past the marker proper, but before any parameters.
  171100. * A suspension will cause us to return with this state still true.
  171101. */
  171102. switch (cinfo->unread_marker) {
  171103. case M_SOI:
  171104. if (! get_soi(cinfo))
  171105. return JPEG_SUSPENDED;
  171106. break;
  171107. case M_SOF0: /* Baseline */
  171108. case M_SOF1: /* Extended sequential, Huffman */
  171109. if (! get_sof(cinfo, FALSE, FALSE))
  171110. return JPEG_SUSPENDED;
  171111. break;
  171112. case M_SOF2: /* Progressive, Huffman */
  171113. if (! get_sof(cinfo, TRUE, FALSE))
  171114. return JPEG_SUSPENDED;
  171115. break;
  171116. case M_SOF9: /* Extended sequential, arithmetic */
  171117. if (! get_sof(cinfo, FALSE, TRUE))
  171118. return JPEG_SUSPENDED;
  171119. break;
  171120. case M_SOF10: /* Progressive, arithmetic */
  171121. if (! get_sof(cinfo, TRUE, TRUE))
  171122. return JPEG_SUSPENDED;
  171123. break;
  171124. /* Currently unsupported SOFn types */
  171125. case M_SOF3: /* Lossless, Huffman */
  171126. case M_SOF5: /* Differential sequential, Huffman */
  171127. case M_SOF6: /* Differential progressive, Huffman */
  171128. case M_SOF7: /* Differential lossless, Huffman */
  171129. case M_JPG: /* Reserved for JPEG extensions */
  171130. case M_SOF11: /* Lossless, arithmetic */
  171131. case M_SOF13: /* Differential sequential, arithmetic */
  171132. case M_SOF14: /* Differential progressive, arithmetic */
  171133. case M_SOF15: /* Differential lossless, arithmetic */
  171134. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171135. break;
  171136. case M_SOS:
  171137. if (! get_sos(cinfo))
  171138. return JPEG_SUSPENDED;
  171139. cinfo->unread_marker = 0; /* processed the marker */
  171140. return JPEG_REACHED_SOS;
  171141. case M_EOI:
  171142. TRACEMS(cinfo, 1, JTRC_EOI);
  171143. cinfo->unread_marker = 0; /* processed the marker */
  171144. return JPEG_REACHED_EOI;
  171145. case M_DAC:
  171146. if (! get_dac(cinfo))
  171147. return JPEG_SUSPENDED;
  171148. break;
  171149. case M_DHT:
  171150. if (! get_dht(cinfo))
  171151. return JPEG_SUSPENDED;
  171152. break;
  171153. case M_DQT:
  171154. if (! get_dqt(cinfo))
  171155. return JPEG_SUSPENDED;
  171156. break;
  171157. case M_DRI:
  171158. if (! get_dri(cinfo))
  171159. return JPEG_SUSPENDED;
  171160. break;
  171161. case M_APP0:
  171162. case M_APP1:
  171163. case M_APP2:
  171164. case M_APP3:
  171165. case M_APP4:
  171166. case M_APP5:
  171167. case M_APP6:
  171168. case M_APP7:
  171169. case M_APP8:
  171170. case M_APP9:
  171171. case M_APP10:
  171172. case M_APP11:
  171173. case M_APP12:
  171174. case M_APP13:
  171175. case M_APP14:
  171176. case M_APP15:
  171177. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171178. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171179. return JPEG_SUSPENDED;
  171180. break;
  171181. case M_COM:
  171182. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171183. return JPEG_SUSPENDED;
  171184. break;
  171185. case M_RST0: /* these are all parameterless */
  171186. case M_RST1:
  171187. case M_RST2:
  171188. case M_RST3:
  171189. case M_RST4:
  171190. case M_RST5:
  171191. case M_RST6:
  171192. case M_RST7:
  171193. case M_TEM:
  171194. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171195. break;
  171196. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171197. if (! skip_variable(cinfo))
  171198. return JPEG_SUSPENDED;
  171199. break;
  171200. default: /* must be DHP, EXP, JPGn, or RESn */
  171201. /* For now, we treat the reserved markers as fatal errors since they are
  171202. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171203. * Once the JPEG 3 version-number marker is well defined, this code
  171204. * ought to change!
  171205. */
  171206. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171207. break;
  171208. }
  171209. /* Successfully processed marker, so reset state variable */
  171210. cinfo->unread_marker = 0;
  171211. } /* end loop */
  171212. }
  171213. /*
  171214. * Read a restart marker, which is expected to appear next in the datastream;
  171215. * if the marker is not there, take appropriate recovery action.
  171216. * Returns FALSE if suspension is required.
  171217. *
  171218. * This is called by the entropy decoder after it has read an appropriate
  171219. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171220. * has already read a marker from the data source. Under normal conditions
  171221. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171222. * it holds a marker which the decoder will be unable to read past.
  171223. */
  171224. METHODDEF(boolean)
  171225. read_restart_marker (j_decompress_ptr cinfo)
  171226. {
  171227. /* Obtain a marker unless we already did. */
  171228. /* Note that next_marker will complain if it skips any data. */
  171229. if (cinfo->unread_marker == 0) {
  171230. if (! next_marker(cinfo))
  171231. return FALSE;
  171232. }
  171233. if (cinfo->unread_marker ==
  171234. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171235. /* Normal case --- swallow the marker and let entropy decoder continue */
  171236. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171237. cinfo->unread_marker = 0;
  171238. } else {
  171239. /* Uh-oh, the restart markers have been messed up. */
  171240. /* Let the data source manager determine how to resync. */
  171241. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171242. cinfo->marker->next_restart_num))
  171243. return FALSE;
  171244. }
  171245. /* Update next-restart state */
  171246. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171247. return TRUE;
  171248. }
  171249. /*
  171250. * This is the default resync_to_restart method for data source managers
  171251. * to use if they don't have any better approach. Some data source managers
  171252. * may be able to back up, or may have additional knowledge about the data
  171253. * which permits a more intelligent recovery strategy; such managers would
  171254. * presumably supply their own resync method.
  171255. *
  171256. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171257. * the restart marker it was expecting. (This code is *not* used unless
  171258. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171259. * the marker code actually found (might be anything, except 0 or FF).
  171260. * The desired restart marker number (0..7) is passed as a parameter.
  171261. * This routine is supposed to apply whatever error recovery strategy seems
  171262. * appropriate in order to position the input stream to the next data segment.
  171263. * Note that cinfo->unread_marker is treated as a marker appearing before
  171264. * the current data-source input point; usually it should be reset to zero
  171265. * before returning.
  171266. * Returns FALSE if suspension is required.
  171267. *
  171268. * This implementation is substantially constrained by wanting to treat the
  171269. * input as a data stream; this means we can't back up. Therefore, we have
  171270. * only the following actions to work with:
  171271. * 1. Simply discard the marker and let the entropy decoder resume at next
  171272. * byte of file.
  171273. * 2. Read forward until we find another marker, discarding intervening
  171274. * data. (In theory we could look ahead within the current bufferload,
  171275. * without having to discard data if we don't find the desired marker.
  171276. * This idea is not implemented here, in part because it makes behavior
  171277. * dependent on buffer size and chance buffer-boundary positions.)
  171278. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171279. * This will cause the entropy decoder to process an empty data segment,
  171280. * inserting dummy zeroes, and then we will reprocess the marker.
  171281. *
  171282. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171283. * appropriate if the found marker is a future restart marker (indicating
  171284. * that we have missed the desired restart marker, probably because it got
  171285. * corrupted).
  171286. * We apply #2 or #3 if the found marker is a restart marker no more than
  171287. * two counts behind or ahead of the expected one. We also apply #2 if the
  171288. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171289. * If the found marker is a restart marker more than 2 counts away, we do #1
  171290. * (too much risk that the marker is erroneous; with luck we will be able to
  171291. * resync at some future point).
  171292. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171293. * overrunning the end of a scan. An implementation limited to single-scan
  171294. * files might find it better to apply #2 for markers other than EOI, since
  171295. * any other marker would have to be bogus data in that case.
  171296. */
  171297. GLOBAL(boolean)
  171298. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171299. {
  171300. int marker = cinfo->unread_marker;
  171301. int action = 1;
  171302. /* Always put up a warning. */
  171303. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171304. /* Outer loop handles repeated decision after scanning forward. */
  171305. for (;;) {
  171306. if (marker < (int) M_SOF0)
  171307. action = 2; /* invalid marker */
  171308. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171309. action = 3; /* valid non-restart marker */
  171310. else {
  171311. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171312. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171313. action = 3; /* one of the next two expected restarts */
  171314. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171315. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171316. action = 2; /* a prior restart, so advance */
  171317. else
  171318. action = 1; /* desired restart or too far away */
  171319. }
  171320. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171321. switch (action) {
  171322. case 1:
  171323. /* Discard marker and let entropy decoder resume processing. */
  171324. cinfo->unread_marker = 0;
  171325. return TRUE;
  171326. case 2:
  171327. /* Scan to the next marker, and repeat the decision loop. */
  171328. if (! next_marker(cinfo))
  171329. return FALSE;
  171330. marker = cinfo->unread_marker;
  171331. break;
  171332. case 3:
  171333. /* Return without advancing past this marker. */
  171334. /* Entropy decoder will be forced to process an empty segment. */
  171335. return TRUE;
  171336. }
  171337. } /* end loop */
  171338. }
  171339. /*
  171340. * Reset marker processing state to begin a fresh datastream.
  171341. */
  171342. METHODDEF(void)
  171343. reset_marker_reader (j_decompress_ptr cinfo)
  171344. {
  171345. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171346. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171347. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171348. cinfo->unread_marker = 0; /* no pending marker */
  171349. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171350. marker->pub.saw_SOF = FALSE;
  171351. marker->pub.discarded_bytes = 0;
  171352. marker->cur_marker = NULL;
  171353. }
  171354. /*
  171355. * Initialize the marker reader module.
  171356. * This is called only once, when the decompression object is created.
  171357. */
  171358. GLOBAL(void)
  171359. jinit_marker_reader (j_decompress_ptr cinfo)
  171360. {
  171361. my_marker_ptr2 marker;
  171362. int i;
  171363. /* Create subobject in permanent pool */
  171364. marker = (my_marker_ptr2)
  171365. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171366. SIZEOF(my_marker_reader));
  171367. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171368. /* Initialize public method pointers */
  171369. marker->pub.reset_marker_reader = reset_marker_reader;
  171370. marker->pub.read_markers = read_markers;
  171371. marker->pub.read_restart_marker = read_restart_marker;
  171372. /* Initialize COM/APPn processing.
  171373. * By default, we examine and then discard APP0 and APP14,
  171374. * but simply discard COM and all other APPn.
  171375. */
  171376. marker->process_COM = skip_variable;
  171377. marker->length_limit_COM = 0;
  171378. for (i = 0; i < 16; i++) {
  171379. marker->process_APPn[i] = skip_variable;
  171380. marker->length_limit_APPn[i] = 0;
  171381. }
  171382. marker->process_APPn[0] = get_interesting_appn;
  171383. marker->process_APPn[14] = get_interesting_appn;
  171384. /* Reset marker processing state */
  171385. reset_marker_reader(cinfo);
  171386. }
  171387. /*
  171388. * Control saving of COM and APPn markers into marker_list.
  171389. */
  171390. #ifdef SAVE_MARKERS_SUPPORTED
  171391. GLOBAL(void)
  171392. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171393. unsigned int length_limit)
  171394. {
  171395. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171396. long maxlength;
  171397. jpeg_marker_parser_method processor;
  171398. /* Length limit mustn't be larger than what we can allocate
  171399. * (should only be a concern in a 16-bit environment).
  171400. */
  171401. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171402. if (((long) length_limit) > maxlength)
  171403. length_limit = (unsigned int) maxlength;
  171404. /* Choose processor routine to use.
  171405. * APP0/APP14 have special requirements.
  171406. */
  171407. if (length_limit) {
  171408. processor = save_marker;
  171409. /* If saving APP0/APP14, save at least enough for our internal use. */
  171410. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171411. length_limit = APP0_DATA_LEN;
  171412. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171413. length_limit = APP14_DATA_LEN;
  171414. } else {
  171415. processor = skip_variable;
  171416. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171417. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171418. processor = get_interesting_appn;
  171419. }
  171420. if (marker_code == (int) M_COM) {
  171421. marker->process_COM = processor;
  171422. marker->length_limit_COM = length_limit;
  171423. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171424. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171425. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171426. } else
  171427. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171428. }
  171429. #endif /* SAVE_MARKERS_SUPPORTED */
  171430. /*
  171431. * Install a special processing method for COM or APPn markers.
  171432. */
  171433. GLOBAL(void)
  171434. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171435. jpeg_marker_parser_method routine)
  171436. {
  171437. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171438. if (marker_code == (int) M_COM)
  171439. marker->process_COM = routine;
  171440. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171441. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171442. else
  171443. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171444. }
  171445. /*** End of inlined file: jdmarker.c ***/
  171446. /*** Start of inlined file: jdmaster.c ***/
  171447. #define JPEG_INTERNALS
  171448. /* Private state */
  171449. typedef struct {
  171450. struct jpeg_decomp_master pub; /* public fields */
  171451. int pass_number; /* # of passes completed */
  171452. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171453. /* Saved references to initialized quantizer modules,
  171454. * in case we need to switch modes.
  171455. */
  171456. struct jpeg_color_quantizer * quantizer_1pass;
  171457. struct jpeg_color_quantizer * quantizer_2pass;
  171458. } my_decomp_master;
  171459. typedef my_decomp_master * my_master_ptr6;
  171460. /*
  171461. * Determine whether merged upsample/color conversion should be used.
  171462. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171463. */
  171464. LOCAL(boolean)
  171465. use_merged_upsample (j_decompress_ptr cinfo)
  171466. {
  171467. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171468. /* Merging is the equivalent of plain box-filter upsampling */
  171469. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171470. return FALSE;
  171471. /* jdmerge.c only supports YCC=>RGB color conversion */
  171472. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171473. cinfo->out_color_space != JCS_RGB ||
  171474. cinfo->out_color_components != RGB_PIXELSIZE)
  171475. return FALSE;
  171476. /* and it only handles 2h1v or 2h2v sampling ratios */
  171477. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171478. cinfo->comp_info[1].h_samp_factor != 1 ||
  171479. cinfo->comp_info[2].h_samp_factor != 1 ||
  171480. cinfo->comp_info[0].v_samp_factor > 2 ||
  171481. cinfo->comp_info[1].v_samp_factor != 1 ||
  171482. cinfo->comp_info[2].v_samp_factor != 1)
  171483. return FALSE;
  171484. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171485. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171486. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171487. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171488. return FALSE;
  171489. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171490. return TRUE; /* by golly, it'll work... */
  171491. #else
  171492. return FALSE;
  171493. #endif
  171494. }
  171495. /*
  171496. * Compute output image dimensions and related values.
  171497. * NOTE: this is exported for possible use by application.
  171498. * Hence it mustn't do anything that can't be done twice.
  171499. * Also note that it may be called before the master module is initialized!
  171500. */
  171501. GLOBAL(void)
  171502. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171503. /* Do computations that are needed before master selection phase */
  171504. {
  171505. #ifdef IDCT_SCALING_SUPPORTED
  171506. int ci;
  171507. jpeg_component_info *compptr;
  171508. #endif
  171509. /* Prevent application from calling me at wrong times */
  171510. if (cinfo->global_state != DSTATE_READY)
  171511. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171512. #ifdef IDCT_SCALING_SUPPORTED
  171513. /* Compute actual output image dimensions and DCT scaling choices. */
  171514. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171515. /* Provide 1/8 scaling */
  171516. cinfo->output_width = (JDIMENSION)
  171517. jdiv_round_up((long) cinfo->image_width, 8L);
  171518. cinfo->output_height = (JDIMENSION)
  171519. jdiv_round_up((long) cinfo->image_height, 8L);
  171520. cinfo->min_DCT_scaled_size = 1;
  171521. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171522. /* Provide 1/4 scaling */
  171523. cinfo->output_width = (JDIMENSION)
  171524. jdiv_round_up((long) cinfo->image_width, 4L);
  171525. cinfo->output_height = (JDIMENSION)
  171526. jdiv_round_up((long) cinfo->image_height, 4L);
  171527. cinfo->min_DCT_scaled_size = 2;
  171528. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171529. /* Provide 1/2 scaling */
  171530. cinfo->output_width = (JDIMENSION)
  171531. jdiv_round_up((long) cinfo->image_width, 2L);
  171532. cinfo->output_height = (JDIMENSION)
  171533. jdiv_round_up((long) cinfo->image_height, 2L);
  171534. cinfo->min_DCT_scaled_size = 4;
  171535. } else {
  171536. /* Provide 1/1 scaling */
  171537. cinfo->output_width = cinfo->image_width;
  171538. cinfo->output_height = cinfo->image_height;
  171539. cinfo->min_DCT_scaled_size = DCTSIZE;
  171540. }
  171541. /* In selecting the actual DCT scaling for each component, we try to
  171542. * scale up the chroma components via IDCT scaling rather than upsampling.
  171543. * This saves time if the upsampler gets to use 1:1 scaling.
  171544. * Note this code assumes that the supported DCT scalings are powers of 2.
  171545. */
  171546. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171547. ci++, compptr++) {
  171548. int ssize = cinfo->min_DCT_scaled_size;
  171549. while (ssize < DCTSIZE &&
  171550. (compptr->h_samp_factor * ssize * 2 <=
  171551. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171552. (compptr->v_samp_factor * ssize * 2 <=
  171553. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171554. ssize = ssize * 2;
  171555. }
  171556. compptr->DCT_scaled_size = ssize;
  171557. }
  171558. /* Recompute downsampled dimensions of components;
  171559. * application needs to know these if using raw downsampled data.
  171560. */
  171561. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171562. ci++, compptr++) {
  171563. /* Size in samples, after IDCT scaling */
  171564. compptr->downsampled_width = (JDIMENSION)
  171565. jdiv_round_up((long) cinfo->image_width *
  171566. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171567. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171568. compptr->downsampled_height = (JDIMENSION)
  171569. jdiv_round_up((long) cinfo->image_height *
  171570. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171571. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171572. }
  171573. #else /* !IDCT_SCALING_SUPPORTED */
  171574. /* Hardwire it to "no scaling" */
  171575. cinfo->output_width = cinfo->image_width;
  171576. cinfo->output_height = cinfo->image_height;
  171577. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171578. * and has computed unscaled downsampled_width and downsampled_height.
  171579. */
  171580. #endif /* IDCT_SCALING_SUPPORTED */
  171581. /* Report number of components in selected colorspace. */
  171582. /* Probably this should be in the color conversion module... */
  171583. switch (cinfo->out_color_space) {
  171584. case JCS_GRAYSCALE:
  171585. cinfo->out_color_components = 1;
  171586. break;
  171587. case JCS_RGB:
  171588. #if RGB_PIXELSIZE != 3
  171589. cinfo->out_color_components = RGB_PIXELSIZE;
  171590. break;
  171591. #endif /* else share code with YCbCr */
  171592. case JCS_YCbCr:
  171593. cinfo->out_color_components = 3;
  171594. break;
  171595. case JCS_CMYK:
  171596. case JCS_YCCK:
  171597. cinfo->out_color_components = 4;
  171598. break;
  171599. default: /* else must be same colorspace as in file */
  171600. cinfo->out_color_components = cinfo->num_components;
  171601. break;
  171602. }
  171603. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171604. cinfo->out_color_components);
  171605. /* See if upsampler will want to emit more than one row at a time */
  171606. if (use_merged_upsample(cinfo))
  171607. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171608. else
  171609. cinfo->rec_outbuf_height = 1;
  171610. }
  171611. /*
  171612. * Several decompression processes need to range-limit values to the range
  171613. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171614. * due to noise introduced by quantization, roundoff error, etc. These
  171615. * processes are inner loops and need to be as fast as possible. On most
  171616. * machines, particularly CPUs with pipelines or instruction prefetch,
  171617. * a (subscript-check-less) C table lookup
  171618. * x = sample_range_limit[x];
  171619. * is faster than explicit tests
  171620. * if (x < 0) x = 0;
  171621. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171622. * These processes all use a common table prepared by the routine below.
  171623. *
  171624. * For most steps we can mathematically guarantee that the initial value
  171625. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171626. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171627. * limiting step (just after the IDCT), a wildly out-of-range value is
  171628. * possible if the input data is corrupt. To avoid any chance of indexing
  171629. * off the end of memory and getting a bad-pointer trap, we perform the
  171630. * post-IDCT limiting thus:
  171631. * x = range_limit[x & MASK];
  171632. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171633. * samples. Under normal circumstances this is more than enough range and
  171634. * a correct output will be generated; with bogus input data the mask will
  171635. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171636. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171637. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171638. * So the post-IDCT limiting table ends up looking like this:
  171639. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171640. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171641. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171642. * 0,1,...,CENTERJSAMPLE-1
  171643. * Negative inputs select values from the upper half of the table after
  171644. * masking.
  171645. *
  171646. * We can save some space by overlapping the start of the post-IDCT table
  171647. * with the simpler range limiting table. The post-IDCT table begins at
  171648. * sample_range_limit + CENTERJSAMPLE.
  171649. *
  171650. * Note that the table is allocated in near data space on PCs; it's small
  171651. * enough and used often enough to justify this.
  171652. */
  171653. LOCAL(void)
  171654. prepare_range_limit_table (j_decompress_ptr cinfo)
  171655. /* Allocate and fill in the sample_range_limit table */
  171656. {
  171657. JSAMPLE * table;
  171658. int i;
  171659. table = (JSAMPLE *)
  171660. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171661. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171662. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171663. cinfo->sample_range_limit = table;
  171664. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171665. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171666. /* Main part of "simple" table: limit[x] = x */
  171667. for (i = 0; i <= MAXJSAMPLE; i++)
  171668. table[i] = (JSAMPLE) i;
  171669. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171670. /* End of simple table, rest of first half of post-IDCT table */
  171671. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171672. table[i] = MAXJSAMPLE;
  171673. /* Second half of post-IDCT table */
  171674. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171675. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171676. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171677. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171678. }
  171679. /*
  171680. * Master selection of decompression modules.
  171681. * This is done once at jpeg_start_decompress time. We determine
  171682. * which modules will be used and give them appropriate initialization calls.
  171683. * We also initialize the decompressor input side to begin consuming data.
  171684. *
  171685. * Since jpeg_read_header has finished, we know what is in the SOF
  171686. * and (first) SOS markers. We also have all the application parameter
  171687. * settings.
  171688. */
  171689. LOCAL(void)
  171690. master_selection (j_decompress_ptr cinfo)
  171691. {
  171692. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171693. boolean use_c_buffer;
  171694. long samplesperrow;
  171695. JDIMENSION jd_samplesperrow;
  171696. /* Initialize dimensions and other stuff */
  171697. jpeg_calc_output_dimensions(cinfo);
  171698. prepare_range_limit_table(cinfo);
  171699. /* Width of an output scanline must be representable as JDIMENSION. */
  171700. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171701. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171702. if ((long) jd_samplesperrow != samplesperrow)
  171703. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171704. /* Initialize my private state */
  171705. master->pass_number = 0;
  171706. master->using_merged_upsample = use_merged_upsample(cinfo);
  171707. /* Color quantizer selection */
  171708. master->quantizer_1pass = NULL;
  171709. master->quantizer_2pass = NULL;
  171710. /* No mode changes if not using buffered-image mode. */
  171711. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171712. cinfo->enable_1pass_quant = FALSE;
  171713. cinfo->enable_external_quant = FALSE;
  171714. cinfo->enable_2pass_quant = FALSE;
  171715. }
  171716. if (cinfo->quantize_colors) {
  171717. if (cinfo->raw_data_out)
  171718. ERREXIT(cinfo, JERR_NOTIMPL);
  171719. /* 2-pass quantizer only works in 3-component color space. */
  171720. if (cinfo->out_color_components != 3) {
  171721. cinfo->enable_1pass_quant = TRUE;
  171722. cinfo->enable_external_quant = FALSE;
  171723. cinfo->enable_2pass_quant = FALSE;
  171724. cinfo->colormap = NULL;
  171725. } else if (cinfo->colormap != NULL) {
  171726. cinfo->enable_external_quant = TRUE;
  171727. } else if (cinfo->two_pass_quantize) {
  171728. cinfo->enable_2pass_quant = TRUE;
  171729. } else {
  171730. cinfo->enable_1pass_quant = TRUE;
  171731. }
  171732. if (cinfo->enable_1pass_quant) {
  171733. #ifdef QUANT_1PASS_SUPPORTED
  171734. jinit_1pass_quantizer(cinfo);
  171735. master->quantizer_1pass = cinfo->cquantize;
  171736. #else
  171737. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171738. #endif
  171739. }
  171740. /* We use the 2-pass code to map to external colormaps. */
  171741. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171742. #ifdef QUANT_2PASS_SUPPORTED
  171743. jinit_2pass_quantizer(cinfo);
  171744. master->quantizer_2pass = cinfo->cquantize;
  171745. #else
  171746. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171747. #endif
  171748. }
  171749. /* If both quantizers are initialized, the 2-pass one is left active;
  171750. * this is necessary for starting with quantization to an external map.
  171751. */
  171752. }
  171753. /* Post-processing: in particular, color conversion first */
  171754. if (! cinfo->raw_data_out) {
  171755. if (master->using_merged_upsample) {
  171756. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171757. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171758. #else
  171759. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171760. #endif
  171761. } else {
  171762. jinit_color_deconverter(cinfo);
  171763. jinit_upsampler(cinfo);
  171764. }
  171765. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171766. }
  171767. /* Inverse DCT */
  171768. jinit_inverse_dct(cinfo);
  171769. /* Entropy decoding: either Huffman or arithmetic coding. */
  171770. if (cinfo->arith_code) {
  171771. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171772. } else {
  171773. if (cinfo->progressive_mode) {
  171774. #ifdef D_PROGRESSIVE_SUPPORTED
  171775. jinit_phuff_decoder(cinfo);
  171776. #else
  171777. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171778. #endif
  171779. } else
  171780. jinit_huff_decoder(cinfo);
  171781. }
  171782. /* Initialize principal buffer controllers. */
  171783. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171784. jinit_d_coef_controller(cinfo, use_c_buffer);
  171785. if (! cinfo->raw_data_out)
  171786. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171787. /* We can now tell the memory manager to allocate virtual arrays. */
  171788. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171789. /* Initialize input side of decompressor to consume first scan. */
  171790. (*cinfo->inputctl->start_input_pass) (cinfo);
  171791. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171792. /* If jpeg_start_decompress will read the whole file, initialize
  171793. * progress monitoring appropriately. The input step is counted
  171794. * as one pass.
  171795. */
  171796. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171797. cinfo->inputctl->has_multiple_scans) {
  171798. int nscans;
  171799. /* Estimate number of scans to set pass_limit. */
  171800. if (cinfo->progressive_mode) {
  171801. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171802. nscans = 2 + 3 * cinfo->num_components;
  171803. } else {
  171804. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171805. nscans = cinfo->num_components;
  171806. }
  171807. cinfo->progress->pass_counter = 0L;
  171808. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171809. cinfo->progress->completed_passes = 0;
  171810. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171811. /* Count the input pass as done */
  171812. master->pass_number++;
  171813. }
  171814. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171815. }
  171816. /*
  171817. * Per-pass setup.
  171818. * This is called at the beginning of each output pass. We determine which
  171819. * modules will be active during this pass and give them appropriate
  171820. * start_pass calls. We also set is_dummy_pass to indicate whether this
  171821. * is a "real" output pass or a dummy pass for color quantization.
  171822. * (In the latter case, jdapistd.c will crank the pass to completion.)
  171823. */
  171824. METHODDEF(void)
  171825. prepare_for_output_pass (j_decompress_ptr cinfo)
  171826. {
  171827. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171828. if (master->pub.is_dummy_pass) {
  171829. #ifdef QUANT_2PASS_SUPPORTED
  171830. /* Final pass of 2-pass quantization */
  171831. master->pub.is_dummy_pass = FALSE;
  171832. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  171833. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  171834. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  171835. #else
  171836. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171837. #endif /* QUANT_2PASS_SUPPORTED */
  171838. } else {
  171839. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  171840. /* Select new quantization method */
  171841. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  171842. cinfo->cquantize = master->quantizer_2pass;
  171843. master->pub.is_dummy_pass = TRUE;
  171844. } else if (cinfo->enable_1pass_quant) {
  171845. cinfo->cquantize = master->quantizer_1pass;
  171846. } else {
  171847. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171848. }
  171849. }
  171850. (*cinfo->idct->start_pass) (cinfo);
  171851. (*cinfo->coef->start_output_pass) (cinfo);
  171852. if (! cinfo->raw_data_out) {
  171853. if (! master->using_merged_upsample)
  171854. (*cinfo->cconvert->start_pass) (cinfo);
  171855. (*cinfo->upsample->start_pass) (cinfo);
  171856. if (cinfo->quantize_colors)
  171857. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  171858. (*cinfo->post->start_pass) (cinfo,
  171859. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  171860. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  171861. }
  171862. }
  171863. /* Set up progress monitor's pass info if present */
  171864. if (cinfo->progress != NULL) {
  171865. cinfo->progress->completed_passes = master->pass_number;
  171866. cinfo->progress->total_passes = master->pass_number +
  171867. (master->pub.is_dummy_pass ? 2 : 1);
  171868. /* In buffered-image mode, we assume one more output pass if EOI not
  171869. * yet reached, but no more passes if EOI has been reached.
  171870. */
  171871. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  171872. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  171873. }
  171874. }
  171875. }
  171876. /*
  171877. * Finish up at end of an output pass.
  171878. */
  171879. METHODDEF(void)
  171880. finish_output_pass (j_decompress_ptr cinfo)
  171881. {
  171882. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171883. if (cinfo->quantize_colors)
  171884. (*cinfo->cquantize->finish_pass) (cinfo);
  171885. master->pass_number++;
  171886. }
  171887. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171888. /*
  171889. * Switch to a new external colormap between output passes.
  171890. */
  171891. GLOBAL(void)
  171892. jpeg_new_colormap (j_decompress_ptr cinfo)
  171893. {
  171894. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171895. /* Prevent application from calling me at wrong times */
  171896. if (cinfo->global_state != DSTATE_BUFIMAGE)
  171897. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171898. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  171899. cinfo->colormap != NULL) {
  171900. /* Select 2-pass quantizer for external colormap use */
  171901. cinfo->cquantize = master->quantizer_2pass;
  171902. /* Notify quantizer of colormap change */
  171903. (*cinfo->cquantize->new_color_map) (cinfo);
  171904. master->pub.is_dummy_pass = FALSE; /* just in case */
  171905. } else
  171906. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171907. }
  171908. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171909. /*
  171910. * Initialize master decompression control and select active modules.
  171911. * This is performed at the start of jpeg_start_decompress.
  171912. */
  171913. GLOBAL(void)
  171914. jinit_master_decompress (j_decompress_ptr cinfo)
  171915. {
  171916. my_master_ptr6 master;
  171917. master = (my_master_ptr6)
  171918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171919. SIZEOF(my_decomp_master));
  171920. cinfo->master = (struct jpeg_decomp_master *) master;
  171921. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  171922. master->pub.finish_output_pass = finish_output_pass;
  171923. master->pub.is_dummy_pass = FALSE;
  171924. master_selection(cinfo);
  171925. }
  171926. /*** End of inlined file: jdmaster.c ***/
  171927. #undef FIX
  171928. /*** Start of inlined file: jdmerge.c ***/
  171929. #define JPEG_INTERNALS
  171930. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171931. /* Private subobject */
  171932. typedef struct {
  171933. struct jpeg_upsampler pub; /* public fields */
  171934. /* Pointer to routine to do actual upsampling/conversion of one row group */
  171935. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  171936. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171937. JSAMPARRAY output_buf));
  171938. /* Private state for YCC->RGB conversion */
  171939. int * Cr_r_tab; /* => table for Cr to R conversion */
  171940. int * Cb_b_tab; /* => table for Cb to B conversion */
  171941. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  171942. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  171943. /* For 2:1 vertical sampling, we produce two output rows at a time.
  171944. * We need a "spare" row buffer to hold the second output row if the
  171945. * application provides just a one-row buffer; we also use the spare
  171946. * to discard the dummy last row if the image height is odd.
  171947. */
  171948. JSAMPROW spare_row;
  171949. boolean spare_full; /* T if spare buffer is occupied */
  171950. JDIMENSION out_row_width; /* samples per output row */
  171951. JDIMENSION rows_to_go; /* counts rows remaining in image */
  171952. } my_upsampler;
  171953. typedef my_upsampler * my_upsample_ptr;
  171954. #define SCALEBITS 16 /* speediest right-shift on some machines */
  171955. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  171956. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  171957. /*
  171958. * Initialize tables for YCC->RGB colorspace conversion.
  171959. * This is taken directly from jdcolor.c; see that file for more info.
  171960. */
  171961. LOCAL(void)
  171962. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  171963. {
  171964. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171965. int i;
  171966. INT32 x;
  171967. SHIFT_TEMPS
  171968. upsample->Cr_r_tab = (int *)
  171969. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171970. (MAXJSAMPLE+1) * SIZEOF(int));
  171971. upsample->Cb_b_tab = (int *)
  171972. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171973. (MAXJSAMPLE+1) * SIZEOF(int));
  171974. upsample->Cr_g_tab = (INT32 *)
  171975. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171976. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171977. upsample->Cb_g_tab = (INT32 *)
  171978. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171979. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171980. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  171981. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  171982. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  171983. /* Cr=>R value is nearest int to 1.40200 * x */
  171984. upsample->Cr_r_tab[i] = (int)
  171985. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  171986. /* Cb=>B value is nearest int to 1.77200 * x */
  171987. upsample->Cb_b_tab[i] = (int)
  171988. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  171989. /* Cr=>G value is scaled-up -0.71414 * x */
  171990. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  171991. /* Cb=>G value is scaled-up -0.34414 * x */
  171992. /* We also add in ONE_HALF so that need not do it in inner loop */
  171993. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  171994. }
  171995. }
  171996. /*
  171997. * Initialize for an upsampling pass.
  171998. */
  171999. METHODDEF(void)
  172000. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172001. {
  172002. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172003. /* Mark the spare buffer empty */
  172004. upsample->spare_full = FALSE;
  172005. /* Initialize total-height counter for detecting bottom of image */
  172006. upsample->rows_to_go = cinfo->output_height;
  172007. }
  172008. /*
  172009. * Control routine to do upsampling (and color conversion).
  172010. *
  172011. * The control routine just handles the row buffering considerations.
  172012. */
  172013. METHODDEF(void)
  172014. merged_2v_upsample (j_decompress_ptr cinfo,
  172015. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172016. JDIMENSION,
  172017. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172018. JDIMENSION out_rows_avail)
  172019. /* 2:1 vertical sampling case: may need a spare row. */
  172020. {
  172021. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172022. JSAMPROW work_ptrs[2];
  172023. JDIMENSION num_rows; /* number of rows returned to caller */
  172024. if (upsample->spare_full) {
  172025. /* If we have a spare row saved from a previous cycle, just return it. */
  172026. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172027. 1, upsample->out_row_width);
  172028. num_rows = 1;
  172029. upsample->spare_full = FALSE;
  172030. } else {
  172031. /* Figure number of rows to return to caller. */
  172032. num_rows = 2;
  172033. /* Not more than the distance to the end of the image. */
  172034. if (num_rows > upsample->rows_to_go)
  172035. num_rows = upsample->rows_to_go;
  172036. /* And not more than what the client can accept: */
  172037. out_rows_avail -= *out_row_ctr;
  172038. if (num_rows > out_rows_avail)
  172039. num_rows = out_rows_avail;
  172040. /* Create output pointer array for upsampler. */
  172041. work_ptrs[0] = output_buf[*out_row_ctr];
  172042. if (num_rows > 1) {
  172043. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172044. } else {
  172045. work_ptrs[1] = upsample->spare_row;
  172046. upsample->spare_full = TRUE;
  172047. }
  172048. /* Now do the upsampling. */
  172049. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172050. }
  172051. /* Adjust counts */
  172052. *out_row_ctr += num_rows;
  172053. upsample->rows_to_go -= num_rows;
  172054. /* When the buffer is emptied, declare this input row group consumed */
  172055. if (! upsample->spare_full)
  172056. (*in_row_group_ctr)++;
  172057. }
  172058. METHODDEF(void)
  172059. merged_1v_upsample (j_decompress_ptr cinfo,
  172060. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172061. JDIMENSION,
  172062. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172063. JDIMENSION)
  172064. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172065. {
  172066. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172067. /* Just do the upsampling. */
  172068. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172069. output_buf + *out_row_ctr);
  172070. /* Adjust counts */
  172071. (*out_row_ctr)++;
  172072. (*in_row_group_ctr)++;
  172073. }
  172074. /*
  172075. * These are the routines invoked by the control routines to do
  172076. * the actual upsampling/conversion. One row group is processed per call.
  172077. *
  172078. * Note: since we may be writing directly into application-supplied buffers,
  172079. * we have to be honest about the output width; we can't assume the buffer
  172080. * has been rounded up to an even width.
  172081. */
  172082. /*
  172083. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172084. */
  172085. METHODDEF(void)
  172086. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172087. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172088. JSAMPARRAY output_buf)
  172089. {
  172090. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172091. register int y, cred, cgreen, cblue;
  172092. int cb, cr;
  172093. register JSAMPROW outptr;
  172094. JSAMPROW inptr0, inptr1, inptr2;
  172095. JDIMENSION col;
  172096. /* copy these pointers into registers if possible */
  172097. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172098. int * Crrtab = upsample->Cr_r_tab;
  172099. int * Cbbtab = upsample->Cb_b_tab;
  172100. INT32 * Crgtab = upsample->Cr_g_tab;
  172101. INT32 * Cbgtab = upsample->Cb_g_tab;
  172102. SHIFT_TEMPS
  172103. inptr0 = input_buf[0][in_row_group_ctr];
  172104. inptr1 = input_buf[1][in_row_group_ctr];
  172105. inptr2 = input_buf[2][in_row_group_ctr];
  172106. outptr = output_buf[0];
  172107. /* Loop for each pair of output pixels */
  172108. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172109. /* Do the chroma part of the calculation */
  172110. cb = GETJSAMPLE(*inptr1++);
  172111. cr = GETJSAMPLE(*inptr2++);
  172112. cred = Crrtab[cr];
  172113. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172114. cblue = Cbbtab[cb];
  172115. /* Fetch 2 Y values and emit 2 pixels */
  172116. y = GETJSAMPLE(*inptr0++);
  172117. outptr[RGB_RED] = range_limit[y + cred];
  172118. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172119. outptr[RGB_BLUE] = range_limit[y + cblue];
  172120. outptr += RGB_PIXELSIZE;
  172121. y = GETJSAMPLE(*inptr0++);
  172122. outptr[RGB_RED] = range_limit[y + cred];
  172123. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172124. outptr[RGB_BLUE] = range_limit[y + cblue];
  172125. outptr += RGB_PIXELSIZE;
  172126. }
  172127. /* If image width is odd, do the last output column separately */
  172128. if (cinfo->output_width & 1) {
  172129. cb = GETJSAMPLE(*inptr1);
  172130. cr = GETJSAMPLE(*inptr2);
  172131. cred = Crrtab[cr];
  172132. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172133. cblue = Cbbtab[cb];
  172134. y = GETJSAMPLE(*inptr0);
  172135. outptr[RGB_RED] = range_limit[y + cred];
  172136. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172137. outptr[RGB_BLUE] = range_limit[y + cblue];
  172138. }
  172139. }
  172140. /*
  172141. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172142. */
  172143. METHODDEF(void)
  172144. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172145. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172146. JSAMPARRAY output_buf)
  172147. {
  172148. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172149. register int y, cred, cgreen, cblue;
  172150. int cb, cr;
  172151. register JSAMPROW outptr0, outptr1;
  172152. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172153. JDIMENSION col;
  172154. /* copy these pointers into registers if possible */
  172155. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172156. int * Crrtab = upsample->Cr_r_tab;
  172157. int * Cbbtab = upsample->Cb_b_tab;
  172158. INT32 * Crgtab = upsample->Cr_g_tab;
  172159. INT32 * Cbgtab = upsample->Cb_g_tab;
  172160. SHIFT_TEMPS
  172161. inptr00 = input_buf[0][in_row_group_ctr*2];
  172162. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172163. inptr1 = input_buf[1][in_row_group_ctr];
  172164. inptr2 = input_buf[2][in_row_group_ctr];
  172165. outptr0 = output_buf[0];
  172166. outptr1 = output_buf[1];
  172167. /* Loop for each group of output pixels */
  172168. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172169. /* Do the chroma part of the calculation */
  172170. cb = GETJSAMPLE(*inptr1++);
  172171. cr = GETJSAMPLE(*inptr2++);
  172172. cred = Crrtab[cr];
  172173. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172174. cblue = Cbbtab[cb];
  172175. /* Fetch 4 Y values and emit 4 pixels */
  172176. y = GETJSAMPLE(*inptr00++);
  172177. outptr0[RGB_RED] = range_limit[y + cred];
  172178. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172179. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172180. outptr0 += RGB_PIXELSIZE;
  172181. y = GETJSAMPLE(*inptr00++);
  172182. outptr0[RGB_RED] = range_limit[y + cred];
  172183. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172184. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172185. outptr0 += RGB_PIXELSIZE;
  172186. y = GETJSAMPLE(*inptr01++);
  172187. outptr1[RGB_RED] = range_limit[y + cred];
  172188. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172189. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172190. outptr1 += RGB_PIXELSIZE;
  172191. y = GETJSAMPLE(*inptr01++);
  172192. outptr1[RGB_RED] = range_limit[y + cred];
  172193. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172194. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172195. outptr1 += RGB_PIXELSIZE;
  172196. }
  172197. /* If image width is odd, do the last output column separately */
  172198. if (cinfo->output_width & 1) {
  172199. cb = GETJSAMPLE(*inptr1);
  172200. cr = GETJSAMPLE(*inptr2);
  172201. cred = Crrtab[cr];
  172202. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172203. cblue = Cbbtab[cb];
  172204. y = GETJSAMPLE(*inptr00);
  172205. outptr0[RGB_RED] = range_limit[y + cred];
  172206. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172207. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172208. y = GETJSAMPLE(*inptr01);
  172209. outptr1[RGB_RED] = range_limit[y + cred];
  172210. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172211. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172212. }
  172213. }
  172214. /*
  172215. * Module initialization routine for merged upsampling/color conversion.
  172216. *
  172217. * NB: this is called under the conditions determined by use_merged_upsample()
  172218. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172219. * of this module; no safety checks are made here.
  172220. */
  172221. GLOBAL(void)
  172222. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172223. {
  172224. my_upsample_ptr upsample;
  172225. upsample = (my_upsample_ptr)
  172226. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172227. SIZEOF(my_upsampler));
  172228. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172229. upsample->pub.start_pass = start_pass_merged_upsample;
  172230. upsample->pub.need_context_rows = FALSE;
  172231. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172232. if (cinfo->max_v_samp_factor == 2) {
  172233. upsample->pub.upsample = merged_2v_upsample;
  172234. upsample->upmethod = h2v2_merged_upsample;
  172235. /* Allocate a spare row buffer */
  172236. upsample->spare_row = (JSAMPROW)
  172237. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172238. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172239. } else {
  172240. upsample->pub.upsample = merged_1v_upsample;
  172241. upsample->upmethod = h2v1_merged_upsample;
  172242. /* No spare row needed */
  172243. upsample->spare_row = NULL;
  172244. }
  172245. build_ycc_rgb_table2(cinfo);
  172246. }
  172247. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172248. /*** End of inlined file: jdmerge.c ***/
  172249. #undef ASSIGN_STATE
  172250. /*** Start of inlined file: jdphuff.c ***/
  172251. #define JPEG_INTERNALS
  172252. #ifdef D_PROGRESSIVE_SUPPORTED
  172253. /*
  172254. * Expanded entropy decoder object for progressive Huffman decoding.
  172255. *
  172256. * The savable_state subrecord contains fields that change within an MCU,
  172257. * but must not be updated permanently until we complete the MCU.
  172258. */
  172259. typedef struct {
  172260. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172261. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172262. } savable_state3;
  172263. /* This macro is to work around compilers with missing or broken
  172264. * structure assignment. You'll need to fix this code if you have
  172265. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172266. */
  172267. #ifndef NO_STRUCT_ASSIGN
  172268. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172269. #else
  172270. #if MAX_COMPS_IN_SCAN == 4
  172271. #define ASSIGN_STATE(dest,src) \
  172272. ((dest).EOBRUN = (src).EOBRUN, \
  172273. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172274. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172275. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172276. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172277. #endif
  172278. #endif
  172279. typedef struct {
  172280. struct jpeg_entropy_decoder pub; /* public fields */
  172281. /* These fields are loaded into local variables at start of each MCU.
  172282. * In case of suspension, we exit WITHOUT updating them.
  172283. */
  172284. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172285. savable_state3 saved; /* Other state at start of MCU */
  172286. /* These fields are NOT loaded into local working state. */
  172287. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172288. /* Pointers to derived tables (these workspaces have image lifespan) */
  172289. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172290. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172291. } phuff_entropy_decoder;
  172292. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172293. /* Forward declarations */
  172294. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172295. JBLOCKROW *MCU_data));
  172296. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172297. JBLOCKROW *MCU_data));
  172298. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172299. JBLOCKROW *MCU_data));
  172300. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172301. JBLOCKROW *MCU_data));
  172302. /*
  172303. * Initialize for a Huffman-compressed scan.
  172304. */
  172305. METHODDEF(void)
  172306. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172307. {
  172308. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172309. boolean is_DC_band, bad;
  172310. int ci, coefi, tbl;
  172311. int *coef_bit_ptr;
  172312. jpeg_component_info * compptr;
  172313. is_DC_band = (cinfo->Ss == 0);
  172314. /* Validate scan parameters */
  172315. bad = FALSE;
  172316. if (is_DC_band) {
  172317. if (cinfo->Se != 0)
  172318. bad = TRUE;
  172319. } else {
  172320. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172321. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172322. bad = TRUE;
  172323. /* AC scans may have only one component */
  172324. if (cinfo->comps_in_scan != 1)
  172325. bad = TRUE;
  172326. }
  172327. if (cinfo->Ah != 0) {
  172328. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172329. if (cinfo->Al != cinfo->Ah-1)
  172330. bad = TRUE;
  172331. }
  172332. if (cinfo->Al > 13) /* need not check for < 0 */
  172333. bad = TRUE;
  172334. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172335. * but the spec doesn't say so, and we try to be liberal about what we
  172336. * accept. Note: large Al values could result in out-of-range DC
  172337. * coefficients during early scans, leading to bizarre displays due to
  172338. * overflows in the IDCT math. But we won't crash.
  172339. */
  172340. if (bad)
  172341. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172342. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172343. /* Update progression status, and verify that scan order is legal.
  172344. * Note that inter-scan inconsistencies are treated as warnings
  172345. * not fatal errors ... not clear if this is right way to behave.
  172346. */
  172347. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172348. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172349. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172350. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172351. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172352. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172353. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172354. if (cinfo->Ah != expected)
  172355. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172356. coef_bit_ptr[coefi] = cinfo->Al;
  172357. }
  172358. }
  172359. /* Select MCU decoding routine */
  172360. if (cinfo->Ah == 0) {
  172361. if (is_DC_band)
  172362. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172363. else
  172364. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172365. } else {
  172366. if (is_DC_band)
  172367. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172368. else
  172369. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172370. }
  172371. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172372. compptr = cinfo->cur_comp_info[ci];
  172373. /* Make sure requested tables are present, and compute derived tables.
  172374. * We may build same derived table more than once, but it's not expensive.
  172375. */
  172376. if (is_DC_band) {
  172377. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172378. tbl = compptr->dc_tbl_no;
  172379. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172380. & entropy->derived_tbls[tbl]);
  172381. }
  172382. } else {
  172383. tbl = compptr->ac_tbl_no;
  172384. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172385. & entropy->derived_tbls[tbl]);
  172386. /* remember the single active table */
  172387. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172388. }
  172389. /* Initialize DC predictions to 0 */
  172390. entropy->saved.last_dc_val[ci] = 0;
  172391. }
  172392. /* Initialize bitread state variables */
  172393. entropy->bitstate.bits_left = 0;
  172394. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172395. entropy->pub.insufficient_data = FALSE;
  172396. /* Initialize private state variables */
  172397. entropy->saved.EOBRUN = 0;
  172398. /* Initialize restart counter */
  172399. entropy->restarts_to_go = cinfo->restart_interval;
  172400. }
  172401. /*
  172402. * Check for a restart marker & resynchronize decoder.
  172403. * Returns FALSE if must suspend.
  172404. */
  172405. LOCAL(boolean)
  172406. process_restartp (j_decompress_ptr cinfo)
  172407. {
  172408. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172409. int ci;
  172410. /* Throw away any unused bits remaining in bit buffer; */
  172411. /* include any full bytes in next_marker's count of discarded bytes */
  172412. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172413. entropy->bitstate.bits_left = 0;
  172414. /* Advance past the RSTn marker */
  172415. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172416. return FALSE;
  172417. /* Re-initialize DC predictions to 0 */
  172418. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172419. entropy->saved.last_dc_val[ci] = 0;
  172420. /* Re-init EOB run count, too */
  172421. entropy->saved.EOBRUN = 0;
  172422. /* Reset restart counter */
  172423. entropy->restarts_to_go = cinfo->restart_interval;
  172424. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172425. * against a marker. In that case we will end up treating the next data
  172426. * segment as empty, and we can avoid producing bogus output pixels by
  172427. * leaving the flag set.
  172428. */
  172429. if (cinfo->unread_marker == 0)
  172430. entropy->pub.insufficient_data = FALSE;
  172431. return TRUE;
  172432. }
  172433. /*
  172434. * Huffman MCU decoding.
  172435. * Each of these routines decodes and returns one MCU's worth of
  172436. * Huffman-compressed coefficients.
  172437. * The coefficients are reordered from zigzag order into natural array order,
  172438. * but are not dequantized.
  172439. *
  172440. * The i'th block of the MCU is stored into the block pointed to by
  172441. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172442. *
  172443. * We return FALSE if data source requested suspension. In that case no
  172444. * changes have been made to permanent state. (Exception: some output
  172445. * coefficients may already have been assigned. This is harmless for
  172446. * spectral selection, since we'll just re-assign them on the next call.
  172447. * Successive approximation AC refinement has to be more careful, however.)
  172448. */
  172449. /*
  172450. * MCU decoding for DC initial scan (either spectral selection,
  172451. * or first pass of successive approximation).
  172452. */
  172453. METHODDEF(boolean)
  172454. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172455. {
  172456. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172457. int Al = cinfo->Al;
  172458. register int s, r;
  172459. int blkn, ci;
  172460. JBLOCKROW block;
  172461. BITREAD_STATE_VARS;
  172462. savable_state3 state;
  172463. d_derived_tbl * tbl;
  172464. jpeg_component_info * compptr;
  172465. /* Process restart marker if needed; may have to suspend */
  172466. if (cinfo->restart_interval) {
  172467. if (entropy->restarts_to_go == 0)
  172468. if (! process_restartp(cinfo))
  172469. return FALSE;
  172470. }
  172471. /* If we've run out of data, just leave the MCU set to zeroes.
  172472. * This way, we return uniform gray for the remainder of the segment.
  172473. */
  172474. if (! entropy->pub.insufficient_data) {
  172475. /* Load up working state */
  172476. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172477. ASSIGN_STATE(state, entropy->saved);
  172478. /* Outer loop handles each block in the MCU */
  172479. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172480. block = MCU_data[blkn];
  172481. ci = cinfo->MCU_membership[blkn];
  172482. compptr = cinfo->cur_comp_info[ci];
  172483. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172484. /* Decode a single block's worth of coefficients */
  172485. /* Section F.2.2.1: decode the DC coefficient difference */
  172486. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172487. if (s) {
  172488. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172489. r = GET_BITS(s);
  172490. s = HUFF_EXTEND(r, s);
  172491. }
  172492. /* Convert DC difference to actual value, update last_dc_val */
  172493. s += state.last_dc_val[ci];
  172494. state.last_dc_val[ci] = s;
  172495. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172496. (*block)[0] = (JCOEF) (s << Al);
  172497. }
  172498. /* Completed MCU, so update state */
  172499. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172500. ASSIGN_STATE(entropy->saved, state);
  172501. }
  172502. /* Account for restart interval (no-op if not using restarts) */
  172503. entropy->restarts_to_go--;
  172504. return TRUE;
  172505. }
  172506. /*
  172507. * MCU decoding for AC initial scan (either spectral selection,
  172508. * or first pass of successive approximation).
  172509. */
  172510. METHODDEF(boolean)
  172511. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172512. {
  172513. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172514. int Se = cinfo->Se;
  172515. int Al = cinfo->Al;
  172516. register int s, k, r;
  172517. unsigned int EOBRUN;
  172518. JBLOCKROW block;
  172519. BITREAD_STATE_VARS;
  172520. d_derived_tbl * tbl;
  172521. /* Process restart marker if needed; may have to suspend */
  172522. if (cinfo->restart_interval) {
  172523. if (entropy->restarts_to_go == 0)
  172524. if (! process_restartp(cinfo))
  172525. return FALSE;
  172526. }
  172527. /* If we've run out of data, just leave the MCU set to zeroes.
  172528. * This way, we return uniform gray for the remainder of the segment.
  172529. */
  172530. if (! entropy->pub.insufficient_data) {
  172531. /* Load up working state.
  172532. * We can avoid loading/saving bitread state if in an EOB run.
  172533. */
  172534. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172535. /* There is always only one block per MCU */
  172536. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172537. EOBRUN--; /* ...process it now (we do nothing) */
  172538. else {
  172539. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172540. block = MCU_data[0];
  172541. tbl = entropy->ac_derived_tbl;
  172542. for (k = cinfo->Ss; k <= Se; k++) {
  172543. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172544. r = s >> 4;
  172545. s &= 15;
  172546. if (s) {
  172547. k += r;
  172548. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172549. r = GET_BITS(s);
  172550. s = HUFF_EXTEND(r, s);
  172551. /* Scale and output coefficient in natural (dezigzagged) order */
  172552. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172553. } else {
  172554. if (r == 15) { /* ZRL */
  172555. k += 15; /* skip 15 zeroes in band */
  172556. } else { /* EOBr, run length is 2^r + appended bits */
  172557. EOBRUN = 1 << r;
  172558. if (r) { /* EOBr, r > 0 */
  172559. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172560. r = GET_BITS(r);
  172561. EOBRUN += r;
  172562. }
  172563. EOBRUN--; /* this band is processed at this moment */
  172564. break; /* force end-of-band */
  172565. }
  172566. }
  172567. }
  172568. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172569. }
  172570. /* Completed MCU, so update state */
  172571. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172572. }
  172573. /* Account for restart interval (no-op if not using restarts) */
  172574. entropy->restarts_to_go--;
  172575. return TRUE;
  172576. }
  172577. /*
  172578. * MCU decoding for DC successive approximation refinement scan.
  172579. * Note: we assume such scans can be multi-component, although the spec
  172580. * is not very clear on the point.
  172581. */
  172582. METHODDEF(boolean)
  172583. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172584. {
  172585. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172586. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172587. int blkn;
  172588. JBLOCKROW block;
  172589. BITREAD_STATE_VARS;
  172590. /* Process restart marker if needed; may have to suspend */
  172591. if (cinfo->restart_interval) {
  172592. if (entropy->restarts_to_go == 0)
  172593. if (! process_restartp(cinfo))
  172594. return FALSE;
  172595. }
  172596. /* Not worth the cycles to check insufficient_data here,
  172597. * since we will not change the data anyway if we read zeroes.
  172598. */
  172599. /* Load up working state */
  172600. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172601. /* Outer loop handles each block in the MCU */
  172602. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172603. block = MCU_data[blkn];
  172604. /* Encoded data is simply the next bit of the two's-complement DC value */
  172605. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172606. if (GET_BITS(1))
  172607. (*block)[0] |= p1;
  172608. /* Note: since we use |=, repeating the assignment later is safe */
  172609. }
  172610. /* Completed MCU, so update state */
  172611. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172612. /* Account for restart interval (no-op if not using restarts) */
  172613. entropy->restarts_to_go--;
  172614. return TRUE;
  172615. }
  172616. /*
  172617. * MCU decoding for AC successive approximation refinement scan.
  172618. */
  172619. METHODDEF(boolean)
  172620. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172621. {
  172622. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172623. int Se = cinfo->Se;
  172624. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172625. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172626. register int s, k, r;
  172627. unsigned int EOBRUN;
  172628. JBLOCKROW block;
  172629. JCOEFPTR thiscoef;
  172630. BITREAD_STATE_VARS;
  172631. d_derived_tbl * tbl;
  172632. int num_newnz;
  172633. int newnz_pos[DCTSIZE2];
  172634. /* Process restart marker if needed; may have to suspend */
  172635. if (cinfo->restart_interval) {
  172636. if (entropy->restarts_to_go == 0)
  172637. if (! process_restartp(cinfo))
  172638. return FALSE;
  172639. }
  172640. /* If we've run out of data, don't modify the MCU.
  172641. */
  172642. if (! entropy->pub.insufficient_data) {
  172643. /* Load up working state */
  172644. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172645. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172646. /* There is always only one block per MCU */
  172647. block = MCU_data[0];
  172648. tbl = entropy->ac_derived_tbl;
  172649. /* If we are forced to suspend, we must undo the assignments to any newly
  172650. * nonzero coefficients in the block, because otherwise we'd get confused
  172651. * next time about which coefficients were already nonzero.
  172652. * But we need not undo addition of bits to already-nonzero coefficients;
  172653. * instead, we can test the current bit to see if we already did it.
  172654. */
  172655. num_newnz = 0;
  172656. /* initialize coefficient loop counter to start of band */
  172657. k = cinfo->Ss;
  172658. if (EOBRUN == 0) {
  172659. for (; k <= Se; k++) {
  172660. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172661. r = s >> 4;
  172662. s &= 15;
  172663. if (s) {
  172664. if (s != 1) /* size of new coef should always be 1 */
  172665. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172666. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172667. if (GET_BITS(1))
  172668. s = p1; /* newly nonzero coef is positive */
  172669. else
  172670. s = m1; /* newly nonzero coef is negative */
  172671. } else {
  172672. if (r != 15) {
  172673. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172674. if (r) {
  172675. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172676. r = GET_BITS(r);
  172677. EOBRUN += r;
  172678. }
  172679. break; /* rest of block is handled by EOB logic */
  172680. }
  172681. /* note s = 0 for processing ZRL */
  172682. }
  172683. /* Advance over already-nonzero coefs and r still-zero coefs,
  172684. * appending correction bits to the nonzeroes. A correction bit is 1
  172685. * if the absolute value of the coefficient must be increased.
  172686. */
  172687. do {
  172688. thiscoef = *block + jpeg_natural_order[k];
  172689. if (*thiscoef != 0) {
  172690. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172691. if (GET_BITS(1)) {
  172692. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172693. if (*thiscoef >= 0)
  172694. *thiscoef += p1;
  172695. else
  172696. *thiscoef += m1;
  172697. }
  172698. }
  172699. } else {
  172700. if (--r < 0)
  172701. break; /* reached target zero coefficient */
  172702. }
  172703. k++;
  172704. } while (k <= Se);
  172705. if (s) {
  172706. int pos = jpeg_natural_order[k];
  172707. /* Output newly nonzero coefficient */
  172708. (*block)[pos] = (JCOEF) s;
  172709. /* Remember its position in case we have to suspend */
  172710. newnz_pos[num_newnz++] = pos;
  172711. }
  172712. }
  172713. }
  172714. if (EOBRUN > 0) {
  172715. /* Scan any remaining coefficient positions after the end-of-band
  172716. * (the last newly nonzero coefficient, if any). Append a correction
  172717. * bit to each already-nonzero coefficient. A correction bit is 1
  172718. * if the absolute value of the coefficient must be increased.
  172719. */
  172720. for (; k <= Se; k++) {
  172721. thiscoef = *block + jpeg_natural_order[k];
  172722. if (*thiscoef != 0) {
  172723. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172724. if (GET_BITS(1)) {
  172725. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172726. if (*thiscoef >= 0)
  172727. *thiscoef += p1;
  172728. else
  172729. *thiscoef += m1;
  172730. }
  172731. }
  172732. }
  172733. }
  172734. /* Count one block completed in EOB run */
  172735. EOBRUN--;
  172736. }
  172737. /* Completed MCU, so update state */
  172738. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172739. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172740. }
  172741. /* Account for restart interval (no-op if not using restarts) */
  172742. entropy->restarts_to_go--;
  172743. return TRUE;
  172744. undoit:
  172745. /* Re-zero any output coefficients that we made newly nonzero */
  172746. while (num_newnz > 0)
  172747. (*block)[newnz_pos[--num_newnz]] = 0;
  172748. return FALSE;
  172749. }
  172750. /*
  172751. * Module initialization routine for progressive Huffman entropy decoding.
  172752. */
  172753. GLOBAL(void)
  172754. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172755. {
  172756. phuff_entropy_ptr2 entropy;
  172757. int *coef_bit_ptr;
  172758. int ci, i;
  172759. entropy = (phuff_entropy_ptr2)
  172760. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172761. SIZEOF(phuff_entropy_decoder));
  172762. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172763. entropy->pub.start_pass = start_pass_phuff_decoder;
  172764. /* Mark derived tables unallocated */
  172765. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172766. entropy->derived_tbls[i] = NULL;
  172767. }
  172768. /* Create progression status table */
  172769. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172770. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172771. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172772. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172773. for (ci = 0; ci < cinfo->num_components; ci++)
  172774. for (i = 0; i < DCTSIZE2; i++)
  172775. *coef_bit_ptr++ = -1;
  172776. }
  172777. #endif /* D_PROGRESSIVE_SUPPORTED */
  172778. /*** End of inlined file: jdphuff.c ***/
  172779. /*** Start of inlined file: jdpostct.c ***/
  172780. #define JPEG_INTERNALS
  172781. /* Private buffer controller object */
  172782. typedef struct {
  172783. struct jpeg_d_post_controller pub; /* public fields */
  172784. /* Color quantization source buffer: this holds output data from
  172785. * the upsample/color conversion step to be passed to the quantizer.
  172786. * For two-pass color quantization, we need a full-image buffer;
  172787. * for one-pass operation, a strip buffer is sufficient.
  172788. */
  172789. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172790. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172791. JDIMENSION strip_height; /* buffer size in rows */
  172792. /* for two-pass mode only: */
  172793. JDIMENSION starting_row; /* row # of first row in current strip */
  172794. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172795. } my_post_controller;
  172796. typedef my_post_controller * my_post_ptr;
  172797. /* Forward declarations */
  172798. METHODDEF(void) post_process_1pass
  172799. JPP((j_decompress_ptr cinfo,
  172800. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172801. JDIMENSION in_row_groups_avail,
  172802. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172803. JDIMENSION out_rows_avail));
  172804. #ifdef QUANT_2PASS_SUPPORTED
  172805. METHODDEF(void) post_process_prepass
  172806. JPP((j_decompress_ptr cinfo,
  172807. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172808. JDIMENSION in_row_groups_avail,
  172809. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172810. JDIMENSION out_rows_avail));
  172811. METHODDEF(void) post_process_2pass
  172812. JPP((j_decompress_ptr cinfo,
  172813. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172814. JDIMENSION in_row_groups_avail,
  172815. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172816. JDIMENSION out_rows_avail));
  172817. #endif
  172818. /*
  172819. * Initialize for a processing pass.
  172820. */
  172821. METHODDEF(void)
  172822. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  172823. {
  172824. my_post_ptr post = (my_post_ptr) cinfo->post;
  172825. switch (pass_mode) {
  172826. case JBUF_PASS_THRU:
  172827. if (cinfo->quantize_colors) {
  172828. /* Single-pass processing with color quantization. */
  172829. post->pub.post_process_data = post_process_1pass;
  172830. /* We could be doing buffered-image output before starting a 2-pass
  172831. * color quantization; in that case, jinit_d_post_controller did not
  172832. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  172833. */
  172834. if (post->buffer == NULL) {
  172835. post->buffer = (*cinfo->mem->access_virt_sarray)
  172836. ((j_common_ptr) cinfo, post->whole_image,
  172837. (JDIMENSION) 0, post->strip_height, TRUE);
  172838. }
  172839. } else {
  172840. /* For single-pass processing without color quantization,
  172841. * I have no work to do; just call the upsampler directly.
  172842. */
  172843. post->pub.post_process_data = cinfo->upsample->upsample;
  172844. }
  172845. break;
  172846. #ifdef QUANT_2PASS_SUPPORTED
  172847. case JBUF_SAVE_AND_PASS:
  172848. /* First pass of 2-pass quantization */
  172849. if (post->whole_image == NULL)
  172850. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172851. post->pub.post_process_data = post_process_prepass;
  172852. break;
  172853. case JBUF_CRANK_DEST:
  172854. /* Second pass of 2-pass quantization */
  172855. if (post->whole_image == NULL)
  172856. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172857. post->pub.post_process_data = post_process_2pass;
  172858. break;
  172859. #endif /* QUANT_2PASS_SUPPORTED */
  172860. default:
  172861. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172862. break;
  172863. }
  172864. post->starting_row = post->next_row = 0;
  172865. }
  172866. /*
  172867. * Process some data in the one-pass (strip buffer) case.
  172868. * This is used for color precision reduction as well as one-pass quantization.
  172869. */
  172870. METHODDEF(void)
  172871. post_process_1pass (j_decompress_ptr cinfo,
  172872. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172873. JDIMENSION in_row_groups_avail,
  172874. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172875. JDIMENSION out_rows_avail)
  172876. {
  172877. my_post_ptr post = (my_post_ptr) cinfo->post;
  172878. JDIMENSION num_rows, max_rows;
  172879. /* Fill the buffer, but not more than what we can dump out in one go. */
  172880. /* Note we rely on the upsampler to detect bottom of image. */
  172881. max_rows = out_rows_avail - *out_row_ctr;
  172882. if (max_rows > post->strip_height)
  172883. max_rows = post->strip_height;
  172884. num_rows = 0;
  172885. (*cinfo->upsample->upsample) (cinfo,
  172886. input_buf, in_row_group_ctr, in_row_groups_avail,
  172887. post->buffer, &num_rows, max_rows);
  172888. /* Quantize and emit data. */
  172889. (*cinfo->cquantize->color_quantize) (cinfo,
  172890. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  172891. *out_row_ctr += num_rows;
  172892. }
  172893. #ifdef QUANT_2PASS_SUPPORTED
  172894. /*
  172895. * Process some data in the first pass of 2-pass quantization.
  172896. */
  172897. METHODDEF(void)
  172898. post_process_prepass (j_decompress_ptr cinfo,
  172899. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172900. JDIMENSION in_row_groups_avail,
  172901. JSAMPARRAY, JDIMENSION *out_row_ctr,
  172902. JDIMENSION)
  172903. {
  172904. my_post_ptr post = (my_post_ptr) cinfo->post;
  172905. JDIMENSION old_next_row, num_rows;
  172906. /* Reposition virtual buffer if at start of strip. */
  172907. if (post->next_row == 0) {
  172908. post->buffer = (*cinfo->mem->access_virt_sarray)
  172909. ((j_common_ptr) cinfo, post->whole_image,
  172910. post->starting_row, post->strip_height, TRUE);
  172911. }
  172912. /* Upsample some data (up to a strip height's worth). */
  172913. old_next_row = post->next_row;
  172914. (*cinfo->upsample->upsample) (cinfo,
  172915. input_buf, in_row_group_ctr, in_row_groups_avail,
  172916. post->buffer, &post->next_row, post->strip_height);
  172917. /* Allow quantizer to scan new data. No data is emitted, */
  172918. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  172919. if (post->next_row > old_next_row) {
  172920. num_rows = post->next_row - old_next_row;
  172921. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  172922. (JSAMPARRAY) NULL, (int) num_rows);
  172923. *out_row_ctr += num_rows;
  172924. }
  172925. /* Advance if we filled the strip. */
  172926. if (post->next_row >= post->strip_height) {
  172927. post->starting_row += post->strip_height;
  172928. post->next_row = 0;
  172929. }
  172930. }
  172931. /*
  172932. * Process some data in the second pass of 2-pass quantization.
  172933. */
  172934. METHODDEF(void)
  172935. post_process_2pass (j_decompress_ptr cinfo,
  172936. JSAMPIMAGE, JDIMENSION *,
  172937. JDIMENSION,
  172938. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172939. JDIMENSION out_rows_avail)
  172940. {
  172941. my_post_ptr post = (my_post_ptr) cinfo->post;
  172942. JDIMENSION num_rows, max_rows;
  172943. /* Reposition virtual buffer if at start of strip. */
  172944. if (post->next_row == 0) {
  172945. post->buffer = (*cinfo->mem->access_virt_sarray)
  172946. ((j_common_ptr) cinfo, post->whole_image,
  172947. post->starting_row, post->strip_height, FALSE);
  172948. }
  172949. /* Determine number of rows to emit. */
  172950. num_rows = post->strip_height - post->next_row; /* available in strip */
  172951. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  172952. if (num_rows > max_rows)
  172953. num_rows = max_rows;
  172954. /* We have to check bottom of image here, can't depend on upsampler. */
  172955. max_rows = cinfo->output_height - post->starting_row;
  172956. if (num_rows > max_rows)
  172957. num_rows = max_rows;
  172958. /* Quantize and emit data. */
  172959. (*cinfo->cquantize->color_quantize) (cinfo,
  172960. post->buffer + post->next_row, output_buf + *out_row_ctr,
  172961. (int) num_rows);
  172962. *out_row_ctr += num_rows;
  172963. /* Advance if we filled the strip. */
  172964. post->next_row += num_rows;
  172965. if (post->next_row >= post->strip_height) {
  172966. post->starting_row += post->strip_height;
  172967. post->next_row = 0;
  172968. }
  172969. }
  172970. #endif /* QUANT_2PASS_SUPPORTED */
  172971. /*
  172972. * Initialize postprocessing controller.
  172973. */
  172974. GLOBAL(void)
  172975. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  172976. {
  172977. my_post_ptr post;
  172978. post = (my_post_ptr)
  172979. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172980. SIZEOF(my_post_controller));
  172981. cinfo->post = (struct jpeg_d_post_controller *) post;
  172982. post->pub.start_pass = start_pass_dpost;
  172983. post->whole_image = NULL; /* flag for no virtual arrays */
  172984. post->buffer = NULL; /* flag for no strip buffer */
  172985. /* Create the quantization buffer, if needed */
  172986. if (cinfo->quantize_colors) {
  172987. /* The buffer strip height is max_v_samp_factor, which is typically
  172988. * an efficient number of rows for upsampling to return.
  172989. * (In the presence of output rescaling, we might want to be smarter?)
  172990. */
  172991. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  172992. if (need_full_buffer) {
  172993. /* Two-pass color quantization: need full-image storage. */
  172994. /* We round up the number of rows to a multiple of the strip height. */
  172995. #ifdef QUANT_2PASS_SUPPORTED
  172996. post->whole_image = (*cinfo->mem->request_virt_sarray)
  172997. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  172998. cinfo->output_width * cinfo->out_color_components,
  172999. (JDIMENSION) jround_up((long) cinfo->output_height,
  173000. (long) post->strip_height),
  173001. post->strip_height);
  173002. #else
  173003. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173004. #endif /* QUANT_2PASS_SUPPORTED */
  173005. } else {
  173006. /* One-pass color quantization: just make a strip buffer. */
  173007. post->buffer = (*cinfo->mem->alloc_sarray)
  173008. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173009. cinfo->output_width * cinfo->out_color_components,
  173010. post->strip_height);
  173011. }
  173012. }
  173013. }
  173014. /*** End of inlined file: jdpostct.c ***/
  173015. #undef FIX
  173016. /*** Start of inlined file: jdsample.c ***/
  173017. #define JPEG_INTERNALS
  173018. /* Pointer to routine to upsample a single component */
  173019. typedef JMETHOD(void, upsample1_ptr,
  173020. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173021. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173022. /* Private subobject */
  173023. typedef struct {
  173024. struct jpeg_upsampler pub; /* public fields */
  173025. /* Color conversion buffer. When using separate upsampling and color
  173026. * conversion steps, this buffer holds one upsampled row group until it
  173027. * has been color converted and output.
  173028. * Note: we do not allocate any storage for component(s) which are full-size,
  173029. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173030. * simply set to point to the input data array, thereby avoiding copying.
  173031. */
  173032. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173033. /* Per-component upsampling method pointers */
  173034. upsample1_ptr methods[MAX_COMPONENTS];
  173035. int next_row_out; /* counts rows emitted from color_buf */
  173036. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173037. /* Height of an input row group for each component. */
  173038. int rowgroup_height[MAX_COMPONENTS];
  173039. /* These arrays save pixel expansion factors so that int_expand need not
  173040. * recompute them each time. They are unused for other upsampling methods.
  173041. */
  173042. UINT8 h_expand[MAX_COMPONENTS];
  173043. UINT8 v_expand[MAX_COMPONENTS];
  173044. } my_upsampler2;
  173045. typedef my_upsampler2 * my_upsample_ptr2;
  173046. /*
  173047. * Initialize for an upsampling pass.
  173048. */
  173049. METHODDEF(void)
  173050. start_pass_upsample (j_decompress_ptr cinfo)
  173051. {
  173052. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173053. /* Mark the conversion buffer empty */
  173054. upsample->next_row_out = cinfo->max_v_samp_factor;
  173055. /* Initialize total-height counter for detecting bottom of image */
  173056. upsample->rows_to_go = cinfo->output_height;
  173057. }
  173058. /*
  173059. * Control routine to do upsampling (and color conversion).
  173060. *
  173061. * In this version we upsample each component independently.
  173062. * We upsample one row group into the conversion buffer, then apply
  173063. * color conversion a row at a time.
  173064. */
  173065. METHODDEF(void)
  173066. sep_upsample (j_decompress_ptr cinfo,
  173067. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173068. JDIMENSION,
  173069. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173070. JDIMENSION out_rows_avail)
  173071. {
  173072. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173073. int ci;
  173074. jpeg_component_info * compptr;
  173075. JDIMENSION num_rows;
  173076. /* Fill the conversion buffer, if it's empty */
  173077. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173078. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173079. ci++, compptr++) {
  173080. /* Invoke per-component upsample method. Notice we pass a POINTER
  173081. * to color_buf[ci], so that fullsize_upsample can change it.
  173082. */
  173083. (*upsample->methods[ci]) (cinfo, compptr,
  173084. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173085. upsample->color_buf + ci);
  173086. }
  173087. upsample->next_row_out = 0;
  173088. }
  173089. /* Color-convert and emit rows */
  173090. /* How many we have in the buffer: */
  173091. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173092. /* Not more than the distance to the end of the image. Need this test
  173093. * in case the image height is not a multiple of max_v_samp_factor:
  173094. */
  173095. if (num_rows > upsample->rows_to_go)
  173096. num_rows = upsample->rows_to_go;
  173097. /* And not more than what the client can accept: */
  173098. out_rows_avail -= *out_row_ctr;
  173099. if (num_rows > out_rows_avail)
  173100. num_rows = out_rows_avail;
  173101. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173102. (JDIMENSION) upsample->next_row_out,
  173103. output_buf + *out_row_ctr,
  173104. (int) num_rows);
  173105. /* Adjust counts */
  173106. *out_row_ctr += num_rows;
  173107. upsample->rows_to_go -= num_rows;
  173108. upsample->next_row_out += num_rows;
  173109. /* When the buffer is emptied, declare this input row group consumed */
  173110. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173111. (*in_row_group_ctr)++;
  173112. }
  173113. /*
  173114. * These are the routines invoked by sep_upsample to upsample pixel values
  173115. * of a single component. One row group is processed per call.
  173116. */
  173117. /*
  173118. * For full-size components, we just make color_buf[ci] point at the
  173119. * input buffer, and thus avoid copying any data. Note that this is
  173120. * safe only because sep_upsample doesn't declare the input row group
  173121. * "consumed" until we are done color converting and emitting it.
  173122. */
  173123. METHODDEF(void)
  173124. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173125. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173126. {
  173127. *output_data_ptr = input_data;
  173128. }
  173129. /*
  173130. * This is a no-op version used for "uninteresting" components.
  173131. * These components will not be referenced by color conversion.
  173132. */
  173133. METHODDEF(void)
  173134. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173135. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173136. {
  173137. *output_data_ptr = NULL; /* safety check */
  173138. }
  173139. /*
  173140. * This version handles any integral sampling ratios.
  173141. * This is not used for typical JPEG files, so it need not be fast.
  173142. * Nor, for that matter, is it particularly accurate: the algorithm is
  173143. * simple replication of the input pixel onto the corresponding output
  173144. * pixels. The hi-falutin sampling literature refers to this as a
  173145. * "box filter". A box filter tends to introduce visible artifacts,
  173146. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173147. * you would be well advised to improve this code.
  173148. */
  173149. METHODDEF(void)
  173150. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173151. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173152. {
  173153. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173154. JSAMPARRAY output_data = *output_data_ptr;
  173155. register JSAMPROW inptr, outptr;
  173156. register JSAMPLE invalue;
  173157. register int h;
  173158. JSAMPROW outend;
  173159. int h_expand, v_expand;
  173160. int inrow, outrow;
  173161. h_expand = upsample->h_expand[compptr->component_index];
  173162. v_expand = upsample->v_expand[compptr->component_index];
  173163. inrow = outrow = 0;
  173164. while (outrow < cinfo->max_v_samp_factor) {
  173165. /* Generate one output row with proper horizontal expansion */
  173166. inptr = input_data[inrow];
  173167. outptr = output_data[outrow];
  173168. outend = outptr + cinfo->output_width;
  173169. while (outptr < outend) {
  173170. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173171. for (h = h_expand; h > 0; h--) {
  173172. *outptr++ = invalue;
  173173. }
  173174. }
  173175. /* Generate any additional output rows by duplicating the first one */
  173176. if (v_expand > 1) {
  173177. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173178. v_expand-1, cinfo->output_width);
  173179. }
  173180. inrow++;
  173181. outrow += v_expand;
  173182. }
  173183. }
  173184. /*
  173185. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173186. * It's still a box filter.
  173187. */
  173188. METHODDEF(void)
  173189. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173190. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173191. {
  173192. JSAMPARRAY output_data = *output_data_ptr;
  173193. register JSAMPROW inptr, outptr;
  173194. register JSAMPLE invalue;
  173195. JSAMPROW outend;
  173196. int inrow;
  173197. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173198. inptr = input_data[inrow];
  173199. outptr = output_data[inrow];
  173200. outend = outptr + cinfo->output_width;
  173201. while (outptr < outend) {
  173202. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173203. *outptr++ = invalue;
  173204. *outptr++ = invalue;
  173205. }
  173206. }
  173207. }
  173208. /*
  173209. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173210. * It's still a box filter.
  173211. */
  173212. METHODDEF(void)
  173213. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173214. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173215. {
  173216. JSAMPARRAY output_data = *output_data_ptr;
  173217. register JSAMPROW inptr, outptr;
  173218. register JSAMPLE invalue;
  173219. JSAMPROW outend;
  173220. int inrow, outrow;
  173221. inrow = outrow = 0;
  173222. while (outrow < cinfo->max_v_samp_factor) {
  173223. inptr = input_data[inrow];
  173224. outptr = output_data[outrow];
  173225. outend = outptr + cinfo->output_width;
  173226. while (outptr < outend) {
  173227. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173228. *outptr++ = invalue;
  173229. *outptr++ = invalue;
  173230. }
  173231. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173232. 1, cinfo->output_width);
  173233. inrow++;
  173234. outrow += 2;
  173235. }
  173236. }
  173237. /*
  173238. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173239. *
  173240. * The upsampling algorithm is linear interpolation between pixel centers,
  173241. * also known as a "triangle filter". This is a good compromise between
  173242. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173243. * of the way between input pixel centers.
  173244. *
  173245. * A note about the "bias" calculations: when rounding fractional values to
  173246. * integer, we do not want to always round 0.5 up to the next integer.
  173247. * If we did that, we'd introduce a noticeable bias towards larger values.
  173248. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173249. * alternate pixel locations (a simple ordered dither pattern).
  173250. */
  173251. METHODDEF(void)
  173252. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173253. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173254. {
  173255. JSAMPARRAY output_data = *output_data_ptr;
  173256. register JSAMPROW inptr, outptr;
  173257. register int invalue;
  173258. register JDIMENSION colctr;
  173259. int inrow;
  173260. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173261. inptr = input_data[inrow];
  173262. outptr = output_data[inrow];
  173263. /* Special case for first column */
  173264. invalue = GETJSAMPLE(*inptr++);
  173265. *outptr++ = (JSAMPLE) invalue;
  173266. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173267. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173268. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173269. invalue = GETJSAMPLE(*inptr++) * 3;
  173270. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173271. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173272. }
  173273. /* Special case for last column */
  173274. invalue = GETJSAMPLE(*inptr);
  173275. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173276. *outptr++ = (JSAMPLE) invalue;
  173277. }
  173278. }
  173279. /*
  173280. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173281. * Again a triangle filter; see comments for h2v1 case, above.
  173282. *
  173283. * It is OK for us to reference the adjacent input rows because we demanded
  173284. * context from the main buffer controller (see initialization code).
  173285. */
  173286. METHODDEF(void)
  173287. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173288. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173289. {
  173290. JSAMPARRAY output_data = *output_data_ptr;
  173291. register JSAMPROW inptr0, inptr1, outptr;
  173292. #if BITS_IN_JSAMPLE == 8
  173293. register int thiscolsum, lastcolsum, nextcolsum;
  173294. #else
  173295. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173296. #endif
  173297. register JDIMENSION colctr;
  173298. int inrow, outrow, v;
  173299. inrow = outrow = 0;
  173300. while (outrow < cinfo->max_v_samp_factor) {
  173301. for (v = 0; v < 2; v++) {
  173302. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173303. inptr0 = input_data[inrow];
  173304. if (v == 0) /* next nearest is row above */
  173305. inptr1 = input_data[inrow-1];
  173306. else /* next nearest is row below */
  173307. inptr1 = input_data[inrow+1];
  173308. outptr = output_data[outrow++];
  173309. /* Special case for first column */
  173310. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173311. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173312. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173313. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173314. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173315. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173316. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173317. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173318. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173319. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173320. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173321. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173322. }
  173323. /* Special case for last column */
  173324. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173325. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173326. }
  173327. inrow++;
  173328. }
  173329. }
  173330. /*
  173331. * Module initialization routine for upsampling.
  173332. */
  173333. GLOBAL(void)
  173334. jinit_upsampler (j_decompress_ptr cinfo)
  173335. {
  173336. my_upsample_ptr2 upsample;
  173337. int ci;
  173338. jpeg_component_info * compptr;
  173339. boolean need_buffer, do_fancy;
  173340. int h_in_group, v_in_group, h_out_group, v_out_group;
  173341. upsample = (my_upsample_ptr2)
  173342. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173343. SIZEOF(my_upsampler2));
  173344. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173345. upsample->pub.start_pass = start_pass_upsample;
  173346. upsample->pub.upsample = sep_upsample;
  173347. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173348. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173349. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173350. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173351. * so don't ask for it.
  173352. */
  173353. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173354. /* Verify we can handle the sampling factors, select per-component methods,
  173355. * and create storage as needed.
  173356. */
  173357. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173358. ci++, compptr++) {
  173359. /* Compute size of an "input group" after IDCT scaling. This many samples
  173360. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173361. */
  173362. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173363. cinfo->min_DCT_scaled_size;
  173364. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173365. cinfo->min_DCT_scaled_size;
  173366. h_out_group = cinfo->max_h_samp_factor;
  173367. v_out_group = cinfo->max_v_samp_factor;
  173368. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173369. need_buffer = TRUE;
  173370. if (! compptr->component_needed) {
  173371. /* Don't bother to upsample an uninteresting component. */
  173372. upsample->methods[ci] = noop_upsample;
  173373. need_buffer = FALSE;
  173374. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173375. /* Fullsize components can be processed without any work. */
  173376. upsample->methods[ci] = fullsize_upsample;
  173377. need_buffer = FALSE;
  173378. } else if (h_in_group * 2 == h_out_group &&
  173379. v_in_group == v_out_group) {
  173380. /* Special cases for 2h1v upsampling */
  173381. if (do_fancy && compptr->downsampled_width > 2)
  173382. upsample->methods[ci] = h2v1_fancy_upsample;
  173383. else
  173384. upsample->methods[ci] = h2v1_upsample;
  173385. } else if (h_in_group * 2 == h_out_group &&
  173386. v_in_group * 2 == v_out_group) {
  173387. /* Special cases for 2h2v upsampling */
  173388. if (do_fancy && compptr->downsampled_width > 2) {
  173389. upsample->methods[ci] = h2v2_fancy_upsample;
  173390. upsample->pub.need_context_rows = TRUE;
  173391. } else
  173392. upsample->methods[ci] = h2v2_upsample;
  173393. } else if ((h_out_group % h_in_group) == 0 &&
  173394. (v_out_group % v_in_group) == 0) {
  173395. /* Generic integral-factors upsampling method */
  173396. upsample->methods[ci] = int_upsample;
  173397. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173398. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173399. } else
  173400. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173401. if (need_buffer) {
  173402. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173403. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173404. (JDIMENSION) jround_up((long) cinfo->output_width,
  173405. (long) cinfo->max_h_samp_factor),
  173406. (JDIMENSION) cinfo->max_v_samp_factor);
  173407. }
  173408. }
  173409. }
  173410. /*** End of inlined file: jdsample.c ***/
  173411. /*** Start of inlined file: jdtrans.c ***/
  173412. #define JPEG_INTERNALS
  173413. /* Forward declarations */
  173414. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173415. /*
  173416. * Read the coefficient arrays from a JPEG file.
  173417. * jpeg_read_header must be completed before calling this.
  173418. *
  173419. * The entire image is read into a set of virtual coefficient-block arrays,
  173420. * one per component. The return value is a pointer to the array of
  173421. * virtual-array descriptors. These can be manipulated directly via the
  173422. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173423. * To release the memory occupied by the virtual arrays, call
  173424. * jpeg_finish_decompress() when done with the data.
  173425. *
  173426. * An alternative usage is to simply obtain access to the coefficient arrays
  173427. * during a buffered-image-mode decompression operation. This is allowed
  173428. * after any jpeg_finish_output() call. The arrays can be accessed until
  173429. * jpeg_finish_decompress() is called. (Note that any call to the library
  173430. * may reposition the arrays, so don't rely on access_virt_barray() results
  173431. * to stay valid across library calls.)
  173432. *
  173433. * Returns NULL if suspended. This case need be checked only if
  173434. * a suspending data source is used.
  173435. */
  173436. GLOBAL(jvirt_barray_ptr *)
  173437. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173438. {
  173439. if (cinfo->global_state == DSTATE_READY) {
  173440. /* First call: initialize active modules */
  173441. transdecode_master_selection(cinfo);
  173442. cinfo->global_state = DSTATE_RDCOEFS;
  173443. }
  173444. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173445. /* Absorb whole file into the coef buffer */
  173446. for (;;) {
  173447. int retcode;
  173448. /* Call progress monitor hook if present */
  173449. if (cinfo->progress != NULL)
  173450. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173451. /* Absorb some more input */
  173452. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173453. if (retcode == JPEG_SUSPENDED)
  173454. return NULL;
  173455. if (retcode == JPEG_REACHED_EOI)
  173456. break;
  173457. /* Advance progress counter if appropriate */
  173458. if (cinfo->progress != NULL &&
  173459. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173460. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173461. /* startup underestimated number of scans; ratchet up one scan */
  173462. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173463. }
  173464. }
  173465. }
  173466. /* Set state so that jpeg_finish_decompress does the right thing */
  173467. cinfo->global_state = DSTATE_STOPPING;
  173468. }
  173469. /* At this point we should be in state DSTATE_STOPPING if being used
  173470. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173471. * to the coefficients during a full buffered-image-mode decompression.
  173472. */
  173473. if ((cinfo->global_state == DSTATE_STOPPING ||
  173474. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173475. return cinfo->coef->coef_arrays;
  173476. }
  173477. /* Oops, improper usage */
  173478. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173479. return NULL; /* keep compiler happy */
  173480. }
  173481. /*
  173482. * Master selection of decompression modules for transcoding.
  173483. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173484. */
  173485. LOCAL(void)
  173486. transdecode_master_selection (j_decompress_ptr cinfo)
  173487. {
  173488. /* This is effectively a buffered-image operation. */
  173489. cinfo->buffered_image = TRUE;
  173490. /* Entropy decoding: either Huffman or arithmetic coding. */
  173491. if (cinfo->arith_code) {
  173492. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173493. } else {
  173494. if (cinfo->progressive_mode) {
  173495. #ifdef D_PROGRESSIVE_SUPPORTED
  173496. jinit_phuff_decoder(cinfo);
  173497. #else
  173498. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173499. #endif
  173500. } else
  173501. jinit_huff_decoder(cinfo);
  173502. }
  173503. /* Always get a full-image coefficient buffer. */
  173504. jinit_d_coef_controller(cinfo, TRUE);
  173505. /* We can now tell the memory manager to allocate virtual arrays. */
  173506. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173507. /* Initialize input side of decompressor to consume first scan. */
  173508. (*cinfo->inputctl->start_input_pass) (cinfo);
  173509. /* Initialize progress monitoring. */
  173510. if (cinfo->progress != NULL) {
  173511. int nscans;
  173512. /* Estimate number of scans to set pass_limit. */
  173513. if (cinfo->progressive_mode) {
  173514. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173515. nscans = 2 + 3 * cinfo->num_components;
  173516. } else if (cinfo->inputctl->has_multiple_scans) {
  173517. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173518. nscans = cinfo->num_components;
  173519. } else {
  173520. nscans = 1;
  173521. }
  173522. cinfo->progress->pass_counter = 0L;
  173523. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173524. cinfo->progress->completed_passes = 0;
  173525. cinfo->progress->total_passes = 1;
  173526. }
  173527. }
  173528. /*** End of inlined file: jdtrans.c ***/
  173529. /*** Start of inlined file: jfdctflt.c ***/
  173530. #define JPEG_INTERNALS
  173531. #ifdef DCT_FLOAT_SUPPORTED
  173532. /*
  173533. * This module is specialized to the case DCTSIZE = 8.
  173534. */
  173535. #if DCTSIZE != 8
  173536. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173537. #endif
  173538. /*
  173539. * Perform the forward DCT on one block of samples.
  173540. */
  173541. GLOBAL(void)
  173542. jpeg_fdct_float (FAST_FLOAT * data)
  173543. {
  173544. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173545. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173546. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173547. FAST_FLOAT *dataptr;
  173548. int ctr;
  173549. /* Pass 1: process rows. */
  173550. dataptr = data;
  173551. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173552. tmp0 = dataptr[0] + dataptr[7];
  173553. tmp7 = dataptr[0] - dataptr[7];
  173554. tmp1 = dataptr[1] + dataptr[6];
  173555. tmp6 = dataptr[1] - dataptr[6];
  173556. tmp2 = dataptr[2] + dataptr[5];
  173557. tmp5 = dataptr[2] - dataptr[5];
  173558. tmp3 = dataptr[3] + dataptr[4];
  173559. tmp4 = dataptr[3] - dataptr[4];
  173560. /* Even part */
  173561. tmp10 = tmp0 + tmp3; /* phase 2 */
  173562. tmp13 = tmp0 - tmp3;
  173563. tmp11 = tmp1 + tmp2;
  173564. tmp12 = tmp1 - tmp2;
  173565. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173566. dataptr[4] = tmp10 - tmp11;
  173567. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173568. dataptr[2] = tmp13 + z1; /* phase 5 */
  173569. dataptr[6] = tmp13 - z1;
  173570. /* Odd part */
  173571. tmp10 = tmp4 + tmp5; /* phase 2 */
  173572. tmp11 = tmp5 + tmp6;
  173573. tmp12 = tmp6 + tmp7;
  173574. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173575. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173576. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173577. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173578. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173579. z11 = tmp7 + z3; /* phase 5 */
  173580. z13 = tmp7 - z3;
  173581. dataptr[5] = z13 + z2; /* phase 6 */
  173582. dataptr[3] = z13 - z2;
  173583. dataptr[1] = z11 + z4;
  173584. dataptr[7] = z11 - z4;
  173585. dataptr += DCTSIZE; /* advance pointer to next row */
  173586. }
  173587. /* Pass 2: process columns. */
  173588. dataptr = data;
  173589. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173590. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173591. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173592. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173593. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173594. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173595. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173596. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173597. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173598. /* Even part */
  173599. tmp10 = tmp0 + tmp3; /* phase 2 */
  173600. tmp13 = tmp0 - tmp3;
  173601. tmp11 = tmp1 + tmp2;
  173602. tmp12 = tmp1 - tmp2;
  173603. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173604. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173605. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173606. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173607. dataptr[DCTSIZE*6] = tmp13 - z1;
  173608. /* Odd part */
  173609. tmp10 = tmp4 + tmp5; /* phase 2 */
  173610. tmp11 = tmp5 + tmp6;
  173611. tmp12 = tmp6 + tmp7;
  173612. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173613. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173614. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173615. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173616. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173617. z11 = tmp7 + z3; /* phase 5 */
  173618. z13 = tmp7 - z3;
  173619. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173620. dataptr[DCTSIZE*3] = z13 - z2;
  173621. dataptr[DCTSIZE*1] = z11 + z4;
  173622. dataptr[DCTSIZE*7] = z11 - z4;
  173623. dataptr++; /* advance pointer to next column */
  173624. }
  173625. }
  173626. #endif /* DCT_FLOAT_SUPPORTED */
  173627. /*** End of inlined file: jfdctflt.c ***/
  173628. /*** Start of inlined file: jfdctint.c ***/
  173629. #define JPEG_INTERNALS
  173630. #ifdef DCT_ISLOW_SUPPORTED
  173631. /*
  173632. * This module is specialized to the case DCTSIZE = 8.
  173633. */
  173634. #if DCTSIZE != 8
  173635. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173636. #endif
  173637. /*
  173638. * The poop on this scaling stuff is as follows:
  173639. *
  173640. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173641. * larger than the true DCT outputs. The final outputs are therefore
  173642. * a factor of N larger than desired; since N=8 this can be cured by
  173643. * a simple right shift at the end of the algorithm. The advantage of
  173644. * this arrangement is that we save two multiplications per 1-D DCT,
  173645. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173646. * In the IJG code, this factor of 8 is removed by the quantization step
  173647. * (in jcdctmgr.c), NOT in this module.
  173648. *
  173649. * We have to do addition and subtraction of the integer inputs, which
  173650. * is no problem, and multiplication by fractional constants, which is
  173651. * a problem to do in integer arithmetic. We multiply all the constants
  173652. * by CONST_SCALE and convert them to integer constants (thus retaining
  173653. * CONST_BITS bits of precision in the constants). After doing a
  173654. * multiplication we have to divide the product by CONST_SCALE, with proper
  173655. * rounding, to produce the correct output. This division can be done
  173656. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173657. * as long as possible so that partial sums can be added together with
  173658. * full fractional precision.
  173659. *
  173660. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173661. * they are represented to better-than-integral precision. These outputs
  173662. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173663. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173664. * array is INT32 anyway.)
  173665. *
  173666. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173667. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173668. * shows that the values given below are the most effective.
  173669. */
  173670. #if BITS_IN_JSAMPLE == 8
  173671. #define CONST_BITS 13
  173672. #define PASS1_BITS 2
  173673. #else
  173674. #define CONST_BITS 13
  173675. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173676. #endif
  173677. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173678. * causing a lot of useless floating-point operations at run time.
  173679. * To get around this we use the following pre-calculated constants.
  173680. * If you change CONST_BITS you may want to add appropriate values.
  173681. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173682. */
  173683. #if CONST_BITS == 13
  173684. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173685. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173686. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173687. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173688. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173689. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173690. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173691. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173692. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173693. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173694. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173695. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173696. #else
  173697. #define FIX_0_298631336 FIX(0.298631336)
  173698. #define FIX_0_390180644 FIX(0.390180644)
  173699. #define FIX_0_541196100 FIX(0.541196100)
  173700. #define FIX_0_765366865 FIX(0.765366865)
  173701. #define FIX_0_899976223 FIX(0.899976223)
  173702. #define FIX_1_175875602 FIX(1.175875602)
  173703. #define FIX_1_501321110 FIX(1.501321110)
  173704. #define FIX_1_847759065 FIX(1.847759065)
  173705. #define FIX_1_961570560 FIX(1.961570560)
  173706. #define FIX_2_053119869 FIX(2.053119869)
  173707. #define FIX_2_562915447 FIX(2.562915447)
  173708. #define FIX_3_072711026 FIX(3.072711026)
  173709. #endif
  173710. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173711. * For 8-bit samples with the recommended scaling, all the variable
  173712. * and constant values involved are no more than 16 bits wide, so a
  173713. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173714. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173715. */
  173716. #if BITS_IN_JSAMPLE == 8
  173717. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173718. #else
  173719. #define MULTIPLY(var,const) ((var) * (const))
  173720. #endif
  173721. /*
  173722. * Perform the forward DCT on one block of samples.
  173723. */
  173724. GLOBAL(void)
  173725. jpeg_fdct_islow (DCTELEM * data)
  173726. {
  173727. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173728. INT32 tmp10, tmp11, tmp12, tmp13;
  173729. INT32 z1, z2, z3, z4, z5;
  173730. DCTELEM *dataptr;
  173731. int ctr;
  173732. SHIFT_TEMPS
  173733. /* Pass 1: process rows. */
  173734. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173735. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173736. dataptr = data;
  173737. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173738. tmp0 = dataptr[0] + dataptr[7];
  173739. tmp7 = dataptr[0] - dataptr[7];
  173740. tmp1 = dataptr[1] + dataptr[6];
  173741. tmp6 = dataptr[1] - dataptr[6];
  173742. tmp2 = dataptr[2] + dataptr[5];
  173743. tmp5 = dataptr[2] - dataptr[5];
  173744. tmp3 = dataptr[3] + dataptr[4];
  173745. tmp4 = dataptr[3] - dataptr[4];
  173746. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173747. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173748. */
  173749. tmp10 = tmp0 + tmp3;
  173750. tmp13 = tmp0 - tmp3;
  173751. tmp11 = tmp1 + tmp2;
  173752. tmp12 = tmp1 - tmp2;
  173753. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173754. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173755. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173756. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173757. CONST_BITS-PASS1_BITS);
  173758. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173759. CONST_BITS-PASS1_BITS);
  173760. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173761. * cK represents cos(K*pi/16).
  173762. * i0..i3 in the paper are tmp4..tmp7 here.
  173763. */
  173764. z1 = tmp4 + tmp7;
  173765. z2 = tmp5 + tmp6;
  173766. z3 = tmp4 + tmp6;
  173767. z4 = tmp5 + tmp7;
  173768. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173769. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173770. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173771. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173772. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173773. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173774. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173775. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173776. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173777. z3 += z5;
  173778. z4 += z5;
  173779. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173780. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173781. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173782. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173783. dataptr += DCTSIZE; /* advance pointer to next row */
  173784. }
  173785. /* Pass 2: process columns.
  173786. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173787. * by an overall factor of 8.
  173788. */
  173789. dataptr = data;
  173790. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173791. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173792. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173793. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173794. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173795. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173796. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173797. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173798. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173799. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173800. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173801. */
  173802. tmp10 = tmp0 + tmp3;
  173803. tmp13 = tmp0 - tmp3;
  173804. tmp11 = tmp1 + tmp2;
  173805. tmp12 = tmp1 - tmp2;
  173806. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173807. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173808. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173809. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173810. CONST_BITS+PASS1_BITS);
  173811. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173812. CONST_BITS+PASS1_BITS);
  173813. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173814. * cK represents cos(K*pi/16).
  173815. * i0..i3 in the paper are tmp4..tmp7 here.
  173816. */
  173817. z1 = tmp4 + tmp7;
  173818. z2 = tmp5 + tmp6;
  173819. z3 = tmp4 + tmp6;
  173820. z4 = tmp5 + tmp7;
  173821. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173822. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173823. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173824. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173825. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173826. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173827. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173828. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173829. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173830. z3 += z5;
  173831. z4 += z5;
  173832. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  173833. CONST_BITS+PASS1_BITS);
  173834. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  173835. CONST_BITS+PASS1_BITS);
  173836. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  173837. CONST_BITS+PASS1_BITS);
  173838. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  173839. CONST_BITS+PASS1_BITS);
  173840. dataptr++; /* advance pointer to next column */
  173841. }
  173842. }
  173843. #endif /* DCT_ISLOW_SUPPORTED */
  173844. /*** End of inlined file: jfdctint.c ***/
  173845. #undef CONST_BITS
  173846. #undef MULTIPLY
  173847. #undef FIX_0_541196100
  173848. /*** Start of inlined file: jfdctfst.c ***/
  173849. #define JPEG_INTERNALS
  173850. #ifdef DCT_IFAST_SUPPORTED
  173851. /*
  173852. * This module is specialized to the case DCTSIZE = 8.
  173853. */
  173854. #if DCTSIZE != 8
  173855. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173856. #endif
  173857. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173858. * see jfdctint.c for more details. However, we choose to descale
  173859. * (right shift) multiplication products as soon as they are formed,
  173860. * rather than carrying additional fractional bits into subsequent additions.
  173861. * This compromises accuracy slightly, but it lets us save a few shifts.
  173862. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173863. * everywhere except in the multiplications proper; this saves a good deal
  173864. * of work on 16-bit-int machines.
  173865. *
  173866. * Again to save a few shifts, the intermediate results between pass 1 and
  173867. * pass 2 are not upscaled, but are represented only to integral precision.
  173868. *
  173869. * A final compromise is to represent the multiplicative constants to only
  173870. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173871. * machines, and may also reduce the cost of multiplication (since there
  173872. * are fewer one-bits in the constants).
  173873. */
  173874. #define CONST_BITS 8
  173875. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173876. * causing a lot of useless floating-point operations at run time.
  173877. * To get around this we use the following pre-calculated constants.
  173878. * If you change CONST_BITS you may want to add appropriate values.
  173879. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173880. */
  173881. #if CONST_BITS == 8
  173882. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  173883. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  173884. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  173885. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  173886. #else
  173887. #define FIX_0_382683433 FIX(0.382683433)
  173888. #define FIX_0_541196100 FIX(0.541196100)
  173889. #define FIX_0_707106781 FIX(0.707106781)
  173890. #define FIX_1_306562965 FIX(1.306562965)
  173891. #endif
  173892. /* We can gain a little more speed, with a further compromise in accuracy,
  173893. * by omitting the addition in a descaling shift. This yields an incorrectly
  173894. * rounded result half the time...
  173895. */
  173896. #ifndef USE_ACCURATE_ROUNDING
  173897. #undef DESCALE
  173898. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173899. #endif
  173900. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173901. * descale to yield a DCTELEM result.
  173902. */
  173903. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173904. /*
  173905. * Perform the forward DCT on one block of samples.
  173906. */
  173907. GLOBAL(void)
  173908. jpeg_fdct_ifast (DCTELEM * data)
  173909. {
  173910. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173911. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173912. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  173913. DCTELEM *dataptr;
  173914. int ctr;
  173915. SHIFT_TEMPS
  173916. /* Pass 1: process rows. */
  173917. dataptr = data;
  173918. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173919. tmp0 = dataptr[0] + dataptr[7];
  173920. tmp7 = dataptr[0] - dataptr[7];
  173921. tmp1 = dataptr[1] + dataptr[6];
  173922. tmp6 = dataptr[1] - dataptr[6];
  173923. tmp2 = dataptr[2] + dataptr[5];
  173924. tmp5 = dataptr[2] - dataptr[5];
  173925. tmp3 = dataptr[3] + dataptr[4];
  173926. tmp4 = dataptr[3] - dataptr[4];
  173927. /* Even part */
  173928. tmp10 = tmp0 + tmp3; /* phase 2 */
  173929. tmp13 = tmp0 - tmp3;
  173930. tmp11 = tmp1 + tmp2;
  173931. tmp12 = tmp1 - tmp2;
  173932. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173933. dataptr[4] = tmp10 - tmp11;
  173934. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173935. dataptr[2] = tmp13 + z1; /* phase 5 */
  173936. dataptr[6] = tmp13 - z1;
  173937. /* Odd part */
  173938. tmp10 = tmp4 + tmp5; /* phase 2 */
  173939. tmp11 = tmp5 + tmp6;
  173940. tmp12 = tmp6 + tmp7;
  173941. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173942. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173943. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173944. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173945. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173946. z11 = tmp7 + z3; /* phase 5 */
  173947. z13 = tmp7 - z3;
  173948. dataptr[5] = z13 + z2; /* phase 6 */
  173949. dataptr[3] = z13 - z2;
  173950. dataptr[1] = z11 + z4;
  173951. dataptr[7] = z11 - z4;
  173952. dataptr += DCTSIZE; /* advance pointer to next row */
  173953. }
  173954. /* Pass 2: process columns. */
  173955. dataptr = data;
  173956. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173957. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173958. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173959. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173960. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173961. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173962. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173963. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173964. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173965. /* Even part */
  173966. tmp10 = tmp0 + tmp3; /* phase 2 */
  173967. tmp13 = tmp0 - tmp3;
  173968. tmp11 = tmp1 + tmp2;
  173969. tmp12 = tmp1 - tmp2;
  173970. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173971. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173972. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173973. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173974. dataptr[DCTSIZE*6] = tmp13 - z1;
  173975. /* Odd part */
  173976. tmp10 = tmp4 + tmp5; /* phase 2 */
  173977. tmp11 = tmp5 + tmp6;
  173978. tmp12 = tmp6 + tmp7;
  173979. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173980. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173981. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173982. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173983. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173984. z11 = tmp7 + z3; /* phase 5 */
  173985. z13 = tmp7 - z3;
  173986. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173987. dataptr[DCTSIZE*3] = z13 - z2;
  173988. dataptr[DCTSIZE*1] = z11 + z4;
  173989. dataptr[DCTSIZE*7] = z11 - z4;
  173990. dataptr++; /* advance pointer to next column */
  173991. }
  173992. }
  173993. #endif /* DCT_IFAST_SUPPORTED */
  173994. /*** End of inlined file: jfdctfst.c ***/
  173995. #undef FIX_0_541196100
  173996. /*** Start of inlined file: jidctflt.c ***/
  173997. #define JPEG_INTERNALS
  173998. #ifdef DCT_FLOAT_SUPPORTED
  173999. /*
  174000. * This module is specialized to the case DCTSIZE = 8.
  174001. */
  174002. #if DCTSIZE != 8
  174003. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174004. #endif
  174005. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174006. * entry; produce a float result.
  174007. */
  174008. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174009. /*
  174010. * Perform dequantization and inverse DCT on one block of coefficients.
  174011. */
  174012. GLOBAL(void)
  174013. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174014. JCOEFPTR coef_block,
  174015. JSAMPARRAY output_buf, JDIMENSION output_col)
  174016. {
  174017. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174018. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174019. FAST_FLOAT z5, z10, z11, z12, z13;
  174020. JCOEFPTR inptr;
  174021. FLOAT_MULT_TYPE * quantptr;
  174022. FAST_FLOAT * wsptr;
  174023. JSAMPROW outptr;
  174024. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174025. int ctr;
  174026. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174027. SHIFT_TEMPS
  174028. /* Pass 1: process columns from input, store into work array. */
  174029. inptr = coef_block;
  174030. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174031. wsptr = workspace;
  174032. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174033. /* Due to quantization, we will usually find that many of the input
  174034. * coefficients are zero, especially the AC terms. We can exploit this
  174035. * by short-circuiting the IDCT calculation for any column in which all
  174036. * the AC terms are zero. In that case each output is equal to the
  174037. * DC coefficient (with scale factor as needed).
  174038. * With typical images and quantization tables, half or more of the
  174039. * column DCT calculations can be simplified this way.
  174040. */
  174041. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174042. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174043. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174044. inptr[DCTSIZE*7] == 0) {
  174045. /* AC terms all zero */
  174046. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174047. wsptr[DCTSIZE*0] = dcval;
  174048. wsptr[DCTSIZE*1] = dcval;
  174049. wsptr[DCTSIZE*2] = dcval;
  174050. wsptr[DCTSIZE*3] = dcval;
  174051. wsptr[DCTSIZE*4] = dcval;
  174052. wsptr[DCTSIZE*5] = dcval;
  174053. wsptr[DCTSIZE*6] = dcval;
  174054. wsptr[DCTSIZE*7] = dcval;
  174055. inptr++; /* advance pointers to next column */
  174056. quantptr++;
  174057. wsptr++;
  174058. continue;
  174059. }
  174060. /* Even part */
  174061. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174062. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174063. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174064. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174065. tmp10 = tmp0 + tmp2; /* phase 3 */
  174066. tmp11 = tmp0 - tmp2;
  174067. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174068. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174069. tmp0 = tmp10 + tmp13; /* phase 2 */
  174070. tmp3 = tmp10 - tmp13;
  174071. tmp1 = tmp11 + tmp12;
  174072. tmp2 = tmp11 - tmp12;
  174073. /* Odd part */
  174074. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174075. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174076. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174077. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174078. z13 = tmp6 + tmp5; /* phase 6 */
  174079. z10 = tmp6 - tmp5;
  174080. z11 = tmp4 + tmp7;
  174081. z12 = tmp4 - tmp7;
  174082. tmp7 = z11 + z13; /* phase 5 */
  174083. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174084. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174085. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174086. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174087. tmp6 = tmp12 - tmp7; /* phase 2 */
  174088. tmp5 = tmp11 - tmp6;
  174089. tmp4 = tmp10 + tmp5;
  174090. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174091. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174092. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174093. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174094. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174095. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174096. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174097. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174098. inptr++; /* advance pointers to next column */
  174099. quantptr++;
  174100. wsptr++;
  174101. }
  174102. /* Pass 2: process rows from work array, store into output array. */
  174103. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174104. wsptr = workspace;
  174105. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174106. outptr = output_buf[ctr] + output_col;
  174107. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174108. * However, the column calculation has created many nonzero AC terms, so
  174109. * the simplification applies less often (typically 5% to 10% of the time).
  174110. * And testing floats for zero is relatively expensive, so we don't bother.
  174111. */
  174112. /* Even part */
  174113. tmp10 = wsptr[0] + wsptr[4];
  174114. tmp11 = wsptr[0] - wsptr[4];
  174115. tmp13 = wsptr[2] + wsptr[6];
  174116. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174117. tmp0 = tmp10 + tmp13;
  174118. tmp3 = tmp10 - tmp13;
  174119. tmp1 = tmp11 + tmp12;
  174120. tmp2 = tmp11 - tmp12;
  174121. /* Odd part */
  174122. z13 = wsptr[5] + wsptr[3];
  174123. z10 = wsptr[5] - wsptr[3];
  174124. z11 = wsptr[1] + wsptr[7];
  174125. z12 = wsptr[1] - wsptr[7];
  174126. tmp7 = z11 + z13;
  174127. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174128. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174129. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174130. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174131. tmp6 = tmp12 - tmp7;
  174132. tmp5 = tmp11 - tmp6;
  174133. tmp4 = tmp10 + tmp5;
  174134. /* Final output stage: scale down by a factor of 8 and range-limit */
  174135. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174136. & RANGE_MASK];
  174137. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174138. & RANGE_MASK];
  174139. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174140. & RANGE_MASK];
  174141. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174142. & RANGE_MASK];
  174143. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174144. & RANGE_MASK];
  174145. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174146. & RANGE_MASK];
  174147. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174148. & RANGE_MASK];
  174149. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174150. & RANGE_MASK];
  174151. wsptr += DCTSIZE; /* advance pointer to next row */
  174152. }
  174153. }
  174154. #endif /* DCT_FLOAT_SUPPORTED */
  174155. /*** End of inlined file: jidctflt.c ***/
  174156. #undef CONST_BITS
  174157. #undef FIX_1_847759065
  174158. #undef MULTIPLY
  174159. #undef DEQUANTIZE
  174160. #undef DESCALE
  174161. /*** Start of inlined file: jidctfst.c ***/
  174162. #define JPEG_INTERNALS
  174163. #ifdef DCT_IFAST_SUPPORTED
  174164. /*
  174165. * This module is specialized to the case DCTSIZE = 8.
  174166. */
  174167. #if DCTSIZE != 8
  174168. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174169. #endif
  174170. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174171. * see jidctint.c for more details. However, we choose to descale
  174172. * (right shift) multiplication products as soon as they are formed,
  174173. * rather than carrying additional fractional bits into subsequent additions.
  174174. * This compromises accuracy slightly, but it lets us save a few shifts.
  174175. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174176. * everywhere except in the multiplications proper; this saves a good deal
  174177. * of work on 16-bit-int machines.
  174178. *
  174179. * The dequantized coefficients are not integers because the AA&N scaling
  174180. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174181. * so that the first and second IDCT rounds have the same input scaling.
  174182. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174183. * avoid a descaling shift; this compromises accuracy rather drastically
  174184. * for small quantization table entries, but it saves a lot of shifts.
  174185. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174186. * so we use a much larger scaling factor to preserve accuracy.
  174187. *
  174188. * A final compromise is to represent the multiplicative constants to only
  174189. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174190. * machines, and may also reduce the cost of multiplication (since there
  174191. * are fewer one-bits in the constants).
  174192. */
  174193. #if BITS_IN_JSAMPLE == 8
  174194. #define CONST_BITS 8
  174195. #define PASS1_BITS 2
  174196. #else
  174197. #define CONST_BITS 8
  174198. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174199. #endif
  174200. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174201. * causing a lot of useless floating-point operations at run time.
  174202. * To get around this we use the following pre-calculated constants.
  174203. * If you change CONST_BITS you may want to add appropriate values.
  174204. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174205. */
  174206. #if CONST_BITS == 8
  174207. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174208. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174209. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174210. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174211. #else
  174212. #define FIX_1_082392200 FIX(1.082392200)
  174213. #define FIX_1_414213562 FIX(1.414213562)
  174214. #define FIX_1_847759065 FIX(1.847759065)
  174215. #define FIX_2_613125930 FIX(2.613125930)
  174216. #endif
  174217. /* We can gain a little more speed, with a further compromise in accuracy,
  174218. * by omitting the addition in a descaling shift. This yields an incorrectly
  174219. * rounded result half the time...
  174220. */
  174221. #ifndef USE_ACCURATE_ROUNDING
  174222. #undef DESCALE
  174223. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174224. #endif
  174225. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174226. * descale to yield a DCTELEM result.
  174227. */
  174228. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174229. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174230. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174231. * multiplication will do. For 12-bit data, the multiplier table is
  174232. * declared INT32, so a 32-bit multiply will be used.
  174233. */
  174234. #if BITS_IN_JSAMPLE == 8
  174235. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174236. #else
  174237. #define DEQUANTIZE(coef,quantval) \
  174238. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174239. #endif
  174240. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174241. * We assume that int right shift is unsigned if INT32 right shift is.
  174242. */
  174243. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174244. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174245. #if BITS_IN_JSAMPLE == 8
  174246. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174247. #else
  174248. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174249. #endif
  174250. #define IRIGHT_SHIFT(x,shft) \
  174251. ((ishift_temp = (x)) < 0 ? \
  174252. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174253. (ishift_temp >> (shft)))
  174254. #else
  174255. #define ISHIFT_TEMPS
  174256. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174257. #endif
  174258. #ifdef USE_ACCURATE_ROUNDING
  174259. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174260. #else
  174261. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174262. #endif
  174263. /*
  174264. * Perform dequantization and inverse DCT on one block of coefficients.
  174265. */
  174266. GLOBAL(void)
  174267. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174268. JCOEFPTR coef_block,
  174269. JSAMPARRAY output_buf, JDIMENSION output_col)
  174270. {
  174271. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174272. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174273. DCTELEM z5, z10, z11, z12, z13;
  174274. JCOEFPTR inptr;
  174275. IFAST_MULT_TYPE * quantptr;
  174276. int * wsptr;
  174277. JSAMPROW outptr;
  174278. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174279. int ctr;
  174280. int workspace[DCTSIZE2]; /* buffers data between passes */
  174281. SHIFT_TEMPS /* for DESCALE */
  174282. ISHIFT_TEMPS /* for IDESCALE */
  174283. /* Pass 1: process columns from input, store into work array. */
  174284. inptr = coef_block;
  174285. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174286. wsptr = workspace;
  174287. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174288. /* Due to quantization, we will usually find that many of the input
  174289. * coefficients are zero, especially the AC terms. We can exploit this
  174290. * by short-circuiting the IDCT calculation for any column in which all
  174291. * the AC terms are zero. In that case each output is equal to the
  174292. * DC coefficient (with scale factor as needed).
  174293. * With typical images and quantization tables, half or more of the
  174294. * column DCT calculations can be simplified this way.
  174295. */
  174296. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174297. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174298. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174299. inptr[DCTSIZE*7] == 0) {
  174300. /* AC terms all zero */
  174301. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174302. wsptr[DCTSIZE*0] = dcval;
  174303. wsptr[DCTSIZE*1] = dcval;
  174304. wsptr[DCTSIZE*2] = dcval;
  174305. wsptr[DCTSIZE*3] = dcval;
  174306. wsptr[DCTSIZE*4] = dcval;
  174307. wsptr[DCTSIZE*5] = dcval;
  174308. wsptr[DCTSIZE*6] = dcval;
  174309. wsptr[DCTSIZE*7] = dcval;
  174310. inptr++; /* advance pointers to next column */
  174311. quantptr++;
  174312. wsptr++;
  174313. continue;
  174314. }
  174315. /* Even part */
  174316. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174317. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174318. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174319. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174320. tmp10 = tmp0 + tmp2; /* phase 3 */
  174321. tmp11 = tmp0 - tmp2;
  174322. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174323. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174324. tmp0 = tmp10 + tmp13; /* phase 2 */
  174325. tmp3 = tmp10 - tmp13;
  174326. tmp1 = tmp11 + tmp12;
  174327. tmp2 = tmp11 - tmp12;
  174328. /* Odd part */
  174329. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174330. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174331. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174332. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174333. z13 = tmp6 + tmp5; /* phase 6 */
  174334. z10 = tmp6 - tmp5;
  174335. z11 = tmp4 + tmp7;
  174336. z12 = tmp4 - tmp7;
  174337. tmp7 = z11 + z13; /* phase 5 */
  174338. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174339. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174340. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174341. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174342. tmp6 = tmp12 - tmp7; /* phase 2 */
  174343. tmp5 = tmp11 - tmp6;
  174344. tmp4 = tmp10 + tmp5;
  174345. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174346. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174347. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174348. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174349. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174350. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174351. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174352. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174353. inptr++; /* advance pointers to next column */
  174354. quantptr++;
  174355. wsptr++;
  174356. }
  174357. /* Pass 2: process rows from work array, store into output array. */
  174358. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174359. /* and also undo the PASS1_BITS scaling. */
  174360. wsptr = workspace;
  174361. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174362. outptr = output_buf[ctr] + output_col;
  174363. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174364. * However, the column calculation has created many nonzero AC terms, so
  174365. * the simplification applies less often (typically 5% to 10% of the time).
  174366. * On machines with very fast multiplication, it's possible that the
  174367. * test takes more time than it's worth. In that case this section
  174368. * may be commented out.
  174369. */
  174370. #ifndef NO_ZERO_ROW_TEST
  174371. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174372. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174373. /* AC terms all zero */
  174374. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174375. & RANGE_MASK];
  174376. outptr[0] = dcval;
  174377. outptr[1] = dcval;
  174378. outptr[2] = dcval;
  174379. outptr[3] = dcval;
  174380. outptr[4] = dcval;
  174381. outptr[5] = dcval;
  174382. outptr[6] = dcval;
  174383. outptr[7] = dcval;
  174384. wsptr += DCTSIZE; /* advance pointer to next row */
  174385. continue;
  174386. }
  174387. #endif
  174388. /* Even part */
  174389. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174390. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174391. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174392. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174393. - tmp13;
  174394. tmp0 = tmp10 + tmp13;
  174395. tmp3 = tmp10 - tmp13;
  174396. tmp1 = tmp11 + tmp12;
  174397. tmp2 = tmp11 - tmp12;
  174398. /* Odd part */
  174399. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174400. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174401. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174402. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174403. tmp7 = z11 + z13; /* phase 5 */
  174404. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174405. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174406. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174407. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174408. tmp6 = tmp12 - tmp7; /* phase 2 */
  174409. tmp5 = tmp11 - tmp6;
  174410. tmp4 = tmp10 + tmp5;
  174411. /* Final output stage: scale down by a factor of 8 and range-limit */
  174412. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174413. & RANGE_MASK];
  174414. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174415. & RANGE_MASK];
  174416. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174417. & RANGE_MASK];
  174418. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174419. & RANGE_MASK];
  174420. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174421. & RANGE_MASK];
  174422. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174423. & RANGE_MASK];
  174424. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174425. & RANGE_MASK];
  174426. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174427. & RANGE_MASK];
  174428. wsptr += DCTSIZE; /* advance pointer to next row */
  174429. }
  174430. }
  174431. #endif /* DCT_IFAST_SUPPORTED */
  174432. /*** End of inlined file: jidctfst.c ***/
  174433. #undef CONST_BITS
  174434. #undef FIX_1_847759065
  174435. #undef MULTIPLY
  174436. #undef DEQUANTIZE
  174437. /*** Start of inlined file: jidctint.c ***/
  174438. #define JPEG_INTERNALS
  174439. #ifdef DCT_ISLOW_SUPPORTED
  174440. /*
  174441. * This module is specialized to the case DCTSIZE = 8.
  174442. */
  174443. #if DCTSIZE != 8
  174444. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174445. #endif
  174446. /*
  174447. * The poop on this scaling stuff is as follows:
  174448. *
  174449. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174450. * larger than the true IDCT outputs. The final outputs are therefore
  174451. * a factor of N larger than desired; since N=8 this can be cured by
  174452. * a simple right shift at the end of the algorithm. The advantage of
  174453. * this arrangement is that we save two multiplications per 1-D IDCT,
  174454. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174455. *
  174456. * We have to do addition and subtraction of the integer inputs, which
  174457. * is no problem, and multiplication by fractional constants, which is
  174458. * a problem to do in integer arithmetic. We multiply all the constants
  174459. * by CONST_SCALE and convert them to integer constants (thus retaining
  174460. * CONST_BITS bits of precision in the constants). After doing a
  174461. * multiplication we have to divide the product by CONST_SCALE, with proper
  174462. * rounding, to produce the correct output. This division can be done
  174463. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174464. * as long as possible so that partial sums can be added together with
  174465. * full fractional precision.
  174466. *
  174467. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174468. * they are represented to better-than-integral precision. These outputs
  174469. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174470. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174471. * intermediate INT32 array would be needed.)
  174472. *
  174473. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174474. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174475. * shows that the values given below are the most effective.
  174476. */
  174477. #if BITS_IN_JSAMPLE == 8
  174478. #define CONST_BITS 13
  174479. #define PASS1_BITS 2
  174480. #else
  174481. #define CONST_BITS 13
  174482. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174483. #endif
  174484. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174485. * causing a lot of useless floating-point operations at run time.
  174486. * To get around this we use the following pre-calculated constants.
  174487. * If you change CONST_BITS you may want to add appropriate values.
  174488. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174489. */
  174490. #if CONST_BITS == 13
  174491. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174492. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174493. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174494. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174495. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174496. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174497. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174498. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174499. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174500. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174501. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174502. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174503. #else
  174504. #define FIX_0_298631336 FIX(0.298631336)
  174505. #define FIX_0_390180644 FIX(0.390180644)
  174506. #define FIX_0_541196100 FIX(0.541196100)
  174507. #define FIX_0_765366865 FIX(0.765366865)
  174508. #define FIX_0_899976223 FIX(0.899976223)
  174509. #define FIX_1_175875602 FIX(1.175875602)
  174510. #define FIX_1_501321110 FIX(1.501321110)
  174511. #define FIX_1_847759065 FIX(1.847759065)
  174512. #define FIX_1_961570560 FIX(1.961570560)
  174513. #define FIX_2_053119869 FIX(2.053119869)
  174514. #define FIX_2_562915447 FIX(2.562915447)
  174515. #define FIX_3_072711026 FIX(3.072711026)
  174516. #endif
  174517. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174518. * For 8-bit samples with the recommended scaling, all the variable
  174519. * and constant values involved are no more than 16 bits wide, so a
  174520. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174521. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174522. */
  174523. #if BITS_IN_JSAMPLE == 8
  174524. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174525. #else
  174526. #define MULTIPLY(var,const) ((var) * (const))
  174527. #endif
  174528. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174529. * entry; produce an int result. In this module, both inputs and result
  174530. * are 16 bits or less, so either int or short multiply will work.
  174531. */
  174532. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174533. /*
  174534. * Perform dequantization and inverse DCT on one block of coefficients.
  174535. */
  174536. GLOBAL(void)
  174537. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174538. JCOEFPTR coef_block,
  174539. JSAMPARRAY output_buf, JDIMENSION output_col)
  174540. {
  174541. INT32 tmp0, tmp1, tmp2, tmp3;
  174542. INT32 tmp10, tmp11, tmp12, tmp13;
  174543. INT32 z1, z2, z3, z4, z5;
  174544. JCOEFPTR inptr;
  174545. ISLOW_MULT_TYPE * quantptr;
  174546. int * wsptr;
  174547. JSAMPROW outptr;
  174548. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174549. int ctr;
  174550. int workspace[DCTSIZE2]; /* buffers data between passes */
  174551. SHIFT_TEMPS
  174552. /* Pass 1: process columns from input, store into work array. */
  174553. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174554. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174555. inptr = coef_block;
  174556. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174557. wsptr = workspace;
  174558. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174559. /* Due to quantization, we will usually find that many of the input
  174560. * coefficients are zero, especially the AC terms. We can exploit this
  174561. * by short-circuiting the IDCT calculation for any column in which all
  174562. * the AC terms are zero. In that case each output is equal to the
  174563. * DC coefficient (with scale factor as needed).
  174564. * With typical images and quantization tables, half or more of the
  174565. * column DCT calculations can be simplified this way.
  174566. */
  174567. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174568. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174569. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174570. inptr[DCTSIZE*7] == 0) {
  174571. /* AC terms all zero */
  174572. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174573. wsptr[DCTSIZE*0] = dcval;
  174574. wsptr[DCTSIZE*1] = dcval;
  174575. wsptr[DCTSIZE*2] = dcval;
  174576. wsptr[DCTSIZE*3] = dcval;
  174577. wsptr[DCTSIZE*4] = dcval;
  174578. wsptr[DCTSIZE*5] = dcval;
  174579. wsptr[DCTSIZE*6] = dcval;
  174580. wsptr[DCTSIZE*7] = dcval;
  174581. inptr++; /* advance pointers to next column */
  174582. quantptr++;
  174583. wsptr++;
  174584. continue;
  174585. }
  174586. /* Even part: reverse the even part of the forward DCT. */
  174587. /* The rotator is sqrt(2)*c(-6). */
  174588. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174589. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174590. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174591. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174592. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174593. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174594. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174595. tmp0 = (z2 + z3) << CONST_BITS;
  174596. tmp1 = (z2 - z3) << CONST_BITS;
  174597. tmp10 = tmp0 + tmp3;
  174598. tmp13 = tmp0 - tmp3;
  174599. tmp11 = tmp1 + tmp2;
  174600. tmp12 = tmp1 - tmp2;
  174601. /* Odd part per figure 8; the matrix is unitary and hence its
  174602. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174603. */
  174604. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174605. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174606. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174607. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174608. z1 = tmp0 + tmp3;
  174609. z2 = tmp1 + tmp2;
  174610. z3 = tmp0 + tmp2;
  174611. z4 = tmp1 + tmp3;
  174612. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174613. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174614. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174615. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174616. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174617. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174618. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174619. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174620. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174621. z3 += z5;
  174622. z4 += z5;
  174623. tmp0 += z1 + z3;
  174624. tmp1 += z2 + z4;
  174625. tmp2 += z2 + z3;
  174626. tmp3 += z1 + z4;
  174627. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174628. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174629. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174630. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174631. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174632. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174633. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174634. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174635. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174636. inptr++; /* advance pointers to next column */
  174637. quantptr++;
  174638. wsptr++;
  174639. }
  174640. /* Pass 2: process rows from work array, store into output array. */
  174641. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174642. /* and also undo the PASS1_BITS scaling. */
  174643. wsptr = workspace;
  174644. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174645. outptr = output_buf[ctr] + output_col;
  174646. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174647. * However, the column calculation has created many nonzero AC terms, so
  174648. * the simplification applies less often (typically 5% to 10% of the time).
  174649. * On machines with very fast multiplication, it's possible that the
  174650. * test takes more time than it's worth. In that case this section
  174651. * may be commented out.
  174652. */
  174653. #ifndef NO_ZERO_ROW_TEST
  174654. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174655. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174656. /* AC terms all zero */
  174657. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174658. & RANGE_MASK];
  174659. outptr[0] = dcval;
  174660. outptr[1] = dcval;
  174661. outptr[2] = dcval;
  174662. outptr[3] = dcval;
  174663. outptr[4] = dcval;
  174664. outptr[5] = dcval;
  174665. outptr[6] = dcval;
  174666. outptr[7] = dcval;
  174667. wsptr += DCTSIZE; /* advance pointer to next row */
  174668. continue;
  174669. }
  174670. #endif
  174671. /* Even part: reverse the even part of the forward DCT. */
  174672. /* The rotator is sqrt(2)*c(-6). */
  174673. z2 = (INT32) wsptr[2];
  174674. z3 = (INT32) wsptr[6];
  174675. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174676. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174677. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174678. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174679. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174680. tmp10 = tmp0 + tmp3;
  174681. tmp13 = tmp0 - tmp3;
  174682. tmp11 = tmp1 + tmp2;
  174683. tmp12 = tmp1 - tmp2;
  174684. /* Odd part per figure 8; the matrix is unitary and hence its
  174685. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174686. */
  174687. tmp0 = (INT32) wsptr[7];
  174688. tmp1 = (INT32) wsptr[5];
  174689. tmp2 = (INT32) wsptr[3];
  174690. tmp3 = (INT32) wsptr[1];
  174691. z1 = tmp0 + tmp3;
  174692. z2 = tmp1 + tmp2;
  174693. z3 = tmp0 + tmp2;
  174694. z4 = tmp1 + tmp3;
  174695. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174696. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174697. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174698. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174699. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174700. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174701. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174702. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174703. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174704. z3 += z5;
  174705. z4 += z5;
  174706. tmp0 += z1 + z3;
  174707. tmp1 += z2 + z4;
  174708. tmp2 += z2 + z3;
  174709. tmp3 += z1 + z4;
  174710. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174711. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174712. CONST_BITS+PASS1_BITS+3)
  174713. & RANGE_MASK];
  174714. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174715. CONST_BITS+PASS1_BITS+3)
  174716. & RANGE_MASK];
  174717. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174718. CONST_BITS+PASS1_BITS+3)
  174719. & RANGE_MASK];
  174720. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174721. CONST_BITS+PASS1_BITS+3)
  174722. & RANGE_MASK];
  174723. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174724. CONST_BITS+PASS1_BITS+3)
  174725. & RANGE_MASK];
  174726. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174727. CONST_BITS+PASS1_BITS+3)
  174728. & RANGE_MASK];
  174729. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174730. CONST_BITS+PASS1_BITS+3)
  174731. & RANGE_MASK];
  174732. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174733. CONST_BITS+PASS1_BITS+3)
  174734. & RANGE_MASK];
  174735. wsptr += DCTSIZE; /* advance pointer to next row */
  174736. }
  174737. }
  174738. #endif /* DCT_ISLOW_SUPPORTED */
  174739. /*** End of inlined file: jidctint.c ***/
  174740. /*** Start of inlined file: jidctred.c ***/
  174741. #define JPEG_INTERNALS
  174742. #ifdef IDCT_SCALING_SUPPORTED
  174743. /*
  174744. * This module is specialized to the case DCTSIZE = 8.
  174745. */
  174746. #if DCTSIZE != 8
  174747. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174748. #endif
  174749. /* Scaling is the same as in jidctint.c. */
  174750. #if BITS_IN_JSAMPLE == 8
  174751. #define CONST_BITS 13
  174752. #define PASS1_BITS 2
  174753. #else
  174754. #define CONST_BITS 13
  174755. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174756. #endif
  174757. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174758. * causing a lot of useless floating-point operations at run time.
  174759. * To get around this we use the following pre-calculated constants.
  174760. * If you change CONST_BITS you may want to add appropriate values.
  174761. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174762. */
  174763. #if CONST_BITS == 13
  174764. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174765. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174766. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174767. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174768. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174769. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174770. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174771. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174772. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174773. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174774. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174775. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174776. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174777. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174778. #else
  174779. #define FIX_0_211164243 FIX(0.211164243)
  174780. #define FIX_0_509795579 FIX(0.509795579)
  174781. #define FIX_0_601344887 FIX(0.601344887)
  174782. #define FIX_0_720959822 FIX(0.720959822)
  174783. #define FIX_0_765366865 FIX(0.765366865)
  174784. #define FIX_0_850430095 FIX(0.850430095)
  174785. #define FIX_0_899976223 FIX(0.899976223)
  174786. #define FIX_1_061594337 FIX(1.061594337)
  174787. #define FIX_1_272758580 FIX(1.272758580)
  174788. #define FIX_1_451774981 FIX(1.451774981)
  174789. #define FIX_1_847759065 FIX(1.847759065)
  174790. #define FIX_2_172734803 FIX(2.172734803)
  174791. #define FIX_2_562915447 FIX(2.562915447)
  174792. #define FIX_3_624509785 FIX(3.624509785)
  174793. #endif
  174794. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174795. * For 8-bit samples with the recommended scaling, all the variable
  174796. * and constant values involved are no more than 16 bits wide, so a
  174797. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174798. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174799. */
  174800. #if BITS_IN_JSAMPLE == 8
  174801. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174802. #else
  174803. #define MULTIPLY(var,const) ((var) * (const))
  174804. #endif
  174805. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174806. * entry; produce an int result. In this module, both inputs and result
  174807. * are 16 bits or less, so either int or short multiply will work.
  174808. */
  174809. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174810. /*
  174811. * Perform dequantization and inverse DCT on one block of coefficients,
  174812. * producing a reduced-size 4x4 output block.
  174813. */
  174814. GLOBAL(void)
  174815. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174816. JCOEFPTR coef_block,
  174817. JSAMPARRAY output_buf, JDIMENSION output_col)
  174818. {
  174819. INT32 tmp0, tmp2, tmp10, tmp12;
  174820. INT32 z1, z2, z3, z4;
  174821. JCOEFPTR inptr;
  174822. ISLOW_MULT_TYPE * quantptr;
  174823. int * wsptr;
  174824. JSAMPROW outptr;
  174825. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174826. int ctr;
  174827. int workspace[DCTSIZE*4]; /* buffers data between passes */
  174828. SHIFT_TEMPS
  174829. /* Pass 1: process columns from input, store into work array. */
  174830. inptr = coef_block;
  174831. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174832. wsptr = workspace;
  174833. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174834. /* Don't bother to process column 4, because second pass won't use it */
  174835. if (ctr == DCTSIZE-4)
  174836. continue;
  174837. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174838. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  174839. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  174840. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  174841. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174842. wsptr[DCTSIZE*0] = dcval;
  174843. wsptr[DCTSIZE*1] = dcval;
  174844. wsptr[DCTSIZE*2] = dcval;
  174845. wsptr[DCTSIZE*3] = dcval;
  174846. continue;
  174847. }
  174848. /* Even part */
  174849. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174850. tmp0 <<= (CONST_BITS+1);
  174851. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174852. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174853. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  174854. tmp10 = tmp0 + tmp2;
  174855. tmp12 = tmp0 - tmp2;
  174856. /* Odd part */
  174857. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174858. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174859. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174860. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174861. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174862. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174863. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174864. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174865. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174866. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174867. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174868. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174869. /* Final output stage */
  174870. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  174871. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  174872. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  174873. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  174874. }
  174875. /* Pass 2: process 4 rows from work array, store into output array. */
  174876. wsptr = workspace;
  174877. for (ctr = 0; ctr < 4; ctr++) {
  174878. outptr = output_buf[ctr] + output_col;
  174879. /* It's not clear whether a zero row test is worthwhile here ... */
  174880. #ifndef NO_ZERO_ROW_TEST
  174881. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  174882. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174883. /* AC terms all zero */
  174884. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174885. & RANGE_MASK];
  174886. outptr[0] = dcval;
  174887. outptr[1] = dcval;
  174888. outptr[2] = dcval;
  174889. outptr[3] = dcval;
  174890. wsptr += DCTSIZE; /* advance pointer to next row */
  174891. continue;
  174892. }
  174893. #endif
  174894. /* Even part */
  174895. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  174896. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  174897. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  174898. tmp10 = tmp0 + tmp2;
  174899. tmp12 = tmp0 - tmp2;
  174900. /* Odd part */
  174901. z1 = (INT32) wsptr[7];
  174902. z2 = (INT32) wsptr[5];
  174903. z3 = (INT32) wsptr[3];
  174904. z4 = (INT32) wsptr[1];
  174905. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174906. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174907. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174908. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174909. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174910. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174911. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174912. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174913. /* Final output stage */
  174914. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  174915. CONST_BITS+PASS1_BITS+3+1)
  174916. & RANGE_MASK];
  174917. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  174918. CONST_BITS+PASS1_BITS+3+1)
  174919. & RANGE_MASK];
  174920. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  174921. CONST_BITS+PASS1_BITS+3+1)
  174922. & RANGE_MASK];
  174923. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  174924. CONST_BITS+PASS1_BITS+3+1)
  174925. & RANGE_MASK];
  174926. wsptr += DCTSIZE; /* advance pointer to next row */
  174927. }
  174928. }
  174929. /*
  174930. * Perform dequantization and inverse DCT on one block of coefficients,
  174931. * producing a reduced-size 2x2 output block.
  174932. */
  174933. GLOBAL(void)
  174934. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174935. JCOEFPTR coef_block,
  174936. JSAMPARRAY output_buf, JDIMENSION output_col)
  174937. {
  174938. INT32 tmp0, tmp10, z1;
  174939. JCOEFPTR inptr;
  174940. ISLOW_MULT_TYPE * quantptr;
  174941. int * wsptr;
  174942. JSAMPROW outptr;
  174943. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174944. int ctr;
  174945. int workspace[DCTSIZE*2]; /* buffers data between passes */
  174946. SHIFT_TEMPS
  174947. /* Pass 1: process columns from input, store into work array. */
  174948. inptr = coef_block;
  174949. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174950. wsptr = workspace;
  174951. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174952. /* Don't bother to process columns 2,4,6 */
  174953. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  174954. continue;
  174955. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  174956. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  174957. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  174958. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174959. wsptr[DCTSIZE*0] = dcval;
  174960. wsptr[DCTSIZE*1] = dcval;
  174961. continue;
  174962. }
  174963. /* Even part */
  174964. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174965. tmp10 = z1 << (CONST_BITS+2);
  174966. /* Odd part */
  174967. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174968. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  174969. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174970. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  174971. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174972. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  174973. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174974. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174975. /* Final output stage */
  174976. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  174977. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  174978. }
  174979. /* Pass 2: process 2 rows from work array, store into output array. */
  174980. wsptr = workspace;
  174981. for (ctr = 0; ctr < 2; ctr++) {
  174982. outptr = output_buf[ctr] + output_col;
  174983. /* It's not clear whether a zero row test is worthwhile here ... */
  174984. #ifndef NO_ZERO_ROW_TEST
  174985. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  174986. /* AC terms all zero */
  174987. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174988. & RANGE_MASK];
  174989. outptr[0] = dcval;
  174990. outptr[1] = dcval;
  174991. wsptr += DCTSIZE; /* advance pointer to next row */
  174992. continue;
  174993. }
  174994. #endif
  174995. /* Even part */
  174996. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  174997. /* Odd part */
  174998. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  174999. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175000. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175001. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175002. /* Final output stage */
  175003. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175004. CONST_BITS+PASS1_BITS+3+2)
  175005. & RANGE_MASK];
  175006. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175007. CONST_BITS+PASS1_BITS+3+2)
  175008. & RANGE_MASK];
  175009. wsptr += DCTSIZE; /* advance pointer to next row */
  175010. }
  175011. }
  175012. /*
  175013. * Perform dequantization and inverse DCT on one block of coefficients,
  175014. * producing a reduced-size 1x1 output block.
  175015. */
  175016. GLOBAL(void)
  175017. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175018. JCOEFPTR coef_block,
  175019. JSAMPARRAY output_buf, JDIMENSION output_col)
  175020. {
  175021. int dcval;
  175022. ISLOW_MULT_TYPE * quantptr;
  175023. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175024. SHIFT_TEMPS
  175025. /* We hardly need an inverse DCT routine for this: just take the
  175026. * average pixel value, which is one-eighth of the DC coefficient.
  175027. */
  175028. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175029. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175030. dcval = (int) DESCALE((INT32) dcval, 3);
  175031. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175032. }
  175033. #endif /* IDCT_SCALING_SUPPORTED */
  175034. /*** End of inlined file: jidctred.c ***/
  175035. /*** Start of inlined file: jmemmgr.c ***/
  175036. #define JPEG_INTERNALS
  175037. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175038. /*** Start of inlined file: jmemsys.h ***/
  175039. #ifndef __jmemsys_h__
  175040. #define __jmemsys_h__
  175041. /* Short forms of external names for systems with brain-damaged linkers. */
  175042. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175043. #define jpeg_get_small jGetSmall
  175044. #define jpeg_free_small jFreeSmall
  175045. #define jpeg_get_large jGetLarge
  175046. #define jpeg_free_large jFreeLarge
  175047. #define jpeg_mem_available jMemAvail
  175048. #define jpeg_open_backing_store jOpenBackStore
  175049. #define jpeg_mem_init jMemInit
  175050. #define jpeg_mem_term jMemTerm
  175051. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175052. /*
  175053. * These two functions are used to allocate and release small chunks of
  175054. * memory. (Typically the total amount requested through jpeg_get_small is
  175055. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175056. * Behavior should be the same as for the standard library functions malloc
  175057. * and free; in particular, jpeg_get_small must return NULL on failure.
  175058. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175059. * size of the object being freed, just in case it's needed.
  175060. * On an 80x86 machine using small-data memory model, these manage near heap.
  175061. */
  175062. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175063. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175064. size_t sizeofobject));
  175065. /*
  175066. * These two functions are used to allocate and release large chunks of
  175067. * memory (up to the total free space designated by jpeg_mem_available).
  175068. * The interface is the same as above, except that on an 80x86 machine,
  175069. * far pointers are used. On most other machines these are identical to
  175070. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175071. * in case a different allocation strategy is desirable for large chunks.
  175072. */
  175073. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175074. size_t sizeofobject));
  175075. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175076. size_t sizeofobject));
  175077. /*
  175078. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175079. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175080. * matter, but that case should never come into play). This macro is needed
  175081. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175082. * On those machines, we expect that jconfig.h will provide a proper value.
  175083. * On machines with 32-bit flat address spaces, any large constant may be used.
  175084. *
  175085. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175086. * size_t and will be a multiple of sizeof(align_type).
  175087. */
  175088. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175089. #define MAX_ALLOC_CHUNK 1000000000L
  175090. #endif
  175091. /*
  175092. * This routine computes the total space still available for allocation by
  175093. * jpeg_get_large. If more space than this is needed, backing store will be
  175094. * used. NOTE: any memory already allocated must not be counted.
  175095. *
  175096. * There is a minimum space requirement, corresponding to the minimum
  175097. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175098. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175099. * all working storage in memory, is also passed in case it is useful.
  175100. * Finally, the total space already allocated is passed. If no better
  175101. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175102. * is often a suitable calculation.
  175103. *
  175104. * It is OK for jpeg_mem_available to underestimate the space available
  175105. * (that'll just lead to more backing-store access than is really necessary).
  175106. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175107. * a slop factor from the true available space. 5% should be enough.
  175108. *
  175109. * On machines with lots of virtual memory, any large constant may be returned.
  175110. * Conversely, zero may be returned to always use the minimum amount of memory.
  175111. */
  175112. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175113. long min_bytes_needed,
  175114. long max_bytes_needed,
  175115. long already_allocated));
  175116. /*
  175117. * This structure holds whatever state is needed to access a single
  175118. * backing-store object. The read/write/close method pointers are called
  175119. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175120. * are private to the system-dependent backing store routines.
  175121. */
  175122. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175123. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175124. typedef unsigned short XMSH; /* type of extended-memory handles */
  175125. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175126. typedef union {
  175127. short file_handle; /* DOS file handle if it's a temp file */
  175128. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175129. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175130. } handle_union;
  175131. #endif /* USE_MSDOS_MEMMGR */
  175132. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175133. #include <Files.h>
  175134. #endif /* USE_MAC_MEMMGR */
  175135. //typedef struct backing_store_struct * backing_store_ptr;
  175136. typedef struct backing_store_struct {
  175137. /* Methods for reading/writing/closing this backing-store object */
  175138. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175139. struct backing_store_struct *info,
  175140. void FAR * buffer_address,
  175141. long file_offset, long byte_count));
  175142. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175143. struct backing_store_struct *info,
  175144. void FAR * buffer_address,
  175145. long file_offset, long byte_count));
  175146. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175147. struct backing_store_struct *info));
  175148. /* Private fields for system-dependent backing-store management */
  175149. #ifdef USE_MSDOS_MEMMGR
  175150. /* For the MS-DOS manager (jmemdos.c), we need: */
  175151. handle_union handle; /* reference to backing-store storage object */
  175152. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175153. #else
  175154. #ifdef USE_MAC_MEMMGR
  175155. /* For the Mac manager (jmemmac.c), we need: */
  175156. short temp_file; /* file reference number to temp file */
  175157. FSSpec tempSpec; /* the FSSpec for the temp file */
  175158. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175159. #else
  175160. /* For a typical implementation with temp files, we need: */
  175161. FILE * temp_file; /* stdio reference to temp file */
  175162. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175163. #endif
  175164. #endif
  175165. } backing_store_info;
  175166. /*
  175167. * Initial opening of a backing-store object. This must fill in the
  175168. * read/write/close pointers in the object. The read/write routines
  175169. * may take an error exit if the specified maximum file size is exceeded.
  175170. * (If jpeg_mem_available always returns a large value, this routine can
  175171. * just take an error exit.)
  175172. */
  175173. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175174. struct backing_store_struct *info,
  175175. long total_bytes_needed));
  175176. /*
  175177. * These routines take care of any system-dependent initialization and
  175178. * cleanup required. jpeg_mem_init will be called before anything is
  175179. * allocated (and, therefore, nothing in cinfo is of use except the error
  175180. * manager pointer). It should return a suitable default value for
  175181. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175182. * application. (Note that max_memory_to_use is only important if
  175183. * jpeg_mem_available chooses to consult it ... no one else will.)
  175184. * jpeg_mem_term may assume that all requested memory has been freed and that
  175185. * all opened backing-store objects have been closed.
  175186. */
  175187. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175188. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175189. #endif
  175190. /*** End of inlined file: jmemsys.h ***/
  175191. /* import the system-dependent declarations */
  175192. #ifndef NO_GETENV
  175193. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175194. extern char * getenv JPP((const char * name));
  175195. #endif
  175196. #endif
  175197. /*
  175198. * Some important notes:
  175199. * The allocation routines provided here must never return NULL.
  175200. * They should exit to error_exit if unsuccessful.
  175201. *
  175202. * It's not a good idea to try to merge the sarray and barray routines,
  175203. * even though they are textually almost the same, because samples are
  175204. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175205. * in machines where byte pointers have a different representation from
  175206. * word pointers, the resulting machine code could not be the same.
  175207. */
  175208. /*
  175209. * Many machines require storage alignment: longs must start on 4-byte
  175210. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175211. * always returns pointers that are multiples of the worst-case alignment
  175212. * requirement, and we had better do so too.
  175213. * There isn't any really portable way to determine the worst-case alignment
  175214. * requirement. This module assumes that the alignment requirement is
  175215. * multiples of sizeof(ALIGN_TYPE).
  175216. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175217. * workstations (where doubles really do need 8-byte alignment) and will work
  175218. * fine on nearly everything. If your machine has lesser alignment needs,
  175219. * you can save a few bytes by making ALIGN_TYPE smaller.
  175220. * The only place I know of where this will NOT work is certain Macintosh
  175221. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175222. * Doing 10-byte alignment is counterproductive because longwords won't be
  175223. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175224. * such a compiler.
  175225. */
  175226. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175227. #define ALIGN_TYPE double
  175228. #endif
  175229. /*
  175230. * We allocate objects from "pools", where each pool is gotten with a single
  175231. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175232. * overhead within a pool, except for alignment padding. Each pool has a
  175233. * header with a link to the next pool of the same class.
  175234. * Small and large pool headers are identical except that the latter's
  175235. * link pointer must be FAR on 80x86 machines.
  175236. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175237. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175238. * of the alignment requirement of ALIGN_TYPE.
  175239. */
  175240. typedef union small_pool_struct * small_pool_ptr;
  175241. typedef union small_pool_struct {
  175242. struct {
  175243. small_pool_ptr next; /* next in list of pools */
  175244. size_t bytes_used; /* how many bytes already used within pool */
  175245. size_t bytes_left; /* bytes still available in this pool */
  175246. } hdr;
  175247. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175248. } small_pool_hdr;
  175249. typedef union large_pool_struct FAR * large_pool_ptr;
  175250. typedef union large_pool_struct {
  175251. struct {
  175252. large_pool_ptr next; /* next in list of pools */
  175253. size_t bytes_used; /* how many bytes already used within pool */
  175254. size_t bytes_left; /* bytes still available in this pool */
  175255. } hdr;
  175256. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175257. } large_pool_hdr;
  175258. /*
  175259. * Here is the full definition of a memory manager object.
  175260. */
  175261. typedef struct {
  175262. struct jpeg_memory_mgr pub; /* public fields */
  175263. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175264. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175265. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175266. /* Since we only have one lifetime class of virtual arrays, only one
  175267. * linked list is necessary (for each datatype). Note that the virtual
  175268. * array control blocks being linked together are actually stored somewhere
  175269. * in the small-pool list.
  175270. */
  175271. jvirt_sarray_ptr virt_sarray_list;
  175272. jvirt_barray_ptr virt_barray_list;
  175273. /* This counts total space obtained from jpeg_get_small/large */
  175274. long total_space_allocated;
  175275. /* alloc_sarray and alloc_barray set this value for use by virtual
  175276. * array routines.
  175277. */
  175278. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175279. } my_memory_mgr;
  175280. typedef my_memory_mgr * my_mem_ptr;
  175281. /*
  175282. * The control blocks for virtual arrays.
  175283. * Note that these blocks are allocated in the "small" pool area.
  175284. * System-dependent info for the associated backing store (if any) is hidden
  175285. * inside the backing_store_info struct.
  175286. */
  175287. struct jvirt_sarray_control {
  175288. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175289. JDIMENSION rows_in_array; /* total virtual array height */
  175290. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175291. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175292. JDIMENSION rows_in_mem; /* height of memory buffer */
  175293. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175294. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175295. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175296. boolean pre_zero; /* pre-zero mode requested? */
  175297. boolean dirty; /* do current buffer contents need written? */
  175298. boolean b_s_open; /* is backing-store data valid? */
  175299. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175300. backing_store_info b_s_info; /* System-dependent control info */
  175301. };
  175302. struct jvirt_barray_control {
  175303. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175304. JDIMENSION rows_in_array; /* total virtual array height */
  175305. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175306. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175307. JDIMENSION rows_in_mem; /* height of memory buffer */
  175308. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175309. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175310. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175311. boolean pre_zero; /* pre-zero mode requested? */
  175312. boolean dirty; /* do current buffer contents need written? */
  175313. boolean b_s_open; /* is backing-store data valid? */
  175314. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175315. backing_store_info b_s_info; /* System-dependent control info */
  175316. };
  175317. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175318. LOCAL(void)
  175319. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175320. {
  175321. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175322. small_pool_ptr shdr_ptr;
  175323. large_pool_ptr lhdr_ptr;
  175324. /* Since this is only a debugging stub, we can cheat a little by using
  175325. * fprintf directly rather than going through the trace message code.
  175326. * This is helpful because message parm array can't handle longs.
  175327. */
  175328. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175329. pool_id, mem->total_space_allocated);
  175330. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175331. lhdr_ptr = lhdr_ptr->hdr.next) {
  175332. fprintf(stderr, " Large chunk used %ld\n",
  175333. (long) lhdr_ptr->hdr.bytes_used);
  175334. }
  175335. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175336. shdr_ptr = shdr_ptr->hdr.next) {
  175337. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175338. (long) shdr_ptr->hdr.bytes_used,
  175339. (long) shdr_ptr->hdr.bytes_left);
  175340. }
  175341. }
  175342. #endif /* MEM_STATS */
  175343. LOCAL(void)
  175344. out_of_memory (j_common_ptr cinfo, int which)
  175345. /* Report an out-of-memory error and stop execution */
  175346. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175347. {
  175348. #ifdef MEM_STATS
  175349. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175350. #endif
  175351. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175352. }
  175353. /*
  175354. * Allocation of "small" objects.
  175355. *
  175356. * For these, we use pooled storage. When a new pool must be created,
  175357. * we try to get enough space for the current request plus a "slop" factor,
  175358. * where the slop will be the amount of leftover space in the new pool.
  175359. * The speed vs. space tradeoff is largely determined by the slop values.
  175360. * A different slop value is provided for each pool class (lifetime),
  175361. * and we also distinguish the first pool of a class from later ones.
  175362. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175363. * machines, but may be too small if longs are 64 bits or more.
  175364. */
  175365. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175366. {
  175367. 1600, /* first PERMANENT pool */
  175368. 16000 /* first IMAGE pool */
  175369. };
  175370. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175371. {
  175372. 0, /* additional PERMANENT pools */
  175373. 5000 /* additional IMAGE pools */
  175374. };
  175375. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175376. METHODDEF(void *)
  175377. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175378. /* Allocate a "small" object */
  175379. {
  175380. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175381. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175382. char * data_ptr;
  175383. size_t odd_bytes, min_request, slop;
  175384. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175385. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175386. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175387. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175388. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175389. if (odd_bytes > 0)
  175390. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175391. /* See if space is available in any existing pool */
  175392. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175393. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175394. prev_hdr_ptr = NULL;
  175395. hdr_ptr = mem->small_list[pool_id];
  175396. while (hdr_ptr != NULL) {
  175397. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175398. break; /* found pool with enough space */
  175399. prev_hdr_ptr = hdr_ptr;
  175400. hdr_ptr = hdr_ptr->hdr.next;
  175401. }
  175402. /* Time to make a new pool? */
  175403. if (hdr_ptr == NULL) {
  175404. /* min_request is what we need now, slop is what will be leftover */
  175405. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175406. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175407. slop = first_pool_slop[pool_id];
  175408. else
  175409. slop = extra_pool_slop[pool_id];
  175410. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175411. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175412. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175413. /* Try to get space, if fail reduce slop and try again */
  175414. for (;;) {
  175415. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175416. if (hdr_ptr != NULL)
  175417. break;
  175418. slop /= 2;
  175419. if (slop < MIN_SLOP) /* give up when it gets real small */
  175420. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175421. }
  175422. mem->total_space_allocated += min_request + slop;
  175423. /* Success, initialize the new pool header and add to end of list */
  175424. hdr_ptr->hdr.next = NULL;
  175425. hdr_ptr->hdr.bytes_used = 0;
  175426. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175427. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175428. mem->small_list[pool_id] = hdr_ptr;
  175429. else
  175430. prev_hdr_ptr->hdr.next = hdr_ptr;
  175431. }
  175432. /* OK, allocate the object from the current pool */
  175433. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175434. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175435. hdr_ptr->hdr.bytes_used += sizeofobject;
  175436. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175437. return (void *) data_ptr;
  175438. }
  175439. /*
  175440. * Allocation of "large" objects.
  175441. *
  175442. * The external semantics of these are the same as "small" objects,
  175443. * except that FAR pointers are used on 80x86. However the pool
  175444. * management heuristics are quite different. We assume that each
  175445. * request is large enough that it may as well be passed directly to
  175446. * jpeg_get_large; the pool management just links everything together
  175447. * so that we can free it all on demand.
  175448. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175449. * structures. The routines that create these structures (see below)
  175450. * deliberately bunch rows together to ensure a large request size.
  175451. */
  175452. METHODDEF(void FAR *)
  175453. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175454. /* Allocate a "large" object */
  175455. {
  175456. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175457. large_pool_ptr hdr_ptr;
  175458. size_t odd_bytes;
  175459. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175460. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175461. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175462. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175463. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175464. if (odd_bytes > 0)
  175465. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175466. /* Always make a new pool */
  175467. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175468. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175469. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175470. SIZEOF(large_pool_hdr));
  175471. if (hdr_ptr == NULL)
  175472. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175473. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175474. /* Success, initialize the new pool header and add to list */
  175475. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175476. /* We maintain space counts in each pool header for statistical purposes,
  175477. * even though they are not needed for allocation.
  175478. */
  175479. hdr_ptr->hdr.bytes_used = sizeofobject;
  175480. hdr_ptr->hdr.bytes_left = 0;
  175481. mem->large_list[pool_id] = hdr_ptr;
  175482. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175483. }
  175484. /*
  175485. * Creation of 2-D sample arrays.
  175486. * The pointers are in near heap, the samples themselves in FAR heap.
  175487. *
  175488. * To minimize allocation overhead and to allow I/O of large contiguous
  175489. * blocks, we allocate the sample rows in groups of as many rows as possible
  175490. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175491. * NB: the virtual array control routines, later in this file, know about
  175492. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175493. * object so that it can be saved away if this sarray is the workspace for
  175494. * a virtual array.
  175495. */
  175496. METHODDEF(JSAMPARRAY)
  175497. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175498. JDIMENSION samplesperrow, JDIMENSION numrows)
  175499. /* Allocate a 2-D sample array */
  175500. {
  175501. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175502. JSAMPARRAY result;
  175503. JSAMPROW workspace;
  175504. JDIMENSION rowsperchunk, currow, i;
  175505. long ltemp;
  175506. /* Calculate max # of rows allowed in one allocation chunk */
  175507. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175508. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175509. if (ltemp <= 0)
  175510. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175511. if (ltemp < (long) numrows)
  175512. rowsperchunk = (JDIMENSION) ltemp;
  175513. else
  175514. rowsperchunk = numrows;
  175515. mem->last_rowsperchunk = rowsperchunk;
  175516. /* Get space for row pointers (small object) */
  175517. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175518. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175519. /* Get the rows themselves (large objects) */
  175520. currow = 0;
  175521. while (currow < numrows) {
  175522. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175523. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175524. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175525. * SIZEOF(JSAMPLE)));
  175526. for (i = rowsperchunk; i > 0; i--) {
  175527. result[currow++] = workspace;
  175528. workspace += samplesperrow;
  175529. }
  175530. }
  175531. return result;
  175532. }
  175533. /*
  175534. * Creation of 2-D coefficient-block arrays.
  175535. * This is essentially the same as the code for sample arrays, above.
  175536. */
  175537. METHODDEF(JBLOCKARRAY)
  175538. alloc_barray (j_common_ptr cinfo, int pool_id,
  175539. JDIMENSION blocksperrow, JDIMENSION numrows)
  175540. /* Allocate a 2-D coefficient-block array */
  175541. {
  175542. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175543. JBLOCKARRAY result;
  175544. JBLOCKROW workspace;
  175545. JDIMENSION rowsperchunk, currow, i;
  175546. long ltemp;
  175547. /* Calculate max # of rows allowed in one allocation chunk */
  175548. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175549. ((long) blocksperrow * SIZEOF(JBLOCK));
  175550. if (ltemp <= 0)
  175551. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175552. if (ltemp < (long) numrows)
  175553. rowsperchunk = (JDIMENSION) ltemp;
  175554. else
  175555. rowsperchunk = numrows;
  175556. mem->last_rowsperchunk = rowsperchunk;
  175557. /* Get space for row pointers (small object) */
  175558. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175559. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175560. /* Get the rows themselves (large objects) */
  175561. currow = 0;
  175562. while (currow < numrows) {
  175563. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175564. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175565. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175566. * SIZEOF(JBLOCK)));
  175567. for (i = rowsperchunk; i > 0; i--) {
  175568. result[currow++] = workspace;
  175569. workspace += blocksperrow;
  175570. }
  175571. }
  175572. return result;
  175573. }
  175574. /*
  175575. * About virtual array management:
  175576. *
  175577. * The above "normal" array routines are only used to allocate strip buffers
  175578. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175579. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175580. * time, but the memory manager must save the whole array for repeated
  175581. * accesses. The intended implementation is that there is a strip buffer in
  175582. * memory (as high as is possible given the desired memory limit), plus a
  175583. * backing file that holds the rest of the array.
  175584. *
  175585. * The request_virt_array routines are told the total size of the image and
  175586. * the maximum number of rows that will be accessed at once. The in-memory
  175587. * buffer must be at least as large as the maxaccess value.
  175588. *
  175589. * The request routines create control blocks but not the in-memory buffers.
  175590. * That is postponed until realize_virt_arrays is called. At that time the
  175591. * total amount of space needed is known (approximately, anyway), so free
  175592. * memory can be divided up fairly.
  175593. *
  175594. * The access_virt_array routines are responsible for making a specific strip
  175595. * area accessible (after reading or writing the backing file, if necessary).
  175596. * Note that the access routines are told whether the caller intends to modify
  175597. * the accessed strip; during a read-only pass this saves having to rewrite
  175598. * data to disk. The access routines are also responsible for pre-zeroing
  175599. * any newly accessed rows, if pre-zeroing was requested.
  175600. *
  175601. * In current usage, the access requests are usually for nonoverlapping
  175602. * strips; that is, successive access start_row numbers differ by exactly
  175603. * num_rows = maxaccess. This means we can get good performance with simple
  175604. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175605. * of the access height; then there will never be accesses across bufferload
  175606. * boundaries. The code will still work with overlapping access requests,
  175607. * but it doesn't handle bufferload overlaps very efficiently.
  175608. */
  175609. METHODDEF(jvirt_sarray_ptr)
  175610. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175611. JDIMENSION samplesperrow, JDIMENSION numrows,
  175612. JDIMENSION maxaccess)
  175613. /* Request a virtual 2-D sample array */
  175614. {
  175615. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175616. jvirt_sarray_ptr result;
  175617. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175618. if (pool_id != JPOOL_IMAGE)
  175619. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175620. /* get control block */
  175621. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175622. SIZEOF(struct jvirt_sarray_control));
  175623. result->mem_buffer = NULL; /* marks array not yet realized */
  175624. result->rows_in_array = numrows;
  175625. result->samplesperrow = samplesperrow;
  175626. result->maxaccess = maxaccess;
  175627. result->pre_zero = pre_zero;
  175628. result->b_s_open = FALSE; /* no associated backing-store object */
  175629. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175630. mem->virt_sarray_list = result;
  175631. return result;
  175632. }
  175633. METHODDEF(jvirt_barray_ptr)
  175634. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175635. JDIMENSION blocksperrow, JDIMENSION numrows,
  175636. JDIMENSION maxaccess)
  175637. /* Request a virtual 2-D coefficient-block array */
  175638. {
  175639. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175640. jvirt_barray_ptr result;
  175641. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175642. if (pool_id != JPOOL_IMAGE)
  175643. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175644. /* get control block */
  175645. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175646. SIZEOF(struct jvirt_barray_control));
  175647. result->mem_buffer = NULL; /* marks array not yet realized */
  175648. result->rows_in_array = numrows;
  175649. result->blocksperrow = blocksperrow;
  175650. result->maxaccess = maxaccess;
  175651. result->pre_zero = pre_zero;
  175652. result->b_s_open = FALSE; /* no associated backing-store object */
  175653. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175654. mem->virt_barray_list = result;
  175655. return result;
  175656. }
  175657. METHODDEF(void)
  175658. realize_virt_arrays (j_common_ptr cinfo)
  175659. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175660. {
  175661. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175662. long space_per_minheight, maximum_space, avail_mem;
  175663. long minheights, max_minheights;
  175664. jvirt_sarray_ptr sptr;
  175665. jvirt_barray_ptr bptr;
  175666. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175667. * and the maximum space needed (full image height in each buffer).
  175668. * These may be of use to the system-dependent jpeg_mem_available routine.
  175669. */
  175670. space_per_minheight = 0;
  175671. maximum_space = 0;
  175672. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175673. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175674. space_per_minheight += (long) sptr->maxaccess *
  175675. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175676. maximum_space += (long) sptr->rows_in_array *
  175677. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175678. }
  175679. }
  175680. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175681. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175682. space_per_minheight += (long) bptr->maxaccess *
  175683. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175684. maximum_space += (long) bptr->rows_in_array *
  175685. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175686. }
  175687. }
  175688. if (space_per_minheight <= 0)
  175689. return; /* no unrealized arrays, no work */
  175690. /* Determine amount of memory to actually use; this is system-dependent. */
  175691. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175692. mem->total_space_allocated);
  175693. /* If the maximum space needed is available, make all the buffers full
  175694. * height; otherwise parcel it out with the same number of minheights
  175695. * in each buffer.
  175696. */
  175697. if (avail_mem >= maximum_space)
  175698. max_minheights = 1000000000L;
  175699. else {
  175700. max_minheights = avail_mem / space_per_minheight;
  175701. /* If there doesn't seem to be enough space, try to get the minimum
  175702. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175703. */
  175704. if (max_minheights <= 0)
  175705. max_minheights = 1;
  175706. }
  175707. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175708. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175709. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175710. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175711. if (minheights <= max_minheights) {
  175712. /* This buffer fits in memory */
  175713. sptr->rows_in_mem = sptr->rows_in_array;
  175714. } else {
  175715. /* It doesn't fit in memory, create backing store. */
  175716. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175717. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175718. (long) sptr->rows_in_array *
  175719. (long) sptr->samplesperrow *
  175720. (long) SIZEOF(JSAMPLE));
  175721. sptr->b_s_open = TRUE;
  175722. }
  175723. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175724. sptr->samplesperrow, sptr->rows_in_mem);
  175725. sptr->rowsperchunk = mem->last_rowsperchunk;
  175726. sptr->cur_start_row = 0;
  175727. sptr->first_undef_row = 0;
  175728. sptr->dirty = FALSE;
  175729. }
  175730. }
  175731. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175732. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175733. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175734. if (minheights <= max_minheights) {
  175735. /* This buffer fits in memory */
  175736. bptr->rows_in_mem = bptr->rows_in_array;
  175737. } else {
  175738. /* It doesn't fit in memory, create backing store. */
  175739. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175740. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175741. (long) bptr->rows_in_array *
  175742. (long) bptr->blocksperrow *
  175743. (long) SIZEOF(JBLOCK));
  175744. bptr->b_s_open = TRUE;
  175745. }
  175746. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175747. bptr->blocksperrow, bptr->rows_in_mem);
  175748. bptr->rowsperchunk = mem->last_rowsperchunk;
  175749. bptr->cur_start_row = 0;
  175750. bptr->first_undef_row = 0;
  175751. bptr->dirty = FALSE;
  175752. }
  175753. }
  175754. }
  175755. LOCAL(void)
  175756. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175757. /* Do backing store read or write of a virtual sample array */
  175758. {
  175759. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175760. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175761. file_offset = ptr->cur_start_row * bytesperrow;
  175762. /* Loop to read or write each allocation chunk in mem_buffer */
  175763. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175764. /* One chunk, but check for short chunk at end of buffer */
  175765. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175766. /* Transfer no more than is currently defined */
  175767. thisrow = (long) ptr->cur_start_row + i;
  175768. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175769. /* Transfer no more than fits in file */
  175770. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175771. if (rows <= 0) /* this chunk might be past end of file! */
  175772. break;
  175773. byte_count = rows * bytesperrow;
  175774. if (writing)
  175775. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175776. (void FAR *) ptr->mem_buffer[i],
  175777. file_offset, byte_count);
  175778. else
  175779. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175780. (void FAR *) ptr->mem_buffer[i],
  175781. file_offset, byte_count);
  175782. file_offset += byte_count;
  175783. }
  175784. }
  175785. LOCAL(void)
  175786. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175787. /* Do backing store read or write of a virtual coefficient-block array */
  175788. {
  175789. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175790. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175791. file_offset = ptr->cur_start_row * bytesperrow;
  175792. /* Loop to read or write each allocation chunk in mem_buffer */
  175793. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175794. /* One chunk, but check for short chunk at end of buffer */
  175795. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175796. /* Transfer no more than is currently defined */
  175797. thisrow = (long) ptr->cur_start_row + i;
  175798. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175799. /* Transfer no more than fits in file */
  175800. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175801. if (rows <= 0) /* this chunk might be past end of file! */
  175802. break;
  175803. byte_count = rows * bytesperrow;
  175804. if (writing)
  175805. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175806. (void FAR *) ptr->mem_buffer[i],
  175807. file_offset, byte_count);
  175808. else
  175809. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175810. (void FAR *) ptr->mem_buffer[i],
  175811. file_offset, byte_count);
  175812. file_offset += byte_count;
  175813. }
  175814. }
  175815. METHODDEF(JSAMPARRAY)
  175816. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175817. JDIMENSION start_row, JDIMENSION num_rows,
  175818. boolean writable)
  175819. /* Access the part of a virtual sample array starting at start_row */
  175820. /* and extending for num_rows rows. writable is true if */
  175821. /* caller intends to modify the accessed area. */
  175822. {
  175823. JDIMENSION end_row = start_row + num_rows;
  175824. JDIMENSION undef_row;
  175825. /* debugging check */
  175826. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175827. ptr->mem_buffer == NULL)
  175828. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175829. /* Make the desired part of the virtual array accessible */
  175830. if (start_row < ptr->cur_start_row ||
  175831. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175832. if (! ptr->b_s_open)
  175833. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175834. /* Flush old buffer contents if necessary */
  175835. if (ptr->dirty) {
  175836. do_sarray_io(cinfo, ptr, TRUE);
  175837. ptr->dirty = FALSE;
  175838. }
  175839. /* Decide what part of virtual array to access.
  175840. * Algorithm: if target address > current window, assume forward scan,
  175841. * load starting at target address. If target address < current window,
  175842. * assume backward scan, load so that target area is top of window.
  175843. * Note that when switching from forward write to forward read, will have
  175844. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175845. */
  175846. if (start_row > ptr->cur_start_row) {
  175847. ptr->cur_start_row = start_row;
  175848. } else {
  175849. /* use long arithmetic here to avoid overflow & unsigned problems */
  175850. long ltemp;
  175851. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175852. if (ltemp < 0)
  175853. ltemp = 0; /* don't fall off front end of file */
  175854. ptr->cur_start_row = (JDIMENSION) ltemp;
  175855. }
  175856. /* Read in the selected part of the array.
  175857. * During the initial write pass, we will do no actual read
  175858. * because the selected part is all undefined.
  175859. */
  175860. do_sarray_io(cinfo, ptr, FALSE);
  175861. }
  175862. /* Ensure the accessed part of the array is defined; prezero if needed.
  175863. * To improve locality of access, we only prezero the part of the array
  175864. * that the caller is about to access, not the entire in-memory array.
  175865. */
  175866. if (ptr->first_undef_row < end_row) {
  175867. if (ptr->first_undef_row < start_row) {
  175868. if (writable) /* writer skipped over a section of array */
  175869. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175870. undef_row = start_row; /* but reader is allowed to read ahead */
  175871. } else {
  175872. undef_row = ptr->first_undef_row;
  175873. }
  175874. if (writable)
  175875. ptr->first_undef_row = end_row;
  175876. if (ptr->pre_zero) {
  175877. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175878. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175879. end_row -= ptr->cur_start_row;
  175880. while (undef_row < end_row) {
  175881. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175882. undef_row++;
  175883. }
  175884. } else {
  175885. if (! writable) /* reader looking at undefined data */
  175886. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175887. }
  175888. }
  175889. /* Flag the buffer dirty if caller will write in it */
  175890. if (writable)
  175891. ptr->dirty = TRUE;
  175892. /* Return address of proper part of the buffer */
  175893. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175894. }
  175895. METHODDEF(JBLOCKARRAY)
  175896. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  175897. JDIMENSION start_row, JDIMENSION num_rows,
  175898. boolean writable)
  175899. /* Access the part of a virtual block array starting at start_row */
  175900. /* and extending for num_rows rows. writable is true if */
  175901. /* caller intends to modify the accessed area. */
  175902. {
  175903. JDIMENSION end_row = start_row + num_rows;
  175904. JDIMENSION undef_row;
  175905. /* debugging check */
  175906. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175907. ptr->mem_buffer == NULL)
  175908. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175909. /* Make the desired part of the virtual array accessible */
  175910. if (start_row < ptr->cur_start_row ||
  175911. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175912. if (! ptr->b_s_open)
  175913. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175914. /* Flush old buffer contents if necessary */
  175915. if (ptr->dirty) {
  175916. do_barray_io(cinfo, ptr, TRUE);
  175917. ptr->dirty = FALSE;
  175918. }
  175919. /* Decide what part of virtual array to access.
  175920. * Algorithm: if target address > current window, assume forward scan,
  175921. * load starting at target address. If target address < current window,
  175922. * assume backward scan, load so that target area is top of window.
  175923. * Note that when switching from forward write to forward read, will have
  175924. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175925. */
  175926. if (start_row > ptr->cur_start_row) {
  175927. ptr->cur_start_row = start_row;
  175928. } else {
  175929. /* use long arithmetic here to avoid overflow & unsigned problems */
  175930. long ltemp;
  175931. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175932. if (ltemp < 0)
  175933. ltemp = 0; /* don't fall off front end of file */
  175934. ptr->cur_start_row = (JDIMENSION) ltemp;
  175935. }
  175936. /* Read in the selected part of the array.
  175937. * During the initial write pass, we will do no actual read
  175938. * because the selected part is all undefined.
  175939. */
  175940. do_barray_io(cinfo, ptr, FALSE);
  175941. }
  175942. /* Ensure the accessed part of the array is defined; prezero if needed.
  175943. * To improve locality of access, we only prezero the part of the array
  175944. * that the caller is about to access, not the entire in-memory array.
  175945. */
  175946. if (ptr->first_undef_row < end_row) {
  175947. if (ptr->first_undef_row < start_row) {
  175948. if (writable) /* writer skipped over a section of array */
  175949. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175950. undef_row = start_row; /* but reader is allowed to read ahead */
  175951. } else {
  175952. undef_row = ptr->first_undef_row;
  175953. }
  175954. if (writable)
  175955. ptr->first_undef_row = end_row;
  175956. if (ptr->pre_zero) {
  175957. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  175958. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175959. end_row -= ptr->cur_start_row;
  175960. while (undef_row < end_row) {
  175961. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175962. undef_row++;
  175963. }
  175964. } else {
  175965. if (! writable) /* reader looking at undefined data */
  175966. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175967. }
  175968. }
  175969. /* Flag the buffer dirty if caller will write in it */
  175970. if (writable)
  175971. ptr->dirty = TRUE;
  175972. /* Return address of proper part of the buffer */
  175973. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175974. }
  175975. /*
  175976. * Release all objects belonging to a specified pool.
  175977. */
  175978. METHODDEF(void)
  175979. free_pool (j_common_ptr cinfo, int pool_id)
  175980. {
  175981. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175982. small_pool_ptr shdr_ptr;
  175983. large_pool_ptr lhdr_ptr;
  175984. size_t space_freed;
  175985. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175986. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175987. #ifdef MEM_STATS
  175988. if (cinfo->err->trace_level > 1)
  175989. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  175990. #endif
  175991. /* If freeing IMAGE pool, close any virtual arrays first */
  175992. if (pool_id == JPOOL_IMAGE) {
  175993. jvirt_sarray_ptr sptr;
  175994. jvirt_barray_ptr bptr;
  175995. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175996. if (sptr->b_s_open) { /* there may be no backing store */
  175997. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  175998. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  175999. }
  176000. }
  176001. mem->virt_sarray_list = NULL;
  176002. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176003. if (bptr->b_s_open) { /* there may be no backing store */
  176004. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176005. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176006. }
  176007. }
  176008. mem->virt_barray_list = NULL;
  176009. }
  176010. /* Release large objects */
  176011. lhdr_ptr = mem->large_list[pool_id];
  176012. mem->large_list[pool_id] = NULL;
  176013. while (lhdr_ptr != NULL) {
  176014. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176015. space_freed = lhdr_ptr->hdr.bytes_used +
  176016. lhdr_ptr->hdr.bytes_left +
  176017. SIZEOF(large_pool_hdr);
  176018. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176019. mem->total_space_allocated -= space_freed;
  176020. lhdr_ptr = next_lhdr_ptr;
  176021. }
  176022. /* Release small objects */
  176023. shdr_ptr = mem->small_list[pool_id];
  176024. mem->small_list[pool_id] = NULL;
  176025. while (shdr_ptr != NULL) {
  176026. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176027. space_freed = shdr_ptr->hdr.bytes_used +
  176028. shdr_ptr->hdr.bytes_left +
  176029. SIZEOF(small_pool_hdr);
  176030. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176031. mem->total_space_allocated -= space_freed;
  176032. shdr_ptr = next_shdr_ptr;
  176033. }
  176034. }
  176035. /*
  176036. * Close up shop entirely.
  176037. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176038. */
  176039. METHODDEF(void)
  176040. self_destruct (j_common_ptr cinfo)
  176041. {
  176042. int pool;
  176043. /* Close all backing store, release all memory.
  176044. * Releasing pools in reverse order might help avoid fragmentation
  176045. * with some (brain-damaged) malloc libraries.
  176046. */
  176047. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176048. free_pool(cinfo, pool);
  176049. }
  176050. /* Release the memory manager control block too. */
  176051. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176052. cinfo->mem = NULL; /* ensures I will be called only once */
  176053. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176054. }
  176055. /*
  176056. * Memory manager initialization.
  176057. * When this is called, only the error manager pointer is valid in cinfo!
  176058. */
  176059. GLOBAL(void)
  176060. jinit_memory_mgr (j_common_ptr cinfo)
  176061. {
  176062. my_mem_ptr mem;
  176063. long max_to_use;
  176064. int pool;
  176065. size_t test_mac;
  176066. cinfo->mem = NULL; /* for safety if init fails */
  176067. /* Check for configuration errors.
  176068. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176069. * doesn't reflect any real hardware alignment requirement.
  176070. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176071. * in common if and only if X is a power of 2, ie has only one one-bit.
  176072. * Some compilers may give an "unreachable code" warning here; ignore it.
  176073. */
  176074. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176075. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176076. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176077. * a multiple of SIZEOF(ALIGN_TYPE).
  176078. * Again, an "unreachable code" warning may be ignored here.
  176079. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176080. */
  176081. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176082. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176083. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176084. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176085. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176086. /* Attempt to allocate memory manager's control block */
  176087. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176088. if (mem == NULL) {
  176089. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176090. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176091. }
  176092. /* OK, fill in the method pointers */
  176093. mem->pub.alloc_small = alloc_small;
  176094. mem->pub.alloc_large = alloc_large;
  176095. mem->pub.alloc_sarray = alloc_sarray;
  176096. mem->pub.alloc_barray = alloc_barray;
  176097. mem->pub.request_virt_sarray = request_virt_sarray;
  176098. mem->pub.request_virt_barray = request_virt_barray;
  176099. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176100. mem->pub.access_virt_sarray = access_virt_sarray;
  176101. mem->pub.access_virt_barray = access_virt_barray;
  176102. mem->pub.free_pool = free_pool;
  176103. mem->pub.self_destruct = self_destruct;
  176104. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176105. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176106. /* Initialize working state */
  176107. mem->pub.max_memory_to_use = max_to_use;
  176108. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176109. mem->small_list[pool] = NULL;
  176110. mem->large_list[pool] = NULL;
  176111. }
  176112. mem->virt_sarray_list = NULL;
  176113. mem->virt_barray_list = NULL;
  176114. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176115. /* Declare ourselves open for business */
  176116. cinfo->mem = & mem->pub;
  176117. /* Check for an environment variable JPEGMEM; if found, override the
  176118. * default max_memory setting from jpeg_mem_init. Note that the
  176119. * surrounding application may again override this value.
  176120. * If your system doesn't support getenv(), define NO_GETENV to disable
  176121. * this feature.
  176122. */
  176123. #ifndef NO_GETENV
  176124. { char * memenv;
  176125. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176126. char ch = 'x';
  176127. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176128. if (ch == 'm' || ch == 'M')
  176129. max_to_use *= 1000L;
  176130. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176131. }
  176132. }
  176133. }
  176134. #endif
  176135. }
  176136. /*** End of inlined file: jmemmgr.c ***/
  176137. /*** Start of inlined file: jmemnobs.c ***/
  176138. #define JPEG_INTERNALS
  176139. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176140. extern void * malloc JPP((size_t size));
  176141. extern void free JPP((void *ptr));
  176142. #endif
  176143. /*
  176144. * Memory allocation and freeing are controlled by the regular library
  176145. * routines malloc() and free().
  176146. */
  176147. GLOBAL(void *)
  176148. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176149. {
  176150. return (void *) malloc(sizeofobject);
  176151. }
  176152. GLOBAL(void)
  176153. jpeg_free_small (j_common_ptr , void * object, size_t)
  176154. {
  176155. free(object);
  176156. }
  176157. /*
  176158. * "Large" objects are treated the same as "small" ones.
  176159. * NB: although we include FAR keywords in the routine declarations,
  176160. * this file won't actually work in 80x86 small/medium model; at least,
  176161. * you probably won't be able to process useful-size images in only 64KB.
  176162. */
  176163. GLOBAL(void FAR *)
  176164. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176165. {
  176166. return (void FAR *) malloc(sizeofobject);
  176167. }
  176168. GLOBAL(void)
  176169. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176170. {
  176171. free(object);
  176172. }
  176173. /*
  176174. * This routine computes the total memory space available for allocation.
  176175. * Here we always say, "we got all you want bud!"
  176176. */
  176177. GLOBAL(long)
  176178. jpeg_mem_available (j_common_ptr, long,
  176179. long max_bytes_needed, long)
  176180. {
  176181. return max_bytes_needed;
  176182. }
  176183. /*
  176184. * Backing store (temporary file) management.
  176185. * Since jpeg_mem_available always promised the moon,
  176186. * this should never be called and we can just error out.
  176187. */
  176188. GLOBAL(void)
  176189. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176190. long )
  176191. {
  176192. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176193. }
  176194. /*
  176195. * These routines take care of any system-dependent initialization and
  176196. * cleanup required. Here, there isn't any.
  176197. */
  176198. GLOBAL(long)
  176199. jpeg_mem_init (j_common_ptr)
  176200. {
  176201. return 0; /* just set max_memory_to_use to 0 */
  176202. }
  176203. GLOBAL(void)
  176204. jpeg_mem_term (j_common_ptr)
  176205. {
  176206. /* no work */
  176207. }
  176208. /*** End of inlined file: jmemnobs.c ***/
  176209. /*** Start of inlined file: jquant1.c ***/
  176210. #define JPEG_INTERNALS
  176211. #ifdef QUANT_1PASS_SUPPORTED
  176212. /*
  176213. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176214. * high quality, colormapped output capability. A 2-pass quantizer usually
  176215. * gives better visual quality; however, for quantized grayscale output this
  176216. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176217. * quantizer, though you can turn it off if you really want to.
  176218. *
  176219. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176220. * image. We use a map consisting of all combinations of Ncolors[i] color
  176221. * values for the i'th component. The Ncolors[] values are chosen so that
  176222. * their product, the total number of colors, is no more than that requested.
  176223. * (In most cases, the product will be somewhat less.)
  176224. *
  176225. * Since the colormap is orthogonal, the representative value for each color
  176226. * component can be determined without considering the other components;
  176227. * then these indexes can be combined into a colormap index by a standard
  176228. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176229. * can be precalculated and stored in the lookup table colorindex[].
  176230. * colorindex[i][j] maps pixel value j in component i to the nearest
  176231. * representative value (grid plane) for that component; this index is
  176232. * multiplied by the array stride for component i, so that the
  176233. * index of the colormap entry closest to a given pixel value is just
  176234. * sum( colorindex[component-number][pixel-component-value] )
  176235. * Aside from being fast, this scheme allows for variable spacing between
  176236. * representative values with no additional lookup cost.
  176237. *
  176238. * If gamma correction has been applied in color conversion, it might be wise
  176239. * to adjust the color grid spacing so that the representative colors are
  176240. * equidistant in linear space. At this writing, gamma correction is not
  176241. * implemented by jdcolor, so nothing is done here.
  176242. */
  176243. /* Declarations for ordered dithering.
  176244. *
  176245. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176246. * dithering is described in many references, for instance Dale Schumacher's
  176247. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176248. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176249. * "dither" value to the input pixel and then round the result to the nearest
  176250. * output value. The dither value is equivalent to (0.5 - threshold) times
  176251. * the distance between output values. For ordered dithering, we assume that
  176252. * the output colors are equally spaced; if not, results will probably be
  176253. * worse, since the dither may be too much or too little at a given point.
  176254. *
  176255. * The normal calculation would be to form pixel value + dither, range-limit
  176256. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176257. * We can skip the separate range-limiting step by extending the colorindex
  176258. * table in both directions.
  176259. */
  176260. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176261. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176262. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176263. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176264. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176265. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176266. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176267. /* Bayer's order-4 dither array. Generated by the code given in
  176268. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176269. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176270. */
  176271. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176272. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176273. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176274. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176275. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176276. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176277. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176278. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176279. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176280. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176281. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176282. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176283. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176284. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176285. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176286. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176287. };
  176288. /* Declarations for Floyd-Steinberg dithering.
  176289. *
  176290. * Errors are accumulated into the array fserrors[], at a resolution of
  176291. * 1/16th of a pixel count. The error at a given pixel is propagated
  176292. * to its not-yet-processed neighbors using the standard F-S fractions,
  176293. * ... (here) 7/16
  176294. * 3/16 5/16 1/16
  176295. * We work left-to-right on even rows, right-to-left on odd rows.
  176296. *
  176297. * We can get away with a single array (holding one row's worth of errors)
  176298. * by using it to store the current row's errors at pixel columns not yet
  176299. * processed, but the next row's errors at columns already processed. We
  176300. * need only a few extra variables to hold the errors immediately around the
  176301. * current column. (If we are lucky, those variables are in registers, but
  176302. * even if not, they're probably cheaper to access than array elements are.)
  176303. *
  176304. * The fserrors[] array is indexed [component#][position].
  176305. * We provide (#columns + 2) entries per component; the extra entry at each
  176306. * end saves us from special-casing the first and last pixels.
  176307. *
  176308. * Note: on a wide image, we might not have enough room in a PC's near data
  176309. * segment to hold the error array; so it is allocated with alloc_large.
  176310. */
  176311. #if BITS_IN_JSAMPLE == 8
  176312. typedef INT16 FSERROR; /* 16 bits should be enough */
  176313. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176314. #else
  176315. typedef INT32 FSERROR; /* may need more than 16 bits */
  176316. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176317. #endif
  176318. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176319. /* Private subobject */
  176320. #define MAX_Q_COMPS 4 /* max components I can handle */
  176321. typedef struct {
  176322. struct jpeg_color_quantizer pub; /* public fields */
  176323. /* Initially allocated colormap is saved here */
  176324. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176325. int sv_actual; /* number of entries in use */
  176326. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176327. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176328. * premultiplied as described above. Since colormap indexes must fit into
  176329. * JSAMPLEs, the entries of this array will too.
  176330. */
  176331. boolean is_padded; /* is the colorindex padded for odither? */
  176332. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176333. /* Variables for ordered dithering */
  176334. int row_index; /* cur row's vertical index in dither matrix */
  176335. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176336. /* Variables for Floyd-Steinberg dithering */
  176337. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176338. boolean on_odd_row; /* flag to remember which row we are on */
  176339. } my_cquantizer;
  176340. typedef my_cquantizer * my_cquantize_ptr;
  176341. /*
  176342. * Policy-making subroutines for create_colormap and create_colorindex.
  176343. * These routines determine the colormap to be used. The rest of the module
  176344. * only assumes that the colormap is orthogonal.
  176345. *
  176346. * * select_ncolors decides how to divvy up the available colors
  176347. * among the components.
  176348. * * output_value defines the set of representative values for a component.
  176349. * * largest_input_value defines the mapping from input values to
  176350. * representative values for a component.
  176351. * Note that the latter two routines may impose different policies for
  176352. * different components, though this is not currently done.
  176353. */
  176354. LOCAL(int)
  176355. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176356. /* Determine allocation of desired colors to components, */
  176357. /* and fill in Ncolors[] array to indicate choice. */
  176358. /* Return value is total number of colors (product of Ncolors[] values). */
  176359. {
  176360. int nc = cinfo->out_color_components; /* number of color components */
  176361. int max_colors = cinfo->desired_number_of_colors;
  176362. int total_colors, iroot, i, j;
  176363. boolean changed;
  176364. long temp;
  176365. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176366. /* We can allocate at least the nc'th root of max_colors per component. */
  176367. /* Compute floor(nc'th root of max_colors). */
  176368. iroot = 1;
  176369. do {
  176370. iroot++;
  176371. temp = iroot; /* set temp = iroot ** nc */
  176372. for (i = 1; i < nc; i++)
  176373. temp *= iroot;
  176374. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176375. iroot--; /* now iroot = floor(root) */
  176376. /* Must have at least 2 color values per component */
  176377. if (iroot < 2)
  176378. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176379. /* Initialize to iroot color values for each component */
  176380. total_colors = 1;
  176381. for (i = 0; i < nc; i++) {
  176382. Ncolors[i] = iroot;
  176383. total_colors *= iroot;
  176384. }
  176385. /* We may be able to increment the count for one or more components without
  176386. * exceeding max_colors, though we know not all can be incremented.
  176387. * Sometimes, the first component can be incremented more than once!
  176388. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176389. * In RGB colorspace, try to increment G first, then R, then B.
  176390. */
  176391. do {
  176392. changed = FALSE;
  176393. for (i = 0; i < nc; i++) {
  176394. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176395. /* calculate new total_colors if Ncolors[j] is incremented */
  176396. temp = total_colors / Ncolors[j];
  176397. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176398. if (temp > (long) max_colors)
  176399. break; /* won't fit, done with this pass */
  176400. Ncolors[j]++; /* OK, apply the increment */
  176401. total_colors = (int) temp;
  176402. changed = TRUE;
  176403. }
  176404. } while (changed);
  176405. return total_colors;
  176406. }
  176407. LOCAL(int)
  176408. output_value (j_decompress_ptr, int, int j, int maxj)
  176409. /* Return j'th output value, where j will range from 0 to maxj */
  176410. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176411. {
  176412. /* We always provide values 0 and MAXJSAMPLE for each component;
  176413. * any additional values are equally spaced between these limits.
  176414. * (Forcing the upper and lower values to the limits ensures that
  176415. * dithering can't produce a color outside the selected gamut.)
  176416. */
  176417. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176418. }
  176419. LOCAL(int)
  176420. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176421. /* Return largest input value that should map to j'th output value */
  176422. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176423. {
  176424. /* Breakpoints are halfway between values returned by output_value */
  176425. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176426. }
  176427. /*
  176428. * Create the colormap.
  176429. */
  176430. LOCAL(void)
  176431. create_colormap (j_decompress_ptr cinfo)
  176432. {
  176433. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176434. JSAMPARRAY colormap; /* Created colormap */
  176435. int total_colors; /* Number of distinct output colors */
  176436. int i,j,k, nci, blksize, blkdist, ptr, val;
  176437. /* Select number of colors for each component */
  176438. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176439. /* Report selected color counts */
  176440. if (cinfo->out_color_components == 3)
  176441. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176442. total_colors, cquantize->Ncolors[0],
  176443. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176444. else
  176445. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176446. /* Allocate and fill in the colormap. */
  176447. /* The colors are ordered in the map in standard row-major order, */
  176448. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176449. colormap = (*cinfo->mem->alloc_sarray)
  176450. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176451. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176452. /* blksize is number of adjacent repeated entries for a component */
  176453. /* blkdist is distance between groups of identical entries for a component */
  176454. blkdist = total_colors;
  176455. for (i = 0; i < cinfo->out_color_components; i++) {
  176456. /* fill in colormap entries for i'th color component */
  176457. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176458. blksize = blkdist / nci;
  176459. for (j = 0; j < nci; j++) {
  176460. /* Compute j'th output value (out of nci) for component */
  176461. val = output_value(cinfo, i, j, nci-1);
  176462. /* Fill in all colormap entries that have this value of this component */
  176463. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176464. /* fill in blksize entries beginning at ptr */
  176465. for (k = 0; k < blksize; k++)
  176466. colormap[i][ptr+k] = (JSAMPLE) val;
  176467. }
  176468. }
  176469. blkdist = blksize; /* blksize of this color is blkdist of next */
  176470. }
  176471. /* Save the colormap in private storage,
  176472. * where it will survive color quantization mode changes.
  176473. */
  176474. cquantize->sv_colormap = colormap;
  176475. cquantize->sv_actual = total_colors;
  176476. }
  176477. /*
  176478. * Create the color index table.
  176479. */
  176480. LOCAL(void)
  176481. create_colorindex (j_decompress_ptr cinfo)
  176482. {
  176483. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176484. JSAMPROW indexptr;
  176485. int i,j,k, nci, blksize, val, pad;
  176486. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176487. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176488. * This is not necessary in the other dithering modes. However, we
  176489. * flag whether it was done in case user changes dithering mode.
  176490. */
  176491. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176492. pad = MAXJSAMPLE*2;
  176493. cquantize->is_padded = TRUE;
  176494. } else {
  176495. pad = 0;
  176496. cquantize->is_padded = FALSE;
  176497. }
  176498. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176499. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176500. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176501. (JDIMENSION) cinfo->out_color_components);
  176502. /* blksize is number of adjacent repeated entries for a component */
  176503. blksize = cquantize->sv_actual;
  176504. for (i = 0; i < cinfo->out_color_components; i++) {
  176505. /* fill in colorindex entries for i'th color component */
  176506. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176507. blksize = blksize / nci;
  176508. /* adjust colorindex pointers to provide padding at negative indexes. */
  176509. if (pad)
  176510. cquantize->colorindex[i] += MAXJSAMPLE;
  176511. /* in loop, val = index of current output value, */
  176512. /* and k = largest j that maps to current val */
  176513. indexptr = cquantize->colorindex[i];
  176514. val = 0;
  176515. k = largest_input_value(cinfo, i, 0, nci-1);
  176516. for (j = 0; j <= MAXJSAMPLE; j++) {
  176517. while (j > k) /* advance val if past boundary */
  176518. k = largest_input_value(cinfo, i, ++val, nci-1);
  176519. /* premultiply so that no multiplication needed in main processing */
  176520. indexptr[j] = (JSAMPLE) (val * blksize);
  176521. }
  176522. /* Pad at both ends if necessary */
  176523. if (pad)
  176524. for (j = 1; j <= MAXJSAMPLE; j++) {
  176525. indexptr[-j] = indexptr[0];
  176526. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176527. }
  176528. }
  176529. }
  176530. /*
  176531. * Create an ordered-dither array for a component having ncolors
  176532. * distinct output values.
  176533. */
  176534. LOCAL(ODITHER_MATRIX_PTR)
  176535. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176536. {
  176537. ODITHER_MATRIX_PTR odither;
  176538. int j,k;
  176539. INT32 num,den;
  176540. odither = (ODITHER_MATRIX_PTR)
  176541. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176542. SIZEOF(ODITHER_MATRIX));
  176543. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176544. * Hence the dither value for the matrix cell with fill order f
  176545. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176546. * On 16-bit-int machine, be careful to avoid overflow.
  176547. */
  176548. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176549. for (j = 0; j < ODITHER_SIZE; j++) {
  176550. for (k = 0; k < ODITHER_SIZE; k++) {
  176551. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176552. * MAXJSAMPLE;
  176553. /* Ensure round towards zero despite C's lack of consistency
  176554. * about rounding negative values in integer division...
  176555. */
  176556. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176557. }
  176558. }
  176559. return odither;
  176560. }
  176561. /*
  176562. * Create the ordered-dither tables.
  176563. * Components having the same number of representative colors may
  176564. * share a dither table.
  176565. */
  176566. LOCAL(void)
  176567. create_odither_tables (j_decompress_ptr cinfo)
  176568. {
  176569. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176570. ODITHER_MATRIX_PTR odither;
  176571. int i, j, nci;
  176572. for (i = 0; i < cinfo->out_color_components; i++) {
  176573. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176574. odither = NULL; /* search for matching prior component */
  176575. for (j = 0; j < i; j++) {
  176576. if (nci == cquantize->Ncolors[j]) {
  176577. odither = cquantize->odither[j];
  176578. break;
  176579. }
  176580. }
  176581. if (odither == NULL) /* need a new table? */
  176582. odither = make_odither_array(cinfo, nci);
  176583. cquantize->odither[i] = odither;
  176584. }
  176585. }
  176586. /*
  176587. * Map some rows of pixels to the output colormapped representation.
  176588. */
  176589. METHODDEF(void)
  176590. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176591. JSAMPARRAY output_buf, int num_rows)
  176592. /* General case, no dithering */
  176593. {
  176594. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176595. JSAMPARRAY colorindex = cquantize->colorindex;
  176596. register int pixcode, ci;
  176597. register JSAMPROW ptrin, ptrout;
  176598. int row;
  176599. JDIMENSION col;
  176600. JDIMENSION width = cinfo->output_width;
  176601. register int nc = cinfo->out_color_components;
  176602. for (row = 0; row < num_rows; row++) {
  176603. ptrin = input_buf[row];
  176604. ptrout = output_buf[row];
  176605. for (col = width; col > 0; col--) {
  176606. pixcode = 0;
  176607. for (ci = 0; ci < nc; ci++) {
  176608. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176609. }
  176610. *ptrout++ = (JSAMPLE) pixcode;
  176611. }
  176612. }
  176613. }
  176614. METHODDEF(void)
  176615. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176616. JSAMPARRAY output_buf, int num_rows)
  176617. /* Fast path for out_color_components==3, no dithering */
  176618. {
  176619. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176620. register int pixcode;
  176621. register JSAMPROW ptrin, ptrout;
  176622. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176623. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176624. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176625. int row;
  176626. JDIMENSION col;
  176627. JDIMENSION width = cinfo->output_width;
  176628. for (row = 0; row < num_rows; row++) {
  176629. ptrin = input_buf[row];
  176630. ptrout = output_buf[row];
  176631. for (col = width; col > 0; col--) {
  176632. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176633. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176634. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176635. *ptrout++ = (JSAMPLE) pixcode;
  176636. }
  176637. }
  176638. }
  176639. METHODDEF(void)
  176640. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176641. JSAMPARRAY output_buf, int num_rows)
  176642. /* General case, with ordered dithering */
  176643. {
  176644. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176645. register JSAMPROW input_ptr;
  176646. register JSAMPROW output_ptr;
  176647. JSAMPROW colorindex_ci;
  176648. int * dither; /* points to active row of dither matrix */
  176649. int row_index, col_index; /* current indexes into dither matrix */
  176650. int nc = cinfo->out_color_components;
  176651. int ci;
  176652. int row;
  176653. JDIMENSION col;
  176654. JDIMENSION width = cinfo->output_width;
  176655. for (row = 0; row < num_rows; row++) {
  176656. /* Initialize output values to 0 so can process components separately */
  176657. jzero_far((void FAR *) output_buf[row],
  176658. (size_t) (width * SIZEOF(JSAMPLE)));
  176659. row_index = cquantize->row_index;
  176660. for (ci = 0; ci < nc; ci++) {
  176661. input_ptr = input_buf[row] + ci;
  176662. output_ptr = output_buf[row];
  176663. colorindex_ci = cquantize->colorindex[ci];
  176664. dither = cquantize->odither[ci][row_index];
  176665. col_index = 0;
  176666. for (col = width; col > 0; col--) {
  176667. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176668. * select output value, accumulate into output code for this pixel.
  176669. * Range-limiting need not be done explicitly, as we have extended
  176670. * the colorindex table to produce the right answers for out-of-range
  176671. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176672. * required amount of padding.
  176673. */
  176674. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176675. input_ptr += nc;
  176676. output_ptr++;
  176677. col_index = (col_index + 1) & ODITHER_MASK;
  176678. }
  176679. }
  176680. /* Advance row index for next row */
  176681. row_index = (row_index + 1) & ODITHER_MASK;
  176682. cquantize->row_index = row_index;
  176683. }
  176684. }
  176685. METHODDEF(void)
  176686. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176687. JSAMPARRAY output_buf, int num_rows)
  176688. /* Fast path for out_color_components==3, with ordered dithering */
  176689. {
  176690. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176691. register int pixcode;
  176692. register JSAMPROW input_ptr;
  176693. register JSAMPROW output_ptr;
  176694. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176695. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176696. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176697. int * dither0; /* points to active row of dither matrix */
  176698. int * dither1;
  176699. int * dither2;
  176700. int row_index, col_index; /* current indexes into dither matrix */
  176701. int row;
  176702. JDIMENSION col;
  176703. JDIMENSION width = cinfo->output_width;
  176704. for (row = 0; row < num_rows; row++) {
  176705. row_index = cquantize->row_index;
  176706. input_ptr = input_buf[row];
  176707. output_ptr = output_buf[row];
  176708. dither0 = cquantize->odither[0][row_index];
  176709. dither1 = cquantize->odither[1][row_index];
  176710. dither2 = cquantize->odither[2][row_index];
  176711. col_index = 0;
  176712. for (col = width; col > 0; col--) {
  176713. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176714. dither0[col_index]]);
  176715. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176716. dither1[col_index]]);
  176717. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176718. dither2[col_index]]);
  176719. *output_ptr++ = (JSAMPLE) pixcode;
  176720. col_index = (col_index + 1) & ODITHER_MASK;
  176721. }
  176722. row_index = (row_index + 1) & ODITHER_MASK;
  176723. cquantize->row_index = row_index;
  176724. }
  176725. }
  176726. METHODDEF(void)
  176727. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176728. JSAMPARRAY output_buf, int num_rows)
  176729. /* General case, with Floyd-Steinberg dithering */
  176730. {
  176731. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176732. register LOCFSERROR cur; /* current error or pixel value */
  176733. LOCFSERROR belowerr; /* error for pixel below cur */
  176734. LOCFSERROR bpreverr; /* error for below/prev col */
  176735. LOCFSERROR bnexterr; /* error for below/next col */
  176736. LOCFSERROR delta;
  176737. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176738. register JSAMPROW input_ptr;
  176739. register JSAMPROW output_ptr;
  176740. JSAMPROW colorindex_ci;
  176741. JSAMPROW colormap_ci;
  176742. int pixcode;
  176743. int nc = cinfo->out_color_components;
  176744. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176745. int dirnc; /* dir * nc */
  176746. int ci;
  176747. int row;
  176748. JDIMENSION col;
  176749. JDIMENSION width = cinfo->output_width;
  176750. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176751. SHIFT_TEMPS
  176752. for (row = 0; row < num_rows; row++) {
  176753. /* Initialize output values to 0 so can process components separately */
  176754. jzero_far((void FAR *) output_buf[row],
  176755. (size_t) (width * SIZEOF(JSAMPLE)));
  176756. for (ci = 0; ci < nc; ci++) {
  176757. input_ptr = input_buf[row] + ci;
  176758. output_ptr = output_buf[row];
  176759. if (cquantize->on_odd_row) {
  176760. /* work right to left in this row */
  176761. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176762. output_ptr += width-1;
  176763. dir = -1;
  176764. dirnc = -nc;
  176765. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176766. } else {
  176767. /* work left to right in this row */
  176768. dir = 1;
  176769. dirnc = nc;
  176770. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176771. }
  176772. colorindex_ci = cquantize->colorindex[ci];
  176773. colormap_ci = cquantize->sv_colormap[ci];
  176774. /* Preset error values: no error propagated to first pixel from left */
  176775. cur = 0;
  176776. /* and no error propagated to row below yet */
  176777. belowerr = bpreverr = 0;
  176778. for (col = width; col > 0; col--) {
  176779. /* cur holds the error propagated from the previous pixel on the
  176780. * current line. Add the error propagated from the previous line
  176781. * to form the complete error correction term for this pixel, and
  176782. * round the error term (which is expressed * 16) to an integer.
  176783. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176784. * for either sign of the error value.
  176785. * Note: errorptr points to *previous* column's array entry.
  176786. */
  176787. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176788. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176789. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176790. * of the range_limit array.
  176791. */
  176792. cur += GETJSAMPLE(*input_ptr);
  176793. cur = GETJSAMPLE(range_limit[cur]);
  176794. /* Select output value, accumulate into output code for this pixel */
  176795. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176796. *output_ptr += (JSAMPLE) pixcode;
  176797. /* Compute actual representation error at this pixel */
  176798. /* Note: we can do this even though we don't have the final */
  176799. /* pixel code, because the colormap is orthogonal. */
  176800. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176801. /* Compute error fractions to be propagated to adjacent pixels.
  176802. * Add these into the running sums, and simultaneously shift the
  176803. * next-line error sums left by 1 column.
  176804. */
  176805. bnexterr = cur;
  176806. delta = cur * 2;
  176807. cur += delta; /* form error * 3 */
  176808. errorptr[0] = (FSERROR) (bpreverr + cur);
  176809. cur += delta; /* form error * 5 */
  176810. bpreverr = belowerr + cur;
  176811. belowerr = bnexterr;
  176812. cur += delta; /* form error * 7 */
  176813. /* At this point cur contains the 7/16 error value to be propagated
  176814. * to the next pixel on the current line, and all the errors for the
  176815. * next line have been shifted over. We are therefore ready to move on.
  176816. */
  176817. input_ptr += dirnc; /* advance input ptr to next column */
  176818. output_ptr += dir; /* advance output ptr to next column */
  176819. errorptr += dir; /* advance errorptr to current column */
  176820. }
  176821. /* Post-loop cleanup: we must unload the final error value into the
  176822. * final fserrors[] entry. Note we need not unload belowerr because
  176823. * it is for the dummy column before or after the actual array.
  176824. */
  176825. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  176826. }
  176827. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  176828. }
  176829. }
  176830. /*
  176831. * Allocate workspace for Floyd-Steinberg errors.
  176832. */
  176833. LOCAL(void)
  176834. alloc_fs_workspace (j_decompress_ptr cinfo)
  176835. {
  176836. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176837. size_t arraysize;
  176838. int i;
  176839. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176840. for (i = 0; i < cinfo->out_color_components; i++) {
  176841. cquantize->fserrors[i] = (FSERRPTR)
  176842. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  176843. }
  176844. }
  176845. /*
  176846. * Initialize for one-pass color quantization.
  176847. */
  176848. METHODDEF(void)
  176849. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  176850. {
  176851. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176852. size_t arraysize;
  176853. int i;
  176854. /* Install my colormap. */
  176855. cinfo->colormap = cquantize->sv_colormap;
  176856. cinfo->actual_number_of_colors = cquantize->sv_actual;
  176857. /* Initialize for desired dithering mode. */
  176858. switch (cinfo->dither_mode) {
  176859. case JDITHER_NONE:
  176860. if (cinfo->out_color_components == 3)
  176861. cquantize->pub.color_quantize = color_quantize3;
  176862. else
  176863. cquantize->pub.color_quantize = color_quantize;
  176864. break;
  176865. case JDITHER_ORDERED:
  176866. if (cinfo->out_color_components == 3)
  176867. cquantize->pub.color_quantize = quantize3_ord_dither;
  176868. else
  176869. cquantize->pub.color_quantize = quantize_ord_dither;
  176870. cquantize->row_index = 0; /* initialize state for ordered dither */
  176871. /* If user changed to ordered dither from another mode,
  176872. * we must recreate the color index table with padding.
  176873. * This will cost extra space, but probably isn't very likely.
  176874. */
  176875. if (! cquantize->is_padded)
  176876. create_colorindex(cinfo);
  176877. /* Create ordered-dither tables if we didn't already. */
  176878. if (cquantize->odither[0] == NULL)
  176879. create_odither_tables(cinfo);
  176880. break;
  176881. case JDITHER_FS:
  176882. cquantize->pub.color_quantize = quantize_fs_dither;
  176883. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  176884. /* Allocate Floyd-Steinberg workspace if didn't already. */
  176885. if (cquantize->fserrors[0] == NULL)
  176886. alloc_fs_workspace(cinfo);
  176887. /* Initialize the propagated errors to zero. */
  176888. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176889. for (i = 0; i < cinfo->out_color_components; i++)
  176890. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  176891. break;
  176892. default:
  176893. ERREXIT(cinfo, JERR_NOT_COMPILED);
  176894. break;
  176895. }
  176896. }
  176897. /*
  176898. * Finish up at the end of the pass.
  176899. */
  176900. METHODDEF(void)
  176901. finish_pass_1_quant (j_decompress_ptr)
  176902. {
  176903. /* no work in 1-pass case */
  176904. }
  176905. /*
  176906. * Switch to a new external colormap between output passes.
  176907. * Shouldn't get to this module!
  176908. */
  176909. METHODDEF(void)
  176910. new_color_map_1_quant (j_decompress_ptr cinfo)
  176911. {
  176912. ERREXIT(cinfo, JERR_MODE_CHANGE);
  176913. }
  176914. /*
  176915. * Module initialization routine for 1-pass color quantization.
  176916. */
  176917. GLOBAL(void)
  176918. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  176919. {
  176920. my_cquantize_ptr cquantize;
  176921. cquantize = (my_cquantize_ptr)
  176922. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176923. SIZEOF(my_cquantizer));
  176924. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  176925. cquantize->pub.start_pass = start_pass_1_quant;
  176926. cquantize->pub.finish_pass = finish_pass_1_quant;
  176927. cquantize->pub.new_color_map = new_color_map_1_quant;
  176928. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  176929. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  176930. /* Make sure my internal arrays won't overflow */
  176931. if (cinfo->out_color_components > MAX_Q_COMPS)
  176932. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  176933. /* Make sure colormap indexes can be represented by JSAMPLEs */
  176934. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  176935. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  176936. /* Create the colormap and color index table. */
  176937. create_colormap(cinfo);
  176938. create_colorindex(cinfo);
  176939. /* Allocate Floyd-Steinberg workspace now if requested.
  176940. * We do this now since it is FAR storage and may affect the memory
  176941. * manager's space calculations. If the user changes to FS dither
  176942. * mode in a later pass, we will allocate the space then, and will
  176943. * possibly overrun the max_memory_to_use setting.
  176944. */
  176945. if (cinfo->dither_mode == JDITHER_FS)
  176946. alloc_fs_workspace(cinfo);
  176947. }
  176948. #endif /* QUANT_1PASS_SUPPORTED */
  176949. /*** End of inlined file: jquant1.c ***/
  176950. /*** Start of inlined file: jquant2.c ***/
  176951. #define JPEG_INTERNALS
  176952. #ifdef QUANT_2PASS_SUPPORTED
  176953. /*
  176954. * This module implements the well-known Heckbert paradigm for color
  176955. * quantization. Most of the ideas used here can be traced back to
  176956. * Heckbert's seminal paper
  176957. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  176958. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  176959. *
  176960. * In the first pass over the image, we accumulate a histogram showing the
  176961. * usage count of each possible color. To keep the histogram to a reasonable
  176962. * size, we reduce the precision of the input; typical practice is to retain
  176963. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  176964. * in the same histogram cell.
  176965. *
  176966. * Next, the color-selection step begins with a box representing the whole
  176967. * color space, and repeatedly splits the "largest" remaining box until we
  176968. * have as many boxes as desired colors. Then the mean color in each
  176969. * remaining box becomes one of the possible output colors.
  176970. *
  176971. * The second pass over the image maps each input pixel to the closest output
  176972. * color (optionally after applying a Floyd-Steinberg dithering correction).
  176973. * This mapping is logically trivial, but making it go fast enough requires
  176974. * considerable care.
  176975. *
  176976. * Heckbert-style quantizers vary a good deal in their policies for choosing
  176977. * the "largest" box and deciding where to cut it. The particular policies
  176978. * used here have proved out well in experimental comparisons, but better ones
  176979. * may yet be found.
  176980. *
  176981. * In earlier versions of the IJG code, this module quantized in YCbCr color
  176982. * space, processing the raw upsampled data without a color conversion step.
  176983. * This allowed the color conversion math to be done only once per colormap
  176984. * entry, not once per pixel. However, that optimization precluded other
  176985. * useful optimizations (such as merging color conversion with upsampling)
  176986. * and it also interfered with desired capabilities such as quantizing to an
  176987. * externally-supplied colormap. We have therefore abandoned that approach.
  176988. * The present code works in the post-conversion color space, typically RGB.
  176989. *
  176990. * To improve the visual quality of the results, we actually work in scaled
  176991. * RGB space, giving G distances more weight than R, and R in turn more than
  176992. * B. To do everything in integer math, we must use integer scale factors.
  176993. * The 2/3/1 scale factors used here correspond loosely to the relative
  176994. * weights of the colors in the NTSC grayscale equation.
  176995. * If you want to use this code to quantize a non-RGB color space, you'll
  176996. * probably need to change these scale factors.
  176997. */
  176998. #define R_SCALE 2 /* scale R distances by this much */
  176999. #define G_SCALE 3 /* scale G distances by this much */
  177000. #define B_SCALE 1 /* and B by this much */
  177001. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177002. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177003. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177004. * you'll get compile errors until you extend this logic. In that case
  177005. * you'll probably want to tweak the histogram sizes too.
  177006. */
  177007. #if RGB_RED == 0
  177008. #define C0_SCALE R_SCALE
  177009. #endif
  177010. #if RGB_BLUE == 0
  177011. #define C0_SCALE B_SCALE
  177012. #endif
  177013. #if RGB_GREEN == 1
  177014. #define C1_SCALE G_SCALE
  177015. #endif
  177016. #if RGB_RED == 2
  177017. #define C2_SCALE R_SCALE
  177018. #endif
  177019. #if RGB_BLUE == 2
  177020. #define C2_SCALE B_SCALE
  177021. #endif
  177022. /*
  177023. * First we have the histogram data structure and routines for creating it.
  177024. *
  177025. * The number of bits of precision can be adjusted by changing these symbols.
  177026. * We recommend keeping 6 bits for G and 5 each for R and B.
  177027. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177028. * better results; if you are short of memory, 5 bits all around will save
  177029. * some space but degrade the results.
  177030. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177031. * (preferably unsigned long) for each cell. In practice this is overkill;
  177032. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177033. * and clamping those that do overflow to the maximum value will give close-
  177034. * enough results. This reduces the recommended histogram size from 256Kb
  177035. * to 128Kb, which is a useful savings on PC-class machines.
  177036. * (In the second pass the histogram space is re-used for pixel mapping data;
  177037. * in that capacity, each cell must be able to store zero to the number of
  177038. * desired colors. 16 bits/cell is plenty for that too.)
  177039. * Since the JPEG code is intended to run in small memory model on 80x86
  177040. * machines, we can't just allocate the histogram in one chunk. Instead
  177041. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177042. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177043. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177044. * on 80x86 machines, the pointer row is in near memory but the actual
  177045. * arrays are in far memory (same arrangement as we use for image arrays).
  177046. */
  177047. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177048. /* These will do the right thing for either R,G,B or B,G,R color order,
  177049. * but you may not like the results for other color orders.
  177050. */
  177051. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177052. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177053. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177054. /* Number of elements along histogram axes. */
  177055. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177056. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177057. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177058. /* These are the amounts to shift an input value to get a histogram index. */
  177059. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177060. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177061. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177062. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177063. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177064. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177065. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177066. typedef hist2d * hist3d; /* type for top-level pointer */
  177067. /* Declarations for Floyd-Steinberg dithering.
  177068. *
  177069. * Errors are accumulated into the array fserrors[], at a resolution of
  177070. * 1/16th of a pixel count. The error at a given pixel is propagated
  177071. * to its not-yet-processed neighbors using the standard F-S fractions,
  177072. * ... (here) 7/16
  177073. * 3/16 5/16 1/16
  177074. * We work left-to-right on even rows, right-to-left on odd rows.
  177075. *
  177076. * We can get away with a single array (holding one row's worth of errors)
  177077. * by using it to store the current row's errors at pixel columns not yet
  177078. * processed, but the next row's errors at columns already processed. We
  177079. * need only a few extra variables to hold the errors immediately around the
  177080. * current column. (If we are lucky, those variables are in registers, but
  177081. * even if not, they're probably cheaper to access than array elements are.)
  177082. *
  177083. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177084. * each end saves us from special-casing the first and last pixels.
  177085. * Each entry is three values long, one value for each color component.
  177086. *
  177087. * Note: on a wide image, we might not have enough room in a PC's near data
  177088. * segment to hold the error array; so it is allocated with alloc_large.
  177089. */
  177090. #if BITS_IN_JSAMPLE == 8
  177091. typedef INT16 FSERROR; /* 16 bits should be enough */
  177092. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177093. #else
  177094. typedef INT32 FSERROR; /* may need more than 16 bits */
  177095. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177096. #endif
  177097. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177098. /* Private subobject */
  177099. typedef struct {
  177100. struct jpeg_color_quantizer pub; /* public fields */
  177101. /* Space for the eventually created colormap is stashed here */
  177102. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177103. int desired; /* desired # of colors = size of colormap */
  177104. /* Variables for accumulating image statistics */
  177105. hist3d histogram; /* pointer to the histogram */
  177106. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177107. /* Variables for Floyd-Steinberg dithering */
  177108. FSERRPTR fserrors; /* accumulated errors */
  177109. boolean on_odd_row; /* flag to remember which row we are on */
  177110. int * error_limiter; /* table for clamping the applied error */
  177111. } my_cquantizer2;
  177112. typedef my_cquantizer2 * my_cquantize_ptr2;
  177113. /*
  177114. * Prescan some rows of pixels.
  177115. * In this module the prescan simply updates the histogram, which has been
  177116. * initialized to zeroes by start_pass.
  177117. * An output_buf parameter is required by the method signature, but no data
  177118. * is actually output (in fact the buffer controller is probably passing a
  177119. * NULL pointer).
  177120. */
  177121. METHODDEF(void)
  177122. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177123. JSAMPARRAY, int num_rows)
  177124. {
  177125. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177126. register JSAMPROW ptr;
  177127. register histptr histp;
  177128. register hist3d histogram = cquantize->histogram;
  177129. int row;
  177130. JDIMENSION col;
  177131. JDIMENSION width = cinfo->output_width;
  177132. for (row = 0; row < num_rows; row++) {
  177133. ptr = input_buf[row];
  177134. for (col = width; col > 0; col--) {
  177135. /* get pixel value and index into the histogram */
  177136. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177137. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177138. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177139. /* increment, check for overflow and undo increment if so. */
  177140. if (++(*histp) <= 0)
  177141. (*histp)--;
  177142. ptr += 3;
  177143. }
  177144. }
  177145. }
  177146. /*
  177147. * Next we have the really interesting routines: selection of a colormap
  177148. * given the completed histogram.
  177149. * These routines work with a list of "boxes", each representing a rectangular
  177150. * subset of the input color space (to histogram precision).
  177151. */
  177152. typedef struct {
  177153. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177154. int c0min, c0max;
  177155. int c1min, c1max;
  177156. int c2min, c2max;
  177157. /* The volume (actually 2-norm) of the box */
  177158. INT32 volume;
  177159. /* The number of nonzero histogram cells within this box */
  177160. long colorcount;
  177161. } box;
  177162. typedef box * boxptr;
  177163. LOCAL(boxptr)
  177164. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177165. /* Find the splittable box with the largest color population */
  177166. /* Returns NULL if no splittable boxes remain */
  177167. {
  177168. register boxptr boxp;
  177169. register int i;
  177170. register long maxc = 0;
  177171. boxptr which = NULL;
  177172. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177173. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177174. which = boxp;
  177175. maxc = boxp->colorcount;
  177176. }
  177177. }
  177178. return which;
  177179. }
  177180. LOCAL(boxptr)
  177181. find_biggest_volume (boxptr boxlist, int numboxes)
  177182. /* Find the splittable box with the largest (scaled) volume */
  177183. /* Returns NULL if no splittable boxes remain */
  177184. {
  177185. register boxptr boxp;
  177186. register int i;
  177187. register INT32 maxv = 0;
  177188. boxptr which = NULL;
  177189. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177190. if (boxp->volume > maxv) {
  177191. which = boxp;
  177192. maxv = boxp->volume;
  177193. }
  177194. }
  177195. return which;
  177196. }
  177197. LOCAL(void)
  177198. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177199. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177200. /* and recompute its volume and population */
  177201. {
  177202. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177203. hist3d histogram = cquantize->histogram;
  177204. histptr histp;
  177205. int c0,c1,c2;
  177206. int c0min,c0max,c1min,c1max,c2min,c2max;
  177207. INT32 dist0,dist1,dist2;
  177208. long ccount;
  177209. c0min = boxp->c0min; c0max = boxp->c0max;
  177210. c1min = boxp->c1min; c1max = boxp->c1max;
  177211. c2min = boxp->c2min; c2max = boxp->c2max;
  177212. if (c0max > c0min)
  177213. for (c0 = c0min; c0 <= c0max; c0++)
  177214. for (c1 = c1min; c1 <= c1max; c1++) {
  177215. histp = & histogram[c0][c1][c2min];
  177216. for (c2 = c2min; c2 <= c2max; c2++)
  177217. if (*histp++ != 0) {
  177218. boxp->c0min = c0min = c0;
  177219. goto have_c0min;
  177220. }
  177221. }
  177222. have_c0min:
  177223. if (c0max > c0min)
  177224. for (c0 = c0max; c0 >= c0min; c0--)
  177225. for (c1 = c1min; c1 <= c1max; c1++) {
  177226. histp = & histogram[c0][c1][c2min];
  177227. for (c2 = c2min; c2 <= c2max; c2++)
  177228. if (*histp++ != 0) {
  177229. boxp->c0max = c0max = c0;
  177230. goto have_c0max;
  177231. }
  177232. }
  177233. have_c0max:
  177234. if (c1max > c1min)
  177235. for (c1 = c1min; c1 <= c1max; c1++)
  177236. for (c0 = c0min; c0 <= c0max; c0++) {
  177237. histp = & histogram[c0][c1][c2min];
  177238. for (c2 = c2min; c2 <= c2max; c2++)
  177239. if (*histp++ != 0) {
  177240. boxp->c1min = c1min = c1;
  177241. goto have_c1min;
  177242. }
  177243. }
  177244. have_c1min:
  177245. if (c1max > c1min)
  177246. for (c1 = c1max; c1 >= c1min; c1--)
  177247. for (c0 = c0min; c0 <= c0max; c0++) {
  177248. histp = & histogram[c0][c1][c2min];
  177249. for (c2 = c2min; c2 <= c2max; c2++)
  177250. if (*histp++ != 0) {
  177251. boxp->c1max = c1max = c1;
  177252. goto have_c1max;
  177253. }
  177254. }
  177255. have_c1max:
  177256. if (c2max > c2min)
  177257. for (c2 = c2min; c2 <= c2max; c2++)
  177258. for (c0 = c0min; c0 <= c0max; c0++) {
  177259. histp = & histogram[c0][c1min][c2];
  177260. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177261. if (*histp != 0) {
  177262. boxp->c2min = c2min = c2;
  177263. goto have_c2min;
  177264. }
  177265. }
  177266. have_c2min:
  177267. if (c2max > c2min)
  177268. for (c2 = c2max; c2 >= c2min; c2--)
  177269. for (c0 = c0min; c0 <= c0max; c0++) {
  177270. histp = & histogram[c0][c1min][c2];
  177271. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177272. if (*histp != 0) {
  177273. boxp->c2max = c2max = c2;
  177274. goto have_c2max;
  177275. }
  177276. }
  177277. have_c2max:
  177278. /* Update box volume.
  177279. * We use 2-norm rather than real volume here; this biases the method
  177280. * against making long narrow boxes, and it has the side benefit that
  177281. * a box is splittable iff norm > 0.
  177282. * Since the differences are expressed in histogram-cell units,
  177283. * we have to shift back to JSAMPLE units to get consistent distances;
  177284. * after which, we scale according to the selected distance scale factors.
  177285. */
  177286. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177287. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177288. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177289. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177290. /* Now scan remaining volume of box and compute population */
  177291. ccount = 0;
  177292. for (c0 = c0min; c0 <= c0max; c0++)
  177293. for (c1 = c1min; c1 <= c1max; c1++) {
  177294. histp = & histogram[c0][c1][c2min];
  177295. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177296. if (*histp != 0) {
  177297. ccount++;
  177298. }
  177299. }
  177300. boxp->colorcount = ccount;
  177301. }
  177302. LOCAL(int)
  177303. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177304. int desired_colors)
  177305. /* Repeatedly select and split the largest box until we have enough boxes */
  177306. {
  177307. int n,lb;
  177308. int c0,c1,c2,cmax;
  177309. register boxptr b1,b2;
  177310. while (numboxes < desired_colors) {
  177311. /* Select box to split.
  177312. * Current algorithm: by population for first half, then by volume.
  177313. */
  177314. if (numboxes*2 <= desired_colors) {
  177315. b1 = find_biggest_color_pop(boxlist, numboxes);
  177316. } else {
  177317. b1 = find_biggest_volume(boxlist, numboxes);
  177318. }
  177319. if (b1 == NULL) /* no splittable boxes left! */
  177320. break;
  177321. b2 = &boxlist[numboxes]; /* where new box will go */
  177322. /* Copy the color bounds to the new box. */
  177323. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177324. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177325. /* Choose which axis to split the box on.
  177326. * Current algorithm: longest scaled axis.
  177327. * See notes in update_box about scaling distances.
  177328. */
  177329. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177330. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177331. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177332. /* We want to break any ties in favor of green, then red, blue last.
  177333. * This code does the right thing for R,G,B or B,G,R color orders only.
  177334. */
  177335. #if RGB_RED == 0
  177336. cmax = c1; n = 1;
  177337. if (c0 > cmax) { cmax = c0; n = 0; }
  177338. if (c2 > cmax) { n = 2; }
  177339. #else
  177340. cmax = c1; n = 1;
  177341. if (c2 > cmax) { cmax = c2; n = 2; }
  177342. if (c0 > cmax) { n = 0; }
  177343. #endif
  177344. /* Choose split point along selected axis, and update box bounds.
  177345. * Current algorithm: split at halfway point.
  177346. * (Since the box has been shrunk to minimum volume,
  177347. * any split will produce two nonempty subboxes.)
  177348. * Note that lb value is max for lower box, so must be < old max.
  177349. */
  177350. switch (n) {
  177351. case 0:
  177352. lb = (b1->c0max + b1->c0min) / 2;
  177353. b1->c0max = lb;
  177354. b2->c0min = lb+1;
  177355. break;
  177356. case 1:
  177357. lb = (b1->c1max + b1->c1min) / 2;
  177358. b1->c1max = lb;
  177359. b2->c1min = lb+1;
  177360. break;
  177361. case 2:
  177362. lb = (b1->c2max + b1->c2min) / 2;
  177363. b1->c2max = lb;
  177364. b2->c2min = lb+1;
  177365. break;
  177366. }
  177367. /* Update stats for boxes */
  177368. update_box(cinfo, b1);
  177369. update_box(cinfo, b2);
  177370. numboxes++;
  177371. }
  177372. return numboxes;
  177373. }
  177374. LOCAL(void)
  177375. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177376. /* Compute representative color for a box, put it in colormap[icolor] */
  177377. {
  177378. /* Current algorithm: mean weighted by pixels (not colors) */
  177379. /* Note it is important to get the rounding correct! */
  177380. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177381. hist3d histogram = cquantize->histogram;
  177382. histptr histp;
  177383. int c0,c1,c2;
  177384. int c0min,c0max,c1min,c1max,c2min,c2max;
  177385. long count;
  177386. long total = 0;
  177387. long c0total = 0;
  177388. long c1total = 0;
  177389. long c2total = 0;
  177390. c0min = boxp->c0min; c0max = boxp->c0max;
  177391. c1min = boxp->c1min; c1max = boxp->c1max;
  177392. c2min = boxp->c2min; c2max = boxp->c2max;
  177393. for (c0 = c0min; c0 <= c0max; c0++)
  177394. for (c1 = c1min; c1 <= c1max; c1++) {
  177395. histp = & histogram[c0][c1][c2min];
  177396. for (c2 = c2min; c2 <= c2max; c2++) {
  177397. if ((count = *histp++) != 0) {
  177398. total += count;
  177399. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177400. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177401. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177402. }
  177403. }
  177404. }
  177405. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177406. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177407. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177408. }
  177409. LOCAL(void)
  177410. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177411. /* Master routine for color selection */
  177412. {
  177413. boxptr boxlist;
  177414. int numboxes;
  177415. int i;
  177416. /* Allocate workspace for box list */
  177417. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177418. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177419. /* Initialize one box containing whole space */
  177420. numboxes = 1;
  177421. boxlist[0].c0min = 0;
  177422. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177423. boxlist[0].c1min = 0;
  177424. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177425. boxlist[0].c2min = 0;
  177426. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177427. /* Shrink it to actually-used volume and set its statistics */
  177428. update_box(cinfo, & boxlist[0]);
  177429. /* Perform median-cut to produce final box list */
  177430. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177431. /* Compute the representative color for each box, fill colormap */
  177432. for (i = 0; i < numboxes; i++)
  177433. compute_color(cinfo, & boxlist[i], i);
  177434. cinfo->actual_number_of_colors = numboxes;
  177435. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177436. }
  177437. /*
  177438. * These routines are concerned with the time-critical task of mapping input
  177439. * colors to the nearest color in the selected colormap.
  177440. *
  177441. * We re-use the histogram space as an "inverse color map", essentially a
  177442. * cache for the results of nearest-color searches. All colors within a
  177443. * histogram cell will be mapped to the same colormap entry, namely the one
  177444. * closest to the cell's center. This may not be quite the closest entry to
  177445. * the actual input color, but it's almost as good. A zero in the cache
  177446. * indicates we haven't found the nearest color for that cell yet; the array
  177447. * is cleared to zeroes before starting the mapping pass. When we find the
  177448. * nearest color for a cell, its colormap index plus one is recorded in the
  177449. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177450. * when they need to use an unfilled entry in the cache.
  177451. *
  177452. * Our method of efficiently finding nearest colors is based on the "locally
  177453. * sorted search" idea described by Heckbert and on the incremental distance
  177454. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177455. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177456. * the distances from a given colormap entry to each cell of the histogram can
  177457. * be computed quickly using an incremental method: the differences between
  177458. * distances to adjacent cells themselves differ by a constant. This allows a
  177459. * fairly fast implementation of the "brute force" approach of computing the
  177460. * distance from every colormap entry to every histogram cell. Unfortunately,
  177461. * it needs a work array to hold the best-distance-so-far for each histogram
  177462. * cell (because the inner loop has to be over cells, not colormap entries).
  177463. * The work array elements have to be INT32s, so the work array would need
  177464. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177465. *
  177466. * To get around these problems, we apply Thomas' method to compute the
  177467. * nearest colors for only the cells within a small subbox of the histogram.
  177468. * The work array need be only as big as the subbox, so the memory usage
  177469. * problem is solved. Furthermore, we need not fill subboxes that are never
  177470. * referenced in pass2; many images use only part of the color gamut, so a
  177471. * fair amount of work is saved. An additional advantage of this
  177472. * approach is that we can apply Heckbert's locality criterion to quickly
  177473. * eliminate colormap entries that are far away from the subbox; typically
  177474. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177475. * and we need not compute their distances to individual cells in the subbox.
  177476. * The speed of this approach is heavily influenced by the subbox size: too
  177477. * small means too much overhead, too big loses because Heckbert's criterion
  177478. * can't eliminate as many colormap entries. Empirically the best subbox
  177479. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177480. *
  177481. * Thomas' article also describes a refined method which is asymptotically
  177482. * faster than the brute-force method, but it is also far more complex and
  177483. * cannot efficiently be applied to small subboxes. It is therefore not
  177484. * useful for programs intended to be portable to DOS machines. On machines
  177485. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177486. * refined method might be faster than the present code --- but then again,
  177487. * it might not be any faster, and it's certainly more complicated.
  177488. */
  177489. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177490. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177491. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177492. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177493. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177494. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177495. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177496. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177497. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177498. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177499. /*
  177500. * The next three routines implement inverse colormap filling. They could
  177501. * all be folded into one big routine, but splitting them up this way saves
  177502. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177503. * and may allow some compilers to produce better code by registerizing more
  177504. * inner-loop variables.
  177505. */
  177506. LOCAL(int)
  177507. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177508. JSAMPLE colorlist[])
  177509. /* Locate the colormap entries close enough to an update box to be candidates
  177510. * for the nearest entry to some cell(s) in the update box. The update box
  177511. * is specified by the center coordinates of its first cell. The number of
  177512. * candidate colormap entries is returned, and their colormap indexes are
  177513. * placed in colorlist[].
  177514. * This routine uses Heckbert's "locally sorted search" criterion to select
  177515. * the colors that need further consideration.
  177516. */
  177517. {
  177518. int numcolors = cinfo->actual_number_of_colors;
  177519. int maxc0, maxc1, maxc2;
  177520. int centerc0, centerc1, centerc2;
  177521. int i, x, ncolors;
  177522. INT32 minmaxdist, min_dist, max_dist, tdist;
  177523. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177524. /* Compute true coordinates of update box's upper corner and center.
  177525. * Actually we compute the coordinates of the center of the upper-corner
  177526. * histogram cell, which are the upper bounds of the volume we care about.
  177527. * Note that since ">>" rounds down, the "center" values may be closer to
  177528. * min than to max; hence comparisons to them must be "<=", not "<".
  177529. */
  177530. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177531. centerc0 = (minc0 + maxc0) >> 1;
  177532. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177533. centerc1 = (minc1 + maxc1) >> 1;
  177534. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177535. centerc2 = (minc2 + maxc2) >> 1;
  177536. /* For each color in colormap, find:
  177537. * 1. its minimum squared-distance to any point in the update box
  177538. * (zero if color is within update box);
  177539. * 2. its maximum squared-distance to any point in the update box.
  177540. * Both of these can be found by considering only the corners of the box.
  177541. * We save the minimum distance for each color in mindist[];
  177542. * only the smallest maximum distance is of interest.
  177543. */
  177544. minmaxdist = 0x7FFFFFFFL;
  177545. for (i = 0; i < numcolors; i++) {
  177546. /* We compute the squared-c0-distance term, then add in the other two. */
  177547. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177548. if (x < minc0) {
  177549. tdist = (x - minc0) * C0_SCALE;
  177550. min_dist = tdist*tdist;
  177551. tdist = (x - maxc0) * C0_SCALE;
  177552. max_dist = tdist*tdist;
  177553. } else if (x > maxc0) {
  177554. tdist = (x - maxc0) * C0_SCALE;
  177555. min_dist = tdist*tdist;
  177556. tdist = (x - minc0) * C0_SCALE;
  177557. max_dist = tdist*tdist;
  177558. } else {
  177559. /* within cell range so no contribution to min_dist */
  177560. min_dist = 0;
  177561. if (x <= centerc0) {
  177562. tdist = (x - maxc0) * C0_SCALE;
  177563. max_dist = tdist*tdist;
  177564. } else {
  177565. tdist = (x - minc0) * C0_SCALE;
  177566. max_dist = tdist*tdist;
  177567. }
  177568. }
  177569. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177570. if (x < minc1) {
  177571. tdist = (x - minc1) * C1_SCALE;
  177572. min_dist += tdist*tdist;
  177573. tdist = (x - maxc1) * C1_SCALE;
  177574. max_dist += tdist*tdist;
  177575. } else if (x > maxc1) {
  177576. tdist = (x - maxc1) * C1_SCALE;
  177577. min_dist += tdist*tdist;
  177578. tdist = (x - minc1) * C1_SCALE;
  177579. max_dist += tdist*tdist;
  177580. } else {
  177581. /* within cell range so no contribution to min_dist */
  177582. if (x <= centerc1) {
  177583. tdist = (x - maxc1) * C1_SCALE;
  177584. max_dist += tdist*tdist;
  177585. } else {
  177586. tdist = (x - minc1) * C1_SCALE;
  177587. max_dist += tdist*tdist;
  177588. }
  177589. }
  177590. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177591. if (x < minc2) {
  177592. tdist = (x - minc2) * C2_SCALE;
  177593. min_dist += tdist*tdist;
  177594. tdist = (x - maxc2) * C2_SCALE;
  177595. max_dist += tdist*tdist;
  177596. } else if (x > maxc2) {
  177597. tdist = (x - maxc2) * C2_SCALE;
  177598. min_dist += tdist*tdist;
  177599. tdist = (x - minc2) * C2_SCALE;
  177600. max_dist += tdist*tdist;
  177601. } else {
  177602. /* within cell range so no contribution to min_dist */
  177603. if (x <= centerc2) {
  177604. tdist = (x - maxc2) * C2_SCALE;
  177605. max_dist += tdist*tdist;
  177606. } else {
  177607. tdist = (x - minc2) * C2_SCALE;
  177608. max_dist += tdist*tdist;
  177609. }
  177610. }
  177611. mindist[i] = min_dist; /* save away the results */
  177612. if (max_dist < minmaxdist)
  177613. minmaxdist = max_dist;
  177614. }
  177615. /* Now we know that no cell in the update box is more than minmaxdist
  177616. * away from some colormap entry. Therefore, only colors that are
  177617. * within minmaxdist of some part of the box need be considered.
  177618. */
  177619. ncolors = 0;
  177620. for (i = 0; i < numcolors; i++) {
  177621. if (mindist[i] <= minmaxdist)
  177622. colorlist[ncolors++] = (JSAMPLE) i;
  177623. }
  177624. return ncolors;
  177625. }
  177626. LOCAL(void)
  177627. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177628. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177629. /* Find the closest colormap entry for each cell in the update box,
  177630. * given the list of candidate colors prepared by find_nearby_colors.
  177631. * Return the indexes of the closest entries in the bestcolor[] array.
  177632. * This routine uses Thomas' incremental distance calculation method to
  177633. * find the distance from a colormap entry to successive cells in the box.
  177634. */
  177635. {
  177636. int ic0, ic1, ic2;
  177637. int i, icolor;
  177638. register INT32 * bptr; /* pointer into bestdist[] array */
  177639. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177640. INT32 dist0, dist1; /* initial distance values */
  177641. register INT32 dist2; /* current distance in inner loop */
  177642. INT32 xx0, xx1; /* distance increments */
  177643. register INT32 xx2;
  177644. INT32 inc0, inc1, inc2; /* initial values for increments */
  177645. /* This array holds the distance to the nearest-so-far color for each cell */
  177646. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177647. /* Initialize best-distance for each cell of the update box */
  177648. bptr = bestdist;
  177649. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177650. *bptr++ = 0x7FFFFFFFL;
  177651. /* For each color selected by find_nearby_colors,
  177652. * compute its distance to the center of each cell in the box.
  177653. * If that's less than best-so-far, update best distance and color number.
  177654. */
  177655. /* Nominal steps between cell centers ("x" in Thomas article) */
  177656. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177657. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177658. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177659. for (i = 0; i < numcolors; i++) {
  177660. icolor = GETJSAMPLE(colorlist[i]);
  177661. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177662. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177663. dist0 = inc0*inc0;
  177664. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177665. dist0 += inc1*inc1;
  177666. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177667. dist0 += inc2*inc2;
  177668. /* Form the initial difference increments */
  177669. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177670. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177671. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177672. /* Now loop over all cells in box, updating distance per Thomas method */
  177673. bptr = bestdist;
  177674. cptr = bestcolor;
  177675. xx0 = inc0;
  177676. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177677. dist1 = dist0;
  177678. xx1 = inc1;
  177679. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177680. dist2 = dist1;
  177681. xx2 = inc2;
  177682. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177683. if (dist2 < *bptr) {
  177684. *bptr = dist2;
  177685. *cptr = (JSAMPLE) icolor;
  177686. }
  177687. dist2 += xx2;
  177688. xx2 += 2 * STEP_C2 * STEP_C2;
  177689. bptr++;
  177690. cptr++;
  177691. }
  177692. dist1 += xx1;
  177693. xx1 += 2 * STEP_C1 * STEP_C1;
  177694. }
  177695. dist0 += xx0;
  177696. xx0 += 2 * STEP_C0 * STEP_C0;
  177697. }
  177698. }
  177699. }
  177700. LOCAL(void)
  177701. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177702. /* Fill the inverse-colormap entries in the update box that contains */
  177703. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177704. /* we can fill as many others as we wish.) */
  177705. {
  177706. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177707. hist3d histogram = cquantize->histogram;
  177708. int minc0, minc1, minc2; /* lower left corner of update box */
  177709. int ic0, ic1, ic2;
  177710. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177711. register histptr cachep; /* pointer into main cache array */
  177712. /* This array lists the candidate colormap indexes. */
  177713. JSAMPLE colorlist[MAXNUMCOLORS];
  177714. int numcolors; /* number of candidate colors */
  177715. /* This array holds the actually closest colormap index for each cell. */
  177716. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177717. /* Convert cell coordinates to update box ID */
  177718. c0 >>= BOX_C0_LOG;
  177719. c1 >>= BOX_C1_LOG;
  177720. c2 >>= BOX_C2_LOG;
  177721. /* Compute true coordinates of update box's origin corner.
  177722. * Actually we compute the coordinates of the center of the corner
  177723. * histogram cell, which are the lower bounds of the volume we care about.
  177724. */
  177725. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177726. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177727. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177728. /* Determine which colormap entries are close enough to be candidates
  177729. * for the nearest entry to some cell in the update box.
  177730. */
  177731. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177732. /* Determine the actually nearest colors. */
  177733. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177734. bestcolor);
  177735. /* Save the best color numbers (plus 1) in the main cache array */
  177736. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177737. c1 <<= BOX_C1_LOG;
  177738. c2 <<= BOX_C2_LOG;
  177739. cptr = bestcolor;
  177740. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177741. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177742. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177743. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177744. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177745. }
  177746. }
  177747. }
  177748. }
  177749. /*
  177750. * Map some rows of pixels to the output colormapped representation.
  177751. */
  177752. METHODDEF(void)
  177753. pass2_no_dither (j_decompress_ptr cinfo,
  177754. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177755. /* This version performs no dithering */
  177756. {
  177757. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177758. hist3d histogram = cquantize->histogram;
  177759. register JSAMPROW inptr, outptr;
  177760. register histptr cachep;
  177761. register int c0, c1, c2;
  177762. int row;
  177763. JDIMENSION col;
  177764. JDIMENSION width = cinfo->output_width;
  177765. for (row = 0; row < num_rows; row++) {
  177766. inptr = input_buf[row];
  177767. outptr = output_buf[row];
  177768. for (col = width; col > 0; col--) {
  177769. /* get pixel value and index into the cache */
  177770. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177771. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177772. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177773. cachep = & histogram[c0][c1][c2];
  177774. /* If we have not seen this color before, find nearest colormap entry */
  177775. /* and update the cache */
  177776. if (*cachep == 0)
  177777. fill_inverse_cmap(cinfo, c0,c1,c2);
  177778. /* Now emit the colormap index for this cell */
  177779. *outptr++ = (JSAMPLE) (*cachep - 1);
  177780. }
  177781. }
  177782. }
  177783. METHODDEF(void)
  177784. pass2_fs_dither (j_decompress_ptr cinfo,
  177785. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177786. /* This version performs Floyd-Steinberg dithering */
  177787. {
  177788. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177789. hist3d histogram = cquantize->histogram;
  177790. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177791. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177792. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177793. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177794. JSAMPROW inptr; /* => current input pixel */
  177795. JSAMPROW outptr; /* => current output pixel */
  177796. histptr cachep;
  177797. int dir; /* +1 or -1 depending on direction */
  177798. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177799. int row;
  177800. JDIMENSION col;
  177801. JDIMENSION width = cinfo->output_width;
  177802. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177803. int *error_limit = cquantize->error_limiter;
  177804. JSAMPROW colormap0 = cinfo->colormap[0];
  177805. JSAMPROW colormap1 = cinfo->colormap[1];
  177806. JSAMPROW colormap2 = cinfo->colormap[2];
  177807. SHIFT_TEMPS
  177808. for (row = 0; row < num_rows; row++) {
  177809. inptr = input_buf[row];
  177810. outptr = output_buf[row];
  177811. if (cquantize->on_odd_row) {
  177812. /* work right to left in this row */
  177813. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177814. outptr += width-1;
  177815. dir = -1;
  177816. dir3 = -3;
  177817. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177818. cquantize->on_odd_row = FALSE; /* flip for next time */
  177819. } else {
  177820. /* work left to right in this row */
  177821. dir = 1;
  177822. dir3 = 3;
  177823. errorptr = cquantize->fserrors; /* => entry before first real column */
  177824. cquantize->on_odd_row = TRUE; /* flip for next time */
  177825. }
  177826. /* Preset error values: no error propagated to first pixel from left */
  177827. cur0 = cur1 = cur2 = 0;
  177828. /* and no error propagated to row below yet */
  177829. belowerr0 = belowerr1 = belowerr2 = 0;
  177830. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  177831. for (col = width; col > 0; col--) {
  177832. /* curN holds the error propagated from the previous pixel on the
  177833. * current line. Add the error propagated from the previous line
  177834. * to form the complete error correction term for this pixel, and
  177835. * round the error term (which is expressed * 16) to an integer.
  177836. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177837. * for either sign of the error value.
  177838. * Note: errorptr points to *previous* column's array entry.
  177839. */
  177840. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  177841. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  177842. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  177843. /* Limit the error using transfer function set by init_error_limit.
  177844. * See comments with init_error_limit for rationale.
  177845. */
  177846. cur0 = error_limit[cur0];
  177847. cur1 = error_limit[cur1];
  177848. cur2 = error_limit[cur2];
  177849. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177850. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  177851. * this sets the required size of the range_limit array.
  177852. */
  177853. cur0 += GETJSAMPLE(inptr[0]);
  177854. cur1 += GETJSAMPLE(inptr[1]);
  177855. cur2 += GETJSAMPLE(inptr[2]);
  177856. cur0 = GETJSAMPLE(range_limit[cur0]);
  177857. cur1 = GETJSAMPLE(range_limit[cur1]);
  177858. cur2 = GETJSAMPLE(range_limit[cur2]);
  177859. /* Index into the cache with adjusted pixel value */
  177860. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  177861. /* If we have not seen this color before, find nearest colormap */
  177862. /* entry and update the cache */
  177863. if (*cachep == 0)
  177864. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  177865. /* Now emit the colormap index for this cell */
  177866. { register int pixcode = *cachep - 1;
  177867. *outptr = (JSAMPLE) pixcode;
  177868. /* Compute representation error for this pixel */
  177869. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  177870. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  177871. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  177872. }
  177873. /* Compute error fractions to be propagated to adjacent pixels.
  177874. * Add these into the running sums, and simultaneously shift the
  177875. * next-line error sums left by 1 column.
  177876. */
  177877. { register LOCFSERROR bnexterr, delta;
  177878. bnexterr = cur0; /* Process component 0 */
  177879. delta = cur0 * 2;
  177880. cur0 += delta; /* form error * 3 */
  177881. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  177882. cur0 += delta; /* form error * 5 */
  177883. bpreverr0 = belowerr0 + cur0;
  177884. belowerr0 = bnexterr;
  177885. cur0 += delta; /* form error * 7 */
  177886. bnexterr = cur1; /* Process component 1 */
  177887. delta = cur1 * 2;
  177888. cur1 += delta; /* form error * 3 */
  177889. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  177890. cur1 += delta; /* form error * 5 */
  177891. bpreverr1 = belowerr1 + cur1;
  177892. belowerr1 = bnexterr;
  177893. cur1 += delta; /* form error * 7 */
  177894. bnexterr = cur2; /* Process component 2 */
  177895. delta = cur2 * 2;
  177896. cur2 += delta; /* form error * 3 */
  177897. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  177898. cur2 += delta; /* form error * 5 */
  177899. bpreverr2 = belowerr2 + cur2;
  177900. belowerr2 = bnexterr;
  177901. cur2 += delta; /* form error * 7 */
  177902. }
  177903. /* At this point curN contains the 7/16 error value to be propagated
  177904. * to the next pixel on the current line, and all the errors for the
  177905. * next line have been shifted over. We are therefore ready to move on.
  177906. */
  177907. inptr += dir3; /* Advance pixel pointers to next column */
  177908. outptr += dir;
  177909. errorptr += dir3; /* advance errorptr to current column */
  177910. }
  177911. /* Post-loop cleanup: we must unload the final error values into the
  177912. * final fserrors[] entry. Note we need not unload belowerrN because
  177913. * it is for the dummy column before or after the actual array.
  177914. */
  177915. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  177916. errorptr[1] = (FSERROR) bpreverr1;
  177917. errorptr[2] = (FSERROR) bpreverr2;
  177918. }
  177919. }
  177920. /*
  177921. * Initialize the error-limiting transfer function (lookup table).
  177922. * The raw F-S error computation can potentially compute error values of up to
  177923. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  177924. * much less, otherwise obviously wrong pixels will be created. (Typical
  177925. * effects include weird fringes at color-area boundaries, isolated bright
  177926. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  177927. * is to ensure that the "corners" of the color cube are allocated as output
  177928. * colors; then repeated errors in the same direction cannot cause cascading
  177929. * error buildup. However, that only prevents the error from getting
  177930. * completely out of hand; Aaron Giles reports that error limiting improves
  177931. * the results even with corner colors allocated.
  177932. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  177933. * well, but the smoother transfer function used below is even better. Thanks
  177934. * to Aaron Giles for this idea.
  177935. */
  177936. LOCAL(void)
  177937. init_error_limit (j_decompress_ptr cinfo)
  177938. /* Allocate and fill in the error_limiter table */
  177939. {
  177940. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177941. int * table;
  177942. int in, out;
  177943. table = (int *) (*cinfo->mem->alloc_small)
  177944. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  177945. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  177946. cquantize->error_limiter = table;
  177947. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  177948. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  177949. out = 0;
  177950. for (in = 0; in < STEPSIZE; in++, out++) {
  177951. table[in] = out; table[-in] = -out;
  177952. }
  177953. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  177954. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  177955. table[in] = out; table[-in] = -out;
  177956. }
  177957. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  177958. for (; in <= MAXJSAMPLE; in++) {
  177959. table[in] = out; table[-in] = -out;
  177960. }
  177961. #undef STEPSIZE
  177962. }
  177963. /*
  177964. * Finish up at the end of each pass.
  177965. */
  177966. METHODDEF(void)
  177967. finish_pass1 (j_decompress_ptr cinfo)
  177968. {
  177969. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177970. /* Select the representative colors and fill in cinfo->colormap */
  177971. cinfo->colormap = cquantize->sv_colormap;
  177972. select_colors(cinfo, cquantize->desired);
  177973. /* Force next pass to zero the color index table */
  177974. cquantize->needs_zeroed = TRUE;
  177975. }
  177976. METHODDEF(void)
  177977. finish_pass2 (j_decompress_ptr)
  177978. {
  177979. /* no work */
  177980. }
  177981. /*
  177982. * Initialize for each processing pass.
  177983. */
  177984. METHODDEF(void)
  177985. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  177986. {
  177987. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177988. hist3d histogram = cquantize->histogram;
  177989. int i;
  177990. /* Only F-S dithering or no dithering is supported. */
  177991. /* If user asks for ordered dither, give him F-S. */
  177992. if (cinfo->dither_mode != JDITHER_NONE)
  177993. cinfo->dither_mode = JDITHER_FS;
  177994. if (is_pre_scan) {
  177995. /* Set up method pointers */
  177996. cquantize->pub.color_quantize = prescan_quantize;
  177997. cquantize->pub.finish_pass = finish_pass1;
  177998. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  177999. } else {
  178000. /* Set up method pointers */
  178001. if (cinfo->dither_mode == JDITHER_FS)
  178002. cquantize->pub.color_quantize = pass2_fs_dither;
  178003. else
  178004. cquantize->pub.color_quantize = pass2_no_dither;
  178005. cquantize->pub.finish_pass = finish_pass2;
  178006. /* Make sure color count is acceptable */
  178007. i = cinfo->actual_number_of_colors;
  178008. if (i < 1)
  178009. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178010. if (i > MAXNUMCOLORS)
  178011. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178012. if (cinfo->dither_mode == JDITHER_FS) {
  178013. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178014. (3 * SIZEOF(FSERROR)));
  178015. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178016. if (cquantize->fserrors == NULL)
  178017. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178018. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178019. /* Initialize the propagated errors to zero. */
  178020. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178021. /* Make the error-limit table if we didn't already. */
  178022. if (cquantize->error_limiter == NULL)
  178023. init_error_limit(cinfo);
  178024. cquantize->on_odd_row = FALSE;
  178025. }
  178026. }
  178027. /* Zero the histogram or inverse color map, if necessary */
  178028. if (cquantize->needs_zeroed) {
  178029. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178030. jzero_far((void FAR *) histogram[i],
  178031. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178032. }
  178033. cquantize->needs_zeroed = FALSE;
  178034. }
  178035. }
  178036. /*
  178037. * Switch to a new external colormap between output passes.
  178038. */
  178039. METHODDEF(void)
  178040. new_color_map_2_quant (j_decompress_ptr cinfo)
  178041. {
  178042. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178043. /* Reset the inverse color map */
  178044. cquantize->needs_zeroed = TRUE;
  178045. }
  178046. /*
  178047. * Module initialization routine for 2-pass color quantization.
  178048. */
  178049. GLOBAL(void)
  178050. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178051. {
  178052. my_cquantize_ptr2 cquantize;
  178053. int i;
  178054. cquantize = (my_cquantize_ptr2)
  178055. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178056. SIZEOF(my_cquantizer2));
  178057. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178058. cquantize->pub.start_pass = start_pass_2_quant;
  178059. cquantize->pub.new_color_map = new_color_map_2_quant;
  178060. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178061. cquantize->error_limiter = NULL;
  178062. /* Make sure jdmaster didn't give me a case I can't handle */
  178063. if (cinfo->out_color_components != 3)
  178064. ERREXIT(cinfo, JERR_NOTIMPL);
  178065. /* Allocate the histogram/inverse colormap storage */
  178066. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178067. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178068. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178069. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178070. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178071. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178072. }
  178073. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178074. /* Allocate storage for the completed colormap, if required.
  178075. * We do this now since it is FAR storage and may affect
  178076. * the memory manager's space calculations.
  178077. */
  178078. if (cinfo->enable_2pass_quant) {
  178079. /* Make sure color count is acceptable */
  178080. int desired = cinfo->desired_number_of_colors;
  178081. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178082. if (desired < 8)
  178083. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178084. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178085. if (desired > MAXNUMCOLORS)
  178086. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178087. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178088. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178089. cquantize->desired = desired;
  178090. } else
  178091. cquantize->sv_colormap = NULL;
  178092. /* Only F-S dithering or no dithering is supported. */
  178093. /* If user asks for ordered dither, give him F-S. */
  178094. if (cinfo->dither_mode != JDITHER_NONE)
  178095. cinfo->dither_mode = JDITHER_FS;
  178096. /* Allocate Floyd-Steinberg workspace if necessary.
  178097. * This isn't really needed until pass 2, but again it is FAR storage.
  178098. * Although we will cope with a later change in dither_mode,
  178099. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178100. */
  178101. if (cinfo->dither_mode == JDITHER_FS) {
  178102. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178103. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178104. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178105. /* Might as well create the error-limiting table too. */
  178106. init_error_limit(cinfo);
  178107. }
  178108. }
  178109. #endif /* QUANT_2PASS_SUPPORTED */
  178110. /*** End of inlined file: jquant2.c ***/
  178111. /*** Start of inlined file: jutils.c ***/
  178112. #define JPEG_INTERNALS
  178113. /*
  178114. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178115. * of a DCT block read in natural order (left to right, top to bottom).
  178116. */
  178117. #if 0 /* This table is not actually needed in v6a */
  178118. const int jpeg_zigzag_order[DCTSIZE2] = {
  178119. 0, 1, 5, 6, 14, 15, 27, 28,
  178120. 2, 4, 7, 13, 16, 26, 29, 42,
  178121. 3, 8, 12, 17, 25, 30, 41, 43,
  178122. 9, 11, 18, 24, 31, 40, 44, 53,
  178123. 10, 19, 23, 32, 39, 45, 52, 54,
  178124. 20, 22, 33, 38, 46, 51, 55, 60,
  178125. 21, 34, 37, 47, 50, 56, 59, 61,
  178126. 35, 36, 48, 49, 57, 58, 62, 63
  178127. };
  178128. #endif
  178129. /*
  178130. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178131. * of zigzag order.
  178132. *
  178133. * When reading corrupted data, the Huffman decoders could attempt
  178134. * to reference an entry beyond the end of this array (if the decoded
  178135. * zero run length reaches past the end of the block). To prevent
  178136. * wild stores without adding an inner-loop test, we put some extra
  178137. * "63"s after the real entries. This will cause the extra coefficient
  178138. * to be stored in location 63 of the block, not somewhere random.
  178139. * The worst case would be a run-length of 15, which means we need 16
  178140. * fake entries.
  178141. */
  178142. const int jpeg_natural_order[DCTSIZE2+16] = {
  178143. 0, 1, 8, 16, 9, 2, 3, 10,
  178144. 17, 24, 32, 25, 18, 11, 4, 5,
  178145. 12, 19, 26, 33, 40, 48, 41, 34,
  178146. 27, 20, 13, 6, 7, 14, 21, 28,
  178147. 35, 42, 49, 56, 57, 50, 43, 36,
  178148. 29, 22, 15, 23, 30, 37, 44, 51,
  178149. 58, 59, 52, 45, 38, 31, 39, 46,
  178150. 53, 60, 61, 54, 47, 55, 62, 63,
  178151. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178152. 63, 63, 63, 63, 63, 63, 63, 63
  178153. };
  178154. /*
  178155. * Arithmetic utilities
  178156. */
  178157. GLOBAL(long)
  178158. jdiv_round_up (long a, long b)
  178159. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178160. /* Assumes a >= 0, b > 0 */
  178161. {
  178162. return (a + b - 1L) / b;
  178163. }
  178164. GLOBAL(long)
  178165. jround_up (long a, long b)
  178166. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178167. /* Assumes a >= 0, b > 0 */
  178168. {
  178169. a += b - 1L;
  178170. return a - (a % b);
  178171. }
  178172. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178173. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178174. * are FAR and we're assuming a small-pointer memory model. However, some
  178175. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178176. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178177. * Otherwise, the routines below do it the hard way. (The performance cost
  178178. * is not all that great, because these routines aren't very heavily used.)
  178179. */
  178180. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178181. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178182. #define FMEMZERO(target,size) MEMZERO(target,size)
  178183. #else /* 80x86 case, define if we can */
  178184. #ifdef USE_FMEM
  178185. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178186. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178187. #endif
  178188. #endif
  178189. GLOBAL(void)
  178190. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178191. JSAMPARRAY output_array, int dest_row,
  178192. int num_rows, JDIMENSION num_cols)
  178193. /* Copy some rows of samples from one place to another.
  178194. * num_rows rows are copied from input_array[source_row++]
  178195. * to output_array[dest_row++]; these areas may overlap for duplication.
  178196. * The source and destination arrays must be at least as wide as num_cols.
  178197. */
  178198. {
  178199. register JSAMPROW inptr, outptr;
  178200. #ifdef FMEMCOPY
  178201. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178202. #else
  178203. register JDIMENSION count;
  178204. #endif
  178205. register int row;
  178206. input_array += source_row;
  178207. output_array += dest_row;
  178208. for (row = num_rows; row > 0; row--) {
  178209. inptr = *input_array++;
  178210. outptr = *output_array++;
  178211. #ifdef FMEMCOPY
  178212. FMEMCOPY(outptr, inptr, count);
  178213. #else
  178214. for (count = num_cols; count > 0; count--)
  178215. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178216. #endif
  178217. }
  178218. }
  178219. GLOBAL(void)
  178220. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178221. JDIMENSION num_blocks)
  178222. /* Copy a row of coefficient blocks from one place to another. */
  178223. {
  178224. #ifdef FMEMCOPY
  178225. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178226. #else
  178227. register JCOEFPTR inptr, outptr;
  178228. register long count;
  178229. inptr = (JCOEFPTR) input_row;
  178230. outptr = (JCOEFPTR) output_row;
  178231. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178232. *outptr++ = *inptr++;
  178233. }
  178234. #endif
  178235. }
  178236. GLOBAL(void)
  178237. jzero_far (void FAR * target, size_t bytestozero)
  178238. /* Zero out a chunk of FAR memory. */
  178239. /* This might be sample-array data, block-array data, or alloc_large data. */
  178240. {
  178241. #ifdef FMEMZERO
  178242. FMEMZERO(target, bytestozero);
  178243. #else
  178244. register char FAR * ptr = (char FAR *) target;
  178245. register size_t count;
  178246. for (count = bytestozero; count > 0; count--) {
  178247. *ptr++ = 0;
  178248. }
  178249. #endif
  178250. }
  178251. /*** End of inlined file: jutils.c ***/
  178252. /*** Start of inlined file: transupp.c ***/
  178253. /* Although this file really shouldn't have access to the library internals,
  178254. * it's helpful to let it call jround_up() and jcopy_block_row().
  178255. */
  178256. #define JPEG_INTERNALS
  178257. /*** Start of inlined file: transupp.h ***/
  178258. /* If you happen not to want the image transform support, disable it here */
  178259. #ifndef TRANSFORMS_SUPPORTED
  178260. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178261. #endif
  178262. /* Short forms of external names for systems with brain-damaged linkers. */
  178263. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178264. #define jtransform_request_workspace jTrRequest
  178265. #define jtransform_adjust_parameters jTrAdjust
  178266. #define jtransform_execute_transformation jTrExec
  178267. #define jcopy_markers_setup jCMrkSetup
  178268. #define jcopy_markers_execute jCMrkExec
  178269. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178270. /*
  178271. * Codes for supported types of image transformations.
  178272. */
  178273. typedef enum {
  178274. JXFORM_NONE, /* no transformation */
  178275. JXFORM_FLIP_H, /* horizontal flip */
  178276. JXFORM_FLIP_V, /* vertical flip */
  178277. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178278. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178279. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178280. JXFORM_ROT_180, /* 180-degree rotation */
  178281. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178282. } JXFORM_CODE;
  178283. /*
  178284. * Although rotating and flipping data expressed as DCT coefficients is not
  178285. * hard, there is an asymmetry in the JPEG format specification for images
  178286. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178287. * image edges are padded out to the next iMCU boundary with junk data; but
  178288. * no padding is possible at the top and left edges. If we were to flip
  178289. * the whole image including the pad data, then pad garbage would become
  178290. * visible at the top and/or left, and real pixels would disappear into the
  178291. * pad margins --- perhaps permanently, since encoders & decoders may not
  178292. * bother to preserve DCT blocks that appear to be completely outside the
  178293. * nominal image area. So, we have to exclude any partial iMCUs from the
  178294. * basic transformation.
  178295. *
  178296. * Transpose is the only transformation that can handle partial iMCUs at the
  178297. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178298. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178299. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178300. * The other transforms are defined as combinations of these basic transforms
  178301. * and process edge blocks in a way that preserves the equivalence.
  178302. *
  178303. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178304. * this is not strictly lossless, but it usually gives the best-looking
  178305. * result for odd-size images. Note that when this option is active,
  178306. * the expected mathematical equivalences between the transforms may not hold.
  178307. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178308. * followed by -rot 180 -trim trims both edges.)
  178309. *
  178310. * We also offer a "force to grayscale" option, which simply discards the
  178311. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178312. * the luminance channel is preserved exactly. It's not the same kind of
  178313. * thing as the rotate/flip transformations, but it's convenient to handle it
  178314. * as part of this package, mainly because the transformation routines have to
  178315. * be aware of the option to know how many components to work on.
  178316. */
  178317. typedef struct {
  178318. /* Options: set by caller */
  178319. JXFORM_CODE transform; /* image transform operator */
  178320. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178321. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178322. /* Internal workspace: caller should not touch these */
  178323. int num_components; /* # of components in workspace */
  178324. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178325. } jpeg_transform_info;
  178326. #if TRANSFORMS_SUPPORTED
  178327. /* Request any required workspace */
  178328. EXTERN(void) jtransform_request_workspace
  178329. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178330. /* Adjust output image parameters */
  178331. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178332. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178333. jvirt_barray_ptr *src_coef_arrays,
  178334. jpeg_transform_info *info));
  178335. /* Execute the actual transformation, if any */
  178336. EXTERN(void) jtransform_execute_transformation
  178337. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178338. jvirt_barray_ptr *src_coef_arrays,
  178339. jpeg_transform_info *info));
  178340. #endif /* TRANSFORMS_SUPPORTED */
  178341. /*
  178342. * Support for copying optional markers from source to destination file.
  178343. */
  178344. typedef enum {
  178345. JCOPYOPT_NONE, /* copy no optional markers */
  178346. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178347. JCOPYOPT_ALL /* copy all optional markers */
  178348. } JCOPY_OPTION;
  178349. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178350. /* Setup decompression object to save desired markers in memory */
  178351. EXTERN(void) jcopy_markers_setup
  178352. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178353. /* Copy markers saved in the given source object to the destination object */
  178354. EXTERN(void) jcopy_markers_execute
  178355. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178356. JCOPY_OPTION option));
  178357. /*** End of inlined file: transupp.h ***/
  178358. /* My own external interface */
  178359. #if TRANSFORMS_SUPPORTED
  178360. /*
  178361. * Lossless image transformation routines. These routines work on DCT
  178362. * coefficient arrays and thus do not require any lossy decompression
  178363. * or recompression of the image.
  178364. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178365. *
  178366. * Horizontal flipping is done in-place, using a single top-to-bottom
  178367. * pass through the virtual source array. It will thus be much the
  178368. * fastest option for images larger than main memory.
  178369. *
  178370. * The other routines require a set of destination virtual arrays, so they
  178371. * need twice as much memory as jpegtran normally does. The destination
  178372. * arrays are always written in normal scan order (top to bottom) because
  178373. * the virtual array manager expects this. The source arrays will be scanned
  178374. * in the corresponding order, which means multiple passes through the source
  178375. * arrays for most of the transforms. That could result in much thrashing
  178376. * if the image is larger than main memory.
  178377. *
  178378. * Some notes about the operating environment of the individual transform
  178379. * routines:
  178380. * 1. Both the source and destination virtual arrays are allocated from the
  178381. * source JPEG object, and therefore should be manipulated by calling the
  178382. * source's memory manager.
  178383. * 2. The destination's component count should be used. It may be smaller
  178384. * than the source's when forcing to grayscale.
  178385. * 3. Likewise the destination's sampling factors should be used. When
  178386. * forcing to grayscale the destination's sampling factors will be all 1,
  178387. * and we may as well take that as the effective iMCU size.
  178388. * 4. When "trim" is in effect, the destination's dimensions will be the
  178389. * trimmed values but the source's will be untrimmed.
  178390. * 5. All the routines assume that the source and destination buffers are
  178391. * padded out to a full iMCU boundary. This is true, although for the
  178392. * source buffer it is an undocumented property of jdcoefct.c.
  178393. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178394. * dimensions and ignore the source's.
  178395. */
  178396. LOCAL(void)
  178397. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178398. jvirt_barray_ptr *src_coef_arrays)
  178399. /* Horizontal flip; done in-place, so no separate dest array is required */
  178400. {
  178401. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178402. int ci, k, offset_y;
  178403. JBLOCKARRAY buffer;
  178404. JCOEFPTR ptr1, ptr2;
  178405. JCOEF temp1, temp2;
  178406. jpeg_component_info *compptr;
  178407. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178408. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178409. * mirroring by changing the signs of odd-numbered columns.
  178410. * Partial iMCUs at the right edge are left untouched.
  178411. */
  178412. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178413. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178414. compptr = dstinfo->comp_info + ci;
  178415. comp_width = MCU_cols * compptr->h_samp_factor;
  178416. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178417. blk_y += compptr->v_samp_factor) {
  178418. buffer = (*srcinfo->mem->access_virt_barray)
  178419. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178420. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178421. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178422. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178423. ptr1 = buffer[offset_y][blk_x];
  178424. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178425. /* this unrolled loop doesn't need to know which row it's on... */
  178426. for (k = 0; k < DCTSIZE2; k += 2) {
  178427. temp1 = *ptr1; /* swap even column */
  178428. temp2 = *ptr2;
  178429. *ptr1++ = temp2;
  178430. *ptr2++ = temp1;
  178431. temp1 = *ptr1; /* swap odd column with sign change */
  178432. temp2 = *ptr2;
  178433. *ptr1++ = -temp2;
  178434. *ptr2++ = -temp1;
  178435. }
  178436. }
  178437. }
  178438. }
  178439. }
  178440. }
  178441. LOCAL(void)
  178442. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178443. jvirt_barray_ptr *src_coef_arrays,
  178444. jvirt_barray_ptr *dst_coef_arrays)
  178445. /* Vertical flip */
  178446. {
  178447. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178448. int ci, i, j, offset_y;
  178449. JBLOCKARRAY src_buffer, dst_buffer;
  178450. JBLOCKROW src_row_ptr, dst_row_ptr;
  178451. JCOEFPTR src_ptr, dst_ptr;
  178452. jpeg_component_info *compptr;
  178453. /* We output into a separate array because we can't touch different
  178454. * rows of the source virtual array simultaneously. Otherwise, this
  178455. * is a pretty straightforward analog of horizontal flip.
  178456. * Within a DCT block, vertical mirroring is done by changing the signs
  178457. * of odd-numbered rows.
  178458. * Partial iMCUs at the bottom edge are copied verbatim.
  178459. */
  178460. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178461. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178462. compptr = dstinfo->comp_info + ci;
  178463. comp_height = MCU_rows * compptr->v_samp_factor;
  178464. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178465. dst_blk_y += compptr->v_samp_factor) {
  178466. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178467. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178468. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178469. if (dst_blk_y < comp_height) {
  178470. /* Row is within the mirrorable area. */
  178471. src_buffer = (*srcinfo->mem->access_virt_barray)
  178472. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178473. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178474. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178475. } else {
  178476. /* Bottom-edge blocks will be copied verbatim. */
  178477. src_buffer = (*srcinfo->mem->access_virt_barray)
  178478. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178479. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178480. }
  178481. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178482. if (dst_blk_y < comp_height) {
  178483. /* Row is within the mirrorable area. */
  178484. dst_row_ptr = dst_buffer[offset_y];
  178485. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178486. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178487. dst_blk_x++) {
  178488. dst_ptr = dst_row_ptr[dst_blk_x];
  178489. src_ptr = src_row_ptr[dst_blk_x];
  178490. for (i = 0; i < DCTSIZE; i += 2) {
  178491. /* copy even row */
  178492. for (j = 0; j < DCTSIZE; j++)
  178493. *dst_ptr++ = *src_ptr++;
  178494. /* copy odd row with sign change */
  178495. for (j = 0; j < DCTSIZE; j++)
  178496. *dst_ptr++ = - *src_ptr++;
  178497. }
  178498. }
  178499. } else {
  178500. /* Just copy row verbatim. */
  178501. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178502. compptr->width_in_blocks);
  178503. }
  178504. }
  178505. }
  178506. }
  178507. }
  178508. LOCAL(void)
  178509. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178510. jvirt_barray_ptr *src_coef_arrays,
  178511. jvirt_barray_ptr *dst_coef_arrays)
  178512. /* Transpose source into destination */
  178513. {
  178514. JDIMENSION dst_blk_x, dst_blk_y;
  178515. int ci, i, j, offset_x, offset_y;
  178516. JBLOCKARRAY src_buffer, dst_buffer;
  178517. JCOEFPTR src_ptr, dst_ptr;
  178518. jpeg_component_info *compptr;
  178519. /* Transposing pixels within a block just requires transposing the
  178520. * DCT coefficients.
  178521. * Partial iMCUs at the edges require no special treatment; we simply
  178522. * process all the available DCT blocks for every component.
  178523. */
  178524. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178525. compptr = dstinfo->comp_info + ci;
  178526. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178527. dst_blk_y += compptr->v_samp_factor) {
  178528. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178529. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178530. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178531. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178532. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178533. dst_blk_x += compptr->h_samp_factor) {
  178534. src_buffer = (*srcinfo->mem->access_virt_barray)
  178535. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178536. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178537. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178538. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178539. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178540. for (i = 0; i < DCTSIZE; i++)
  178541. for (j = 0; j < DCTSIZE; j++)
  178542. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178543. }
  178544. }
  178545. }
  178546. }
  178547. }
  178548. }
  178549. LOCAL(void)
  178550. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178551. jvirt_barray_ptr *src_coef_arrays,
  178552. jvirt_barray_ptr *dst_coef_arrays)
  178553. /* 90 degree rotation is equivalent to
  178554. * 1. Transposing the image;
  178555. * 2. Horizontal mirroring.
  178556. * These two steps are merged into a single processing routine.
  178557. */
  178558. {
  178559. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178560. int ci, i, j, offset_x, offset_y;
  178561. JBLOCKARRAY src_buffer, dst_buffer;
  178562. JCOEFPTR src_ptr, dst_ptr;
  178563. jpeg_component_info *compptr;
  178564. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178565. * at the (output) right edge properly. They just get transposed and
  178566. * not mirrored.
  178567. */
  178568. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178569. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178570. compptr = dstinfo->comp_info + ci;
  178571. comp_width = MCU_cols * compptr->h_samp_factor;
  178572. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178573. dst_blk_y += compptr->v_samp_factor) {
  178574. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178575. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178576. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178577. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178578. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178579. dst_blk_x += compptr->h_samp_factor) {
  178580. src_buffer = (*srcinfo->mem->access_virt_barray)
  178581. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178582. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178583. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178584. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178585. if (dst_blk_x < comp_width) {
  178586. /* Block is within the mirrorable area. */
  178587. dst_ptr = dst_buffer[offset_y]
  178588. [comp_width - dst_blk_x - offset_x - 1];
  178589. for (i = 0; i < DCTSIZE; i++) {
  178590. for (j = 0; j < DCTSIZE; j++)
  178591. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178592. i++;
  178593. for (j = 0; j < DCTSIZE; j++)
  178594. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178595. }
  178596. } else {
  178597. /* Edge blocks are transposed but not mirrored. */
  178598. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178599. for (i = 0; i < DCTSIZE; i++)
  178600. for (j = 0; j < DCTSIZE; j++)
  178601. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178602. }
  178603. }
  178604. }
  178605. }
  178606. }
  178607. }
  178608. }
  178609. LOCAL(void)
  178610. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178611. jvirt_barray_ptr *src_coef_arrays,
  178612. jvirt_barray_ptr *dst_coef_arrays)
  178613. /* 270 degree rotation is equivalent to
  178614. * 1. Horizontal mirroring;
  178615. * 2. Transposing the image.
  178616. * These two steps are merged into a single processing routine.
  178617. */
  178618. {
  178619. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178620. int ci, i, j, offset_x, offset_y;
  178621. JBLOCKARRAY src_buffer, dst_buffer;
  178622. JCOEFPTR src_ptr, dst_ptr;
  178623. jpeg_component_info *compptr;
  178624. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178625. * at the (output) bottom edge properly. They just get transposed and
  178626. * not mirrored.
  178627. */
  178628. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178629. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178630. compptr = dstinfo->comp_info + ci;
  178631. comp_height = MCU_rows * compptr->v_samp_factor;
  178632. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178633. dst_blk_y += compptr->v_samp_factor) {
  178634. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178635. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178636. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178637. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178638. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178639. dst_blk_x += compptr->h_samp_factor) {
  178640. src_buffer = (*srcinfo->mem->access_virt_barray)
  178641. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178642. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178643. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178644. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178645. if (dst_blk_y < comp_height) {
  178646. /* Block is within the mirrorable area. */
  178647. src_ptr = src_buffer[offset_x]
  178648. [comp_height - dst_blk_y - offset_y - 1];
  178649. for (i = 0; i < DCTSIZE; i++) {
  178650. for (j = 0; j < DCTSIZE; j++) {
  178651. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178652. j++;
  178653. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178654. }
  178655. }
  178656. } else {
  178657. /* Edge blocks are transposed but not mirrored. */
  178658. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178659. for (i = 0; i < DCTSIZE; i++)
  178660. for (j = 0; j < DCTSIZE; j++)
  178661. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178662. }
  178663. }
  178664. }
  178665. }
  178666. }
  178667. }
  178668. }
  178669. LOCAL(void)
  178670. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178671. jvirt_barray_ptr *src_coef_arrays,
  178672. jvirt_barray_ptr *dst_coef_arrays)
  178673. /* 180 degree rotation is equivalent to
  178674. * 1. Vertical mirroring;
  178675. * 2. Horizontal mirroring.
  178676. * These two steps are merged into a single processing routine.
  178677. */
  178678. {
  178679. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178680. int ci, i, j, offset_y;
  178681. JBLOCKARRAY src_buffer, dst_buffer;
  178682. JBLOCKROW src_row_ptr, dst_row_ptr;
  178683. JCOEFPTR src_ptr, dst_ptr;
  178684. jpeg_component_info *compptr;
  178685. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178686. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178687. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178688. compptr = dstinfo->comp_info + ci;
  178689. comp_width = MCU_cols * compptr->h_samp_factor;
  178690. comp_height = MCU_rows * compptr->v_samp_factor;
  178691. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178692. dst_blk_y += compptr->v_samp_factor) {
  178693. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178694. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178695. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178696. if (dst_blk_y < comp_height) {
  178697. /* Row is within the vertically mirrorable area. */
  178698. src_buffer = (*srcinfo->mem->access_virt_barray)
  178699. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178700. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178701. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178702. } else {
  178703. /* Bottom-edge rows are only mirrored horizontally. */
  178704. src_buffer = (*srcinfo->mem->access_virt_barray)
  178705. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178706. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178707. }
  178708. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178709. if (dst_blk_y < comp_height) {
  178710. /* Row is within the mirrorable area. */
  178711. dst_row_ptr = dst_buffer[offset_y];
  178712. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178713. /* Process the blocks that can be mirrored both ways. */
  178714. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178715. dst_ptr = dst_row_ptr[dst_blk_x];
  178716. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178717. for (i = 0; i < DCTSIZE; i += 2) {
  178718. /* For even row, negate every odd column. */
  178719. for (j = 0; j < DCTSIZE; j += 2) {
  178720. *dst_ptr++ = *src_ptr++;
  178721. *dst_ptr++ = - *src_ptr++;
  178722. }
  178723. /* For odd row, negate every even column. */
  178724. for (j = 0; j < DCTSIZE; j += 2) {
  178725. *dst_ptr++ = - *src_ptr++;
  178726. *dst_ptr++ = *src_ptr++;
  178727. }
  178728. }
  178729. }
  178730. /* Any remaining right-edge blocks are only mirrored vertically. */
  178731. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178732. dst_ptr = dst_row_ptr[dst_blk_x];
  178733. src_ptr = src_row_ptr[dst_blk_x];
  178734. for (i = 0; i < DCTSIZE; i += 2) {
  178735. for (j = 0; j < DCTSIZE; j++)
  178736. *dst_ptr++ = *src_ptr++;
  178737. for (j = 0; j < DCTSIZE; j++)
  178738. *dst_ptr++ = - *src_ptr++;
  178739. }
  178740. }
  178741. } else {
  178742. /* Remaining rows are just mirrored horizontally. */
  178743. dst_row_ptr = dst_buffer[offset_y];
  178744. src_row_ptr = src_buffer[offset_y];
  178745. /* Process the blocks that can be mirrored. */
  178746. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178747. dst_ptr = dst_row_ptr[dst_blk_x];
  178748. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178749. for (i = 0; i < DCTSIZE2; i += 2) {
  178750. *dst_ptr++ = *src_ptr++;
  178751. *dst_ptr++ = - *src_ptr++;
  178752. }
  178753. }
  178754. /* Any remaining right-edge blocks are only copied. */
  178755. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178756. dst_ptr = dst_row_ptr[dst_blk_x];
  178757. src_ptr = src_row_ptr[dst_blk_x];
  178758. for (i = 0; i < DCTSIZE2; i++)
  178759. *dst_ptr++ = *src_ptr++;
  178760. }
  178761. }
  178762. }
  178763. }
  178764. }
  178765. }
  178766. LOCAL(void)
  178767. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178768. jvirt_barray_ptr *src_coef_arrays,
  178769. jvirt_barray_ptr *dst_coef_arrays)
  178770. /* Transverse transpose is equivalent to
  178771. * 1. 180 degree rotation;
  178772. * 2. Transposition;
  178773. * or
  178774. * 1. Horizontal mirroring;
  178775. * 2. Transposition;
  178776. * 3. Horizontal mirroring.
  178777. * These steps are merged into a single processing routine.
  178778. */
  178779. {
  178780. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178781. int ci, i, j, offset_x, offset_y;
  178782. JBLOCKARRAY src_buffer, dst_buffer;
  178783. JCOEFPTR src_ptr, dst_ptr;
  178784. jpeg_component_info *compptr;
  178785. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178786. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178787. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178788. compptr = dstinfo->comp_info + ci;
  178789. comp_width = MCU_cols * compptr->h_samp_factor;
  178790. comp_height = MCU_rows * compptr->v_samp_factor;
  178791. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178792. dst_blk_y += compptr->v_samp_factor) {
  178793. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178794. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178795. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178796. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178797. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178798. dst_blk_x += compptr->h_samp_factor) {
  178799. src_buffer = (*srcinfo->mem->access_virt_barray)
  178800. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178801. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178802. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178803. if (dst_blk_y < comp_height) {
  178804. src_ptr = src_buffer[offset_x]
  178805. [comp_height - dst_blk_y - offset_y - 1];
  178806. if (dst_blk_x < comp_width) {
  178807. /* Block is within the mirrorable area. */
  178808. dst_ptr = dst_buffer[offset_y]
  178809. [comp_width - dst_blk_x - offset_x - 1];
  178810. for (i = 0; i < DCTSIZE; i++) {
  178811. for (j = 0; j < DCTSIZE; j++) {
  178812. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178813. j++;
  178814. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178815. }
  178816. i++;
  178817. for (j = 0; j < DCTSIZE; j++) {
  178818. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178819. j++;
  178820. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178821. }
  178822. }
  178823. } else {
  178824. /* Right-edge blocks are mirrored in y only */
  178825. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178826. for (i = 0; i < DCTSIZE; i++) {
  178827. for (j = 0; j < DCTSIZE; j++) {
  178828. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178829. j++;
  178830. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178831. }
  178832. }
  178833. }
  178834. } else {
  178835. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178836. if (dst_blk_x < comp_width) {
  178837. /* Bottom-edge blocks are mirrored in x only */
  178838. dst_ptr = dst_buffer[offset_y]
  178839. [comp_width - dst_blk_x - offset_x - 1];
  178840. for (i = 0; i < DCTSIZE; i++) {
  178841. for (j = 0; j < DCTSIZE; j++)
  178842. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178843. i++;
  178844. for (j = 0; j < DCTSIZE; j++)
  178845. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178846. }
  178847. } else {
  178848. /* At lower right corner, just transpose, no mirroring */
  178849. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178850. for (i = 0; i < DCTSIZE; i++)
  178851. for (j = 0; j < DCTSIZE; j++)
  178852. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178853. }
  178854. }
  178855. }
  178856. }
  178857. }
  178858. }
  178859. }
  178860. }
  178861. /* Request any required workspace.
  178862. *
  178863. * We allocate the workspace virtual arrays from the source decompression
  178864. * object, so that all the arrays (both the original data and the workspace)
  178865. * will be taken into account while making memory management decisions.
  178866. * Hence, this routine must be called after jpeg_read_header (which reads
  178867. * the image dimensions) and before jpeg_read_coefficients (which realizes
  178868. * the source's virtual arrays).
  178869. */
  178870. GLOBAL(void)
  178871. jtransform_request_workspace (j_decompress_ptr srcinfo,
  178872. jpeg_transform_info *info)
  178873. {
  178874. jvirt_barray_ptr *coef_arrays = NULL;
  178875. jpeg_component_info *compptr;
  178876. int ci;
  178877. if (info->force_grayscale &&
  178878. srcinfo->jpeg_color_space == JCS_YCbCr &&
  178879. srcinfo->num_components == 3) {
  178880. /* We'll only process the first component */
  178881. info->num_components = 1;
  178882. } else {
  178883. /* Process all the components */
  178884. info->num_components = srcinfo->num_components;
  178885. }
  178886. switch (info->transform) {
  178887. case JXFORM_NONE:
  178888. case JXFORM_FLIP_H:
  178889. /* Don't need a workspace array */
  178890. break;
  178891. case JXFORM_FLIP_V:
  178892. case JXFORM_ROT_180:
  178893. /* Need workspace arrays having same dimensions as source image.
  178894. * Note that we allocate arrays padded out to the next iMCU boundary,
  178895. * so that transform routines need not worry about missing edge blocks.
  178896. */
  178897. coef_arrays = (jvirt_barray_ptr *)
  178898. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178899. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178900. for (ci = 0; ci < info->num_components; ci++) {
  178901. compptr = srcinfo->comp_info + ci;
  178902. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178903. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178904. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178905. (long) compptr->h_samp_factor),
  178906. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178907. (long) compptr->v_samp_factor),
  178908. (JDIMENSION) compptr->v_samp_factor);
  178909. }
  178910. break;
  178911. case JXFORM_TRANSPOSE:
  178912. case JXFORM_TRANSVERSE:
  178913. case JXFORM_ROT_90:
  178914. case JXFORM_ROT_270:
  178915. /* Need workspace arrays having transposed dimensions.
  178916. * Note that we allocate arrays padded out to the next iMCU boundary,
  178917. * so that transform routines need not worry about missing edge blocks.
  178918. */
  178919. coef_arrays = (jvirt_barray_ptr *)
  178920. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178921. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178922. for (ci = 0; ci < info->num_components; ci++) {
  178923. compptr = srcinfo->comp_info + ci;
  178924. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178925. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178926. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178927. (long) compptr->v_samp_factor),
  178928. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178929. (long) compptr->h_samp_factor),
  178930. (JDIMENSION) compptr->h_samp_factor);
  178931. }
  178932. break;
  178933. }
  178934. info->workspace_coef_arrays = coef_arrays;
  178935. }
  178936. /* Transpose destination image parameters */
  178937. LOCAL(void)
  178938. transpose_critical_parameters (j_compress_ptr dstinfo)
  178939. {
  178940. int tblno, i, j, ci, itemp;
  178941. jpeg_component_info *compptr;
  178942. JQUANT_TBL *qtblptr;
  178943. JDIMENSION dtemp;
  178944. UINT16 qtemp;
  178945. /* Transpose basic image dimensions */
  178946. dtemp = dstinfo->image_width;
  178947. dstinfo->image_width = dstinfo->image_height;
  178948. dstinfo->image_height = dtemp;
  178949. /* Transpose sampling factors */
  178950. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178951. compptr = dstinfo->comp_info + ci;
  178952. itemp = compptr->h_samp_factor;
  178953. compptr->h_samp_factor = compptr->v_samp_factor;
  178954. compptr->v_samp_factor = itemp;
  178955. }
  178956. /* Transpose quantization tables */
  178957. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  178958. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  178959. if (qtblptr != NULL) {
  178960. for (i = 0; i < DCTSIZE; i++) {
  178961. for (j = 0; j < i; j++) {
  178962. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  178963. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  178964. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  178965. }
  178966. }
  178967. }
  178968. }
  178969. }
  178970. /* Trim off any partial iMCUs on the indicated destination edge */
  178971. LOCAL(void)
  178972. trim_right_edge (j_compress_ptr dstinfo)
  178973. {
  178974. int ci, max_h_samp_factor;
  178975. JDIMENSION MCU_cols;
  178976. /* We have to compute max_h_samp_factor ourselves,
  178977. * because it hasn't been set yet in the destination
  178978. * (and we don't want to use the source's value).
  178979. */
  178980. max_h_samp_factor = 1;
  178981. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178982. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  178983. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  178984. }
  178985. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  178986. if (MCU_cols > 0) /* can't trim to 0 pixels */
  178987. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  178988. }
  178989. LOCAL(void)
  178990. trim_bottom_edge (j_compress_ptr dstinfo)
  178991. {
  178992. int ci, max_v_samp_factor;
  178993. JDIMENSION MCU_rows;
  178994. /* We have to compute max_v_samp_factor ourselves,
  178995. * because it hasn't been set yet in the destination
  178996. * (and we don't want to use the source's value).
  178997. */
  178998. max_v_samp_factor = 1;
  178999. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179000. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179001. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179002. }
  179003. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179004. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179005. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179006. }
  179007. /* Adjust output image parameters as needed.
  179008. *
  179009. * This must be called after jpeg_copy_critical_parameters()
  179010. * and before jpeg_write_coefficients().
  179011. *
  179012. * The return value is the set of virtual coefficient arrays to be written
  179013. * (either the ones allocated by jtransform_request_workspace, or the
  179014. * original source data arrays). The caller will need to pass this value
  179015. * to jpeg_write_coefficients().
  179016. */
  179017. GLOBAL(jvirt_barray_ptr *)
  179018. jtransform_adjust_parameters (j_decompress_ptr,
  179019. j_compress_ptr dstinfo,
  179020. jvirt_barray_ptr *src_coef_arrays,
  179021. jpeg_transform_info *info)
  179022. {
  179023. /* If force-to-grayscale is requested, adjust destination parameters */
  179024. if (info->force_grayscale) {
  179025. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179026. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179027. * will get set to 1, which typically won't match the source.
  179028. * In fact we do this even if the source is already grayscale; that
  179029. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179030. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179031. */
  179032. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179033. dstinfo->num_components == 3) ||
  179034. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179035. dstinfo->num_components == 1)) {
  179036. /* We have to preserve the source's quantization table number. */
  179037. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179038. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179039. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179040. } else {
  179041. /* Sorry, can't do it */
  179042. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179043. }
  179044. }
  179045. /* Correct the destination's image dimensions etc if necessary */
  179046. switch (info->transform) {
  179047. case JXFORM_NONE:
  179048. /* Nothing to do */
  179049. break;
  179050. case JXFORM_FLIP_H:
  179051. if (info->trim)
  179052. trim_right_edge(dstinfo);
  179053. break;
  179054. case JXFORM_FLIP_V:
  179055. if (info->trim)
  179056. trim_bottom_edge(dstinfo);
  179057. break;
  179058. case JXFORM_TRANSPOSE:
  179059. transpose_critical_parameters(dstinfo);
  179060. /* transpose does NOT have to trim anything */
  179061. break;
  179062. case JXFORM_TRANSVERSE:
  179063. transpose_critical_parameters(dstinfo);
  179064. if (info->trim) {
  179065. trim_right_edge(dstinfo);
  179066. trim_bottom_edge(dstinfo);
  179067. }
  179068. break;
  179069. case JXFORM_ROT_90:
  179070. transpose_critical_parameters(dstinfo);
  179071. if (info->trim)
  179072. trim_right_edge(dstinfo);
  179073. break;
  179074. case JXFORM_ROT_180:
  179075. if (info->trim) {
  179076. trim_right_edge(dstinfo);
  179077. trim_bottom_edge(dstinfo);
  179078. }
  179079. break;
  179080. case JXFORM_ROT_270:
  179081. transpose_critical_parameters(dstinfo);
  179082. if (info->trim)
  179083. trim_bottom_edge(dstinfo);
  179084. break;
  179085. }
  179086. /* Return the appropriate output data set */
  179087. if (info->workspace_coef_arrays != NULL)
  179088. return info->workspace_coef_arrays;
  179089. return src_coef_arrays;
  179090. }
  179091. /* Execute the actual transformation, if any.
  179092. *
  179093. * This must be called *after* jpeg_write_coefficients, because it depends
  179094. * on jpeg_write_coefficients to have computed subsidiary values such as
  179095. * the per-component width and height fields in the destination object.
  179096. *
  179097. * Note that some transformations will modify the source data arrays!
  179098. */
  179099. GLOBAL(void)
  179100. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179101. j_compress_ptr dstinfo,
  179102. jvirt_barray_ptr *src_coef_arrays,
  179103. jpeg_transform_info *info)
  179104. {
  179105. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179106. switch (info->transform) {
  179107. case JXFORM_NONE:
  179108. break;
  179109. case JXFORM_FLIP_H:
  179110. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179111. break;
  179112. case JXFORM_FLIP_V:
  179113. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179114. break;
  179115. case JXFORM_TRANSPOSE:
  179116. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179117. break;
  179118. case JXFORM_TRANSVERSE:
  179119. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179120. break;
  179121. case JXFORM_ROT_90:
  179122. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179123. break;
  179124. case JXFORM_ROT_180:
  179125. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179126. break;
  179127. case JXFORM_ROT_270:
  179128. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179129. break;
  179130. }
  179131. }
  179132. #endif /* TRANSFORMS_SUPPORTED */
  179133. /* Setup decompression object to save desired markers in memory.
  179134. * This must be called before jpeg_read_header() to have the desired effect.
  179135. */
  179136. GLOBAL(void)
  179137. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179138. {
  179139. #ifdef SAVE_MARKERS_SUPPORTED
  179140. int m;
  179141. /* Save comments except under NONE option */
  179142. if (option != JCOPYOPT_NONE) {
  179143. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179144. }
  179145. /* Save all types of APPn markers iff ALL option */
  179146. if (option == JCOPYOPT_ALL) {
  179147. for (m = 0; m < 16; m++)
  179148. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179149. }
  179150. #endif /* SAVE_MARKERS_SUPPORTED */
  179151. }
  179152. /* Copy markers saved in the given source object to the destination object.
  179153. * This should be called just after jpeg_start_compress() or
  179154. * jpeg_write_coefficients().
  179155. * Note that those routines will have written the SOI, and also the
  179156. * JFIF APP0 or Adobe APP14 markers if selected.
  179157. */
  179158. GLOBAL(void)
  179159. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179160. JCOPY_OPTION)
  179161. {
  179162. jpeg_saved_marker_ptr marker;
  179163. /* In the current implementation, we don't actually need to examine the
  179164. * option flag here; we just copy everything that got saved.
  179165. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179166. * if the encoder library already wrote one.
  179167. */
  179168. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179169. if (dstinfo->write_JFIF_header &&
  179170. marker->marker == JPEG_APP0 &&
  179171. marker->data_length >= 5 &&
  179172. GETJOCTET(marker->data[0]) == 0x4A &&
  179173. GETJOCTET(marker->data[1]) == 0x46 &&
  179174. GETJOCTET(marker->data[2]) == 0x49 &&
  179175. GETJOCTET(marker->data[3]) == 0x46 &&
  179176. GETJOCTET(marker->data[4]) == 0)
  179177. continue; /* reject duplicate JFIF */
  179178. if (dstinfo->write_Adobe_marker &&
  179179. marker->marker == JPEG_APP0+14 &&
  179180. marker->data_length >= 5 &&
  179181. GETJOCTET(marker->data[0]) == 0x41 &&
  179182. GETJOCTET(marker->data[1]) == 0x64 &&
  179183. GETJOCTET(marker->data[2]) == 0x6F &&
  179184. GETJOCTET(marker->data[3]) == 0x62 &&
  179185. GETJOCTET(marker->data[4]) == 0x65)
  179186. continue; /* reject duplicate Adobe */
  179187. #ifdef NEED_FAR_POINTERS
  179188. /* We could use jpeg_write_marker if the data weren't FAR... */
  179189. {
  179190. unsigned int i;
  179191. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179192. for (i = 0; i < marker->data_length; i++)
  179193. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179194. }
  179195. #else
  179196. jpeg_write_marker(dstinfo, marker->marker,
  179197. marker->data, marker->data_length);
  179198. #endif
  179199. }
  179200. }
  179201. /*** End of inlined file: transupp.c ***/
  179202. }
  179203. #else
  179204. #define JPEG_INTERNALS
  179205. #undef FAR
  179206. #include <jpeglib.h>
  179207. #endif
  179208. }
  179209. #undef max
  179210. #undef min
  179211. #if JUCE_MSVC
  179212. #pragma warning (pop)
  179213. #endif
  179214. BEGIN_JUCE_NAMESPACE
  179215. namespace JPEGHelpers
  179216. {
  179217. using namespace jpeglibNamespace;
  179218. #if ! JUCE_MSVC
  179219. using jpeglibNamespace::boolean;
  179220. #endif
  179221. struct JPEGDecodingFailure {};
  179222. static void fatalErrorHandler (j_common_ptr)
  179223. {
  179224. throw JPEGDecodingFailure();
  179225. }
  179226. static void silentErrorCallback1 (j_common_ptr) {}
  179227. static void silentErrorCallback2 (j_common_ptr, int) {}
  179228. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179229. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179230. {
  179231. zerostruct (err);
  179232. err.error_exit = fatalErrorHandler;
  179233. err.emit_message = silentErrorCallback2;
  179234. err.output_message = silentErrorCallback1;
  179235. err.format_message = silentErrorCallback3;
  179236. err.reset_error_mgr = silentErrorCallback1;
  179237. }
  179238. static void dummyCallback1 (j_decompress_ptr)
  179239. {
  179240. }
  179241. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179242. {
  179243. decompStruct->src->next_input_byte += num;
  179244. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179245. decompStruct->src->bytes_in_buffer -= num;
  179246. }
  179247. static boolean jpegFill (j_decompress_ptr)
  179248. {
  179249. return 0;
  179250. }
  179251. static const int jpegBufferSize = 512;
  179252. struct JuceJpegDest : public jpeg_destination_mgr
  179253. {
  179254. OutputStream* output;
  179255. char* buffer;
  179256. };
  179257. static void jpegWriteInit (j_compress_ptr)
  179258. {
  179259. }
  179260. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179261. {
  179262. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179263. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179264. dest->output->write (dest->buffer, (int) numToWrite);
  179265. }
  179266. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179267. {
  179268. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179269. const int numToWrite = jpegBufferSize;
  179270. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179271. dest->free_in_buffer = jpegBufferSize;
  179272. return dest->output->write (dest->buffer, numToWrite);
  179273. }
  179274. }
  179275. JPEGImageFormat::JPEGImageFormat()
  179276. : quality (-1.0f)
  179277. {
  179278. }
  179279. JPEGImageFormat::~JPEGImageFormat() {}
  179280. void JPEGImageFormat::setQuality (const float newQuality)
  179281. {
  179282. quality = newQuality;
  179283. }
  179284. const String JPEGImageFormat::getFormatName()
  179285. {
  179286. return "JPEG";
  179287. }
  179288. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179289. {
  179290. const int bytesNeeded = 10;
  179291. uint8 header [bytesNeeded];
  179292. if (in.read (header, bytesNeeded) == bytesNeeded)
  179293. {
  179294. return header[0] == 0xff
  179295. && header[1] == 0xd8
  179296. && header[2] == 0xff
  179297. && (header[3] == 0xe0 || header[3] == 0xe1);
  179298. }
  179299. return false;
  179300. }
  179301. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179302. {
  179303. using namespace jpeglibNamespace;
  179304. using namespace JPEGHelpers;
  179305. MemoryBlock mb;
  179306. in.readIntoMemoryBlock (mb);
  179307. Image image;
  179308. if (mb.getSize() > 16)
  179309. {
  179310. struct jpeg_decompress_struct jpegDecompStruct;
  179311. struct jpeg_error_mgr jerr;
  179312. setupSilentErrorHandler (jerr);
  179313. jpegDecompStruct.err = &jerr;
  179314. jpeg_create_decompress (&jpegDecompStruct);
  179315. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179316. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179317. jpegDecompStruct.src->init_source = dummyCallback1;
  179318. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179319. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179320. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179321. jpegDecompStruct.src->term_source = dummyCallback1;
  179322. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179323. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  179324. try
  179325. {
  179326. jpeg_read_header (&jpegDecompStruct, TRUE);
  179327. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179328. const int width = jpegDecompStruct.output_width;
  179329. const int height = jpegDecompStruct.output_height;
  179330. jpegDecompStruct.out_color_space = JCS_RGB;
  179331. JSAMPARRAY buffer
  179332. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179333. JPOOL_IMAGE,
  179334. width * 3, 1);
  179335. if (jpeg_start_decompress (&jpegDecompStruct))
  179336. {
  179337. image = Image (Image::RGB, width, height, false);
  179338. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179339. const Image::BitmapData destData (image, 0, 0, width, height, true);
  179340. for (int y = 0; y < height; ++y)
  179341. {
  179342. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179343. const uint8* src = *buffer;
  179344. uint8* dest = destData.getLinePointer (y);
  179345. if (hasAlphaChan)
  179346. {
  179347. for (int i = width; --i >= 0;)
  179348. {
  179349. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179350. ((PixelARGB*) dest)->premultiply();
  179351. dest += destData.pixelStride;
  179352. src += 3;
  179353. }
  179354. }
  179355. else
  179356. {
  179357. for (int i = width; --i >= 0;)
  179358. {
  179359. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179360. dest += destData.pixelStride;
  179361. src += 3;
  179362. }
  179363. }
  179364. }
  179365. jpeg_finish_decompress (&jpegDecompStruct);
  179366. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179367. }
  179368. jpeg_destroy_decompress (&jpegDecompStruct);
  179369. }
  179370. catch (...)
  179371. {}
  179372. }
  179373. return image;
  179374. }
  179375. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179376. {
  179377. using namespace jpeglibNamespace;
  179378. using namespace JPEGHelpers;
  179379. if (image.hasAlphaChannel())
  179380. {
  179381. // this method could fill the background in white and still save the image..
  179382. jassertfalse;
  179383. return true;
  179384. }
  179385. struct jpeg_compress_struct jpegCompStruct;
  179386. struct jpeg_error_mgr jerr;
  179387. setupSilentErrorHandler (jerr);
  179388. jpegCompStruct.err = &jerr;
  179389. jpeg_create_compress (&jpegCompStruct);
  179390. JuceJpegDest dest;
  179391. jpegCompStruct.dest = &dest;
  179392. dest.output = &out;
  179393. HeapBlock <char> tempBuffer (jpegBufferSize);
  179394. dest.buffer = tempBuffer;
  179395. dest.next_output_byte = (JOCTET*) dest.buffer;
  179396. dest.free_in_buffer = jpegBufferSize;
  179397. dest.init_destination = jpegWriteInit;
  179398. dest.empty_output_buffer = jpegWriteFlush;
  179399. dest.term_destination = jpegWriteTerminate;
  179400. jpegCompStruct.image_width = image.getWidth();
  179401. jpegCompStruct.image_height = image.getHeight();
  179402. jpegCompStruct.input_components = 3;
  179403. jpegCompStruct.in_color_space = JCS_RGB;
  179404. jpegCompStruct.write_JFIF_header = 1;
  179405. jpegCompStruct.X_density = 72;
  179406. jpegCompStruct.Y_density = 72;
  179407. jpeg_set_defaults (&jpegCompStruct);
  179408. jpegCompStruct.dct_method = JDCT_FLOAT;
  179409. jpegCompStruct.optimize_coding = 1;
  179410. //jpegCompStruct.smoothing_factor = 10;
  179411. if (quality < 0.0f)
  179412. quality = 0.85f;
  179413. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179414. jpeg_start_compress (&jpegCompStruct, TRUE);
  179415. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179416. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179417. JPOOL_IMAGE, strideBytes, 1);
  179418. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  179419. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179420. {
  179421. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179422. uint8* dst = *buffer;
  179423. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179424. {
  179425. *dst++ = ((const PixelRGB*) src)->getRed();
  179426. *dst++ = ((const PixelRGB*) src)->getGreen();
  179427. *dst++ = ((const PixelRGB*) src)->getBlue();
  179428. src += srcData.pixelStride;
  179429. }
  179430. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179431. }
  179432. jpeg_finish_compress (&jpegCompStruct);
  179433. jpeg_destroy_compress (&jpegCompStruct);
  179434. out.flush();
  179435. return true;
  179436. }
  179437. END_JUCE_NAMESPACE
  179438. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179439. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179440. #if JUCE_MSVC
  179441. #pragma warning (push)
  179442. #pragma warning (disable: 4390 4611)
  179443. #endif
  179444. namespace zlibNamespace
  179445. {
  179446. #if JUCE_INCLUDE_ZLIB_CODE
  179447. #undef OS_CODE
  179448. #undef fdopen
  179449. #undef OS_CODE
  179450. #else
  179451. #include <zlib.h>
  179452. #endif
  179453. }
  179454. namespace pnglibNamespace
  179455. {
  179456. using namespace zlibNamespace;
  179457. #if JUCE_INCLUDE_PNGLIB_CODE
  179458. #if _MSC_VER != 1310
  179459. using ::calloc; // (causes conflict in VS.NET 2003)
  179460. using ::malloc;
  179461. using ::free;
  179462. #endif
  179463. extern "C"
  179464. {
  179465. using ::abs;
  179466. #define PNG_INTERNAL
  179467. #define NO_DUMMY_DECL
  179468. #define PNG_SETJMP_NOT_SUPPORTED
  179469. /*** Start of inlined file: png.h ***/
  179470. /* png.h - header file for PNG reference library
  179471. *
  179472. * libpng version 1.2.21 - October 4, 2007
  179473. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179474. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179475. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179476. *
  179477. * Authors and maintainers:
  179478. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179479. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179480. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179481. * See also "Contributing Authors", below.
  179482. *
  179483. * Note about libpng version numbers:
  179484. *
  179485. * Due to various miscommunications, unforeseen code incompatibilities
  179486. * and occasional factors outside the authors' control, version numbering
  179487. * on the library has not always been consistent and straightforward.
  179488. * The following table summarizes matters since version 0.89c, which was
  179489. * the first widely used release:
  179490. *
  179491. * source png.h png.h shared-lib
  179492. * version string int version
  179493. * ------- ------ ----- ----------
  179494. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179495. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179496. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179497. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179498. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179499. * 0.97c 0.97 97 2.0.97
  179500. * 0.98 0.98 98 2.0.98
  179501. * 0.99 0.99 98 2.0.99
  179502. * 0.99a-m 0.99 99 2.0.99
  179503. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179504. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179505. * 1.0.1 png.h string is 10001 2.1.0
  179506. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179507. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179508. * 1.0.2a-b 10003 version, except as noted.
  179509. * 1.0.3 10003
  179510. * 1.0.3a-d 10004
  179511. * 1.0.4 10004
  179512. * 1.0.4a-f 10005
  179513. * 1.0.5 (+ 2 patches) 10005
  179514. * 1.0.5a-d 10006
  179515. * 1.0.5e-r 10100 (not source compatible)
  179516. * 1.0.5s-v 10006 (not binary compatible)
  179517. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179518. * 1.0.6d-f 10007 (still binary incompatible)
  179519. * 1.0.6g 10007
  179520. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179521. * 1.0.6i 10007 10.6i
  179522. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179523. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179524. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179525. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179526. * 1.0.7 1 10007 (still compatible)
  179527. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179528. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179529. * 1.0.8 1 10008 2.1.0.8
  179530. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179531. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179532. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179533. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179534. * 1.0.9 1 10009 2.1.0.9
  179535. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179536. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179537. * 1.0.10 1 10010 2.1.0.10
  179538. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179539. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179540. * 1.0.11 1 10011 2.1.0.11
  179541. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179542. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179543. * 1.0.12 2 10012 2.1.0.12
  179544. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179545. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179546. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179547. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179548. * 1.2.0 3 10200 3.1.2.0
  179549. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179550. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179551. * 1.2.1 3 10201 3.1.2.1
  179552. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179553. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179554. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179555. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179556. * 1.0.13 10 10013 10.so.0.1.0.13
  179557. * 1.2.2 12 10202 12.so.0.1.2.2
  179558. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179559. * 1.2.3 12 10203 12.so.0.1.2.3
  179560. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179561. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179562. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179563. * 1.0.14 10 10014 10.so.0.1.0.14
  179564. * 1.2.4 13 10204 12.so.0.1.2.4
  179565. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179566. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179567. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179568. * 1.0.15 10 10015 10.so.0.1.0.15
  179569. * 1.2.5 13 10205 12.so.0.1.2.5
  179570. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179571. * 1.0.16 10 10016 10.so.0.1.0.16
  179572. * 1.2.6 13 10206 12.so.0.1.2.6
  179573. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179574. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179575. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179576. * 1.0.17 10 10017 10.so.0.1.0.17
  179577. * 1.2.7 13 10207 12.so.0.1.2.7
  179578. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179579. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179580. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179581. * 1.0.18 10 10018 10.so.0.1.0.18
  179582. * 1.2.8 13 10208 12.so.0.1.2.8
  179583. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179584. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179585. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179586. * 1.2.9 13 10209 12.so.0.9[.0]
  179587. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179588. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179589. * 1.2.10 13 10210 12.so.0.10[.0]
  179590. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179591. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179592. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179593. * 1.0.19 10 10019 10.so.0.19[.0]
  179594. * 1.2.11 13 10211 12.so.0.11[.0]
  179595. * 1.0.20 10 10020 10.so.0.20[.0]
  179596. * 1.2.12 13 10212 12.so.0.12[.0]
  179597. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179598. * 1.0.21 10 10021 10.so.0.21[.0]
  179599. * 1.2.13 13 10213 12.so.0.13[.0]
  179600. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179601. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179602. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179603. * 1.0.22 10 10022 10.so.0.22[.0]
  179604. * 1.2.14 13 10214 12.so.0.14[.0]
  179605. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179606. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179607. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179608. * 1.0.23 10 10023 10.so.0.23[.0]
  179609. * 1.2.15 13 10215 12.so.0.15[.0]
  179610. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179611. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179612. * 1.0.24 10 10024 10.so.0.24[.0]
  179613. * 1.2.16 13 10216 12.so.0.16[.0]
  179614. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179615. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179616. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179617. * 1.0.25 10 10025 10.so.0.25[.0]
  179618. * 1.2.17 13 10217 12.so.0.17[.0]
  179619. * 1.0.26 10 10026 10.so.0.26[.0]
  179620. * 1.2.18 13 10218 12.so.0.18[.0]
  179621. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179622. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179623. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179624. * 1.0.27 10 10027 10.so.0.27[.0]
  179625. * 1.2.19 13 10219 12.so.0.19[.0]
  179626. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179627. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179628. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179629. * 1.0.28 10 10028 10.so.0.28[.0]
  179630. * 1.2.20 13 10220 12.so.0.20[.0]
  179631. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179632. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179633. * 1.0.29 10 10029 10.so.0.29[.0]
  179634. * 1.2.21 13 10221 12.so.0.21[.0]
  179635. *
  179636. * Henceforth the source version will match the shared-library major
  179637. * and minor numbers; the shared-library major version number will be
  179638. * used for changes in backward compatibility, as it is intended. The
  179639. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179640. * for applications, is an unsigned integer of the form xyyzz corresponding
  179641. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179642. * were given the previous public release number plus a letter, until
  179643. * version 1.0.6j; from then on they were given the upcoming public
  179644. * release number plus "betaNN" or "rcN".
  179645. *
  179646. * Binary incompatibility exists only when applications make direct access
  179647. * to the info_ptr or png_ptr members through png.h, and the compiled
  179648. * application is loaded with a different version of the library.
  179649. *
  179650. * DLLNUM will change each time there are forward or backward changes
  179651. * in binary compatibility (e.g., when a new feature is added).
  179652. *
  179653. * See libpng.txt or libpng.3 for more information. The PNG specification
  179654. * is available as a W3C Recommendation and as an ISO Specification,
  179655. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179656. */
  179657. /*
  179658. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179659. *
  179660. * If you modify libpng you may insert additional notices immediately following
  179661. * this sentence.
  179662. *
  179663. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179664. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179665. * distributed according to the same disclaimer and license as libpng-1.2.5
  179666. * with the following individual added to the list of Contributing Authors:
  179667. *
  179668. * Cosmin Truta
  179669. *
  179670. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179671. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179672. * distributed according to the same disclaimer and license as libpng-1.0.6
  179673. * with the following individuals added to the list of Contributing Authors:
  179674. *
  179675. * Simon-Pierre Cadieux
  179676. * Eric S. Raymond
  179677. * Gilles Vollant
  179678. *
  179679. * and with the following additions to the disclaimer:
  179680. *
  179681. * There is no warranty against interference with your enjoyment of the
  179682. * library or against infringement. There is no warranty that our
  179683. * efforts or the library will fulfill any of your particular purposes
  179684. * or needs. This library is provided with all faults, and the entire
  179685. * risk of satisfactory quality, performance, accuracy, and effort is with
  179686. * the user.
  179687. *
  179688. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179689. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179690. * distributed according to the same disclaimer and license as libpng-0.96,
  179691. * with the following individuals added to the list of Contributing Authors:
  179692. *
  179693. * Tom Lane
  179694. * Glenn Randers-Pehrson
  179695. * Willem van Schaik
  179696. *
  179697. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179698. * Copyright (c) 1996, 1997 Andreas Dilger
  179699. * Distributed according to the same disclaimer and license as libpng-0.88,
  179700. * with the following individuals added to the list of Contributing Authors:
  179701. *
  179702. * John Bowler
  179703. * Kevin Bracey
  179704. * Sam Bushell
  179705. * Magnus Holmgren
  179706. * Greg Roelofs
  179707. * Tom Tanner
  179708. *
  179709. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179710. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179711. *
  179712. * For the purposes of this copyright and license, "Contributing Authors"
  179713. * is defined as the following set of individuals:
  179714. *
  179715. * Andreas Dilger
  179716. * Dave Martindale
  179717. * Guy Eric Schalnat
  179718. * Paul Schmidt
  179719. * Tim Wegner
  179720. *
  179721. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179722. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179723. * including, without limitation, the warranties of merchantability and of
  179724. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179725. * assume no liability for direct, indirect, incidental, special, exemplary,
  179726. * or consequential damages, which may result from the use of the PNG
  179727. * Reference Library, even if advised of the possibility of such damage.
  179728. *
  179729. * Permission is hereby granted to use, copy, modify, and distribute this
  179730. * source code, or portions hereof, for any purpose, without fee, subject
  179731. * to the following restrictions:
  179732. *
  179733. * 1. The origin of this source code must not be misrepresented.
  179734. *
  179735. * 2. Altered versions must be plainly marked as such and
  179736. * must not be misrepresented as being the original source.
  179737. *
  179738. * 3. This Copyright notice may not be removed or altered from
  179739. * any source or altered source distribution.
  179740. *
  179741. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179742. * fee, and encourage the use of this source code as a component to
  179743. * supporting the PNG file format in commercial products. If you use this
  179744. * source code in a product, acknowledgment is not required but would be
  179745. * appreciated.
  179746. */
  179747. /*
  179748. * A "png_get_copyright" function is available, for convenient use in "about"
  179749. * boxes and the like:
  179750. *
  179751. * printf("%s",png_get_copyright(NULL));
  179752. *
  179753. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179754. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179755. */
  179756. /*
  179757. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179758. * certification mark of the Open Source Initiative.
  179759. */
  179760. /*
  179761. * The contributing authors would like to thank all those who helped
  179762. * with testing, bug fixes, and patience. This wouldn't have been
  179763. * possible without all of you.
  179764. *
  179765. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179766. */
  179767. /*
  179768. * Y2K compliance in libpng:
  179769. * =========================
  179770. *
  179771. * October 4, 2007
  179772. *
  179773. * Since the PNG Development group is an ad-hoc body, we can't make
  179774. * an official declaration.
  179775. *
  179776. * This is your unofficial assurance that libpng from version 0.71 and
  179777. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179778. * versions were also Y2K compliant.
  179779. *
  179780. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179781. * that will hold years up to 65535. The other two hold the date in text
  179782. * format, and will hold years up to 9999.
  179783. *
  179784. * The integer is
  179785. * "png_uint_16 year" in png_time_struct.
  179786. *
  179787. * The strings are
  179788. * "png_charp time_buffer" in png_struct and
  179789. * "near_time_buffer", which is a local character string in png.c.
  179790. *
  179791. * There are seven time-related functions:
  179792. * png.c: png_convert_to_rfc_1123() in png.c
  179793. * (formerly png_convert_to_rfc_1152() in error)
  179794. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179795. * png_convert_from_time_t() in pngwrite.c
  179796. * png_get_tIME() in pngget.c
  179797. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179798. * png_set_tIME() in pngset.c
  179799. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179800. *
  179801. * All handle dates properly in a Y2K environment. The
  179802. * png_convert_from_time_t() function calls gmtime() to convert from system
  179803. * clock time, which returns (year - 1900), which we properly convert to
  179804. * the full 4-digit year. There is a possibility that applications using
  179805. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179806. * function, or that they are incorrectly passing only a 2-digit year
  179807. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179808. * but this is not under our control. The libpng documentation has always
  179809. * stated that it works with 4-digit years, and the APIs have been
  179810. * documented as such.
  179811. *
  179812. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179813. * integer to hold the year, and can hold years as large as 65535.
  179814. *
  179815. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179816. * no date-related code.
  179817. *
  179818. * Glenn Randers-Pehrson
  179819. * libpng maintainer
  179820. * PNG Development Group
  179821. */
  179822. #ifndef PNG_H
  179823. #define PNG_H
  179824. /* This is not the place to learn how to use libpng. The file libpng.txt
  179825. * describes how to use libpng, and the file example.c summarizes it
  179826. * with some code on which to build. This file is useful for looking
  179827. * at the actual function definitions and structure components.
  179828. */
  179829. /* Version information for png.h - this should match the version in png.c */
  179830. #define PNG_LIBPNG_VER_STRING "1.2.21"
  179831. #define PNG_HEADER_VERSION_STRING \
  179832. " libpng version 1.2.21 - October 4, 2007\n"
  179833. #define PNG_LIBPNG_VER_SONUM 0
  179834. #define PNG_LIBPNG_VER_DLLNUM 13
  179835. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  179836. #define PNG_LIBPNG_VER_MAJOR 1
  179837. #define PNG_LIBPNG_VER_MINOR 2
  179838. #define PNG_LIBPNG_VER_RELEASE 21
  179839. /* This should match the numeric part of the final component of
  179840. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  179841. #define PNG_LIBPNG_VER_BUILD 0
  179842. /* Release Status */
  179843. #define PNG_LIBPNG_BUILD_ALPHA 1
  179844. #define PNG_LIBPNG_BUILD_BETA 2
  179845. #define PNG_LIBPNG_BUILD_RC 3
  179846. #define PNG_LIBPNG_BUILD_STABLE 4
  179847. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  179848. /* Release-Specific Flags */
  179849. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  179850. PNG_LIBPNG_BUILD_STABLE only */
  179851. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  179852. PNG_LIBPNG_BUILD_SPECIAL */
  179853. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  179854. PNG_LIBPNG_BUILD_PRIVATE */
  179855. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  179856. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  179857. * We must not include leading zeros.
  179858. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  179859. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  179860. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  179861. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  179862. #ifndef PNG_VERSION_INFO_ONLY
  179863. /* include the compression library's header */
  179864. #endif
  179865. /* include all user configurable info, including optional assembler routines */
  179866. /*** Start of inlined file: pngconf.h ***/
  179867. /* pngconf.h - machine configurable file for libpng
  179868. *
  179869. * libpng version 1.2.21 - October 4, 2007
  179870. * For conditions of distribution and use, see copyright notice in png.h
  179871. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179872. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179873. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179874. */
  179875. /* Any machine specific code is near the front of this file, so if you
  179876. * are configuring libpng for a machine, you may want to read the section
  179877. * starting here down to where it starts to typedef png_color, png_text,
  179878. * and png_info.
  179879. */
  179880. #ifndef PNGCONF_H
  179881. #define PNGCONF_H
  179882. #define PNG_1_2_X
  179883. // These are some Juce config settings that should remove any unnecessary code bloat..
  179884. #define PNG_NO_STDIO 1
  179885. #define PNG_DEBUG 0
  179886. #define PNG_NO_WARNINGS 1
  179887. #define PNG_NO_ERROR_TEXT 1
  179888. #define PNG_NO_ERROR_NUMBERS 1
  179889. #define PNG_NO_USER_MEM 1
  179890. #define PNG_NO_READ_iCCP 1
  179891. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  179892. #define PNG_NO_READ_USER_CHUNKS 1
  179893. #define PNG_NO_READ_iTXt 1
  179894. #define PNG_NO_READ_sCAL 1
  179895. #define PNG_NO_READ_sPLT 1
  179896. #define png_error(a, b) png_err(a)
  179897. #define png_warning(a, b)
  179898. #define png_chunk_error(a, b) png_err(a)
  179899. #define png_chunk_warning(a, b)
  179900. /*
  179901. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  179902. * includes the resource compiler for Windows DLL configurations.
  179903. */
  179904. #ifdef PNG_USER_CONFIG
  179905. # ifndef PNG_USER_PRIVATEBUILD
  179906. # define PNG_USER_PRIVATEBUILD
  179907. # endif
  179908. #include "pngusr.h"
  179909. #endif
  179910. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  179911. #ifdef PNG_CONFIGURE_LIBPNG
  179912. #ifdef HAVE_CONFIG_H
  179913. #include "config.h"
  179914. #endif
  179915. #endif
  179916. /*
  179917. * Added at libpng-1.2.8
  179918. *
  179919. * If you create a private DLL you need to define in "pngusr.h" the followings:
  179920. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  179921. * the DLL was built>
  179922. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  179923. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  179924. * distinguish your DLL from those of the official release. These
  179925. * correspond to the trailing letters that come after the version
  179926. * number and must match your private DLL name>
  179927. * e.g. // private DLL "libpng13gx.dll"
  179928. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  179929. *
  179930. * The following macros are also at your disposal if you want to complete the
  179931. * DLL VERSIONINFO structure.
  179932. * - PNG_USER_VERSIONINFO_COMMENTS
  179933. * - PNG_USER_VERSIONINFO_COMPANYNAME
  179934. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  179935. */
  179936. #ifdef __STDC__
  179937. #ifdef SPECIALBUILD
  179938. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  179939. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  179940. #endif
  179941. #ifdef PRIVATEBUILD
  179942. # pragma message("PRIVATEBUILD is deprecated.\
  179943. Use PNG_USER_PRIVATEBUILD instead.")
  179944. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  179945. #endif
  179946. #endif /* __STDC__ */
  179947. #ifndef PNG_VERSION_INFO_ONLY
  179948. /* End of material added to libpng-1.2.8 */
  179949. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  179950. Restored at libpng-1.2.21 */
  179951. # define PNG_WARN_UNINITIALIZED_ROW 1
  179952. /* End of material added at libpng-1.2.19/1.2.21 */
  179953. /* This is the size of the compression buffer, and thus the size of
  179954. * an IDAT chunk. Make this whatever size you feel is best for your
  179955. * machine. One of these will be allocated per png_struct. When this
  179956. * is full, it writes the data to the disk, and does some other
  179957. * calculations. Making this an extremely small size will slow
  179958. * the library down, but you may want to experiment to determine
  179959. * where it becomes significant, if you are concerned with memory
  179960. * usage. Note that zlib allocates at least 32Kb also. For readers,
  179961. * this describes the size of the buffer available to read the data in.
  179962. * Unless this gets smaller than the size of a row (compressed),
  179963. * it should not make much difference how big this is.
  179964. */
  179965. #ifndef PNG_ZBUF_SIZE
  179966. # define PNG_ZBUF_SIZE 8192
  179967. #endif
  179968. /* Enable if you want a write-only libpng */
  179969. #ifndef PNG_NO_READ_SUPPORTED
  179970. # define PNG_READ_SUPPORTED
  179971. #endif
  179972. /* Enable if you want a read-only libpng */
  179973. #ifndef PNG_NO_WRITE_SUPPORTED
  179974. # define PNG_WRITE_SUPPORTED
  179975. #endif
  179976. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  179977. support PNGs that are embedded in MNG datastreams */
  179978. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  179979. # ifndef PNG_MNG_FEATURES_SUPPORTED
  179980. # define PNG_MNG_FEATURES_SUPPORTED
  179981. # endif
  179982. #endif
  179983. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  179984. # ifndef PNG_FLOATING_POINT_SUPPORTED
  179985. # define PNG_FLOATING_POINT_SUPPORTED
  179986. # endif
  179987. #endif
  179988. /* If you are running on a machine where you cannot allocate more
  179989. * than 64K of memory at once, uncomment this. While libpng will not
  179990. * normally need that much memory in a chunk (unless you load up a very
  179991. * large file), zlib needs to know how big of a chunk it can use, and
  179992. * libpng thus makes sure to check any memory allocation to verify it
  179993. * will fit into memory.
  179994. #define PNG_MAX_MALLOC_64K
  179995. */
  179996. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  179997. # define PNG_MAX_MALLOC_64K
  179998. #endif
  179999. /* Special munging to support doing things the 'cygwin' way:
  180000. * 'Normal' png-on-win32 defines/defaults:
  180001. * PNG_BUILD_DLL -- building dll
  180002. * PNG_USE_DLL -- building an application, linking to dll
  180003. * (no define) -- building static library, or building an
  180004. * application and linking to the static lib
  180005. * 'Cygwin' defines/defaults:
  180006. * PNG_BUILD_DLL -- (ignored) building the dll
  180007. * (no define) -- (ignored) building an application, linking to the dll
  180008. * PNG_STATIC -- (ignored) building the static lib, or building an
  180009. * application that links to the static lib.
  180010. * ALL_STATIC -- (ignored) building various static libs, or building an
  180011. * application that links to the static libs.
  180012. * Thus,
  180013. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180014. * this bit of #ifdefs will define the 'correct' config variables based on
  180015. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180016. * unnecessary.
  180017. *
  180018. * Also, the precedence order is:
  180019. * ALL_STATIC (since we can't #undef something outside our namespace)
  180020. * PNG_BUILD_DLL
  180021. * PNG_STATIC
  180022. * (nothing) == PNG_USE_DLL
  180023. *
  180024. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180025. * of auto-import in binutils, we no longer need to worry about
  180026. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180027. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180028. * to __declspec() stuff. However, we DO need to worry about
  180029. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180030. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180031. */
  180032. #if defined(__CYGWIN__)
  180033. # if defined(ALL_STATIC)
  180034. # if defined(PNG_BUILD_DLL)
  180035. # undef PNG_BUILD_DLL
  180036. # endif
  180037. # if defined(PNG_USE_DLL)
  180038. # undef PNG_USE_DLL
  180039. # endif
  180040. # if defined(PNG_DLL)
  180041. # undef PNG_DLL
  180042. # endif
  180043. # if !defined(PNG_STATIC)
  180044. # define PNG_STATIC
  180045. # endif
  180046. # else
  180047. # if defined (PNG_BUILD_DLL)
  180048. # if defined(PNG_STATIC)
  180049. # undef PNG_STATIC
  180050. # endif
  180051. # if defined(PNG_USE_DLL)
  180052. # undef PNG_USE_DLL
  180053. # endif
  180054. # if !defined(PNG_DLL)
  180055. # define PNG_DLL
  180056. # endif
  180057. # else
  180058. # if defined(PNG_STATIC)
  180059. # if defined(PNG_USE_DLL)
  180060. # undef PNG_USE_DLL
  180061. # endif
  180062. # if defined(PNG_DLL)
  180063. # undef PNG_DLL
  180064. # endif
  180065. # else
  180066. # if !defined(PNG_USE_DLL)
  180067. # define PNG_USE_DLL
  180068. # endif
  180069. # if !defined(PNG_DLL)
  180070. # define PNG_DLL
  180071. # endif
  180072. # endif
  180073. # endif
  180074. # endif
  180075. #endif
  180076. /* This protects us against compilers that run on a windowing system
  180077. * and thus don't have or would rather us not use the stdio types:
  180078. * stdin, stdout, and stderr. The only one currently used is stderr
  180079. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180080. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180081. * will also prevent these, plus will prevent the entire set of stdio
  180082. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180083. * unless (PNG_DEBUG > 0) has been #defined.
  180084. *
  180085. * #define PNG_NO_CONSOLE_IO
  180086. * #define PNG_NO_STDIO
  180087. */
  180088. #if defined(_WIN32_WCE)
  180089. # include <windows.h>
  180090. /* Console I/O functions are not supported on WindowsCE */
  180091. # define PNG_NO_CONSOLE_IO
  180092. # ifdef PNG_DEBUG
  180093. # undef PNG_DEBUG
  180094. # endif
  180095. #endif
  180096. #ifdef PNG_BUILD_DLL
  180097. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180098. # ifndef PNG_NO_CONSOLE_IO
  180099. # define PNG_NO_CONSOLE_IO
  180100. # endif
  180101. # endif
  180102. #endif
  180103. # ifdef PNG_NO_STDIO
  180104. # ifndef PNG_NO_CONSOLE_IO
  180105. # define PNG_NO_CONSOLE_IO
  180106. # endif
  180107. # ifdef PNG_DEBUG
  180108. # if (PNG_DEBUG > 0)
  180109. # include <stdio.h>
  180110. # endif
  180111. # endif
  180112. # else
  180113. # if !defined(_WIN32_WCE)
  180114. /* "stdio.h" functions are not supported on WindowsCE */
  180115. # include <stdio.h>
  180116. # endif
  180117. # endif
  180118. /* This macro protects us against machines that don't have function
  180119. * prototypes (ie K&R style headers). If your compiler does not handle
  180120. * function prototypes, define this macro and use the included ansi2knr.
  180121. * I've always been able to use _NO_PROTO as the indicator, but you may
  180122. * need to drag the empty declaration out in front of here, or change the
  180123. * ifdef to suit your own needs.
  180124. */
  180125. #ifndef PNGARG
  180126. #ifdef OF /* zlib prototype munger */
  180127. # define PNGARG(arglist) OF(arglist)
  180128. #else
  180129. #ifdef _NO_PROTO
  180130. # define PNGARG(arglist) ()
  180131. # ifndef PNG_TYPECAST_NULL
  180132. # define PNG_TYPECAST_NULL
  180133. # endif
  180134. #else
  180135. # define PNGARG(arglist) arglist
  180136. #endif /* _NO_PROTO */
  180137. #endif /* OF */
  180138. #endif /* PNGARG */
  180139. /* Try to determine if we are compiling on a Mac. Note that testing for
  180140. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180141. * on non-Mac platforms.
  180142. */
  180143. #ifndef MACOS
  180144. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180145. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180146. # define MACOS
  180147. # endif
  180148. #endif
  180149. /* enough people need this for various reasons to include it here */
  180150. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180151. # include <sys/types.h>
  180152. #endif
  180153. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180154. # define PNG_SETJMP_SUPPORTED
  180155. #endif
  180156. #ifdef PNG_SETJMP_SUPPORTED
  180157. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180158. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180159. */
  180160. # ifdef __linux__
  180161. # ifdef _BSD_SOURCE
  180162. # define PNG_SAVE_BSD_SOURCE
  180163. # undef _BSD_SOURCE
  180164. # endif
  180165. # ifdef _SETJMP_H
  180166. /* If you encounter a compiler error here, see the explanation
  180167. * near the end of INSTALL.
  180168. */
  180169. __png.h__ already includes setjmp.h;
  180170. __dont__ include it again.;
  180171. # endif
  180172. # endif /* __linux__ */
  180173. /* include setjmp.h for error handling */
  180174. # include <setjmp.h>
  180175. # ifdef __linux__
  180176. # ifdef PNG_SAVE_BSD_SOURCE
  180177. # define _BSD_SOURCE
  180178. # undef PNG_SAVE_BSD_SOURCE
  180179. # endif
  180180. # endif /* __linux__ */
  180181. #endif /* PNG_SETJMP_SUPPORTED */
  180182. #ifdef BSD
  180183. #if ! JUCE_MAC
  180184. # include <strings.h>
  180185. #endif
  180186. #else
  180187. # include <string.h>
  180188. #endif
  180189. /* Other defines for things like memory and the like can go here. */
  180190. #ifdef PNG_INTERNAL
  180191. #include <stdlib.h>
  180192. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180193. * aren't usually used outside the library (as far as I know), so it is
  180194. * debatable if they should be exported at all. In the future, when it is
  180195. * possible to have run-time registry of chunk-handling functions, some of
  180196. * these will be made available again.
  180197. #define PNG_EXTERN extern
  180198. */
  180199. #define PNG_EXTERN
  180200. /* Other defines specific to compilers can go here. Try to keep
  180201. * them inside an appropriate ifdef/endif pair for portability.
  180202. */
  180203. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180204. # if defined(MACOS)
  180205. /* We need to check that <math.h> hasn't already been included earlier
  180206. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180207. * <fp.h> if possible.
  180208. */
  180209. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180210. # include <fp.h>
  180211. # endif
  180212. # else
  180213. # include <math.h>
  180214. # endif
  180215. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180216. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180217. * MATH=68881
  180218. */
  180219. # include <m68881.h>
  180220. # endif
  180221. #endif
  180222. /* Codewarrior on NT has linking problems without this. */
  180223. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180224. # define PNG_ALWAYS_EXTERN
  180225. #endif
  180226. /* This provides the non-ANSI (far) memory allocation routines. */
  180227. #if defined(__TURBOC__) && defined(__MSDOS__)
  180228. # include <mem.h>
  180229. # include <alloc.h>
  180230. #endif
  180231. /* I have no idea why is this necessary... */
  180232. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180233. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180234. # include <malloc.h>
  180235. #endif
  180236. /* This controls how fine the dithering gets. As this allocates
  180237. * a largish chunk of memory (32K), those who are not as concerned
  180238. * with dithering quality can decrease some or all of these.
  180239. */
  180240. #ifndef PNG_DITHER_RED_BITS
  180241. # define PNG_DITHER_RED_BITS 5
  180242. #endif
  180243. #ifndef PNG_DITHER_GREEN_BITS
  180244. # define PNG_DITHER_GREEN_BITS 5
  180245. #endif
  180246. #ifndef PNG_DITHER_BLUE_BITS
  180247. # define PNG_DITHER_BLUE_BITS 5
  180248. #endif
  180249. /* This controls how fine the gamma correction becomes when you
  180250. * are only interested in 8 bits anyway. Increasing this value
  180251. * results in more memory being used, and more pow() functions
  180252. * being called to fill in the gamma tables. Don't set this value
  180253. * less then 8, and even that may not work (I haven't tested it).
  180254. */
  180255. #ifndef PNG_MAX_GAMMA_8
  180256. # define PNG_MAX_GAMMA_8 11
  180257. #endif
  180258. /* This controls how much a difference in gamma we can tolerate before
  180259. * we actually start doing gamma conversion.
  180260. */
  180261. #ifndef PNG_GAMMA_THRESHOLD
  180262. # define PNG_GAMMA_THRESHOLD 0.05
  180263. #endif
  180264. #endif /* PNG_INTERNAL */
  180265. /* The following uses const char * instead of char * for error
  180266. * and warning message functions, so some compilers won't complain.
  180267. * If you do not want to use const, define PNG_NO_CONST here.
  180268. */
  180269. #ifndef PNG_NO_CONST
  180270. # define PNG_CONST const
  180271. #else
  180272. # define PNG_CONST
  180273. #endif
  180274. /* The following defines give you the ability to remove code from the
  180275. * library that you will not be using. I wish I could figure out how to
  180276. * automate this, but I can't do that without making it seriously hard
  180277. * on the users. So if you are not using an ability, change the #define
  180278. * to and #undef, and that part of the library will not be compiled. If
  180279. * your linker can't find a function, you may want to make sure the
  180280. * ability is defined here. Some of these depend upon some others being
  180281. * defined. I haven't figured out all the interactions here, so you may
  180282. * have to experiment awhile to get everything to compile. If you are
  180283. * creating or using a shared library, you probably shouldn't touch this,
  180284. * as it will affect the size of the structures, and this will cause bad
  180285. * things to happen if the library and/or application ever change.
  180286. */
  180287. /* Any features you will not be using can be undef'ed here */
  180288. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180289. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180290. * on the compile line, then pick and choose which ones to define without
  180291. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180292. * if you only want to have a png-compliant reader/writer but don't need
  180293. * any of the extra transformations. This saves about 80 kbytes in a
  180294. * typical installation of the library. (PNG_NO_* form added in version
  180295. * 1.0.1c, for consistency)
  180296. */
  180297. /* The size of the png_text structure changed in libpng-1.0.6 when
  180298. * iTXt support was added. iTXt support was turned off by default through
  180299. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180300. * instead of calling png_set_text() and letting libpng malloc it. It
  180301. * was turned on by default in libpng-1.3.0.
  180302. */
  180303. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180304. # ifndef PNG_NO_iTXt_SUPPORTED
  180305. # define PNG_NO_iTXt_SUPPORTED
  180306. # endif
  180307. # ifndef PNG_NO_READ_iTXt
  180308. # define PNG_NO_READ_iTXt
  180309. # endif
  180310. # ifndef PNG_NO_WRITE_iTXt
  180311. # define PNG_NO_WRITE_iTXt
  180312. # endif
  180313. #endif
  180314. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180315. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180316. # define PNG_READ_iTXt
  180317. # endif
  180318. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180319. # define PNG_WRITE_iTXt
  180320. # endif
  180321. #endif
  180322. /* The following support, added after version 1.0.0, can be turned off here en
  180323. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180324. * with old applications that require the length of png_struct and png_info
  180325. * to remain unchanged.
  180326. */
  180327. #ifdef PNG_LEGACY_SUPPORTED
  180328. # define PNG_NO_FREE_ME
  180329. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180330. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180331. # define PNG_NO_READ_USER_CHUNKS
  180332. # define PNG_NO_READ_iCCP
  180333. # define PNG_NO_WRITE_iCCP
  180334. # define PNG_NO_READ_iTXt
  180335. # define PNG_NO_WRITE_iTXt
  180336. # define PNG_NO_READ_sCAL
  180337. # define PNG_NO_WRITE_sCAL
  180338. # define PNG_NO_READ_sPLT
  180339. # define PNG_NO_WRITE_sPLT
  180340. # define PNG_NO_INFO_IMAGE
  180341. # define PNG_NO_READ_RGB_TO_GRAY
  180342. # define PNG_NO_READ_USER_TRANSFORM
  180343. # define PNG_NO_WRITE_USER_TRANSFORM
  180344. # define PNG_NO_USER_MEM
  180345. # define PNG_NO_READ_EMPTY_PLTE
  180346. # define PNG_NO_MNG_FEATURES
  180347. # define PNG_NO_FIXED_POINT_SUPPORTED
  180348. #endif
  180349. /* Ignore attempt to turn off both floating and fixed point support */
  180350. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180351. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180352. # define PNG_FIXED_POINT_SUPPORTED
  180353. #endif
  180354. #ifndef PNG_NO_FREE_ME
  180355. # define PNG_FREE_ME_SUPPORTED
  180356. #endif
  180357. #if defined(PNG_READ_SUPPORTED)
  180358. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180359. !defined(PNG_NO_READ_TRANSFORMS)
  180360. # define PNG_READ_TRANSFORMS_SUPPORTED
  180361. #endif
  180362. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180363. # ifndef PNG_NO_READ_EXPAND
  180364. # define PNG_READ_EXPAND_SUPPORTED
  180365. # endif
  180366. # ifndef PNG_NO_READ_SHIFT
  180367. # define PNG_READ_SHIFT_SUPPORTED
  180368. # endif
  180369. # ifndef PNG_NO_READ_PACK
  180370. # define PNG_READ_PACK_SUPPORTED
  180371. # endif
  180372. # ifndef PNG_NO_READ_BGR
  180373. # define PNG_READ_BGR_SUPPORTED
  180374. # endif
  180375. # ifndef PNG_NO_READ_SWAP
  180376. # define PNG_READ_SWAP_SUPPORTED
  180377. # endif
  180378. # ifndef PNG_NO_READ_PACKSWAP
  180379. # define PNG_READ_PACKSWAP_SUPPORTED
  180380. # endif
  180381. # ifndef PNG_NO_READ_INVERT
  180382. # define PNG_READ_INVERT_SUPPORTED
  180383. # endif
  180384. # ifndef PNG_NO_READ_DITHER
  180385. # define PNG_READ_DITHER_SUPPORTED
  180386. # endif
  180387. # ifndef PNG_NO_READ_BACKGROUND
  180388. # define PNG_READ_BACKGROUND_SUPPORTED
  180389. # endif
  180390. # ifndef PNG_NO_READ_16_TO_8
  180391. # define PNG_READ_16_TO_8_SUPPORTED
  180392. # endif
  180393. # ifndef PNG_NO_READ_FILLER
  180394. # define PNG_READ_FILLER_SUPPORTED
  180395. # endif
  180396. # ifndef PNG_NO_READ_GAMMA
  180397. # define PNG_READ_GAMMA_SUPPORTED
  180398. # endif
  180399. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180400. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180401. # endif
  180402. # ifndef PNG_NO_READ_SWAP_ALPHA
  180403. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180404. # endif
  180405. # ifndef PNG_NO_READ_INVERT_ALPHA
  180406. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180407. # endif
  180408. # ifndef PNG_NO_READ_STRIP_ALPHA
  180409. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180410. # endif
  180411. # ifndef PNG_NO_READ_USER_TRANSFORM
  180412. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180413. # endif
  180414. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180415. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180416. # endif
  180417. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180418. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180419. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180420. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180421. #endif /* about interlacing capability! You'll */
  180422. /* still have interlacing unless you change the following line: */
  180423. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180424. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180425. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180426. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180427. # endif
  180428. #endif
  180429. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180430. /* Deprecated, will be removed from version 2.0.0.
  180431. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180432. #ifndef PNG_NO_READ_EMPTY_PLTE
  180433. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180434. #endif
  180435. #endif
  180436. #endif /* PNG_READ_SUPPORTED */
  180437. #if defined(PNG_WRITE_SUPPORTED)
  180438. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180439. !defined(PNG_NO_WRITE_TRANSFORMS)
  180440. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180441. #endif
  180442. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180443. # ifndef PNG_NO_WRITE_SHIFT
  180444. # define PNG_WRITE_SHIFT_SUPPORTED
  180445. # endif
  180446. # ifndef PNG_NO_WRITE_PACK
  180447. # define PNG_WRITE_PACK_SUPPORTED
  180448. # endif
  180449. # ifndef PNG_NO_WRITE_BGR
  180450. # define PNG_WRITE_BGR_SUPPORTED
  180451. # endif
  180452. # ifndef PNG_NO_WRITE_SWAP
  180453. # define PNG_WRITE_SWAP_SUPPORTED
  180454. # endif
  180455. # ifndef PNG_NO_WRITE_PACKSWAP
  180456. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180457. # endif
  180458. # ifndef PNG_NO_WRITE_INVERT
  180459. # define PNG_WRITE_INVERT_SUPPORTED
  180460. # endif
  180461. # ifndef PNG_NO_WRITE_FILLER
  180462. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180463. # endif
  180464. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180465. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180466. # endif
  180467. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180468. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180469. # endif
  180470. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180471. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180472. # endif
  180473. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180474. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180475. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180476. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180477. encoders, but can cause trouble
  180478. if left undefined */
  180479. #endif
  180480. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180481. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180482. defined(PNG_FLOATING_POINT_SUPPORTED)
  180483. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180484. #endif
  180485. #ifndef PNG_NO_WRITE_FLUSH
  180486. # define PNG_WRITE_FLUSH_SUPPORTED
  180487. #endif
  180488. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180489. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180490. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180491. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180492. #endif
  180493. #endif
  180494. #endif /* PNG_WRITE_SUPPORTED */
  180495. #ifndef PNG_1_0_X
  180496. # ifndef PNG_NO_ERROR_NUMBERS
  180497. # define PNG_ERROR_NUMBERS_SUPPORTED
  180498. # endif
  180499. #endif /* PNG_1_0_X */
  180500. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180501. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180502. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180503. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180504. # endif
  180505. #endif
  180506. #ifndef PNG_NO_STDIO
  180507. # define PNG_TIME_RFC1123_SUPPORTED
  180508. #endif
  180509. /* This adds extra functions in pngget.c for accessing data from the
  180510. * info pointer (added in version 0.99)
  180511. * png_get_image_width()
  180512. * png_get_image_height()
  180513. * png_get_bit_depth()
  180514. * png_get_color_type()
  180515. * png_get_compression_type()
  180516. * png_get_filter_type()
  180517. * png_get_interlace_type()
  180518. * png_get_pixel_aspect_ratio()
  180519. * png_get_pixels_per_meter()
  180520. * png_get_x_offset_pixels()
  180521. * png_get_y_offset_pixels()
  180522. * png_get_x_offset_microns()
  180523. * png_get_y_offset_microns()
  180524. */
  180525. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180526. # define PNG_EASY_ACCESS_SUPPORTED
  180527. #endif
  180528. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180529. * and removed from version 1.2.20. The following will be removed
  180530. * from libpng-1.4.0
  180531. */
  180532. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180533. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180534. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180535. # endif
  180536. #endif
  180537. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180538. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180539. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180540. # endif
  180541. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180542. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180543. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180544. # define PNG_NO_MMX_CODE
  180545. # endif
  180546. # endif
  180547. # if defined(__APPLE__)
  180548. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180549. # define PNG_NO_MMX_CODE
  180550. # endif
  180551. # endif
  180552. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180553. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180554. # define PNG_NO_MMX_CODE
  180555. # endif
  180556. # endif
  180557. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180558. # define PNG_MMX_CODE_SUPPORTED
  180559. # endif
  180560. #endif
  180561. /* end of obsolete code to be removed from libpng-1.4.0 */
  180562. #if !defined(PNG_1_0_X)
  180563. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180564. # define PNG_USER_MEM_SUPPORTED
  180565. #endif
  180566. #endif /* PNG_1_0_X */
  180567. /* Added at libpng-1.2.6 */
  180568. #if !defined(PNG_1_0_X)
  180569. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180570. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180571. # define PNG_SET_USER_LIMITS_SUPPORTED
  180572. #endif
  180573. #endif
  180574. #endif /* PNG_1_0_X */
  180575. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180576. * how large, set these limits to 0x7fffffffL
  180577. */
  180578. #ifndef PNG_USER_WIDTH_MAX
  180579. # define PNG_USER_WIDTH_MAX 1000000L
  180580. #endif
  180581. #ifndef PNG_USER_HEIGHT_MAX
  180582. # define PNG_USER_HEIGHT_MAX 1000000L
  180583. #endif
  180584. /* These are currently experimental features, define them if you want */
  180585. /* very little testing */
  180586. /*
  180587. #ifdef PNG_READ_SUPPORTED
  180588. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180589. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180590. # endif
  180591. #endif
  180592. */
  180593. /* This is only for PowerPC big-endian and 680x0 systems */
  180594. /* some testing */
  180595. /*
  180596. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180597. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180598. #endif
  180599. */
  180600. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180601. /*
  180602. #define PNG_NO_POINTER_INDEXING
  180603. */
  180604. /* These functions are turned off by default, as they will be phased out. */
  180605. /*
  180606. #define PNG_USELESS_TESTS_SUPPORTED
  180607. #define PNG_CORRECT_PALETTE_SUPPORTED
  180608. */
  180609. /* Any chunks you are not interested in, you can undef here. The
  180610. * ones that allocate memory may be expecially important (hIST,
  180611. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180612. * a bit smaller.
  180613. */
  180614. #if defined(PNG_READ_SUPPORTED) && \
  180615. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180616. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180617. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180618. #endif
  180619. #if defined(PNG_WRITE_SUPPORTED) && \
  180620. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180621. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180622. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180623. #endif
  180624. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180625. #ifdef PNG_NO_READ_TEXT
  180626. # define PNG_NO_READ_iTXt
  180627. # define PNG_NO_READ_tEXt
  180628. # define PNG_NO_READ_zTXt
  180629. #endif
  180630. #ifndef PNG_NO_READ_bKGD
  180631. # define PNG_READ_bKGD_SUPPORTED
  180632. # define PNG_bKGD_SUPPORTED
  180633. #endif
  180634. #ifndef PNG_NO_READ_cHRM
  180635. # define PNG_READ_cHRM_SUPPORTED
  180636. # define PNG_cHRM_SUPPORTED
  180637. #endif
  180638. #ifndef PNG_NO_READ_gAMA
  180639. # define PNG_READ_gAMA_SUPPORTED
  180640. # define PNG_gAMA_SUPPORTED
  180641. #endif
  180642. #ifndef PNG_NO_READ_hIST
  180643. # define PNG_READ_hIST_SUPPORTED
  180644. # define PNG_hIST_SUPPORTED
  180645. #endif
  180646. #ifndef PNG_NO_READ_iCCP
  180647. # define PNG_READ_iCCP_SUPPORTED
  180648. # define PNG_iCCP_SUPPORTED
  180649. #endif
  180650. #ifndef PNG_NO_READ_iTXt
  180651. # ifndef PNG_READ_iTXt_SUPPORTED
  180652. # define PNG_READ_iTXt_SUPPORTED
  180653. # endif
  180654. # ifndef PNG_iTXt_SUPPORTED
  180655. # define PNG_iTXt_SUPPORTED
  180656. # endif
  180657. #endif
  180658. #ifndef PNG_NO_READ_oFFs
  180659. # define PNG_READ_oFFs_SUPPORTED
  180660. # define PNG_oFFs_SUPPORTED
  180661. #endif
  180662. #ifndef PNG_NO_READ_pCAL
  180663. # define PNG_READ_pCAL_SUPPORTED
  180664. # define PNG_pCAL_SUPPORTED
  180665. #endif
  180666. #ifndef PNG_NO_READ_sCAL
  180667. # define PNG_READ_sCAL_SUPPORTED
  180668. # define PNG_sCAL_SUPPORTED
  180669. #endif
  180670. #ifndef PNG_NO_READ_pHYs
  180671. # define PNG_READ_pHYs_SUPPORTED
  180672. # define PNG_pHYs_SUPPORTED
  180673. #endif
  180674. #ifndef PNG_NO_READ_sBIT
  180675. # define PNG_READ_sBIT_SUPPORTED
  180676. # define PNG_sBIT_SUPPORTED
  180677. #endif
  180678. #ifndef PNG_NO_READ_sPLT
  180679. # define PNG_READ_sPLT_SUPPORTED
  180680. # define PNG_sPLT_SUPPORTED
  180681. #endif
  180682. #ifndef PNG_NO_READ_sRGB
  180683. # define PNG_READ_sRGB_SUPPORTED
  180684. # define PNG_sRGB_SUPPORTED
  180685. #endif
  180686. #ifndef PNG_NO_READ_tEXt
  180687. # define PNG_READ_tEXt_SUPPORTED
  180688. # define PNG_tEXt_SUPPORTED
  180689. #endif
  180690. #ifndef PNG_NO_READ_tIME
  180691. # define PNG_READ_tIME_SUPPORTED
  180692. # define PNG_tIME_SUPPORTED
  180693. #endif
  180694. #ifndef PNG_NO_READ_tRNS
  180695. # define PNG_READ_tRNS_SUPPORTED
  180696. # define PNG_tRNS_SUPPORTED
  180697. #endif
  180698. #ifndef PNG_NO_READ_zTXt
  180699. # define PNG_READ_zTXt_SUPPORTED
  180700. # define PNG_zTXt_SUPPORTED
  180701. #endif
  180702. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180703. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180704. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180705. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180706. # endif
  180707. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180708. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180709. # endif
  180710. #endif
  180711. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180712. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180713. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180714. # define PNG_USER_CHUNKS_SUPPORTED
  180715. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180716. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180717. # endif
  180718. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180719. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180720. # endif
  180721. #endif
  180722. #ifndef PNG_NO_READ_OPT_PLTE
  180723. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180724. #endif /* optional PLTE chunk in RGB and RGBA images */
  180725. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180726. defined(PNG_READ_zTXt_SUPPORTED)
  180727. # define PNG_READ_TEXT_SUPPORTED
  180728. # define PNG_TEXT_SUPPORTED
  180729. #endif
  180730. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180731. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180732. #ifdef PNG_NO_WRITE_TEXT
  180733. # define PNG_NO_WRITE_iTXt
  180734. # define PNG_NO_WRITE_tEXt
  180735. # define PNG_NO_WRITE_zTXt
  180736. #endif
  180737. #ifndef PNG_NO_WRITE_bKGD
  180738. # define PNG_WRITE_bKGD_SUPPORTED
  180739. # ifndef PNG_bKGD_SUPPORTED
  180740. # define PNG_bKGD_SUPPORTED
  180741. # endif
  180742. #endif
  180743. #ifndef PNG_NO_WRITE_cHRM
  180744. # define PNG_WRITE_cHRM_SUPPORTED
  180745. # ifndef PNG_cHRM_SUPPORTED
  180746. # define PNG_cHRM_SUPPORTED
  180747. # endif
  180748. #endif
  180749. #ifndef PNG_NO_WRITE_gAMA
  180750. # define PNG_WRITE_gAMA_SUPPORTED
  180751. # ifndef PNG_gAMA_SUPPORTED
  180752. # define PNG_gAMA_SUPPORTED
  180753. # endif
  180754. #endif
  180755. #ifndef PNG_NO_WRITE_hIST
  180756. # define PNG_WRITE_hIST_SUPPORTED
  180757. # ifndef PNG_hIST_SUPPORTED
  180758. # define PNG_hIST_SUPPORTED
  180759. # endif
  180760. #endif
  180761. #ifndef PNG_NO_WRITE_iCCP
  180762. # define PNG_WRITE_iCCP_SUPPORTED
  180763. # ifndef PNG_iCCP_SUPPORTED
  180764. # define PNG_iCCP_SUPPORTED
  180765. # endif
  180766. #endif
  180767. #ifndef PNG_NO_WRITE_iTXt
  180768. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180769. # define PNG_WRITE_iTXt_SUPPORTED
  180770. # endif
  180771. # ifndef PNG_iTXt_SUPPORTED
  180772. # define PNG_iTXt_SUPPORTED
  180773. # endif
  180774. #endif
  180775. #ifndef PNG_NO_WRITE_oFFs
  180776. # define PNG_WRITE_oFFs_SUPPORTED
  180777. # ifndef PNG_oFFs_SUPPORTED
  180778. # define PNG_oFFs_SUPPORTED
  180779. # endif
  180780. #endif
  180781. #ifndef PNG_NO_WRITE_pCAL
  180782. # define PNG_WRITE_pCAL_SUPPORTED
  180783. # ifndef PNG_pCAL_SUPPORTED
  180784. # define PNG_pCAL_SUPPORTED
  180785. # endif
  180786. #endif
  180787. #ifndef PNG_NO_WRITE_sCAL
  180788. # define PNG_WRITE_sCAL_SUPPORTED
  180789. # ifndef PNG_sCAL_SUPPORTED
  180790. # define PNG_sCAL_SUPPORTED
  180791. # endif
  180792. #endif
  180793. #ifndef PNG_NO_WRITE_pHYs
  180794. # define PNG_WRITE_pHYs_SUPPORTED
  180795. # ifndef PNG_pHYs_SUPPORTED
  180796. # define PNG_pHYs_SUPPORTED
  180797. # endif
  180798. #endif
  180799. #ifndef PNG_NO_WRITE_sBIT
  180800. # define PNG_WRITE_sBIT_SUPPORTED
  180801. # ifndef PNG_sBIT_SUPPORTED
  180802. # define PNG_sBIT_SUPPORTED
  180803. # endif
  180804. #endif
  180805. #ifndef PNG_NO_WRITE_sPLT
  180806. # define PNG_WRITE_sPLT_SUPPORTED
  180807. # ifndef PNG_sPLT_SUPPORTED
  180808. # define PNG_sPLT_SUPPORTED
  180809. # endif
  180810. #endif
  180811. #ifndef PNG_NO_WRITE_sRGB
  180812. # define PNG_WRITE_sRGB_SUPPORTED
  180813. # ifndef PNG_sRGB_SUPPORTED
  180814. # define PNG_sRGB_SUPPORTED
  180815. # endif
  180816. #endif
  180817. #ifndef PNG_NO_WRITE_tEXt
  180818. # define PNG_WRITE_tEXt_SUPPORTED
  180819. # ifndef PNG_tEXt_SUPPORTED
  180820. # define PNG_tEXt_SUPPORTED
  180821. # endif
  180822. #endif
  180823. #ifndef PNG_NO_WRITE_tIME
  180824. # define PNG_WRITE_tIME_SUPPORTED
  180825. # ifndef PNG_tIME_SUPPORTED
  180826. # define PNG_tIME_SUPPORTED
  180827. # endif
  180828. #endif
  180829. #ifndef PNG_NO_WRITE_tRNS
  180830. # define PNG_WRITE_tRNS_SUPPORTED
  180831. # ifndef PNG_tRNS_SUPPORTED
  180832. # define PNG_tRNS_SUPPORTED
  180833. # endif
  180834. #endif
  180835. #ifndef PNG_NO_WRITE_zTXt
  180836. # define PNG_WRITE_zTXt_SUPPORTED
  180837. # ifndef PNG_zTXt_SUPPORTED
  180838. # define PNG_zTXt_SUPPORTED
  180839. # endif
  180840. #endif
  180841. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  180842. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  180843. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180844. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180845. # endif
  180846. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180847. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180848. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180849. # endif
  180850. # endif
  180851. #endif
  180852. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  180853. defined(PNG_WRITE_zTXt_SUPPORTED)
  180854. # define PNG_WRITE_TEXT_SUPPORTED
  180855. # ifndef PNG_TEXT_SUPPORTED
  180856. # define PNG_TEXT_SUPPORTED
  180857. # endif
  180858. #endif
  180859. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  180860. /* Turn this off to disable png_read_png() and
  180861. * png_write_png() and leave the row_pointers member
  180862. * out of the info structure.
  180863. */
  180864. #ifndef PNG_NO_INFO_IMAGE
  180865. # define PNG_INFO_IMAGE_SUPPORTED
  180866. #endif
  180867. /* need the time information for reading tIME chunks */
  180868. #if defined(PNG_tIME_SUPPORTED)
  180869. # if !defined(_WIN32_WCE)
  180870. /* "time.h" functions are not supported on WindowsCE */
  180871. # include <time.h>
  180872. # endif
  180873. #endif
  180874. /* Some typedefs to get us started. These should be safe on most of the
  180875. * common platforms. The typedefs should be at least as large as the
  180876. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  180877. * don't have to be exactly that size. Some compilers dislike passing
  180878. * unsigned shorts as function parameters, so you may be better off using
  180879. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  180880. * want to have unsigned int for png_uint_32 instead of unsigned long.
  180881. */
  180882. typedef unsigned long png_uint_32;
  180883. typedef long png_int_32;
  180884. typedef unsigned short png_uint_16;
  180885. typedef short png_int_16;
  180886. typedef unsigned char png_byte;
  180887. /* This is usually size_t. It is typedef'ed just in case you need it to
  180888. change (I'm not sure if you will or not, so I thought I'd be safe) */
  180889. #ifdef PNG_SIZE_T
  180890. typedef PNG_SIZE_T png_size_t;
  180891. # define png_sizeof(x) png_convert_size(sizeof (x))
  180892. #else
  180893. typedef size_t png_size_t;
  180894. # define png_sizeof(x) sizeof (x)
  180895. #endif
  180896. /* The following is needed for medium model support. It cannot be in the
  180897. * PNG_INTERNAL section. Needs modification for other compilers besides
  180898. * MSC. Model independent support declares all arrays and pointers to be
  180899. * large using the far keyword. The zlib version used must also support
  180900. * model independent data. As of version zlib 1.0.4, the necessary changes
  180901. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  180902. * changes that are needed. (Tim Wegner)
  180903. */
  180904. /* Separate compiler dependencies (problem here is that zlib.h always
  180905. defines FAR. (SJT) */
  180906. #ifdef __BORLANDC__
  180907. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  180908. # define LDATA 1
  180909. # else
  180910. # define LDATA 0
  180911. # endif
  180912. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  180913. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  180914. # define PNG_MAX_MALLOC_64K
  180915. # if (LDATA != 1)
  180916. # ifndef FAR
  180917. # define FAR __far
  180918. # endif
  180919. # define USE_FAR_KEYWORD
  180920. # endif /* LDATA != 1 */
  180921. /* Possibly useful for moving data out of default segment.
  180922. * Uncomment it if you want. Could also define FARDATA as
  180923. * const if your compiler supports it. (SJT)
  180924. # define FARDATA FAR
  180925. */
  180926. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  180927. #endif /* __BORLANDC__ */
  180928. /* Suggest testing for specific compiler first before testing for
  180929. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  180930. * making reliance oncertain keywords suspect. (SJT)
  180931. */
  180932. /* MSC Medium model */
  180933. #if defined(FAR)
  180934. # if defined(M_I86MM)
  180935. # define USE_FAR_KEYWORD
  180936. # define FARDATA FAR
  180937. # include <dos.h>
  180938. # endif
  180939. #endif
  180940. /* SJT: default case */
  180941. #ifndef FAR
  180942. # define FAR
  180943. #endif
  180944. /* At this point FAR is always defined */
  180945. #ifndef FARDATA
  180946. # define FARDATA
  180947. #endif
  180948. /* Typedef for floating-point numbers that are converted
  180949. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  180950. typedef png_int_32 png_fixed_point;
  180951. /* Add typedefs for pointers */
  180952. typedef void FAR * png_voidp;
  180953. typedef png_byte FAR * png_bytep;
  180954. typedef png_uint_32 FAR * png_uint_32p;
  180955. typedef png_int_32 FAR * png_int_32p;
  180956. typedef png_uint_16 FAR * png_uint_16p;
  180957. typedef png_int_16 FAR * png_int_16p;
  180958. typedef PNG_CONST char FAR * png_const_charp;
  180959. typedef char FAR * png_charp;
  180960. typedef png_fixed_point FAR * png_fixed_point_p;
  180961. #ifndef PNG_NO_STDIO
  180962. #if defined(_WIN32_WCE)
  180963. typedef HANDLE png_FILE_p;
  180964. #else
  180965. typedef FILE * png_FILE_p;
  180966. #endif
  180967. #endif
  180968. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180969. typedef double FAR * png_doublep;
  180970. #endif
  180971. /* Pointers to pointers; i.e. arrays */
  180972. typedef png_byte FAR * FAR * png_bytepp;
  180973. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  180974. typedef png_int_32 FAR * FAR * png_int_32pp;
  180975. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  180976. typedef png_int_16 FAR * FAR * png_int_16pp;
  180977. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  180978. typedef char FAR * FAR * png_charpp;
  180979. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  180980. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180981. typedef double FAR * FAR * png_doublepp;
  180982. #endif
  180983. /* Pointers to pointers to pointers; i.e., pointer to array */
  180984. typedef char FAR * FAR * FAR * png_charppp;
  180985. #if 0
  180986. /* SPC - Is this stuff deprecated? */
  180987. /* It'll be removed as of libpng-1.3.0 - GR-P */
  180988. /* libpng typedefs for types in zlib. If zlib changes
  180989. * or another compression library is used, then change these.
  180990. * Eliminates need to change all the source files.
  180991. */
  180992. typedef charf * png_zcharp;
  180993. typedef charf * FAR * png_zcharpp;
  180994. typedef z_stream FAR * png_zstreamp;
  180995. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  180996. /*
  180997. * Define PNG_BUILD_DLL if the module being built is a Windows
  180998. * LIBPNG DLL.
  180999. *
  181000. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181001. * It is equivalent to Microsoft predefined macro _DLL that is
  181002. * automatically defined when you compile using the share
  181003. * version of the CRT (C Run-Time library)
  181004. *
  181005. * The cygwin mods make this behavior a little different:
  181006. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181007. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181008. * -or- if you are building an application that you want to link to the
  181009. * static library.
  181010. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181011. * the other flags is defined.
  181012. */
  181013. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181014. # define PNG_DLL
  181015. #endif
  181016. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181017. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181018. * command-line override
  181019. */
  181020. #if defined(__CYGWIN__)
  181021. # if !defined(PNG_STATIC)
  181022. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181023. # undef PNG_USE_GLOBAL_ARRAYS
  181024. # endif
  181025. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181026. # define PNG_USE_LOCAL_ARRAYS
  181027. # endif
  181028. # else
  181029. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181030. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181031. # undef PNG_USE_GLOBAL_ARRAYS
  181032. # endif
  181033. # endif
  181034. # endif
  181035. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181036. # define PNG_USE_LOCAL_ARRAYS
  181037. # endif
  181038. #endif
  181039. /* Do not use global arrays (helps with building DLL's)
  181040. * They are no longer used in libpng itself, since version 1.0.5c,
  181041. * but might be required for some pre-1.0.5c applications.
  181042. */
  181043. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181044. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181045. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181046. # define PNG_USE_LOCAL_ARRAYS
  181047. # else
  181048. # define PNG_USE_GLOBAL_ARRAYS
  181049. # endif
  181050. #endif
  181051. #if defined(__CYGWIN__)
  181052. # undef PNGAPI
  181053. # define PNGAPI __cdecl
  181054. # undef PNG_IMPEXP
  181055. # define PNG_IMPEXP
  181056. #endif
  181057. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181058. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181059. * Don't ignore those warnings; you must also reset the default calling
  181060. * convention in your compiler to match your PNGAPI, and you must build
  181061. * zlib and your applications the same way you build libpng.
  181062. */
  181063. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181064. # ifndef PNG_NO_MODULEDEF
  181065. # define PNG_NO_MODULEDEF
  181066. # endif
  181067. #endif
  181068. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181069. # define PNG_IMPEXP
  181070. #endif
  181071. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181072. (( defined(_Windows) || defined(_WINDOWS) || \
  181073. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181074. # ifndef PNGAPI
  181075. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181076. # define PNGAPI __cdecl
  181077. # else
  181078. # define PNGAPI _cdecl
  181079. # endif
  181080. # endif
  181081. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181082. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181083. # define PNG_IMPEXP
  181084. # endif
  181085. # if !defined(PNG_IMPEXP)
  181086. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181087. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181088. /* Borland/Microsoft */
  181089. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181090. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181091. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181092. # else
  181093. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181094. # if defined(PNG_BUILD_DLL)
  181095. # define PNG_IMPEXP __export
  181096. # else
  181097. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181098. VC++ */
  181099. # endif /* Exists in Borland C++ for
  181100. C++ classes (== huge) */
  181101. # endif
  181102. # endif
  181103. # if !defined(PNG_IMPEXP)
  181104. # if defined(PNG_BUILD_DLL)
  181105. # define PNG_IMPEXP __declspec(dllexport)
  181106. # else
  181107. # define PNG_IMPEXP __declspec(dllimport)
  181108. # endif
  181109. # endif
  181110. # endif /* PNG_IMPEXP */
  181111. #else /* !(DLL || non-cygwin WINDOWS) */
  181112. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181113. # ifndef PNGAPI
  181114. # define PNGAPI _System
  181115. # endif
  181116. # else
  181117. # if 0 /* ... other platforms, with other meanings */
  181118. # endif
  181119. # endif
  181120. #endif
  181121. #ifndef PNGAPI
  181122. # define PNGAPI
  181123. #endif
  181124. #ifndef PNG_IMPEXP
  181125. # define PNG_IMPEXP
  181126. #endif
  181127. #ifdef PNG_BUILDSYMS
  181128. # ifndef PNG_EXPORT
  181129. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181130. # endif
  181131. # ifdef PNG_USE_GLOBAL_ARRAYS
  181132. # ifndef PNG_EXPORT_VAR
  181133. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181134. # endif
  181135. # endif
  181136. #endif
  181137. #ifndef PNG_EXPORT
  181138. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181139. #endif
  181140. #ifdef PNG_USE_GLOBAL_ARRAYS
  181141. # ifndef PNG_EXPORT_VAR
  181142. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181143. # endif
  181144. #endif
  181145. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181146. * functions that are passed far data must be model independent.
  181147. */
  181148. #ifndef PNG_ABORT
  181149. # define PNG_ABORT() abort()
  181150. #endif
  181151. #ifdef PNG_SETJMP_SUPPORTED
  181152. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181153. #else
  181154. # define png_jmpbuf(png_ptr) \
  181155. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181156. #endif
  181157. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181158. /* use this to make far-to-near assignments */
  181159. # define CHECK 1
  181160. # define NOCHECK 0
  181161. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181162. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181163. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181164. # define png_strcpy _fstrcpy
  181165. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181166. # define png_strlen _fstrlen
  181167. # define png_memcmp _fmemcmp /* SJT: added */
  181168. # define png_memcpy _fmemcpy
  181169. # define png_memset _fmemset
  181170. #else /* use the usual functions */
  181171. # define CVT_PTR(ptr) (ptr)
  181172. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181173. # ifndef PNG_NO_SNPRINTF
  181174. # ifdef _MSC_VER
  181175. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181176. # define png_snprintf2 _snprintf
  181177. # define png_snprintf6 _snprintf
  181178. # else
  181179. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181180. # define png_snprintf2 snprintf
  181181. # define png_snprintf6 snprintf
  181182. # endif
  181183. # else
  181184. /* You don't have or don't want to use snprintf(). Caution: Using
  181185. * sprintf instead of snprintf exposes your application to accidental
  181186. * or malevolent buffer overflows. If you don't have snprintf()
  181187. * as a general rule you should provide one (you can get one from
  181188. * Portable OpenSSH). */
  181189. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181190. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181191. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181192. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181193. # endif
  181194. # define png_strcpy strcpy
  181195. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181196. # define png_strlen strlen
  181197. # define png_memcmp memcmp /* SJT: added */
  181198. # define png_memcpy memcpy
  181199. # define png_memset memset
  181200. #endif
  181201. /* End of memory model independent support */
  181202. /* Just a little check that someone hasn't tried to define something
  181203. * contradictory.
  181204. */
  181205. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181206. # undef PNG_ZBUF_SIZE
  181207. # define PNG_ZBUF_SIZE 65536L
  181208. #endif
  181209. /* Added at libpng-1.2.8 */
  181210. #endif /* PNG_VERSION_INFO_ONLY */
  181211. #endif /* PNGCONF_H */
  181212. /*** End of inlined file: pngconf.h ***/
  181213. #ifdef _MSC_VER
  181214. #pragma warning (disable: 4996 4100)
  181215. #endif
  181216. /*
  181217. * Added at libpng-1.2.8 */
  181218. /* Ref MSDN: Private as priority over Special
  181219. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181220. * procedures. If this value is given, the StringFileInfo block must
  181221. * contain a PrivateBuild string.
  181222. *
  181223. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181224. * standard release procedures but is a variation of the standard
  181225. * file of the same version number. If this value is given, the
  181226. * StringFileInfo block must contain a SpecialBuild string.
  181227. */
  181228. #if defined(PNG_USER_PRIVATEBUILD)
  181229. # define PNG_LIBPNG_BUILD_TYPE \
  181230. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181231. #else
  181232. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181233. # define PNG_LIBPNG_BUILD_TYPE \
  181234. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181235. # else
  181236. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181237. # endif
  181238. #endif
  181239. #ifndef PNG_VERSION_INFO_ONLY
  181240. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181241. #ifdef __cplusplus
  181242. extern "C" {
  181243. #endif /* __cplusplus */
  181244. /* This file is arranged in several sections. The first section contains
  181245. * structure and type definitions. The second section contains the external
  181246. * library functions, while the third has the internal library functions,
  181247. * which applications aren't expected to use directly.
  181248. */
  181249. #ifndef PNG_NO_TYPECAST_NULL
  181250. #define int_p_NULL (int *)NULL
  181251. #define png_bytep_NULL (png_bytep)NULL
  181252. #define png_bytepp_NULL (png_bytepp)NULL
  181253. #define png_doublep_NULL (png_doublep)NULL
  181254. #define png_error_ptr_NULL (png_error_ptr)NULL
  181255. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181256. #define png_free_ptr_NULL (png_free_ptr)NULL
  181257. #define png_infopp_NULL (png_infopp)NULL
  181258. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181259. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181260. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181261. #define png_structp_NULL (png_structp)NULL
  181262. #define png_uint_16p_NULL (png_uint_16p)NULL
  181263. #define png_voidp_NULL (png_voidp)NULL
  181264. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181265. #else
  181266. #define int_p_NULL NULL
  181267. #define png_bytep_NULL NULL
  181268. #define png_bytepp_NULL NULL
  181269. #define png_doublep_NULL NULL
  181270. #define png_error_ptr_NULL NULL
  181271. #define png_flush_ptr_NULL NULL
  181272. #define png_free_ptr_NULL NULL
  181273. #define png_infopp_NULL NULL
  181274. #define png_malloc_ptr_NULL NULL
  181275. #define png_read_status_ptr_NULL NULL
  181276. #define png_rw_ptr_NULL NULL
  181277. #define png_structp_NULL NULL
  181278. #define png_uint_16p_NULL NULL
  181279. #define png_voidp_NULL NULL
  181280. #define png_write_status_ptr_NULL NULL
  181281. #endif
  181282. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181283. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181284. /* Version information for C files, stored in png.c. This had better match
  181285. * the version above.
  181286. */
  181287. #ifdef PNG_USE_GLOBAL_ARRAYS
  181288. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181289. /* need room for 99.99.99beta99z */
  181290. #else
  181291. #define png_libpng_ver png_get_header_ver(NULL)
  181292. #endif
  181293. #ifdef PNG_USE_GLOBAL_ARRAYS
  181294. /* This was removed in version 1.0.5c */
  181295. /* Structures to facilitate easy interlacing. See png.c for more details */
  181296. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181297. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181298. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181299. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181300. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181301. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181302. /* This isn't currently used. If you need it, see png.c for more details.
  181303. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181304. */
  181305. #endif
  181306. #endif /* PNG_NO_EXTERN */
  181307. /* Three color definitions. The order of the red, green, and blue, (and the
  181308. * exact size) is not important, although the size of the fields need to
  181309. * be png_byte or png_uint_16 (as defined below).
  181310. */
  181311. typedef struct png_color_struct
  181312. {
  181313. png_byte red;
  181314. png_byte green;
  181315. png_byte blue;
  181316. } png_color;
  181317. typedef png_color FAR * png_colorp;
  181318. typedef png_color FAR * FAR * png_colorpp;
  181319. typedef struct png_color_16_struct
  181320. {
  181321. png_byte index; /* used for palette files */
  181322. png_uint_16 red; /* for use in red green blue files */
  181323. png_uint_16 green;
  181324. png_uint_16 blue;
  181325. png_uint_16 gray; /* for use in grayscale files */
  181326. } png_color_16;
  181327. typedef png_color_16 FAR * png_color_16p;
  181328. typedef png_color_16 FAR * FAR * png_color_16pp;
  181329. typedef struct png_color_8_struct
  181330. {
  181331. png_byte red; /* for use in red green blue files */
  181332. png_byte green;
  181333. png_byte blue;
  181334. png_byte gray; /* for use in grayscale files */
  181335. png_byte alpha; /* for alpha channel files */
  181336. } png_color_8;
  181337. typedef png_color_8 FAR * png_color_8p;
  181338. typedef png_color_8 FAR * FAR * png_color_8pp;
  181339. /*
  181340. * The following two structures are used for the in-core representation
  181341. * of sPLT chunks.
  181342. */
  181343. typedef struct png_sPLT_entry_struct
  181344. {
  181345. png_uint_16 red;
  181346. png_uint_16 green;
  181347. png_uint_16 blue;
  181348. png_uint_16 alpha;
  181349. png_uint_16 frequency;
  181350. } png_sPLT_entry;
  181351. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181352. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181353. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181354. * occupy the LSB of their respective members, and the MSB of each member
  181355. * is zero-filled. The frequency member always occupies the full 16 bits.
  181356. */
  181357. typedef struct png_sPLT_struct
  181358. {
  181359. png_charp name; /* palette name */
  181360. png_byte depth; /* depth of palette samples */
  181361. png_sPLT_entryp entries; /* palette entries */
  181362. png_int_32 nentries; /* number of palette entries */
  181363. } png_sPLT_t;
  181364. typedef png_sPLT_t FAR * png_sPLT_tp;
  181365. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181366. #ifdef PNG_TEXT_SUPPORTED
  181367. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181368. * and whether that contents is compressed or not. The "key" field
  181369. * points to a regular zero-terminated C string. The "text", "lang", and
  181370. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181371. * However, the * structure returned by png_get_text() will always contain
  181372. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181373. * so they can be safely used in printf() and other string-handling functions.
  181374. */
  181375. typedef struct png_text_struct
  181376. {
  181377. int compression; /* compression value:
  181378. -1: tEXt, none
  181379. 0: zTXt, deflate
  181380. 1: iTXt, none
  181381. 2: iTXt, deflate */
  181382. png_charp key; /* keyword, 1-79 character description of "text" */
  181383. png_charp text; /* comment, may be an empty string (ie "")
  181384. or a NULL pointer */
  181385. png_size_t text_length; /* length of the text string */
  181386. #ifdef PNG_iTXt_SUPPORTED
  181387. png_size_t itxt_length; /* length of the itxt string */
  181388. png_charp lang; /* language code, 0-79 characters
  181389. or a NULL pointer */
  181390. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181391. chars or a NULL pointer */
  181392. #endif
  181393. } png_text;
  181394. typedef png_text FAR * png_textp;
  181395. typedef png_text FAR * FAR * png_textpp;
  181396. #endif
  181397. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181398. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181399. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181400. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181401. #define PNG_TEXT_COMPRESSION_NONE -1
  181402. #define PNG_TEXT_COMPRESSION_zTXt 0
  181403. #define PNG_ITXT_COMPRESSION_NONE 1
  181404. #define PNG_ITXT_COMPRESSION_zTXt 2
  181405. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181406. /* png_time is a way to hold the time in an machine independent way.
  181407. * Two conversions are provided, both from time_t and struct tm. There
  181408. * is no portable way to convert to either of these structures, as far
  181409. * as I know. If you know of a portable way, send it to me. As a side
  181410. * note - PNG has always been Year 2000 compliant!
  181411. */
  181412. typedef struct png_time_struct
  181413. {
  181414. png_uint_16 year; /* full year, as in, 1995 */
  181415. png_byte month; /* month of year, 1 - 12 */
  181416. png_byte day; /* day of month, 1 - 31 */
  181417. png_byte hour; /* hour of day, 0 - 23 */
  181418. png_byte minute; /* minute of hour, 0 - 59 */
  181419. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181420. } png_time;
  181421. typedef png_time FAR * png_timep;
  181422. typedef png_time FAR * FAR * png_timepp;
  181423. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181424. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181425. * no specific support. The idea is that we can use this to queue
  181426. * up private chunks for output even though the library doesn't actually
  181427. * know about their semantics.
  181428. */
  181429. typedef struct png_unknown_chunk_t
  181430. {
  181431. png_byte name[5];
  181432. png_byte *data;
  181433. png_size_t size;
  181434. /* libpng-using applications should NOT directly modify this byte. */
  181435. png_byte location; /* mode of operation at read time */
  181436. }
  181437. png_unknown_chunk;
  181438. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181439. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181440. #endif
  181441. /* png_info is a structure that holds the information in a PNG file so
  181442. * that the application can find out the characteristics of the image.
  181443. * If you are reading the file, this structure will tell you what is
  181444. * in the PNG file. If you are writing the file, fill in the information
  181445. * you want to put into the PNG file, then call png_write_info().
  181446. * The names chosen should be very close to the PNG specification, so
  181447. * consult that document for information about the meaning of each field.
  181448. *
  181449. * With libpng < 0.95, it was only possible to directly set and read the
  181450. * the values in the png_info_struct, which meant that the contents and
  181451. * order of the values had to remain fixed. With libpng 0.95 and later,
  181452. * however, there are now functions that abstract the contents of
  181453. * png_info_struct from the application, so this makes it easier to use
  181454. * libpng with dynamic libraries, and even makes it possible to use
  181455. * libraries that don't have all of the libpng ancillary chunk-handing
  181456. * functionality.
  181457. *
  181458. * In any case, the order of the parameters in png_info_struct should NOT
  181459. * be changed for as long as possible to keep compatibility with applications
  181460. * that use the old direct-access method with png_info_struct.
  181461. *
  181462. * The following members may have allocated storage attached that should be
  181463. * cleaned up before the structure is discarded: palette, trans, text,
  181464. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181465. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181466. * are automatically freed when the info structure is deallocated, if they were
  181467. * allocated internally by libpng. This behavior can be changed by means
  181468. * of the png_data_freer() function.
  181469. *
  181470. * More allocation details: all the chunk-reading functions that
  181471. * change these members go through the corresponding png_set_*
  181472. * functions. A function to clear these members is available: see
  181473. * png_free_data(). The png_set_* functions do not depend on being
  181474. * able to point info structure members to any of the storage they are
  181475. * passed (they make their own copies), EXCEPT that the png_set_text
  181476. * functions use the same storage passed to them in the text_ptr or
  181477. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181478. * functions do not make their own copies.
  181479. */
  181480. typedef struct png_info_struct
  181481. {
  181482. /* the following are necessary for every PNG file */
  181483. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181484. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181485. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181486. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181487. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181488. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181489. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181490. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181491. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181492. /* The following three should have been named *_method not *_type */
  181493. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181494. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181495. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181496. /* The following is informational only on read, and not used on writes. */
  181497. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181498. png_byte pixel_depth; /* number of bits per pixel */
  181499. png_byte spare_byte; /* to align the data, and for future use */
  181500. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181501. /* The rest of the data is optional. If you are reading, check the
  181502. * valid field to see if the information in these are valid. If you
  181503. * are writing, set the valid field to those chunks you want written,
  181504. * and initialize the appropriate fields below.
  181505. */
  181506. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181507. /* The gAMA chunk describes the gamma characteristics of the system
  181508. * on which the image was created, normally in the range [1.0, 2.5].
  181509. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181510. */
  181511. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181512. #endif
  181513. #if defined(PNG_sRGB_SUPPORTED)
  181514. /* GR-P, 0.96a */
  181515. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181516. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181517. #endif
  181518. #if defined(PNG_TEXT_SUPPORTED)
  181519. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181520. * uncompressed, compressed, and optionally compressed forms, respectively.
  181521. * The data in "text" is an array of pointers to uncompressed,
  181522. * null-terminated C strings. Each chunk has a keyword that describes the
  181523. * textual data contained in that chunk. Keywords are not required to be
  181524. * unique, and the text string may be empty. Any number of text chunks may
  181525. * be in an image.
  181526. */
  181527. int num_text; /* number of comments read/to write */
  181528. int max_text; /* current size of text array */
  181529. png_textp text; /* array of comments read/to write */
  181530. #endif /* PNG_TEXT_SUPPORTED */
  181531. #if defined(PNG_tIME_SUPPORTED)
  181532. /* The tIME chunk holds the last time the displayed image data was
  181533. * modified. See the png_time struct for the contents of this struct.
  181534. */
  181535. png_time mod_time;
  181536. #endif
  181537. #if defined(PNG_sBIT_SUPPORTED)
  181538. /* The sBIT chunk specifies the number of significant high-order bits
  181539. * in the pixel data. Values are in the range [1, bit_depth], and are
  181540. * only specified for the channels in the pixel data. The contents of
  181541. * the low-order bits is not specified. Data is valid if
  181542. * (valid & PNG_INFO_sBIT) is non-zero.
  181543. */
  181544. png_color_8 sig_bit; /* significant bits in color channels */
  181545. #endif
  181546. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181547. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181548. /* The tRNS chunk supplies transparency data for paletted images and
  181549. * other image types that don't need a full alpha channel. There are
  181550. * "num_trans" transparency values for a paletted image, stored in the
  181551. * same order as the palette colors, starting from index 0. Values
  181552. * for the data are in the range [0, 255], ranging from fully transparent
  181553. * to fully opaque, respectively. For non-paletted images, there is a
  181554. * single color specified that should be treated as fully transparent.
  181555. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181556. */
  181557. png_bytep trans; /* transparent values for paletted image */
  181558. png_color_16 trans_values; /* transparent color for non-palette image */
  181559. #endif
  181560. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181561. /* The bKGD chunk gives the suggested image background color if the
  181562. * display program does not have its own background color and the image
  181563. * is needs to composited onto a background before display. The colors
  181564. * in "background" are normally in the same color space/depth as the
  181565. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181566. */
  181567. png_color_16 background;
  181568. #endif
  181569. #if defined(PNG_oFFs_SUPPORTED)
  181570. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181571. * and downwards from the top-left corner of the display, page, or other
  181572. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181573. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181574. */
  181575. png_int_32 x_offset; /* x offset on page */
  181576. png_int_32 y_offset; /* y offset on page */
  181577. png_byte offset_unit_type; /* offset units type */
  181578. #endif
  181579. #if defined(PNG_pHYs_SUPPORTED)
  181580. /* The pHYs chunk gives the physical pixel density of the image for
  181581. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181582. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181583. */
  181584. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181585. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181586. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181587. #endif
  181588. #if defined(PNG_hIST_SUPPORTED)
  181589. /* The hIST chunk contains the relative frequency or importance of the
  181590. * various palette entries, so that a viewer can intelligently select a
  181591. * reduced-color palette, if required. Data is an array of "num_palette"
  181592. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181593. * is non-zero.
  181594. */
  181595. png_uint_16p hist;
  181596. #endif
  181597. #ifdef PNG_cHRM_SUPPORTED
  181598. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181599. * on which the PNG was created. This data allows the viewer to do gamut
  181600. * mapping of the input image to ensure that the viewer sees the same
  181601. * colors in the image as the creator. Values are in the range
  181602. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181603. */
  181604. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181605. float x_white;
  181606. float y_white;
  181607. float x_red;
  181608. float y_red;
  181609. float x_green;
  181610. float y_green;
  181611. float x_blue;
  181612. float y_blue;
  181613. #endif
  181614. #endif
  181615. #if defined(PNG_pCAL_SUPPORTED)
  181616. /* The pCAL chunk describes a transformation between the stored pixel
  181617. * values and original physical data values used to create the image.
  181618. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181619. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181620. * (possibly non-linear) transformation function given by "pcal_type"
  181621. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181622. * defines below, and the PNG-Group's PNG extensions document for a
  181623. * complete description of the transformations and how they should be
  181624. * implemented, and for a description of the ASCII parameter strings.
  181625. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181626. */
  181627. png_charp pcal_purpose; /* pCAL chunk description string */
  181628. png_int_32 pcal_X0; /* minimum value */
  181629. png_int_32 pcal_X1; /* maximum value */
  181630. png_charp pcal_units; /* Latin-1 string giving physical units */
  181631. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181632. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181633. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181634. #endif
  181635. /* New members added in libpng-1.0.6 */
  181636. #ifdef PNG_FREE_ME_SUPPORTED
  181637. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181638. #endif
  181639. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181640. /* storage for unknown chunks that the library doesn't recognize. */
  181641. png_unknown_chunkp unknown_chunks;
  181642. png_size_t unknown_chunks_num;
  181643. #endif
  181644. #if defined(PNG_iCCP_SUPPORTED)
  181645. /* iCCP chunk data. */
  181646. png_charp iccp_name; /* profile name */
  181647. png_charp iccp_profile; /* International Color Consortium profile data */
  181648. /* Note to maintainer: should be png_bytep */
  181649. png_uint_32 iccp_proflen; /* ICC profile data length */
  181650. png_byte iccp_compression; /* Always zero */
  181651. #endif
  181652. #if defined(PNG_sPLT_SUPPORTED)
  181653. /* data on sPLT chunks (there may be more than one). */
  181654. png_sPLT_tp splt_palettes;
  181655. png_uint_32 splt_palettes_num;
  181656. #endif
  181657. #if defined(PNG_sCAL_SUPPORTED)
  181658. /* The sCAL chunk describes the actual physical dimensions of the
  181659. * subject matter of the graphic. The chunk contains a unit specification
  181660. * a byte value, and two ASCII strings representing floating-point
  181661. * values. The values are width and height corresponsing to one pixel
  181662. * in the image. This external representation is converted to double
  181663. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181664. */
  181665. png_byte scal_unit; /* unit of physical scale */
  181666. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181667. double scal_pixel_width; /* width of one pixel */
  181668. double scal_pixel_height; /* height of one pixel */
  181669. #endif
  181670. #ifdef PNG_FIXED_POINT_SUPPORTED
  181671. png_charp scal_s_width; /* string containing height */
  181672. png_charp scal_s_height; /* string containing width */
  181673. #endif
  181674. #endif
  181675. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181676. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181677. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181678. png_bytepp row_pointers; /* the image bits */
  181679. #endif
  181680. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181681. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181682. #endif
  181683. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181684. png_fixed_point int_x_white;
  181685. png_fixed_point int_y_white;
  181686. png_fixed_point int_x_red;
  181687. png_fixed_point int_y_red;
  181688. png_fixed_point int_x_green;
  181689. png_fixed_point int_y_green;
  181690. png_fixed_point int_x_blue;
  181691. png_fixed_point int_y_blue;
  181692. #endif
  181693. } png_info;
  181694. typedef png_info FAR * png_infop;
  181695. typedef png_info FAR * FAR * png_infopp;
  181696. /* Maximum positive integer used in PNG is (2^31)-1 */
  181697. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181698. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181699. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181700. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181701. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181702. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181703. #endif
  181704. /* These describe the color_type field in png_info. */
  181705. /* color type masks */
  181706. #define PNG_COLOR_MASK_PALETTE 1
  181707. #define PNG_COLOR_MASK_COLOR 2
  181708. #define PNG_COLOR_MASK_ALPHA 4
  181709. /* color types. Note that not all combinations are legal */
  181710. #define PNG_COLOR_TYPE_GRAY 0
  181711. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181712. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181713. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181714. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181715. /* aliases */
  181716. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181717. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181718. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181719. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181720. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181721. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181722. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181723. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181724. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181725. /* These are for the interlacing type. These values should NOT be changed. */
  181726. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181727. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181728. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181729. /* These are for the oFFs chunk. These values should NOT be changed. */
  181730. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181731. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181732. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181733. /* These are for the pCAL chunk. These values should NOT be changed. */
  181734. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181735. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181736. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181737. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181738. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181739. /* These are for the sCAL chunk. These values should NOT be changed. */
  181740. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181741. #define PNG_SCALE_METER 1 /* meters per pixel */
  181742. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181743. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181744. /* These are for the pHYs chunk. These values should NOT be changed. */
  181745. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181746. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181747. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181748. /* These are for the sRGB chunk. These values should NOT be changed. */
  181749. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181750. #define PNG_sRGB_INTENT_RELATIVE 1
  181751. #define PNG_sRGB_INTENT_SATURATION 2
  181752. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181753. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181754. /* This is for text chunks */
  181755. #define PNG_KEYWORD_MAX_LENGTH 79
  181756. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181757. #define PNG_MAX_PALETTE_LENGTH 256
  181758. /* These determine if an ancillary chunk's data has been successfully read
  181759. * from the PNG header, or if the application has filled in the corresponding
  181760. * data in the info_struct to be written into the output file. The values
  181761. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181762. */
  181763. #define PNG_INFO_gAMA 0x0001
  181764. #define PNG_INFO_sBIT 0x0002
  181765. #define PNG_INFO_cHRM 0x0004
  181766. #define PNG_INFO_PLTE 0x0008
  181767. #define PNG_INFO_tRNS 0x0010
  181768. #define PNG_INFO_bKGD 0x0020
  181769. #define PNG_INFO_hIST 0x0040
  181770. #define PNG_INFO_pHYs 0x0080
  181771. #define PNG_INFO_oFFs 0x0100
  181772. #define PNG_INFO_tIME 0x0200
  181773. #define PNG_INFO_pCAL 0x0400
  181774. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181775. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181776. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181777. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181778. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181779. /* This is used for the transformation routines, as some of them
  181780. * change these values for the row. It also should enable using
  181781. * the routines for other purposes.
  181782. */
  181783. typedef struct png_row_info_struct
  181784. {
  181785. png_uint_32 width; /* width of row */
  181786. png_uint_32 rowbytes; /* number of bytes in row */
  181787. png_byte color_type; /* color type of row */
  181788. png_byte bit_depth; /* bit depth of row */
  181789. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181790. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181791. } png_row_info;
  181792. typedef png_row_info FAR * png_row_infop;
  181793. typedef png_row_info FAR * FAR * png_row_infopp;
  181794. /* These are the function types for the I/O functions and for the functions
  181795. * that allow the user to override the default I/O functions with his or her
  181796. * own. The png_error_ptr type should match that of user-supplied warning
  181797. * and error functions, while the png_rw_ptr type should match that of the
  181798. * user read/write data functions.
  181799. */
  181800. typedef struct png_struct_def png_struct;
  181801. typedef png_struct FAR * png_structp;
  181802. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181803. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181804. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181805. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181806. int));
  181807. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181808. int));
  181809. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181810. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181811. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181812. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181813. png_uint_32, int));
  181814. #endif
  181815. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181816. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181817. defined(PNG_LEGACY_SUPPORTED)
  181818. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181819. png_row_infop, png_bytep));
  181820. #endif
  181821. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181822. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  181823. #endif
  181824. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181825. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  181826. #endif
  181827. /* Transform masks for the high-level interface */
  181828. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  181829. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  181830. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  181831. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  181832. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  181833. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  181834. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  181835. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  181836. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  181837. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  181838. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  181839. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  181840. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  181841. /* Flags for MNG supported features */
  181842. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  181843. #define PNG_FLAG_MNG_FILTER_64 0x04
  181844. #define PNG_ALL_MNG_FEATURES 0x05
  181845. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  181846. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  181847. /* The structure that holds the information to read and write PNG files.
  181848. * The only people who need to care about what is inside of this are the
  181849. * people who will be modifying the library for their own special needs.
  181850. * It should NOT be accessed directly by an application, except to store
  181851. * the jmp_buf.
  181852. */
  181853. struct png_struct_def
  181854. {
  181855. #ifdef PNG_SETJMP_SUPPORTED
  181856. jmp_buf jmpbuf; /* used in png_error */
  181857. #endif
  181858. png_error_ptr error_fn; /* function for printing errors and aborting */
  181859. png_error_ptr warning_fn; /* function for printing warnings */
  181860. png_voidp error_ptr; /* user supplied struct for error functions */
  181861. png_rw_ptr write_data_fn; /* function for writing output data */
  181862. png_rw_ptr read_data_fn; /* function for reading input data */
  181863. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  181864. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  181865. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  181866. #endif
  181867. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181868. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  181869. #endif
  181870. /* These were added in libpng-1.0.2 */
  181871. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  181872. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181873. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181874. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  181875. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  181876. png_byte user_transform_channels; /* channels in user transformed pixels */
  181877. #endif
  181878. #endif
  181879. png_uint_32 mode; /* tells us where we are in the PNG file */
  181880. png_uint_32 flags; /* flags indicating various things to libpng */
  181881. png_uint_32 transformations; /* which transformations to perform */
  181882. z_stream zstream; /* pointer to decompression structure (below) */
  181883. png_bytep zbuf; /* buffer for zlib */
  181884. png_size_t zbuf_size; /* size of zbuf */
  181885. int zlib_level; /* holds zlib compression level */
  181886. int zlib_method; /* holds zlib compression method */
  181887. int zlib_window_bits; /* holds zlib compression window bits */
  181888. int zlib_mem_level; /* holds zlib compression memory level */
  181889. int zlib_strategy; /* holds zlib compression strategy */
  181890. png_uint_32 width; /* width of image in pixels */
  181891. png_uint_32 height; /* height of image in pixels */
  181892. png_uint_32 num_rows; /* number of rows in current pass */
  181893. png_uint_32 usr_width; /* width of row at start of write */
  181894. png_uint_32 rowbytes; /* size of row in bytes */
  181895. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  181896. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  181897. png_uint_32 row_number; /* current row in interlace pass */
  181898. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  181899. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  181900. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  181901. png_bytep up_row; /* buffer to save "up" row when filtering */
  181902. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  181903. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  181904. png_row_info row_info; /* used for transformation routines */
  181905. png_uint_32 idat_size; /* current IDAT size for read */
  181906. png_uint_32 crc; /* current chunk CRC value */
  181907. png_colorp palette; /* palette from the input file */
  181908. png_uint_16 num_palette; /* number of color entries in palette */
  181909. png_uint_16 num_trans; /* number of transparency values */
  181910. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  181911. png_byte compression; /* file compression type (always 0) */
  181912. png_byte filter; /* file filter type (always 0) */
  181913. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181914. png_byte pass; /* current interlace pass (0 - 6) */
  181915. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  181916. png_byte color_type; /* color type of file */
  181917. png_byte bit_depth; /* bit depth of file */
  181918. png_byte usr_bit_depth; /* bit depth of users row */
  181919. png_byte pixel_depth; /* number of bits per pixel */
  181920. png_byte channels; /* number of channels in file */
  181921. png_byte usr_channels; /* channels at start of write */
  181922. png_byte sig_bytes; /* magic bytes read/written from start of file */
  181923. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181924. #ifdef PNG_LEGACY_SUPPORTED
  181925. png_byte filler; /* filler byte for pixel expansion */
  181926. #else
  181927. png_uint_16 filler; /* filler bytes for pixel expansion */
  181928. #endif
  181929. #endif
  181930. #if defined(PNG_bKGD_SUPPORTED)
  181931. png_byte background_gamma_type;
  181932. # ifdef PNG_FLOATING_POINT_SUPPORTED
  181933. float background_gamma;
  181934. # endif
  181935. png_color_16 background; /* background color in screen gamma space */
  181936. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181937. png_color_16 background_1; /* background normalized to gamma 1.0 */
  181938. #endif
  181939. #endif /* PNG_bKGD_SUPPORTED */
  181940. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181941. png_flush_ptr output_flush_fn;/* Function for flushing output */
  181942. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  181943. png_uint_32 flush_rows; /* number of rows written since last flush */
  181944. #endif
  181945. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181946. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  181947. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181948. float gamma; /* file gamma value */
  181949. float screen_gamma; /* screen gamma value (display_exponent) */
  181950. #endif
  181951. #endif
  181952. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181953. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  181954. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  181955. png_bytep gamma_to_1; /* converts from file to 1.0 */
  181956. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  181957. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  181958. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  181959. #endif
  181960. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  181961. png_color_8 sig_bit; /* significant bits in each available channel */
  181962. #endif
  181963. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181964. png_color_8 shift; /* shift for significant bit tranformation */
  181965. #endif
  181966. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  181967. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181968. png_bytep trans; /* transparency values for paletted files */
  181969. png_color_16 trans_values; /* transparency values for non-paletted files */
  181970. #endif
  181971. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  181972. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  181973. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181974. png_progressive_info_ptr info_fn; /* called after header data fully read */
  181975. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  181976. png_progressive_end_ptr end_fn; /* called after image is complete */
  181977. png_bytep save_buffer_ptr; /* current location in save_buffer */
  181978. png_bytep save_buffer; /* buffer for previously read data */
  181979. png_bytep current_buffer_ptr; /* current location in current_buffer */
  181980. png_bytep current_buffer; /* buffer for recently used data */
  181981. png_uint_32 push_length; /* size of current input chunk */
  181982. png_uint_32 skip_length; /* bytes to skip in input data */
  181983. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  181984. png_size_t save_buffer_max; /* total size of save_buffer */
  181985. png_size_t buffer_size; /* total amount of available input data */
  181986. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  181987. int process_mode; /* what push library is currently doing */
  181988. int cur_palette; /* current push library palette index */
  181989. # if defined(PNG_TEXT_SUPPORTED)
  181990. png_size_t current_text_size; /* current size of text input data */
  181991. png_size_t current_text_left; /* how much text left to read in input */
  181992. png_charp current_text; /* current text chunk buffer */
  181993. png_charp current_text_ptr; /* current location in current_text */
  181994. # endif /* PNG_TEXT_SUPPORTED */
  181995. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181996. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181997. /* for the Borland special 64K segment handler */
  181998. png_bytepp offset_table_ptr;
  181999. png_bytep offset_table;
  182000. png_uint_16 offset_table_number;
  182001. png_uint_16 offset_table_count;
  182002. png_uint_16 offset_table_count_free;
  182003. #endif
  182004. #if defined(PNG_READ_DITHER_SUPPORTED)
  182005. png_bytep palette_lookup; /* lookup table for dithering */
  182006. png_bytep dither_index; /* index translation for palette files */
  182007. #endif
  182008. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182009. png_uint_16p hist; /* histogram */
  182010. #endif
  182011. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182012. png_byte heuristic_method; /* heuristic for row filter selection */
  182013. png_byte num_prev_filters; /* number of weights for previous rows */
  182014. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182015. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182016. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182017. png_uint_16p filter_costs; /* relative filter calculation cost */
  182018. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182019. #endif
  182020. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182021. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182022. #endif
  182023. /* New members added in libpng-1.0.6 */
  182024. #ifdef PNG_FREE_ME_SUPPORTED
  182025. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182026. #endif
  182027. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182028. png_voidp user_chunk_ptr;
  182029. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182030. #endif
  182031. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182032. int num_chunk_list;
  182033. png_bytep chunk_list;
  182034. #endif
  182035. /* New members added in libpng-1.0.3 */
  182036. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182037. png_byte rgb_to_gray_status;
  182038. /* These were changed from png_byte in libpng-1.0.6 */
  182039. png_uint_16 rgb_to_gray_red_coeff;
  182040. png_uint_16 rgb_to_gray_green_coeff;
  182041. png_uint_16 rgb_to_gray_blue_coeff;
  182042. #endif
  182043. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182044. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182045. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182046. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182047. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182048. #ifdef PNG_1_0_X
  182049. png_byte mng_features_permitted;
  182050. #else
  182051. png_uint_32 mng_features_permitted;
  182052. #endif /* PNG_1_0_X */
  182053. #endif
  182054. /* New member added in libpng-1.0.7 */
  182055. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182056. png_fixed_point int_gamma;
  182057. #endif
  182058. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182059. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182060. png_byte filter_type;
  182061. #endif
  182062. #if defined(PNG_1_0_X)
  182063. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182064. png_uint_32 row_buf_size;
  182065. #endif
  182066. /* New members added in libpng-1.2.0 */
  182067. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182068. # if !defined(PNG_1_0_X)
  182069. # if defined(PNG_MMX_CODE_SUPPORTED)
  182070. png_byte mmx_bitdepth_threshold;
  182071. png_uint_32 mmx_rowbytes_threshold;
  182072. # endif
  182073. png_uint_32 asm_flags;
  182074. # endif
  182075. #endif
  182076. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182077. #ifdef PNG_USER_MEM_SUPPORTED
  182078. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182079. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182080. png_free_ptr free_fn; /* function for freeing memory */
  182081. #endif
  182082. /* New member added in libpng-1.0.13 and 1.2.0 */
  182083. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182084. #if defined(PNG_READ_DITHER_SUPPORTED)
  182085. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182086. png_bytep dither_sort; /* working sort array */
  182087. png_bytep index_to_palette; /* where the original index currently is */
  182088. /* in the palette */
  182089. png_bytep palette_to_index; /* which original index points to this */
  182090. /* palette color */
  182091. #endif
  182092. /* New members added in libpng-1.0.16 and 1.2.6 */
  182093. png_byte compression_type;
  182094. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182095. png_uint_32 user_width_max;
  182096. png_uint_32 user_height_max;
  182097. #endif
  182098. /* New member added in libpng-1.0.25 and 1.2.17 */
  182099. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182100. /* storage for unknown chunk that the library doesn't recognize. */
  182101. png_unknown_chunk unknown_chunk;
  182102. #endif
  182103. };
  182104. /* This triggers a compiler error in png.c, if png.c and png.h
  182105. * do not agree upon the version number.
  182106. */
  182107. typedef png_structp version_1_2_21;
  182108. typedef png_struct FAR * FAR * png_structpp;
  182109. /* Here are the function definitions most commonly used. This is not
  182110. * the place to find out how to use libpng. See libpng.txt for the
  182111. * full explanation, see example.c for the summary. This just provides
  182112. * a simple one line description of the use of each function.
  182113. */
  182114. /* Returns the version number of the library */
  182115. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182116. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182117. * Handling more than 8 bytes from the beginning of the file is an error.
  182118. */
  182119. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182120. int num_bytes));
  182121. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182122. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182123. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182124. * start > 7 will always fail (ie return non-zero).
  182125. */
  182126. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182127. png_size_t num_to_check));
  182128. /* Simple signature checking function. This is the same as calling
  182129. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182130. */
  182131. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182132. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182133. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182134. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182135. png_error_ptr error_fn, png_error_ptr warn_fn));
  182136. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182137. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182138. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182139. png_error_ptr error_fn, png_error_ptr warn_fn));
  182140. #ifdef PNG_WRITE_SUPPORTED
  182141. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182142. PNGARG((png_structp png_ptr));
  182143. #endif
  182144. #ifdef PNG_WRITE_SUPPORTED
  182145. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182146. PNGARG((png_structp png_ptr, png_uint_32 size));
  182147. #endif
  182148. /* Reset the compression stream */
  182149. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182150. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182151. #ifdef PNG_USER_MEM_SUPPORTED
  182152. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182153. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182154. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182155. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182156. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182157. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182158. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182159. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182160. #endif
  182161. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182162. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182163. png_bytep chunk_name, png_bytep data, png_size_t length));
  182164. /* Write the start of a PNG chunk - length and chunk name. */
  182165. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182166. png_bytep chunk_name, png_uint_32 length));
  182167. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182168. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182169. png_bytep data, png_size_t length));
  182170. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182171. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182172. /* Allocate and initialize the info structure */
  182173. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182174. PNGARG((png_structp png_ptr));
  182175. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182176. /* Initialize the info structure (old interface - DEPRECATED) */
  182177. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182178. #undef png_info_init
  182179. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182180. png_sizeof(png_info));
  182181. #endif
  182182. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182183. png_size_t png_info_struct_size));
  182184. /* Writes all the PNG information before the image. */
  182185. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182186. png_infop info_ptr));
  182187. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182188. png_infop info_ptr));
  182189. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182190. /* read the information before the actual image data. */
  182191. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182192. png_infop info_ptr));
  182193. #endif
  182194. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182195. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182196. PNGARG((png_structp png_ptr, png_timep ptime));
  182197. #endif
  182198. #if !defined(_WIN32_WCE)
  182199. /* "time.h" functions are not supported on WindowsCE */
  182200. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182201. /* convert from a struct tm to png_time */
  182202. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182203. struct tm FAR * ttime));
  182204. /* convert from time_t to png_time. Uses gmtime() */
  182205. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182206. time_t ttime));
  182207. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182208. #endif /* _WIN32_WCE */
  182209. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182210. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182211. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182212. #if !defined(PNG_1_0_X)
  182213. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182214. png_ptr));
  182215. #endif
  182216. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182217. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182218. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182219. /* Deprecated */
  182220. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182221. #endif
  182222. #endif
  182223. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182224. /* Use blue, green, red order for pixels. */
  182225. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182226. #endif
  182227. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182228. /* Expand the grayscale to 24-bit RGB if necessary. */
  182229. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182230. #endif
  182231. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182232. /* Reduce RGB to grayscale. */
  182233. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182234. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182235. int error_action, double red, double green ));
  182236. #endif
  182237. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182238. int error_action, png_fixed_point red, png_fixed_point green ));
  182239. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182240. png_ptr));
  182241. #endif
  182242. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182243. png_colorp palette));
  182244. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182245. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182246. #endif
  182247. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182248. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182249. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182250. #endif
  182251. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182252. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182253. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182254. #endif
  182255. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182256. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182257. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182258. png_uint_32 filler, int flags));
  182259. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182260. #define PNG_FILLER_BEFORE 0
  182261. #define PNG_FILLER_AFTER 1
  182262. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182263. #if !defined(PNG_1_0_X)
  182264. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182265. png_uint_32 filler, int flags));
  182266. #endif
  182267. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182268. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182269. /* Swap bytes in 16-bit depth files. */
  182270. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182271. #endif
  182272. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182273. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182274. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182275. #endif
  182276. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182277. /* Swap packing order of pixels in bytes. */
  182278. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182279. #endif
  182280. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182281. /* Converts files to legal bit depths. */
  182282. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182283. png_color_8p true_bits));
  182284. #endif
  182285. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182286. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182287. /* Have the code handle the interlacing. Returns the number of passes. */
  182288. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182289. #endif
  182290. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182291. /* Invert monochrome files */
  182292. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182293. #endif
  182294. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182295. /* Handle alpha and tRNS by replacing with a background color. */
  182296. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182297. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182298. png_color_16p background_color, int background_gamma_code,
  182299. int need_expand, double background_gamma));
  182300. #endif
  182301. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182302. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182303. #define PNG_BACKGROUND_GAMMA_FILE 2
  182304. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182305. #endif
  182306. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182307. /* strip the second byte of information from a 16-bit depth file. */
  182308. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182309. #endif
  182310. #if defined(PNG_READ_DITHER_SUPPORTED)
  182311. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182312. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182313. png_colorp palette, int num_palette, int maximum_colors,
  182314. png_uint_16p histogram, int full_dither));
  182315. #endif
  182316. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182317. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182318. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182319. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182320. double screen_gamma, double default_file_gamma));
  182321. #endif
  182322. #endif
  182323. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182324. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182325. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182326. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182327. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182328. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182329. int empty_plte_permitted));
  182330. #endif
  182331. #endif
  182332. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182333. /* Set how many lines between output flushes - 0 for no flushing */
  182334. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182335. /* Flush the current PNG output buffer */
  182336. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182337. #endif
  182338. /* optional update palette with requested transformations */
  182339. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182340. /* optional call to update the users info structure */
  182341. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182342. png_infop info_ptr));
  182343. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182344. /* read one or more rows of image data. */
  182345. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182346. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182347. #endif
  182348. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182349. /* read a row of data. */
  182350. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182351. png_bytep row,
  182352. png_bytep display_row));
  182353. #endif
  182354. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182355. /* read the whole image into memory at once. */
  182356. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182357. png_bytepp image));
  182358. #endif
  182359. /* write a row of image data */
  182360. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182361. png_bytep row));
  182362. /* write a few rows of image data */
  182363. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182364. png_bytepp row, png_uint_32 num_rows));
  182365. /* write the image data */
  182366. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182367. png_bytepp image));
  182368. /* writes the end of the PNG file. */
  182369. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182370. png_infop info_ptr));
  182371. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182372. /* read the end of the PNG file. */
  182373. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182374. png_infop info_ptr));
  182375. #endif
  182376. /* free any memory associated with the png_info_struct */
  182377. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182378. png_infopp info_ptr_ptr));
  182379. /* free any memory associated with the png_struct and the png_info_structs */
  182380. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182381. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182382. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182383. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182384. png_infop end_info_ptr));
  182385. /* free any memory associated with the png_struct and the png_info_structs */
  182386. extern PNG_EXPORT(void,png_destroy_write_struct)
  182387. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182388. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182389. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182390. /* set the libpng method of handling chunk CRC errors */
  182391. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182392. int crit_action, int ancil_action));
  182393. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182394. * ancillary and critical chunks, and whether to use the data contained
  182395. * therein. Note that it is impossible to "discard" data in a critical
  182396. * chunk. For versions prior to 0.90, the action was always error/quit,
  182397. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182398. * chunks is warn/discard. These values should NOT be changed.
  182399. *
  182400. * value action:critical action:ancillary
  182401. */
  182402. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182403. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182404. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182405. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182406. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182407. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182408. /* These functions give the user control over the scan-line filtering in
  182409. * libpng and the compression methods used by zlib. These functions are
  182410. * mainly useful for testing, as the defaults should work with most users.
  182411. * Those users who are tight on memory or want faster performance at the
  182412. * expense of compression can modify them. See the compression library
  182413. * header file (zlib.h) for an explination of the compression functions.
  182414. */
  182415. /* set the filtering method(s) used by libpng. Currently, the only valid
  182416. * value for "method" is 0.
  182417. */
  182418. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182419. int filters));
  182420. /* Flags for png_set_filter() to say which filters to use. The flags
  182421. * are chosen so that they don't conflict with real filter types
  182422. * below, in case they are supplied instead of the #defined constants.
  182423. * These values should NOT be changed.
  182424. */
  182425. #define PNG_NO_FILTERS 0x00
  182426. #define PNG_FILTER_NONE 0x08
  182427. #define PNG_FILTER_SUB 0x10
  182428. #define PNG_FILTER_UP 0x20
  182429. #define PNG_FILTER_AVG 0x40
  182430. #define PNG_FILTER_PAETH 0x80
  182431. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182432. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182433. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182434. * These defines should NOT be changed.
  182435. */
  182436. #define PNG_FILTER_VALUE_NONE 0
  182437. #define PNG_FILTER_VALUE_SUB 1
  182438. #define PNG_FILTER_VALUE_UP 2
  182439. #define PNG_FILTER_VALUE_AVG 3
  182440. #define PNG_FILTER_VALUE_PAETH 4
  182441. #define PNG_FILTER_VALUE_LAST 5
  182442. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182443. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182444. * defines, either the default (minimum-sum-of-absolute-differences), or
  182445. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182446. *
  182447. * Weights are factors >= 1.0, indicating how important it is to keep the
  182448. * filter type consistent between rows. Larger numbers mean the current
  182449. * filter is that many times as likely to be the same as the "num_weights"
  182450. * previous filters. This is cumulative for each previous row with a weight.
  182451. * There needs to be "num_weights" values in "filter_weights", or it can be
  182452. * NULL if the weights aren't being specified. Weights have no influence on
  182453. * the selection of the first row filter. Well chosen weights can (in theory)
  182454. * improve the compression for a given image.
  182455. *
  182456. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182457. * filter type. Higher costs indicate more decoding expense, and are
  182458. * therefore less likely to be selected over a filter with lower computational
  182459. * costs. There needs to be a value in "filter_costs" for each valid filter
  182460. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182461. * setting the costs. Costs try to improve the speed of decompression without
  182462. * unduly increasing the compressed image size.
  182463. *
  182464. * A negative weight or cost indicates the default value is to be used, and
  182465. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182466. * The default values for both weights and costs are currently 1.0, but may
  182467. * change if good general weighting/cost heuristics can be found. If both
  182468. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182469. * to the UNWEIGHTED method, but with added encoding time/computation.
  182470. */
  182471. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182472. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182473. int heuristic_method, int num_weights, png_doublep filter_weights,
  182474. png_doublep filter_costs));
  182475. #endif
  182476. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182477. /* Heuristic used for row filter selection. These defines should NOT be
  182478. * changed.
  182479. */
  182480. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182481. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182482. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182483. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182484. /* Set the library compression level. Currently, valid values range from
  182485. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182486. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182487. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182488. * for PNG images, and do considerably fewer caclulations. In the future,
  182489. * these values may not correspond directly to the zlib compression levels.
  182490. */
  182491. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182492. int level));
  182493. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182494. PNGARG((png_structp png_ptr, int mem_level));
  182495. extern PNG_EXPORT(void,png_set_compression_strategy)
  182496. PNGARG((png_structp png_ptr, int strategy));
  182497. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182498. PNGARG((png_structp png_ptr, int window_bits));
  182499. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182500. int method));
  182501. /* These next functions are called for input/output, memory, and error
  182502. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182503. * and call standard C I/O routines such as fread(), fwrite(), and
  182504. * fprintf(). These functions can be made to use other I/O routines
  182505. * at run time for those applications that need to handle I/O in a
  182506. * different manner by calling png_set_???_fn(). See libpng.txt for
  182507. * more information.
  182508. */
  182509. #if !defined(PNG_NO_STDIO)
  182510. /* Initialize the input/output for the PNG file to the default functions. */
  182511. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182512. #endif
  182513. /* Replace the (error and abort), and warning functions with user
  182514. * supplied functions. If no messages are to be printed you must still
  182515. * write and use replacement functions. The replacement error_fn should
  182516. * still do a longjmp to the last setjmp location if you are using this
  182517. * method of error handling. If error_fn or warning_fn is NULL, the
  182518. * default function will be used.
  182519. */
  182520. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182521. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182522. /* Return the user pointer associated with the error functions */
  182523. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182524. /* Replace the default data output functions with a user supplied one(s).
  182525. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182526. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182527. * output_flush_fn will be ignored (and thus can be NULL).
  182528. */
  182529. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182530. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182531. /* Replace the default data input function with a user supplied one. */
  182532. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182533. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182534. /* Return the user pointer associated with the I/O functions */
  182535. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182536. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182537. png_read_status_ptr read_row_fn));
  182538. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182539. png_write_status_ptr write_row_fn));
  182540. #ifdef PNG_USER_MEM_SUPPORTED
  182541. /* Replace the default memory allocation functions with user supplied one(s). */
  182542. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182543. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182544. /* Return the user pointer associated with the memory functions */
  182545. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182546. #endif
  182547. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182548. defined(PNG_LEGACY_SUPPORTED)
  182549. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182550. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182551. #endif
  182552. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182553. defined(PNG_LEGACY_SUPPORTED)
  182554. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182555. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182556. #endif
  182557. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182558. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182559. defined(PNG_LEGACY_SUPPORTED)
  182560. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182561. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182562. int user_transform_channels));
  182563. /* Return the user pointer associated with the user transform functions */
  182564. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182565. PNGARG((png_structp png_ptr));
  182566. #endif
  182567. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182568. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182569. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182570. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182571. png_ptr));
  182572. #endif
  182573. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182574. /* Sets the function callbacks for the push reader, and a pointer to a
  182575. * user-defined structure available to the callback functions.
  182576. */
  182577. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182578. png_voidp progressive_ptr,
  182579. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182580. png_progressive_end_ptr end_fn));
  182581. /* returns the user pointer associated with the push read functions */
  182582. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182583. PNGARG((png_structp png_ptr));
  182584. /* function to be called when data becomes available */
  182585. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182586. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182587. /* function that combines rows. Not very much different than the
  182588. * png_combine_row() call. Is this even used?????
  182589. */
  182590. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182591. png_bytep old_row, png_bytep new_row));
  182592. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182593. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182594. png_uint_32 size));
  182595. #if defined(PNG_1_0_X)
  182596. # define png_malloc_warn png_malloc
  182597. #else
  182598. /* Added at libpng version 1.2.4 */
  182599. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182600. png_uint_32 size));
  182601. #endif
  182602. /* frees a pointer allocated by png_malloc() */
  182603. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182604. #if defined(PNG_1_0_X)
  182605. /* Function to allocate memory for zlib. */
  182606. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182607. uInt size));
  182608. /* Function to free memory for zlib */
  182609. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182610. #endif
  182611. /* Free data that was allocated internally */
  182612. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182613. png_infop info_ptr, png_uint_32 free_me, int num));
  182614. #ifdef PNG_FREE_ME_SUPPORTED
  182615. /* Reassign responsibility for freeing existing data, whether allocated
  182616. * by libpng or by the application */
  182617. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182618. png_infop info_ptr, int freer, png_uint_32 mask));
  182619. #endif
  182620. /* assignments for png_data_freer */
  182621. #define PNG_DESTROY_WILL_FREE_DATA 1
  182622. #define PNG_SET_WILL_FREE_DATA 1
  182623. #define PNG_USER_WILL_FREE_DATA 2
  182624. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182625. #define PNG_FREE_HIST 0x0008
  182626. #define PNG_FREE_ICCP 0x0010
  182627. #define PNG_FREE_SPLT 0x0020
  182628. #define PNG_FREE_ROWS 0x0040
  182629. #define PNG_FREE_PCAL 0x0080
  182630. #define PNG_FREE_SCAL 0x0100
  182631. #define PNG_FREE_UNKN 0x0200
  182632. #define PNG_FREE_LIST 0x0400
  182633. #define PNG_FREE_PLTE 0x1000
  182634. #define PNG_FREE_TRNS 0x2000
  182635. #define PNG_FREE_TEXT 0x4000
  182636. #define PNG_FREE_ALL 0x7fff
  182637. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182638. #ifdef PNG_USER_MEM_SUPPORTED
  182639. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182640. png_uint_32 size));
  182641. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182642. png_voidp ptr));
  182643. #endif
  182644. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182645. png_voidp s1, png_voidp s2, png_uint_32 size));
  182646. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182647. png_voidp s1, int value, png_uint_32 size));
  182648. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182649. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182650. int check));
  182651. #endif /* USE_FAR_KEYWORD */
  182652. #ifndef PNG_NO_ERROR_TEXT
  182653. /* Fatal error in PNG image of libpng - can't continue */
  182654. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182655. png_const_charp error_message));
  182656. /* The same, but the chunk name is prepended to the error string. */
  182657. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182658. png_const_charp error_message));
  182659. #else
  182660. /* Fatal error in PNG image of libpng - can't continue */
  182661. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182662. #endif
  182663. #ifndef PNG_NO_WARNINGS
  182664. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182665. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182666. png_const_charp warning_message));
  182667. #ifdef PNG_READ_SUPPORTED
  182668. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182669. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182670. png_const_charp warning_message));
  182671. #endif /* PNG_READ_SUPPORTED */
  182672. #endif /* PNG_NO_WARNINGS */
  182673. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182674. * Similarly, the png_get_<chunk> calls are used to read values from the
  182675. * png_info_struct, either storing the parameters in the passed variables, or
  182676. * setting pointers into the png_info_struct where the data is stored. The
  182677. * png_get_<chunk> functions return a non-zero value if the data was available
  182678. * in info_ptr, or return zero and do not change any of the parameters if the
  182679. * data was not available.
  182680. *
  182681. * These functions should be used instead of directly accessing png_info
  182682. * to avoid problems with future changes in the size and internal layout of
  182683. * png_info_struct.
  182684. */
  182685. /* Returns "flag" if chunk data is valid in info_ptr. */
  182686. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182687. png_infop info_ptr, png_uint_32 flag));
  182688. /* Returns number of bytes needed to hold a transformed row. */
  182689. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182690. png_infop info_ptr));
  182691. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182692. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182693. returned from png_read_png(). */
  182694. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182695. png_infop info_ptr));
  182696. /* Set row_pointers, which is an array of pointers to scanlines for use
  182697. by png_write_png(). */
  182698. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182699. png_infop info_ptr, png_bytepp row_pointers));
  182700. #endif
  182701. /* Returns number of color channels in image. */
  182702. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182703. png_infop info_ptr));
  182704. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182705. /* Returns image width in pixels. */
  182706. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182707. png_ptr, png_infop info_ptr));
  182708. /* Returns image height in pixels. */
  182709. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182710. png_ptr, png_infop info_ptr));
  182711. /* Returns image bit_depth. */
  182712. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182713. png_ptr, png_infop info_ptr));
  182714. /* Returns image color_type. */
  182715. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182716. png_ptr, png_infop info_ptr));
  182717. /* Returns image filter_type. */
  182718. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182719. png_ptr, png_infop info_ptr));
  182720. /* Returns image interlace_type. */
  182721. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182722. png_ptr, png_infop info_ptr));
  182723. /* Returns image compression_type. */
  182724. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182725. png_ptr, png_infop info_ptr));
  182726. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182727. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182728. png_ptr, png_infop info_ptr));
  182729. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182730. png_ptr, png_infop info_ptr));
  182731. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182732. png_ptr, png_infop info_ptr));
  182733. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182734. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182735. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182736. png_ptr, png_infop info_ptr));
  182737. #endif
  182738. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182739. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182740. png_ptr, png_infop info_ptr));
  182741. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182742. png_ptr, png_infop info_ptr));
  182743. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182744. png_ptr, png_infop info_ptr));
  182745. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182746. png_ptr, png_infop info_ptr));
  182747. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182748. /* Returns pointer to signature string read from PNG header */
  182749. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182750. png_infop info_ptr));
  182751. #if defined(PNG_bKGD_SUPPORTED)
  182752. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182753. png_infop info_ptr, png_color_16p *background));
  182754. #endif
  182755. #if defined(PNG_bKGD_SUPPORTED)
  182756. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182757. png_infop info_ptr, png_color_16p background));
  182758. #endif
  182759. #if defined(PNG_cHRM_SUPPORTED)
  182760. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182761. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182762. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182763. double *red_y, double *green_x, double *green_y, double *blue_x,
  182764. double *blue_y));
  182765. #endif
  182766. #ifdef PNG_FIXED_POINT_SUPPORTED
  182767. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182768. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182769. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182770. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182771. *int_blue_x, png_fixed_point *int_blue_y));
  182772. #endif
  182773. #endif
  182774. #if defined(PNG_cHRM_SUPPORTED)
  182775. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182776. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182777. png_infop info_ptr, double white_x, double white_y, double red_x,
  182778. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182779. #endif
  182780. #ifdef PNG_FIXED_POINT_SUPPORTED
  182781. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182782. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182783. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182784. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182785. png_fixed_point int_blue_y));
  182786. #endif
  182787. #endif
  182788. #if defined(PNG_gAMA_SUPPORTED)
  182789. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182790. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182791. png_infop info_ptr, double *file_gamma));
  182792. #endif
  182793. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182794. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182795. #endif
  182796. #if defined(PNG_gAMA_SUPPORTED)
  182797. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182798. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182799. png_infop info_ptr, double file_gamma));
  182800. #endif
  182801. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182802. png_infop info_ptr, png_fixed_point int_file_gamma));
  182803. #endif
  182804. #if defined(PNG_hIST_SUPPORTED)
  182805. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182806. png_infop info_ptr, png_uint_16p *hist));
  182807. #endif
  182808. #if defined(PNG_hIST_SUPPORTED)
  182809. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182810. png_infop info_ptr, png_uint_16p hist));
  182811. #endif
  182812. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182813. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182814. int *bit_depth, int *color_type, int *interlace_method,
  182815. int *compression_method, int *filter_method));
  182816. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182817. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182818. int color_type, int interlace_method, int compression_method,
  182819. int filter_method));
  182820. #if defined(PNG_oFFs_SUPPORTED)
  182821. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  182822. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  182823. int *unit_type));
  182824. #endif
  182825. #if defined(PNG_oFFs_SUPPORTED)
  182826. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  182827. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  182828. int unit_type));
  182829. #endif
  182830. #if defined(PNG_pCAL_SUPPORTED)
  182831. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  182832. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  182833. int *type, int *nparams, png_charp *units, png_charpp *params));
  182834. #endif
  182835. #if defined(PNG_pCAL_SUPPORTED)
  182836. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  182837. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  182838. int type, int nparams, png_charp units, png_charpp params));
  182839. #endif
  182840. #if defined(PNG_pHYs_SUPPORTED)
  182841. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  182842. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  182843. #endif
  182844. #if defined(PNG_pHYs_SUPPORTED)
  182845. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  182846. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  182847. #endif
  182848. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  182849. png_infop info_ptr, png_colorp *palette, int *num_palette));
  182850. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  182851. png_infop info_ptr, png_colorp palette, int num_palette));
  182852. #if defined(PNG_sBIT_SUPPORTED)
  182853. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  182854. png_infop info_ptr, png_color_8p *sig_bit));
  182855. #endif
  182856. #if defined(PNG_sBIT_SUPPORTED)
  182857. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  182858. png_infop info_ptr, png_color_8p sig_bit));
  182859. #endif
  182860. #if defined(PNG_sRGB_SUPPORTED)
  182861. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  182862. png_infop info_ptr, int *intent));
  182863. #endif
  182864. #if defined(PNG_sRGB_SUPPORTED)
  182865. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  182866. png_infop info_ptr, int intent));
  182867. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  182868. png_infop info_ptr, int intent));
  182869. #endif
  182870. #if defined(PNG_iCCP_SUPPORTED)
  182871. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  182872. png_infop info_ptr, png_charpp name, int *compression_type,
  182873. png_charpp profile, png_uint_32 *proflen));
  182874. /* Note to maintainer: profile should be png_bytepp */
  182875. #endif
  182876. #if defined(PNG_iCCP_SUPPORTED)
  182877. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  182878. png_infop info_ptr, png_charp name, int compression_type,
  182879. png_charp profile, png_uint_32 proflen));
  182880. /* Note to maintainer: profile should be png_bytep */
  182881. #endif
  182882. #if defined(PNG_sPLT_SUPPORTED)
  182883. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  182884. png_infop info_ptr, png_sPLT_tpp entries));
  182885. #endif
  182886. #if defined(PNG_sPLT_SUPPORTED)
  182887. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  182888. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  182889. #endif
  182890. #if defined(PNG_TEXT_SUPPORTED)
  182891. /* png_get_text also returns the number of text chunks in *num_text */
  182892. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  182893. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  182894. #endif
  182895. /*
  182896. * Note while png_set_text() will accept a structure whose text,
  182897. * language, and translated keywords are NULL pointers, the structure
  182898. * returned by png_get_text will always contain regular
  182899. * zero-terminated C strings. They might be empty strings but
  182900. * they will never be NULL pointers.
  182901. */
  182902. #if defined(PNG_TEXT_SUPPORTED)
  182903. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  182904. png_infop info_ptr, png_textp text_ptr, int num_text));
  182905. #endif
  182906. #if defined(PNG_tIME_SUPPORTED)
  182907. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  182908. png_infop info_ptr, png_timep *mod_time));
  182909. #endif
  182910. #if defined(PNG_tIME_SUPPORTED)
  182911. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  182912. png_infop info_ptr, png_timep mod_time));
  182913. #endif
  182914. #if defined(PNG_tRNS_SUPPORTED)
  182915. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  182916. png_infop info_ptr, png_bytep *trans, int *num_trans,
  182917. png_color_16p *trans_values));
  182918. #endif
  182919. #if defined(PNG_tRNS_SUPPORTED)
  182920. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  182921. png_infop info_ptr, png_bytep trans, int num_trans,
  182922. png_color_16p trans_values));
  182923. #endif
  182924. #if defined(PNG_tRNS_SUPPORTED)
  182925. #endif
  182926. #if defined(PNG_sCAL_SUPPORTED)
  182927. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182928. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  182929. png_infop info_ptr, int *unit, double *width, double *height));
  182930. #else
  182931. #ifdef PNG_FIXED_POINT_SUPPORTED
  182932. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  182933. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  182934. #endif
  182935. #endif
  182936. #endif /* PNG_sCAL_SUPPORTED */
  182937. #if defined(PNG_sCAL_SUPPORTED)
  182938. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182939. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  182940. png_infop info_ptr, int unit, double width, double height));
  182941. #else
  182942. #ifdef PNG_FIXED_POINT_SUPPORTED
  182943. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  182944. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  182945. #endif
  182946. #endif
  182947. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  182948. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182949. /* provide a list of chunks and how they are to be handled, if the built-in
  182950. handling or default unknown chunk handling is not desired. Any chunks not
  182951. listed will be handled in the default manner. The IHDR and IEND chunks
  182952. must not be listed.
  182953. keep = 0: follow default behaviour
  182954. = 1: do not keep
  182955. = 2: keep only if safe-to-copy
  182956. = 3: keep even if unsafe-to-copy
  182957. */
  182958. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  182959. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  182960. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  182961. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  182962. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  182963. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  182964. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  182965. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  182966. #endif
  182967. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182968. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  182969. chunk_name));
  182970. #endif
  182971. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  182972. If you need to turn it off for a chunk that your application has freed,
  182973. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  182974. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  182975. png_infop info_ptr, int mask));
  182976. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182977. /* The "params" pointer is currently not used and is for future expansion. */
  182978. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  182979. png_infop info_ptr,
  182980. int transforms,
  182981. png_voidp params));
  182982. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  182983. png_infop info_ptr,
  182984. int transforms,
  182985. png_voidp params));
  182986. #endif
  182987. /* Define PNG_DEBUG at compile time for debugging information. Higher
  182988. * numbers for PNG_DEBUG mean more debugging information. This has
  182989. * only been added since version 0.95 so it is not implemented throughout
  182990. * libpng yet, but more support will be added as needed.
  182991. */
  182992. #ifdef PNG_DEBUG
  182993. #if (PNG_DEBUG > 0)
  182994. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  182995. #include <crtdbg.h>
  182996. #if (PNG_DEBUG > 1)
  182997. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  182998. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  182999. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183000. #endif
  183001. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183002. #ifndef PNG_DEBUG_FILE
  183003. #define PNG_DEBUG_FILE stderr
  183004. #endif /* PNG_DEBUG_FILE */
  183005. #if (PNG_DEBUG > 1)
  183006. #define png_debug(l,m) \
  183007. { \
  183008. int num_tabs=l; \
  183009. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183010. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183011. }
  183012. #define png_debug1(l,m,p1) \
  183013. { \
  183014. int num_tabs=l; \
  183015. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183016. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183017. }
  183018. #define png_debug2(l,m,p1,p2) \
  183019. { \
  183020. int num_tabs=l; \
  183021. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183022. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183023. }
  183024. #endif /* (PNG_DEBUG > 1) */
  183025. #endif /* _MSC_VER */
  183026. #endif /* (PNG_DEBUG > 0) */
  183027. #endif /* PNG_DEBUG */
  183028. #ifndef png_debug
  183029. #define png_debug(l, m)
  183030. #endif
  183031. #ifndef png_debug1
  183032. #define png_debug1(l, m, p1)
  183033. #endif
  183034. #ifndef png_debug2
  183035. #define png_debug2(l, m, p1, p2)
  183036. #endif
  183037. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183038. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183039. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183040. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183041. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183042. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183043. png_ptr, png_uint_32 mng_features_permitted));
  183044. #endif
  183045. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183046. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183047. #define PNG_HANDLE_CHUNK_NEVER 1
  183048. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183049. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183050. /* Added to version 1.2.0 */
  183051. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183052. #if defined(PNG_MMX_CODE_SUPPORTED)
  183053. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183054. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183055. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183056. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183057. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183058. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183059. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183060. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183061. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183062. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183063. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183064. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183065. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183066. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183067. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183068. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183069. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183070. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183071. | PNG_MMX_READ_FLAGS \
  183072. | PNG_MMX_WRITE_FLAGS )
  183073. #define PNG_SELECT_READ 1
  183074. #define PNG_SELECT_WRITE 2
  183075. #endif /* PNG_MMX_CODE_SUPPORTED */
  183076. #if !defined(PNG_1_0_X)
  183077. /* pngget.c */
  183078. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183079. PNGARG((int flag_select, int *compilerID));
  183080. /* pngget.c */
  183081. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183082. PNGARG((int flag_select));
  183083. /* pngget.c */
  183084. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183085. PNGARG((png_structp png_ptr));
  183086. /* pngget.c */
  183087. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183088. PNGARG((png_structp png_ptr));
  183089. /* pngget.c */
  183090. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183091. PNGARG((png_structp png_ptr));
  183092. /* pngset.c */
  183093. extern PNG_EXPORT(void,png_set_asm_flags)
  183094. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183095. /* pngset.c */
  183096. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183097. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183098. png_uint_32 mmx_rowbytes_threshold));
  183099. #endif /* PNG_1_0_X */
  183100. #if !defined(PNG_1_0_X)
  183101. /* png.c, pnggccrd.c, or pngvcrd.c */
  183102. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183103. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183104. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183105. * messages before passing them to the error or warning handler. */
  183106. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183107. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183108. png_ptr, png_uint_32 strip_mode));
  183109. #endif
  183110. #endif /* PNG_1_0_X */
  183111. /* Added at libpng-1.2.6 */
  183112. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183113. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183114. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183115. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183116. png_ptr));
  183117. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183118. png_ptr));
  183119. #endif
  183120. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183121. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183122. /* With these routines we avoid an integer divide, which will be slower on
  183123. * most machines. However, it does take more operations than the corresponding
  183124. * divide method, so it may be slower on a few RISC systems. There are two
  183125. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183126. *
  183127. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183128. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183129. * standard method.
  183130. *
  183131. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183132. */
  183133. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183134. # define png_composite(composite, fg, alpha, bg) \
  183135. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183136. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183137. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183138. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183139. # define png_composite_16(composite, fg, alpha, bg) \
  183140. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183141. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183142. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183143. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183144. #else /* standard method using integer division */
  183145. # define png_composite(composite, fg, alpha, bg) \
  183146. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183147. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183148. (png_uint_16)127) / 255)
  183149. # define png_composite_16(composite, fg, alpha, bg) \
  183150. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183151. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183152. (png_uint_32)32767) / (png_uint_32)65535L)
  183153. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183154. /* Inline macros to do direct reads of bytes from the input buffer. These
  183155. * require that you are using an architecture that uses PNG byte ordering
  183156. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183157. * in big-endian mode and 680x0 are the only ones that will support this.
  183158. * The x86 line of processors definitely do not. The png_get_int_32()
  183159. * routine also assumes we are using two's complement format for negative
  183160. * values, which is almost certainly true.
  183161. */
  183162. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183163. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183164. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183165. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183166. #else
  183167. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183168. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183169. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183170. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183171. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183172. PNGARG((png_structp png_ptr, png_bytep buf));
  183173. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183174. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183175. */
  183176. extern PNG_EXPORT(void,png_save_uint_32)
  183177. PNGARG((png_bytep buf, png_uint_32 i));
  183178. extern PNG_EXPORT(void,png_save_int_32)
  183179. PNGARG((png_bytep buf, png_int_32 i));
  183180. /* Place a 16-bit number into a buffer in PNG byte order.
  183181. * The parameter is declared unsigned int, not png_uint_16,
  183182. * just to avoid potential problems on pre-ANSI C compilers.
  183183. */
  183184. extern PNG_EXPORT(void,png_save_uint_16)
  183185. PNGARG((png_bytep buf, unsigned int i));
  183186. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183187. /* ************************************************************************* */
  183188. /* These next functions are used internally in the code. They generally
  183189. * shouldn't be used unless you are writing code to add or replace some
  183190. * functionality in libpng. More information about most functions can
  183191. * be found in the files where the functions are located.
  183192. */
  183193. /* Various modes of operation, that are visible to applications because
  183194. * they are used for unknown chunk location.
  183195. */
  183196. #define PNG_HAVE_IHDR 0x01
  183197. #define PNG_HAVE_PLTE 0x02
  183198. #define PNG_HAVE_IDAT 0x04
  183199. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183200. #define PNG_HAVE_IEND 0x10
  183201. #if defined(PNG_INTERNAL)
  183202. /* More modes of operation. Note that after an init, mode is set to
  183203. * zero automatically when the structure is created.
  183204. */
  183205. #define PNG_HAVE_gAMA 0x20
  183206. #define PNG_HAVE_cHRM 0x40
  183207. #define PNG_HAVE_sRGB 0x80
  183208. #define PNG_HAVE_CHUNK_HEADER 0x100
  183209. #define PNG_WROTE_tIME 0x200
  183210. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183211. #define PNG_BACKGROUND_IS_GRAY 0x800
  183212. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183213. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183214. /* flags for the transformations the PNG library does on the image data */
  183215. #define PNG_BGR 0x0001
  183216. #define PNG_INTERLACE 0x0002
  183217. #define PNG_PACK 0x0004
  183218. #define PNG_SHIFT 0x0008
  183219. #define PNG_SWAP_BYTES 0x0010
  183220. #define PNG_INVERT_MONO 0x0020
  183221. #define PNG_DITHER 0x0040
  183222. #define PNG_BACKGROUND 0x0080
  183223. #define PNG_BACKGROUND_EXPAND 0x0100
  183224. /* 0x0200 unused */
  183225. #define PNG_16_TO_8 0x0400
  183226. #define PNG_RGBA 0x0800
  183227. #define PNG_EXPAND 0x1000
  183228. #define PNG_GAMMA 0x2000
  183229. #define PNG_GRAY_TO_RGB 0x4000
  183230. #define PNG_FILLER 0x8000L
  183231. #define PNG_PACKSWAP 0x10000L
  183232. #define PNG_SWAP_ALPHA 0x20000L
  183233. #define PNG_STRIP_ALPHA 0x40000L
  183234. #define PNG_INVERT_ALPHA 0x80000L
  183235. #define PNG_USER_TRANSFORM 0x100000L
  183236. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183237. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183238. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183239. /* 0x800000L Unused */
  183240. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183241. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183242. /* 0x4000000L unused */
  183243. /* 0x8000000L unused */
  183244. /* 0x10000000L unused */
  183245. /* 0x20000000L unused */
  183246. /* 0x40000000L unused */
  183247. /* flags for png_create_struct */
  183248. #define PNG_STRUCT_PNG 0x0001
  183249. #define PNG_STRUCT_INFO 0x0002
  183250. /* Scaling factor for filter heuristic weighting calculations */
  183251. #define PNG_WEIGHT_SHIFT 8
  183252. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183253. #define PNG_COST_SHIFT 3
  183254. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183255. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183256. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183257. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183258. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183259. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183260. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183261. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183262. #define PNG_FLAG_ROW_INIT 0x0040
  183263. #define PNG_FLAG_FILLER_AFTER 0x0080
  183264. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183265. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183266. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183267. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183268. #define PNG_FLAG_FREE_PLTE 0x1000
  183269. #define PNG_FLAG_FREE_TRNS 0x2000
  183270. #define PNG_FLAG_FREE_HIST 0x4000
  183271. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183272. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183273. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183274. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183275. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183276. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183277. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183278. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183279. /* 0x800000L unused */
  183280. /* 0x1000000L unused */
  183281. /* 0x2000000L unused */
  183282. /* 0x4000000L unused */
  183283. /* 0x8000000L unused */
  183284. /* 0x10000000L unused */
  183285. /* 0x20000000L unused */
  183286. /* 0x40000000L unused */
  183287. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183288. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183289. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183290. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183291. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183292. PNG_FLAG_CRC_CRITICAL_MASK)
  183293. /* save typing and make code easier to understand */
  183294. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183295. abs((int)((c1).green) - (int)((c2).green)) + \
  183296. abs((int)((c1).blue) - (int)((c2).blue)))
  183297. /* Added to libpng-1.2.6 JB */
  183298. #define PNG_ROWBYTES(pixel_bits, width) \
  183299. ((pixel_bits) >= 8 ? \
  183300. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183301. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183302. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183303. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183304. "ideal" and "delta" should be constants, normally simple
  183305. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183306. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183307. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183308. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183309. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183310. /* place to hold the signature string for a PNG file. */
  183311. #ifdef PNG_USE_GLOBAL_ARRAYS
  183312. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183313. #else
  183314. #endif
  183315. #endif /* PNG_NO_EXTERN */
  183316. /* Constant strings for known chunk types. If you need to add a chunk,
  183317. * define the name here, and add an invocation of the macro in png.c and
  183318. * wherever it's needed.
  183319. */
  183320. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183321. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183322. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183323. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183324. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183325. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183326. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183327. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183328. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183329. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183330. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183331. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183332. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183333. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183334. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183335. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183336. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183337. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183338. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183339. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183340. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183341. #ifdef PNG_USE_GLOBAL_ARRAYS
  183342. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183343. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183344. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183345. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183346. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183347. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183348. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183349. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183350. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183351. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183352. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183353. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183354. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183355. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183356. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183357. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183358. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183359. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183360. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183361. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183362. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183363. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183364. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183365. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183366. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183367. */
  183368. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183369. #undef png_read_init
  183370. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183371. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183372. #endif
  183373. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183374. png_const_charp user_png_ver, png_size_t png_struct_size));
  183375. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183376. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183377. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183378. png_info_size));
  183379. #endif
  183380. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183381. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183382. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183383. */
  183384. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183385. #undef png_write_init
  183386. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183387. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183388. #endif
  183389. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183390. png_const_charp user_png_ver, png_size_t png_struct_size));
  183391. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183392. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183393. png_info_size));
  183394. /* Allocate memory for an internal libpng struct */
  183395. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183396. /* Free memory from internal libpng struct */
  183397. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183398. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183399. malloc_fn, png_voidp mem_ptr));
  183400. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183401. png_free_ptr free_fn, png_voidp mem_ptr));
  183402. /* Free any memory that info_ptr points to and reset struct. */
  183403. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183404. png_infop info_ptr));
  183405. #ifndef PNG_1_0_X
  183406. /* Function to allocate memory for zlib. */
  183407. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183408. /* Function to free memory for zlib */
  183409. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183410. #ifdef PNG_SIZE_T
  183411. /* Function to convert a sizeof an item to png_sizeof item */
  183412. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183413. #endif
  183414. /* Next four functions are used internally as callbacks. PNGAPI is required
  183415. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183416. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183417. png_bytep data, png_size_t length));
  183418. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183419. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183420. png_bytep buffer, png_size_t length));
  183421. #endif
  183422. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183423. png_bytep data, png_size_t length));
  183424. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183425. #if !defined(PNG_NO_STDIO)
  183426. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183427. #endif
  183428. #endif
  183429. #else /* PNG_1_0_X */
  183430. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183431. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183432. png_bytep buffer, png_size_t length));
  183433. #endif
  183434. #endif /* PNG_1_0_X */
  183435. /* Reset the CRC variable */
  183436. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183437. /* Write the "data" buffer to whatever output you are using. */
  183438. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183439. png_size_t length));
  183440. /* Read data from whatever input you are using into the "data" buffer */
  183441. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183442. png_size_t length));
  183443. /* Read bytes into buf, and update png_ptr->crc */
  183444. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183445. png_size_t length));
  183446. /* Decompress data in a chunk that uses compression */
  183447. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183448. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183449. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183450. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183451. png_size_t prefix_length, png_size_t *data_length));
  183452. #endif
  183453. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183454. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183455. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183456. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183457. /* Calculate the CRC over a section of data. Note that we are only
  183458. * passing a maximum of 64K on systems that have this as a memory limit,
  183459. * since this is the maximum buffer size we can specify.
  183460. */
  183461. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183462. png_size_t length));
  183463. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183464. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183465. #endif
  183466. /* simple function to write the signature */
  183467. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183468. /* write various chunks */
  183469. /* Write the IHDR chunk, and update the png_struct with the necessary
  183470. * information.
  183471. */
  183472. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183473. png_uint_32 height,
  183474. int bit_depth, int color_type, int compression_method, int filter_method,
  183475. int interlace_method));
  183476. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183477. png_uint_32 num_pal));
  183478. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183479. png_size_t length));
  183480. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183481. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183482. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183483. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183484. #endif
  183485. #ifdef PNG_FIXED_POINT_SUPPORTED
  183486. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183487. file_gamma));
  183488. #endif
  183489. #endif
  183490. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183491. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183492. int color_type));
  183493. #endif
  183494. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183495. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183496. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183497. double white_x, double white_y,
  183498. double red_x, double red_y, double green_x, double green_y,
  183499. double blue_x, double blue_y));
  183500. #endif
  183501. #ifdef PNG_FIXED_POINT_SUPPORTED
  183502. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183503. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183504. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183505. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183506. png_fixed_point int_blue_y));
  183507. #endif
  183508. #endif
  183509. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183510. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183511. int intent));
  183512. #endif
  183513. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183514. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183515. png_charp name, int compression_type,
  183516. png_charp profile, int proflen));
  183517. /* Note to maintainer: profile should be png_bytep */
  183518. #endif
  183519. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183520. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183521. png_sPLT_tp palette));
  183522. #endif
  183523. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183524. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183525. png_color_16p values, int number, int color_type));
  183526. #endif
  183527. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183528. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183529. png_color_16p values, int color_type));
  183530. #endif
  183531. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183532. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183533. int num_hist));
  183534. #endif
  183535. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183536. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183537. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183538. png_charp key, png_charpp new_key));
  183539. #endif
  183540. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183541. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183542. png_charp text, png_size_t text_len));
  183543. #endif
  183544. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183545. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183546. png_charp text, png_size_t text_len, int compression));
  183547. #endif
  183548. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183549. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183550. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183551. png_charp text));
  183552. #endif
  183553. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183554. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183555. png_infop info_ptr, png_textp text_ptr, int num_text));
  183556. #endif
  183557. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183558. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183559. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183560. #endif
  183561. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183562. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183563. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183564. png_charp units, png_charpp params));
  183565. #endif
  183566. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183567. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183568. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183569. int unit_type));
  183570. #endif
  183571. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183572. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183573. png_timep mod_time));
  183574. #endif
  183575. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183576. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183577. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183578. int unit, double width, double height));
  183579. #else
  183580. #ifdef PNG_FIXED_POINT_SUPPORTED
  183581. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183582. int unit, png_charp width, png_charp height));
  183583. #endif
  183584. #endif
  183585. #endif
  183586. /* Called when finished processing a row of data */
  183587. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183588. /* Internal use only. Called before first row of data */
  183589. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183590. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183591. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183592. #endif
  183593. /* combine a row of data, dealing with alpha, etc. if requested */
  183594. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183595. int mask));
  183596. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183597. /* expand an interlaced row */
  183598. /* OLD pre-1.0.9 interface:
  183599. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183600. png_bytep row, int pass, png_uint_32 transformations));
  183601. */
  183602. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183603. #endif
  183604. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183605. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183606. /* grab pixels out of a row for an interlaced pass */
  183607. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183608. png_bytep row, int pass));
  183609. #endif
  183610. /* unfilter a row */
  183611. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183612. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183613. /* Choose the best filter to use and filter the row data */
  183614. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183615. png_row_infop row_info));
  183616. /* Write out the filtered row. */
  183617. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183618. png_bytep filtered_row));
  183619. /* finish a row while reading, dealing with interlacing passes, etc. */
  183620. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183621. /* initialize the row buffers, etc. */
  183622. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183623. /* optional call to update the users info structure */
  183624. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183625. png_infop info_ptr));
  183626. /* these are the functions that do the transformations */
  183627. #if defined(PNG_READ_FILLER_SUPPORTED)
  183628. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183629. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183630. #endif
  183631. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183632. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183633. png_bytep row));
  183634. #endif
  183635. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183636. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183637. png_bytep row));
  183638. #endif
  183639. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183640. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183641. png_bytep row));
  183642. #endif
  183643. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183644. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183645. png_bytep row));
  183646. #endif
  183647. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183648. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183649. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183650. png_bytep row, png_uint_32 flags));
  183651. #endif
  183652. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183653. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183654. #endif
  183655. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183656. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183657. #endif
  183658. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183659. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183660. row_info, png_bytep row));
  183661. #endif
  183662. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183663. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183664. png_bytep row));
  183665. #endif
  183666. #if defined(PNG_READ_PACK_SUPPORTED)
  183667. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183668. #endif
  183669. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183670. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183671. png_color_8p sig_bits));
  183672. #endif
  183673. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183674. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183675. #endif
  183676. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183677. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183678. #endif
  183679. #if defined(PNG_READ_DITHER_SUPPORTED)
  183680. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183681. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183682. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183683. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183684. png_colorp palette, int num_palette));
  183685. # endif
  183686. #endif
  183687. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183688. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183689. #endif
  183690. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183691. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183692. png_bytep row, png_uint_32 bit_depth));
  183693. #endif
  183694. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183695. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183696. png_color_8p bit_depth));
  183697. #endif
  183698. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183699. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183700. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183701. png_color_16p trans_values, png_color_16p background,
  183702. png_color_16p background_1,
  183703. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183704. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183705. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183706. #else
  183707. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183708. png_color_16p trans_values, png_color_16p background));
  183709. #endif
  183710. #endif
  183711. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183712. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183713. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183714. int gamma_shift));
  183715. #endif
  183716. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183717. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183718. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183719. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183720. png_bytep row, png_color_16p trans_value));
  183721. #endif
  183722. /* The following decodes the appropriate chunks, and does error correction,
  183723. * then calls the appropriate callback for the chunk if it is valid.
  183724. */
  183725. /* decode the IHDR chunk */
  183726. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183727. png_uint_32 length));
  183728. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183729. png_uint_32 length));
  183730. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183731. png_uint_32 length));
  183732. #if defined(PNG_READ_bKGD_SUPPORTED)
  183733. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183734. png_uint_32 length));
  183735. #endif
  183736. #if defined(PNG_READ_cHRM_SUPPORTED)
  183737. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183738. png_uint_32 length));
  183739. #endif
  183740. #if defined(PNG_READ_gAMA_SUPPORTED)
  183741. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183742. png_uint_32 length));
  183743. #endif
  183744. #if defined(PNG_READ_hIST_SUPPORTED)
  183745. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183746. png_uint_32 length));
  183747. #endif
  183748. #if defined(PNG_READ_iCCP_SUPPORTED)
  183749. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183750. png_uint_32 length));
  183751. #endif /* PNG_READ_iCCP_SUPPORTED */
  183752. #if defined(PNG_READ_iTXt_SUPPORTED)
  183753. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183754. png_uint_32 length));
  183755. #endif
  183756. #if defined(PNG_READ_oFFs_SUPPORTED)
  183757. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183758. png_uint_32 length));
  183759. #endif
  183760. #if defined(PNG_READ_pCAL_SUPPORTED)
  183761. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183762. png_uint_32 length));
  183763. #endif
  183764. #if defined(PNG_READ_pHYs_SUPPORTED)
  183765. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183766. png_uint_32 length));
  183767. #endif
  183768. #if defined(PNG_READ_sBIT_SUPPORTED)
  183769. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183770. png_uint_32 length));
  183771. #endif
  183772. #if defined(PNG_READ_sCAL_SUPPORTED)
  183773. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183774. png_uint_32 length));
  183775. #endif
  183776. #if defined(PNG_READ_sPLT_SUPPORTED)
  183777. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183778. png_uint_32 length));
  183779. #endif /* PNG_READ_sPLT_SUPPORTED */
  183780. #if defined(PNG_READ_sRGB_SUPPORTED)
  183781. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183782. png_uint_32 length));
  183783. #endif
  183784. #if defined(PNG_READ_tEXt_SUPPORTED)
  183785. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183786. png_uint_32 length));
  183787. #endif
  183788. #if defined(PNG_READ_tIME_SUPPORTED)
  183789. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183790. png_uint_32 length));
  183791. #endif
  183792. #if defined(PNG_READ_tRNS_SUPPORTED)
  183793. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183794. png_uint_32 length));
  183795. #endif
  183796. #if defined(PNG_READ_zTXt_SUPPORTED)
  183797. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183798. png_uint_32 length));
  183799. #endif
  183800. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183801. png_infop info_ptr, png_uint_32 length));
  183802. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183803. png_bytep chunk_name));
  183804. /* handle the transformations for reading and writing */
  183805. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183806. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183807. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183808. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183809. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183810. png_infop info_ptr));
  183811. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183812. png_infop info_ptr));
  183813. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183814. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183815. png_uint_32 length));
  183816. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183817. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183818. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183819. png_bytep buffer, png_size_t buffer_length));
  183820. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  183821. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  183822. png_bytep buffer, png_size_t buffer_length));
  183823. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  183824. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  183825. png_infop info_ptr, png_uint_32 length));
  183826. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  183827. png_infop info_ptr));
  183828. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  183829. png_infop info_ptr));
  183830. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  183831. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  183832. png_infop info_ptr));
  183833. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  183834. png_infop info_ptr));
  183835. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  183836. #if defined(PNG_READ_tEXt_SUPPORTED)
  183837. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  183838. png_infop info_ptr, png_uint_32 length));
  183839. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  183840. png_infop info_ptr));
  183841. #endif
  183842. #if defined(PNG_READ_zTXt_SUPPORTED)
  183843. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  183844. png_infop info_ptr, png_uint_32 length));
  183845. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  183846. png_infop info_ptr));
  183847. #endif
  183848. #if defined(PNG_READ_iTXt_SUPPORTED)
  183849. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  183850. png_infop info_ptr, png_uint_32 length));
  183851. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  183852. png_infop info_ptr));
  183853. #endif
  183854. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183855. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183856. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  183857. png_bytep row));
  183858. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  183859. png_bytep row));
  183860. #endif
  183861. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183862. #if defined(PNG_MMX_CODE_SUPPORTED)
  183863. /* png.c */ /* PRIVATE */
  183864. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  183865. #endif
  183866. #endif
  183867. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183868. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  183869. png_infop info_ptr));
  183870. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  183871. png_infop info_ptr));
  183872. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  183873. png_infop info_ptr));
  183874. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  183875. png_infop info_ptr));
  183876. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  183877. png_infop info_ptr));
  183878. #if defined(PNG_pHYs_SUPPORTED)
  183879. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  183880. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183881. #endif /* PNG_pHYs_SUPPORTED */
  183882. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  183883. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  183884. #endif /* PNG_INTERNAL */
  183885. #ifdef __cplusplus
  183886. }
  183887. #endif
  183888. #endif /* PNG_VERSION_INFO_ONLY */
  183889. /* do not put anything past this line */
  183890. #endif /* PNG_H */
  183891. /*** End of inlined file: png.h ***/
  183892. #define PNG_NO_EXTERN
  183893. /*** Start of inlined file: png.c ***/
  183894. /* png.c - location for general purpose libpng functions
  183895. *
  183896. * Last changed in libpng 1.2.21 [October 4, 2007]
  183897. * For conditions of distribution and use, see copyright notice in png.h
  183898. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183899. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183900. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183901. */
  183902. #define PNG_INTERNAL
  183903. #define PNG_NO_EXTERN
  183904. /* Generate a compiler error if there is an old png.h in the search path. */
  183905. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  183906. /* Version information for C files. This had better match the version
  183907. * string defined in png.h. */
  183908. #ifdef PNG_USE_GLOBAL_ARRAYS
  183909. /* png_libpng_ver was changed to a function in version 1.0.5c */
  183910. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  183911. #ifdef PNG_READ_SUPPORTED
  183912. /* png_sig was changed to a function in version 1.0.5c */
  183913. /* Place to hold the signature string for a PNG file. */
  183914. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183915. #endif /* PNG_READ_SUPPORTED */
  183916. /* Invoke global declarations for constant strings for known chunk types */
  183917. PNG_IHDR;
  183918. PNG_IDAT;
  183919. PNG_IEND;
  183920. PNG_PLTE;
  183921. PNG_bKGD;
  183922. PNG_cHRM;
  183923. PNG_gAMA;
  183924. PNG_hIST;
  183925. PNG_iCCP;
  183926. PNG_iTXt;
  183927. PNG_oFFs;
  183928. PNG_pCAL;
  183929. PNG_sCAL;
  183930. PNG_pHYs;
  183931. PNG_sBIT;
  183932. PNG_sPLT;
  183933. PNG_sRGB;
  183934. PNG_tEXt;
  183935. PNG_tIME;
  183936. PNG_tRNS;
  183937. PNG_zTXt;
  183938. #ifdef PNG_READ_SUPPORTED
  183939. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183940. /* start of interlace block */
  183941. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183942. /* offset to next interlace block */
  183943. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183944. /* start of interlace block in the y direction */
  183945. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183946. /* offset to next interlace block in the y direction */
  183947. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183948. /* Height of interlace block. This is not currently used - if you need
  183949. * it, uncomment it here and in png.h
  183950. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183951. */
  183952. /* Mask to determine which pixels are valid in a pass */
  183953. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183954. /* Mask to determine which pixels to overwrite while displaying */
  183955. PNG_CONST int FARDATA png_pass_dsp_mask[]
  183956. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183957. #endif /* PNG_READ_SUPPORTED */
  183958. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183959. /* Tells libpng that we have already handled the first "num_bytes" bytes
  183960. * of the PNG file signature. If the PNG data is embedded into another
  183961. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  183962. * or write any of the magic bytes before it starts on the IHDR.
  183963. */
  183964. #ifdef PNG_READ_SUPPORTED
  183965. void PNGAPI
  183966. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  183967. {
  183968. if(png_ptr == NULL) return;
  183969. png_debug(1, "in png_set_sig_bytes\n");
  183970. if (num_bytes > 8)
  183971. png_error(png_ptr, "Too many bytes for PNG signature.");
  183972. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  183973. }
  183974. /* Checks whether the supplied bytes match the PNG signature. We allow
  183975. * checking less than the full 8-byte signature so that those apps that
  183976. * already read the first few bytes of a file to determine the file type
  183977. * can simply check the remaining bytes for extra assurance. Returns
  183978. * an integer less than, equal to, or greater than zero if sig is found,
  183979. * respectively, to be less than, to match, or be greater than the correct
  183980. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  183981. */
  183982. int PNGAPI
  183983. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  183984. {
  183985. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183986. if (num_to_check > 8)
  183987. num_to_check = 8;
  183988. else if (num_to_check < 1)
  183989. return (-1);
  183990. if (start > 7)
  183991. return (-1);
  183992. if (start + num_to_check > 8)
  183993. num_to_check = 8 - start;
  183994. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  183995. }
  183996. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183997. /* (Obsolete) function to check signature bytes. It does not allow one
  183998. * to check a partial signature. This function might be removed in the
  183999. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184000. */
  184001. int PNGAPI
  184002. png_check_sig(png_bytep sig, int num)
  184003. {
  184004. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184005. }
  184006. #endif
  184007. #endif /* PNG_READ_SUPPORTED */
  184008. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184009. /* Function to allocate memory for zlib and clear it to 0. */
  184010. #ifdef PNG_1_0_X
  184011. voidpf PNGAPI
  184012. #else
  184013. voidpf /* private */
  184014. #endif
  184015. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184016. {
  184017. png_voidp ptr;
  184018. png_structp p=(png_structp)png_ptr;
  184019. png_uint_32 save_flags=p->flags;
  184020. png_uint_32 num_bytes;
  184021. if(png_ptr == NULL) return (NULL);
  184022. if (items > PNG_UINT_32_MAX/size)
  184023. {
  184024. png_warning (p, "Potential overflow in png_zalloc()");
  184025. return (NULL);
  184026. }
  184027. num_bytes = (png_uint_32)items * size;
  184028. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184029. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184030. p->flags=save_flags;
  184031. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184032. if (ptr == NULL)
  184033. return ((voidpf)ptr);
  184034. if (num_bytes > (png_uint_32)0x8000L)
  184035. {
  184036. png_memset(ptr, 0, (png_size_t)0x8000L);
  184037. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184038. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184039. }
  184040. else
  184041. {
  184042. png_memset(ptr, 0, (png_size_t)num_bytes);
  184043. }
  184044. #endif
  184045. return ((voidpf)ptr);
  184046. }
  184047. /* function to free memory for zlib */
  184048. #ifdef PNG_1_0_X
  184049. void PNGAPI
  184050. #else
  184051. void /* private */
  184052. #endif
  184053. png_zfree(voidpf png_ptr, voidpf ptr)
  184054. {
  184055. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184056. }
  184057. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184058. * in case CRC is > 32 bits to leave the top bits 0.
  184059. */
  184060. void /* PRIVATE */
  184061. png_reset_crc(png_structp png_ptr)
  184062. {
  184063. png_ptr->crc = crc32(0, Z_NULL, 0);
  184064. }
  184065. /* Calculate the CRC over a section of data. We can only pass as
  184066. * much data to this routine as the largest single buffer size. We
  184067. * also check that this data will actually be used before going to the
  184068. * trouble of calculating it.
  184069. */
  184070. void /* PRIVATE */
  184071. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184072. {
  184073. int need_crc = 1;
  184074. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184075. {
  184076. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184077. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184078. need_crc = 0;
  184079. }
  184080. else /* critical */
  184081. {
  184082. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184083. need_crc = 0;
  184084. }
  184085. if (need_crc)
  184086. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184087. }
  184088. /* Allocate the memory for an info_struct for the application. We don't
  184089. * really need the png_ptr, but it could potentially be useful in the
  184090. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184091. * and png_info_init() so that applications that want to use a shared
  184092. * libpng don't have to be recompiled if png_info changes size.
  184093. */
  184094. png_infop PNGAPI
  184095. png_create_info_struct(png_structp png_ptr)
  184096. {
  184097. png_infop info_ptr;
  184098. png_debug(1, "in png_create_info_struct\n");
  184099. if(png_ptr == NULL) return (NULL);
  184100. #ifdef PNG_USER_MEM_SUPPORTED
  184101. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184102. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184103. #else
  184104. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184105. #endif
  184106. if (info_ptr != NULL)
  184107. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184108. return (info_ptr);
  184109. }
  184110. /* This function frees the memory associated with a single info struct.
  184111. * Normally, one would use either png_destroy_read_struct() or
  184112. * png_destroy_write_struct() to free an info struct, but this may be
  184113. * useful for some applications.
  184114. */
  184115. void PNGAPI
  184116. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184117. {
  184118. png_infop info_ptr = NULL;
  184119. if(png_ptr == NULL) return;
  184120. png_debug(1, "in png_destroy_info_struct\n");
  184121. if (info_ptr_ptr != NULL)
  184122. info_ptr = *info_ptr_ptr;
  184123. if (info_ptr != NULL)
  184124. {
  184125. png_info_destroy(png_ptr, info_ptr);
  184126. #ifdef PNG_USER_MEM_SUPPORTED
  184127. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184128. png_ptr->mem_ptr);
  184129. #else
  184130. png_destroy_struct((png_voidp)info_ptr);
  184131. #endif
  184132. *info_ptr_ptr = NULL;
  184133. }
  184134. }
  184135. /* Initialize the info structure. This is now an internal function (0.89)
  184136. * and applications using it are urged to use png_create_info_struct()
  184137. * instead.
  184138. */
  184139. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184140. #undef png_info_init
  184141. void PNGAPI
  184142. png_info_init(png_infop info_ptr)
  184143. {
  184144. /* We only come here via pre-1.0.12-compiled applications */
  184145. png_info_init_3(&info_ptr, 0);
  184146. }
  184147. #endif
  184148. void PNGAPI
  184149. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184150. {
  184151. png_infop info_ptr = *ptr_ptr;
  184152. if(info_ptr == NULL) return;
  184153. png_debug(1, "in png_info_init_3\n");
  184154. if(png_sizeof(png_info) > png_info_struct_size)
  184155. {
  184156. png_destroy_struct(info_ptr);
  184157. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184158. *ptr_ptr = info_ptr;
  184159. }
  184160. /* set everything to 0 */
  184161. png_memset(info_ptr, 0, png_sizeof (png_info));
  184162. }
  184163. #ifdef PNG_FREE_ME_SUPPORTED
  184164. void PNGAPI
  184165. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184166. int freer, png_uint_32 mask)
  184167. {
  184168. png_debug(1, "in png_data_freer\n");
  184169. if (png_ptr == NULL || info_ptr == NULL)
  184170. return;
  184171. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184172. info_ptr->free_me |= mask;
  184173. else if(freer == PNG_USER_WILL_FREE_DATA)
  184174. info_ptr->free_me &= ~mask;
  184175. else
  184176. png_warning(png_ptr,
  184177. "Unknown freer parameter in png_data_freer.");
  184178. }
  184179. #endif
  184180. void PNGAPI
  184181. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184182. int num)
  184183. {
  184184. png_debug(1, "in png_free_data\n");
  184185. if (png_ptr == NULL || info_ptr == NULL)
  184186. return;
  184187. #if defined(PNG_TEXT_SUPPORTED)
  184188. /* free text item num or (if num == -1) all text items */
  184189. #ifdef PNG_FREE_ME_SUPPORTED
  184190. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184191. #else
  184192. if (mask & PNG_FREE_TEXT)
  184193. #endif
  184194. {
  184195. if (num != -1)
  184196. {
  184197. if (info_ptr->text && info_ptr->text[num].key)
  184198. {
  184199. png_free(png_ptr, info_ptr->text[num].key);
  184200. info_ptr->text[num].key = NULL;
  184201. }
  184202. }
  184203. else
  184204. {
  184205. int i;
  184206. for (i = 0; i < info_ptr->num_text; i++)
  184207. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184208. png_free(png_ptr, info_ptr->text);
  184209. info_ptr->text = NULL;
  184210. info_ptr->num_text=0;
  184211. }
  184212. }
  184213. #endif
  184214. #if defined(PNG_tRNS_SUPPORTED)
  184215. /* free any tRNS entry */
  184216. #ifdef PNG_FREE_ME_SUPPORTED
  184217. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184218. #else
  184219. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184220. #endif
  184221. {
  184222. png_free(png_ptr, info_ptr->trans);
  184223. info_ptr->valid &= ~PNG_INFO_tRNS;
  184224. #ifndef PNG_FREE_ME_SUPPORTED
  184225. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184226. #endif
  184227. info_ptr->trans = NULL;
  184228. }
  184229. #endif
  184230. #if defined(PNG_sCAL_SUPPORTED)
  184231. /* free any sCAL entry */
  184232. #ifdef PNG_FREE_ME_SUPPORTED
  184233. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184234. #else
  184235. if (mask & PNG_FREE_SCAL)
  184236. #endif
  184237. {
  184238. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184239. png_free(png_ptr, info_ptr->scal_s_width);
  184240. png_free(png_ptr, info_ptr->scal_s_height);
  184241. info_ptr->scal_s_width = NULL;
  184242. info_ptr->scal_s_height = NULL;
  184243. #endif
  184244. info_ptr->valid &= ~PNG_INFO_sCAL;
  184245. }
  184246. #endif
  184247. #if defined(PNG_pCAL_SUPPORTED)
  184248. /* free any pCAL entry */
  184249. #ifdef PNG_FREE_ME_SUPPORTED
  184250. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184251. #else
  184252. if (mask & PNG_FREE_PCAL)
  184253. #endif
  184254. {
  184255. png_free(png_ptr, info_ptr->pcal_purpose);
  184256. png_free(png_ptr, info_ptr->pcal_units);
  184257. info_ptr->pcal_purpose = NULL;
  184258. info_ptr->pcal_units = NULL;
  184259. if (info_ptr->pcal_params != NULL)
  184260. {
  184261. int i;
  184262. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184263. {
  184264. png_free(png_ptr, info_ptr->pcal_params[i]);
  184265. info_ptr->pcal_params[i]=NULL;
  184266. }
  184267. png_free(png_ptr, info_ptr->pcal_params);
  184268. info_ptr->pcal_params = NULL;
  184269. }
  184270. info_ptr->valid &= ~PNG_INFO_pCAL;
  184271. }
  184272. #endif
  184273. #if defined(PNG_iCCP_SUPPORTED)
  184274. /* free any iCCP entry */
  184275. #ifdef PNG_FREE_ME_SUPPORTED
  184276. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184277. #else
  184278. if (mask & PNG_FREE_ICCP)
  184279. #endif
  184280. {
  184281. png_free(png_ptr, info_ptr->iccp_name);
  184282. png_free(png_ptr, info_ptr->iccp_profile);
  184283. info_ptr->iccp_name = NULL;
  184284. info_ptr->iccp_profile = NULL;
  184285. info_ptr->valid &= ~PNG_INFO_iCCP;
  184286. }
  184287. #endif
  184288. #if defined(PNG_sPLT_SUPPORTED)
  184289. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184290. #ifdef PNG_FREE_ME_SUPPORTED
  184291. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184292. #else
  184293. if (mask & PNG_FREE_SPLT)
  184294. #endif
  184295. {
  184296. if (num != -1)
  184297. {
  184298. if(info_ptr->splt_palettes)
  184299. {
  184300. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184301. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184302. info_ptr->splt_palettes[num].name = NULL;
  184303. info_ptr->splt_palettes[num].entries = NULL;
  184304. }
  184305. }
  184306. else
  184307. {
  184308. if(info_ptr->splt_palettes_num)
  184309. {
  184310. int i;
  184311. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184312. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184313. png_free(png_ptr, info_ptr->splt_palettes);
  184314. info_ptr->splt_palettes = NULL;
  184315. info_ptr->splt_palettes_num = 0;
  184316. }
  184317. info_ptr->valid &= ~PNG_INFO_sPLT;
  184318. }
  184319. }
  184320. #endif
  184321. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184322. if(png_ptr->unknown_chunk.data)
  184323. {
  184324. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184325. png_ptr->unknown_chunk.data = NULL;
  184326. }
  184327. #ifdef PNG_FREE_ME_SUPPORTED
  184328. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184329. #else
  184330. if (mask & PNG_FREE_UNKN)
  184331. #endif
  184332. {
  184333. if (num != -1)
  184334. {
  184335. if(info_ptr->unknown_chunks)
  184336. {
  184337. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184338. info_ptr->unknown_chunks[num].data = NULL;
  184339. }
  184340. }
  184341. else
  184342. {
  184343. int i;
  184344. if(info_ptr->unknown_chunks_num)
  184345. {
  184346. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184347. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184348. png_free(png_ptr, info_ptr->unknown_chunks);
  184349. info_ptr->unknown_chunks = NULL;
  184350. info_ptr->unknown_chunks_num = 0;
  184351. }
  184352. }
  184353. }
  184354. #endif
  184355. #if defined(PNG_hIST_SUPPORTED)
  184356. /* free any hIST entry */
  184357. #ifdef PNG_FREE_ME_SUPPORTED
  184358. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184359. #else
  184360. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184361. #endif
  184362. {
  184363. png_free(png_ptr, info_ptr->hist);
  184364. info_ptr->hist = NULL;
  184365. info_ptr->valid &= ~PNG_INFO_hIST;
  184366. #ifndef PNG_FREE_ME_SUPPORTED
  184367. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184368. #endif
  184369. }
  184370. #endif
  184371. /* free any PLTE entry that was internally allocated */
  184372. #ifdef PNG_FREE_ME_SUPPORTED
  184373. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184374. #else
  184375. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184376. #endif
  184377. {
  184378. png_zfree(png_ptr, info_ptr->palette);
  184379. info_ptr->palette = NULL;
  184380. info_ptr->valid &= ~PNG_INFO_PLTE;
  184381. #ifndef PNG_FREE_ME_SUPPORTED
  184382. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184383. #endif
  184384. info_ptr->num_palette = 0;
  184385. }
  184386. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184387. /* free any image bits attached to the info structure */
  184388. #ifdef PNG_FREE_ME_SUPPORTED
  184389. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184390. #else
  184391. if (mask & PNG_FREE_ROWS)
  184392. #endif
  184393. {
  184394. if(info_ptr->row_pointers)
  184395. {
  184396. int row;
  184397. for (row = 0; row < (int)info_ptr->height; row++)
  184398. {
  184399. png_free(png_ptr, info_ptr->row_pointers[row]);
  184400. info_ptr->row_pointers[row]=NULL;
  184401. }
  184402. png_free(png_ptr, info_ptr->row_pointers);
  184403. info_ptr->row_pointers=NULL;
  184404. }
  184405. info_ptr->valid &= ~PNG_INFO_IDAT;
  184406. }
  184407. #endif
  184408. #ifdef PNG_FREE_ME_SUPPORTED
  184409. if(num == -1)
  184410. info_ptr->free_me &= ~mask;
  184411. else
  184412. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184413. #endif
  184414. }
  184415. /* This is an internal routine to free any memory that the info struct is
  184416. * pointing to before re-using it or freeing the struct itself. Recall
  184417. * that png_free() checks for NULL pointers for us.
  184418. */
  184419. void /* PRIVATE */
  184420. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184421. {
  184422. png_debug(1, "in png_info_destroy\n");
  184423. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184424. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184425. if (png_ptr->num_chunk_list)
  184426. {
  184427. png_free(png_ptr, png_ptr->chunk_list);
  184428. png_ptr->chunk_list=NULL;
  184429. png_ptr->num_chunk_list=0;
  184430. }
  184431. #endif
  184432. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184433. }
  184434. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184435. /* This function returns a pointer to the io_ptr associated with the user
  184436. * functions. The application should free any memory associated with this
  184437. * pointer before png_write_destroy() or png_read_destroy() are called.
  184438. */
  184439. png_voidp PNGAPI
  184440. png_get_io_ptr(png_structp png_ptr)
  184441. {
  184442. if(png_ptr == NULL) return (NULL);
  184443. return (png_ptr->io_ptr);
  184444. }
  184445. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184446. #if !defined(PNG_NO_STDIO)
  184447. /* Initialize the default input/output functions for the PNG file. If you
  184448. * use your own read or write routines, you can call either png_set_read_fn()
  184449. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184450. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184451. * necessarily available.
  184452. */
  184453. void PNGAPI
  184454. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184455. {
  184456. png_debug(1, "in png_init_io\n");
  184457. if(png_ptr == NULL) return;
  184458. png_ptr->io_ptr = (png_voidp)fp;
  184459. }
  184460. #endif
  184461. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184462. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184463. * a "Creation Time" or other text-based time string.
  184464. */
  184465. png_charp PNGAPI
  184466. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184467. {
  184468. static PNG_CONST char short_months[12][4] =
  184469. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184470. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184471. if(png_ptr == NULL) return (NULL);
  184472. if (png_ptr->time_buffer == NULL)
  184473. {
  184474. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184475. png_sizeof(char)));
  184476. }
  184477. #if defined(_WIN32_WCE)
  184478. {
  184479. wchar_t time_buf[29];
  184480. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184481. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184482. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184483. ptime->second % 61);
  184484. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184485. NULL, NULL);
  184486. }
  184487. #else
  184488. #ifdef USE_FAR_KEYWORD
  184489. {
  184490. char near_time_buf[29];
  184491. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184492. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184493. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184494. ptime->second % 61);
  184495. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184496. 29*png_sizeof(char));
  184497. }
  184498. #else
  184499. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184500. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184501. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184502. ptime->second % 61);
  184503. #endif
  184504. #endif /* _WIN32_WCE */
  184505. return ((png_charp)png_ptr->time_buffer);
  184506. }
  184507. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184508. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184509. png_charp PNGAPI
  184510. png_get_copyright(png_structp png_ptr)
  184511. {
  184512. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184513. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184514. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184515. Copyright (c) 1996-1997 Andreas Dilger\n\
  184516. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184517. }
  184518. /* The following return the library version as a short string in the
  184519. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184520. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184521. * is defined in png.h.
  184522. * Note: now there is no difference between png_get_libpng_ver() and
  184523. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184524. * it is guaranteed that png.c uses the correct version of png.h.
  184525. */
  184526. png_charp PNGAPI
  184527. png_get_libpng_ver(png_structp png_ptr)
  184528. {
  184529. /* Version of *.c files used when building libpng */
  184530. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184531. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184532. }
  184533. png_charp PNGAPI
  184534. png_get_header_ver(png_structp png_ptr)
  184535. {
  184536. /* Version of *.h files used when building libpng */
  184537. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184538. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184539. }
  184540. png_charp PNGAPI
  184541. png_get_header_version(png_structp png_ptr)
  184542. {
  184543. /* Returns longer string containing both version and date */
  184544. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184545. return ((png_charp) PNG_HEADER_VERSION_STRING
  184546. #ifndef PNG_READ_SUPPORTED
  184547. " (NO READ SUPPORT)"
  184548. #endif
  184549. "\n");
  184550. }
  184551. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184552. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184553. int PNGAPI
  184554. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184555. {
  184556. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184557. int i;
  184558. png_bytep p;
  184559. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184560. return 0;
  184561. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184562. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184563. if (!png_memcmp(chunk_name, p, 4))
  184564. return ((int)*(p+4));
  184565. return 0;
  184566. }
  184567. #endif
  184568. /* This function, added to libpng-1.0.6g, is untested. */
  184569. int PNGAPI
  184570. png_reset_zstream(png_structp png_ptr)
  184571. {
  184572. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184573. return (inflateReset(&png_ptr->zstream));
  184574. }
  184575. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184576. /* This function was added to libpng-1.0.7 */
  184577. png_uint_32 PNGAPI
  184578. png_access_version_number(void)
  184579. {
  184580. /* Version of *.c files used when building libpng */
  184581. return((png_uint_32) PNG_LIBPNG_VER);
  184582. }
  184583. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184584. #if !defined(PNG_1_0_X)
  184585. /* this function was added to libpng 1.2.0 */
  184586. int PNGAPI
  184587. png_mmx_support(void)
  184588. {
  184589. /* obsolete, to be removed from libpng-1.4.0 */
  184590. return -1;
  184591. }
  184592. #endif /* PNG_1_0_X */
  184593. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184594. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184595. #ifdef PNG_SIZE_T
  184596. /* Added at libpng version 1.2.6 */
  184597. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184598. png_size_t PNGAPI
  184599. png_convert_size(size_t size)
  184600. {
  184601. if (size > (png_size_t)-1)
  184602. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184603. return ((png_size_t)size);
  184604. }
  184605. #endif /* PNG_SIZE_T */
  184606. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184607. /*** End of inlined file: png.c ***/
  184608. /*** Start of inlined file: pngerror.c ***/
  184609. /* pngerror.c - stub functions for i/o and memory allocation
  184610. *
  184611. * Last changed in libpng 1.2.20 October 4, 2007
  184612. * For conditions of distribution and use, see copyright notice in png.h
  184613. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184614. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184615. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184616. *
  184617. * This file provides a location for all error handling. Users who
  184618. * need special error handling are expected to write replacement functions
  184619. * and use png_set_error_fn() to use those functions. See the instructions
  184620. * at each function.
  184621. */
  184622. #define PNG_INTERNAL
  184623. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184624. static void /* PRIVATE */
  184625. png_default_error PNGARG((png_structp png_ptr,
  184626. png_const_charp error_message));
  184627. #ifndef PNG_NO_WARNINGS
  184628. static void /* PRIVATE */
  184629. png_default_warning PNGARG((png_structp png_ptr,
  184630. png_const_charp warning_message));
  184631. #endif /* PNG_NO_WARNINGS */
  184632. /* This function is called whenever there is a fatal error. This function
  184633. * should not be changed. If there is a need to handle errors differently,
  184634. * you should supply a replacement error function and use png_set_error_fn()
  184635. * to replace the error function at run-time.
  184636. */
  184637. #ifndef PNG_NO_ERROR_TEXT
  184638. void PNGAPI
  184639. png_error(png_structp png_ptr, png_const_charp error_message)
  184640. {
  184641. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184642. char msg[16];
  184643. if (png_ptr != NULL)
  184644. {
  184645. if (png_ptr->flags&
  184646. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184647. {
  184648. if (*error_message == '#')
  184649. {
  184650. int offset;
  184651. for (offset=1; offset<15; offset++)
  184652. if (*(error_message+offset) == ' ')
  184653. break;
  184654. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184655. {
  184656. int i;
  184657. for (i=0; i<offset-1; i++)
  184658. msg[i]=error_message[i+1];
  184659. msg[i]='\0';
  184660. error_message=msg;
  184661. }
  184662. else
  184663. error_message+=offset;
  184664. }
  184665. else
  184666. {
  184667. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184668. {
  184669. msg[0]='0';
  184670. msg[1]='\0';
  184671. error_message=msg;
  184672. }
  184673. }
  184674. }
  184675. }
  184676. #endif
  184677. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184678. (*(png_ptr->error_fn))(png_ptr, error_message);
  184679. /* If the custom handler doesn't exist, or if it returns,
  184680. use the default handler, which will not return. */
  184681. png_default_error(png_ptr, error_message);
  184682. }
  184683. #else
  184684. void PNGAPI
  184685. png_err(png_structp png_ptr)
  184686. {
  184687. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184688. (*(png_ptr->error_fn))(png_ptr, '\0');
  184689. /* If the custom handler doesn't exist, or if it returns,
  184690. use the default handler, which will not return. */
  184691. png_default_error(png_ptr, '\0');
  184692. }
  184693. #endif /* PNG_NO_ERROR_TEXT */
  184694. #ifndef PNG_NO_WARNINGS
  184695. /* This function is called whenever there is a non-fatal error. This function
  184696. * should not be changed. If there is a need to handle warnings differently,
  184697. * you should supply a replacement warning function and use
  184698. * png_set_error_fn() to replace the warning function at run-time.
  184699. */
  184700. void PNGAPI
  184701. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184702. {
  184703. int offset = 0;
  184704. if (png_ptr != NULL)
  184705. {
  184706. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184707. if (png_ptr->flags&
  184708. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184709. #endif
  184710. {
  184711. if (*warning_message == '#')
  184712. {
  184713. for (offset=1; offset<15; offset++)
  184714. if (*(warning_message+offset) == ' ')
  184715. break;
  184716. }
  184717. }
  184718. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184719. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184720. }
  184721. else
  184722. png_default_warning(png_ptr, warning_message+offset);
  184723. }
  184724. #endif /* PNG_NO_WARNINGS */
  184725. /* These utilities are used internally to build an error message that relates
  184726. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184727. * this is used to prefix the message. The message is limited in length
  184728. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184729. * if the character is invalid.
  184730. */
  184731. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184732. /*static PNG_CONST char png_digit[16] = {
  184733. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184734. 'A', 'B', 'C', 'D', 'E', 'F'
  184735. };*/
  184736. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184737. static void /* PRIVATE */
  184738. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184739. error_message)
  184740. {
  184741. int iout = 0, iin = 0;
  184742. while (iin < 4)
  184743. {
  184744. int c = png_ptr->chunk_name[iin++];
  184745. if (isnonalpha(c))
  184746. {
  184747. buffer[iout++] = '[';
  184748. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184749. buffer[iout++] = png_digit[c & 0x0f];
  184750. buffer[iout++] = ']';
  184751. }
  184752. else
  184753. {
  184754. buffer[iout++] = (png_byte)c;
  184755. }
  184756. }
  184757. if (error_message == NULL)
  184758. buffer[iout] = 0;
  184759. else
  184760. {
  184761. buffer[iout++] = ':';
  184762. buffer[iout++] = ' ';
  184763. png_strncpy(buffer+iout, error_message, 63);
  184764. buffer[iout+63] = 0;
  184765. }
  184766. }
  184767. #ifdef PNG_READ_SUPPORTED
  184768. void PNGAPI
  184769. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184770. {
  184771. char msg[18+64];
  184772. if (png_ptr == NULL)
  184773. png_error(png_ptr, error_message);
  184774. else
  184775. {
  184776. png_format_buffer(png_ptr, msg, error_message);
  184777. png_error(png_ptr, msg);
  184778. }
  184779. }
  184780. #endif /* PNG_READ_SUPPORTED */
  184781. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184782. #ifndef PNG_NO_WARNINGS
  184783. void PNGAPI
  184784. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184785. {
  184786. char msg[18+64];
  184787. if (png_ptr == NULL)
  184788. png_warning(png_ptr, warning_message);
  184789. else
  184790. {
  184791. png_format_buffer(png_ptr, msg, warning_message);
  184792. png_warning(png_ptr, msg);
  184793. }
  184794. }
  184795. #endif /* PNG_NO_WARNINGS */
  184796. /* This is the default error handling function. Note that replacements for
  184797. * this function MUST NOT RETURN, or the program will likely crash. This
  184798. * function is used by default, or if the program supplies NULL for the
  184799. * error function pointer in png_set_error_fn().
  184800. */
  184801. static void /* PRIVATE */
  184802. png_default_error(png_structp, png_const_charp error_message)
  184803. {
  184804. #ifndef PNG_NO_CONSOLE_IO
  184805. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184806. if (*error_message == '#')
  184807. {
  184808. int offset;
  184809. char error_number[16];
  184810. for (offset=0; offset<15; offset++)
  184811. {
  184812. error_number[offset] = *(error_message+offset+1);
  184813. if (*(error_message+offset) == ' ')
  184814. break;
  184815. }
  184816. if((offset > 1) && (offset < 15))
  184817. {
  184818. error_number[offset-1]='\0';
  184819. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  184820. error_message+offset);
  184821. }
  184822. else
  184823. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  184824. }
  184825. else
  184826. #endif
  184827. fprintf(stderr, "libpng error: %s\n", error_message);
  184828. #endif
  184829. #ifdef PNG_SETJMP_SUPPORTED
  184830. if (png_ptr)
  184831. {
  184832. # ifdef USE_FAR_KEYWORD
  184833. {
  184834. jmp_buf jmpbuf;
  184835. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  184836. longjmp(jmpbuf, 1);
  184837. }
  184838. # else
  184839. longjmp(png_ptr->jmpbuf, 1);
  184840. # endif
  184841. }
  184842. #else
  184843. PNG_ABORT();
  184844. #endif
  184845. #ifdef PNG_NO_CONSOLE_IO
  184846. error_message = error_message; /* make compiler happy */
  184847. #endif
  184848. }
  184849. #ifndef PNG_NO_WARNINGS
  184850. /* This function is called when there is a warning, but the library thinks
  184851. * it can continue anyway. Replacement functions don't have to do anything
  184852. * here if you don't want them to. In the default configuration, png_ptr is
  184853. * not used, but it is passed in case it may be useful.
  184854. */
  184855. static void /* PRIVATE */
  184856. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  184857. {
  184858. #ifndef PNG_NO_CONSOLE_IO
  184859. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184860. if (*warning_message == '#')
  184861. {
  184862. int offset;
  184863. char warning_number[16];
  184864. for (offset=0; offset<15; offset++)
  184865. {
  184866. warning_number[offset]=*(warning_message+offset+1);
  184867. if (*(warning_message+offset) == ' ')
  184868. break;
  184869. }
  184870. if((offset > 1) && (offset < 15))
  184871. {
  184872. warning_number[offset-1]='\0';
  184873. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  184874. warning_message+offset);
  184875. }
  184876. else
  184877. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184878. }
  184879. else
  184880. # endif
  184881. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184882. #else
  184883. warning_message = warning_message; /* make compiler happy */
  184884. #endif
  184885. png_ptr = png_ptr; /* make compiler happy */
  184886. }
  184887. #endif /* PNG_NO_WARNINGS */
  184888. /* This function is called when the application wants to use another method
  184889. * of handling errors and warnings. Note that the error function MUST NOT
  184890. * return to the calling routine or serious problems will occur. The return
  184891. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  184892. */
  184893. void PNGAPI
  184894. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  184895. png_error_ptr error_fn, png_error_ptr warning_fn)
  184896. {
  184897. if (png_ptr == NULL)
  184898. return;
  184899. png_ptr->error_ptr = error_ptr;
  184900. png_ptr->error_fn = error_fn;
  184901. png_ptr->warning_fn = warning_fn;
  184902. }
  184903. /* This function returns a pointer to the error_ptr associated with the user
  184904. * functions. The application should free any memory associated with this
  184905. * pointer before png_write_destroy and png_read_destroy are called.
  184906. */
  184907. png_voidp PNGAPI
  184908. png_get_error_ptr(png_structp png_ptr)
  184909. {
  184910. if (png_ptr == NULL)
  184911. return NULL;
  184912. return ((png_voidp)png_ptr->error_ptr);
  184913. }
  184914. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184915. void PNGAPI
  184916. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  184917. {
  184918. if(png_ptr != NULL)
  184919. {
  184920. png_ptr->flags &=
  184921. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  184922. }
  184923. }
  184924. #endif
  184925. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184926. /*** End of inlined file: pngerror.c ***/
  184927. /*** Start of inlined file: pngget.c ***/
  184928. /* pngget.c - retrieval of values from info struct
  184929. *
  184930. * Last changed in libpng 1.2.15 January 5, 2007
  184931. * For conditions of distribution and use, see copyright notice in png.h
  184932. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184933. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184934. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184935. */
  184936. #define PNG_INTERNAL
  184937. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184938. png_uint_32 PNGAPI
  184939. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  184940. {
  184941. if (png_ptr != NULL && info_ptr != NULL)
  184942. return(info_ptr->valid & flag);
  184943. else
  184944. return(0);
  184945. }
  184946. png_uint_32 PNGAPI
  184947. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  184948. {
  184949. if (png_ptr != NULL && info_ptr != NULL)
  184950. return(info_ptr->rowbytes);
  184951. else
  184952. return(0);
  184953. }
  184954. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184955. png_bytepp PNGAPI
  184956. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  184957. {
  184958. if (png_ptr != NULL && info_ptr != NULL)
  184959. return(info_ptr->row_pointers);
  184960. else
  184961. return(0);
  184962. }
  184963. #endif
  184964. #ifdef PNG_EASY_ACCESS_SUPPORTED
  184965. /* easy access to info, added in libpng-0.99 */
  184966. png_uint_32 PNGAPI
  184967. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  184968. {
  184969. if (png_ptr != NULL && info_ptr != NULL)
  184970. {
  184971. return info_ptr->width;
  184972. }
  184973. return (0);
  184974. }
  184975. png_uint_32 PNGAPI
  184976. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  184977. {
  184978. if (png_ptr != NULL && info_ptr != NULL)
  184979. {
  184980. return info_ptr->height;
  184981. }
  184982. return (0);
  184983. }
  184984. png_byte PNGAPI
  184985. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  184986. {
  184987. if (png_ptr != NULL && info_ptr != NULL)
  184988. {
  184989. return info_ptr->bit_depth;
  184990. }
  184991. return (0);
  184992. }
  184993. png_byte PNGAPI
  184994. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  184995. {
  184996. if (png_ptr != NULL && info_ptr != NULL)
  184997. {
  184998. return info_ptr->color_type;
  184999. }
  185000. return (0);
  185001. }
  185002. png_byte PNGAPI
  185003. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185004. {
  185005. if (png_ptr != NULL && info_ptr != NULL)
  185006. {
  185007. return info_ptr->filter_type;
  185008. }
  185009. return (0);
  185010. }
  185011. png_byte PNGAPI
  185012. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185013. {
  185014. if (png_ptr != NULL && info_ptr != NULL)
  185015. {
  185016. return info_ptr->interlace_type;
  185017. }
  185018. return (0);
  185019. }
  185020. png_byte PNGAPI
  185021. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185022. {
  185023. if (png_ptr != NULL && info_ptr != NULL)
  185024. {
  185025. return info_ptr->compression_type;
  185026. }
  185027. return (0);
  185028. }
  185029. png_uint_32 PNGAPI
  185030. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185031. {
  185032. if (png_ptr != NULL && info_ptr != NULL)
  185033. #if defined(PNG_pHYs_SUPPORTED)
  185034. if (info_ptr->valid & PNG_INFO_pHYs)
  185035. {
  185036. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185037. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185038. return (0);
  185039. else return (info_ptr->x_pixels_per_unit);
  185040. }
  185041. #else
  185042. return (0);
  185043. #endif
  185044. return (0);
  185045. }
  185046. png_uint_32 PNGAPI
  185047. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185048. {
  185049. if (png_ptr != NULL && info_ptr != NULL)
  185050. #if defined(PNG_pHYs_SUPPORTED)
  185051. if (info_ptr->valid & PNG_INFO_pHYs)
  185052. {
  185053. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185054. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185055. return (0);
  185056. else return (info_ptr->y_pixels_per_unit);
  185057. }
  185058. #else
  185059. return (0);
  185060. #endif
  185061. return (0);
  185062. }
  185063. png_uint_32 PNGAPI
  185064. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185065. {
  185066. if (png_ptr != NULL && info_ptr != NULL)
  185067. #if defined(PNG_pHYs_SUPPORTED)
  185068. if (info_ptr->valid & PNG_INFO_pHYs)
  185069. {
  185070. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185071. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185072. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185073. return (0);
  185074. else return (info_ptr->x_pixels_per_unit);
  185075. }
  185076. #else
  185077. return (0);
  185078. #endif
  185079. return (0);
  185080. }
  185081. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185082. float PNGAPI
  185083. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185084. {
  185085. if (png_ptr != NULL && info_ptr != NULL)
  185086. #if defined(PNG_pHYs_SUPPORTED)
  185087. if (info_ptr->valid & PNG_INFO_pHYs)
  185088. {
  185089. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185090. if (info_ptr->x_pixels_per_unit == 0)
  185091. return ((float)0.0);
  185092. else
  185093. return ((float)((float)info_ptr->y_pixels_per_unit
  185094. /(float)info_ptr->x_pixels_per_unit));
  185095. }
  185096. #else
  185097. return (0.0);
  185098. #endif
  185099. return ((float)0.0);
  185100. }
  185101. #endif
  185102. png_int_32 PNGAPI
  185103. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185104. {
  185105. if (png_ptr != NULL && info_ptr != NULL)
  185106. #if defined(PNG_oFFs_SUPPORTED)
  185107. if (info_ptr->valid & PNG_INFO_oFFs)
  185108. {
  185109. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185110. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185111. return (0);
  185112. else return (info_ptr->x_offset);
  185113. }
  185114. #else
  185115. return (0);
  185116. #endif
  185117. return (0);
  185118. }
  185119. png_int_32 PNGAPI
  185120. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185121. {
  185122. if (png_ptr != NULL && info_ptr != NULL)
  185123. #if defined(PNG_oFFs_SUPPORTED)
  185124. if (info_ptr->valid & PNG_INFO_oFFs)
  185125. {
  185126. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185127. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185128. return (0);
  185129. else return (info_ptr->y_offset);
  185130. }
  185131. #else
  185132. return (0);
  185133. #endif
  185134. return (0);
  185135. }
  185136. png_int_32 PNGAPI
  185137. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185138. {
  185139. if (png_ptr != NULL && info_ptr != NULL)
  185140. #if defined(PNG_oFFs_SUPPORTED)
  185141. if (info_ptr->valid & PNG_INFO_oFFs)
  185142. {
  185143. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185144. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185145. return (0);
  185146. else return (info_ptr->x_offset);
  185147. }
  185148. #else
  185149. return (0);
  185150. #endif
  185151. return (0);
  185152. }
  185153. png_int_32 PNGAPI
  185154. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185155. {
  185156. if (png_ptr != NULL && info_ptr != NULL)
  185157. #if defined(PNG_oFFs_SUPPORTED)
  185158. if (info_ptr->valid & PNG_INFO_oFFs)
  185159. {
  185160. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185161. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185162. return (0);
  185163. else return (info_ptr->y_offset);
  185164. }
  185165. #else
  185166. return (0);
  185167. #endif
  185168. return (0);
  185169. }
  185170. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185171. png_uint_32 PNGAPI
  185172. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185173. {
  185174. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185175. *.0254 +.5));
  185176. }
  185177. png_uint_32 PNGAPI
  185178. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185179. {
  185180. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185181. *.0254 +.5));
  185182. }
  185183. png_uint_32 PNGAPI
  185184. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185185. {
  185186. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185187. *.0254 +.5));
  185188. }
  185189. float PNGAPI
  185190. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185191. {
  185192. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185193. *.00003937);
  185194. }
  185195. float PNGAPI
  185196. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185197. {
  185198. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185199. *.00003937);
  185200. }
  185201. #if defined(PNG_pHYs_SUPPORTED)
  185202. png_uint_32 PNGAPI
  185203. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185204. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185205. {
  185206. png_uint_32 retval = 0;
  185207. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185208. {
  185209. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185210. if (res_x != NULL)
  185211. {
  185212. *res_x = info_ptr->x_pixels_per_unit;
  185213. retval |= PNG_INFO_pHYs;
  185214. }
  185215. if (res_y != NULL)
  185216. {
  185217. *res_y = info_ptr->y_pixels_per_unit;
  185218. retval |= PNG_INFO_pHYs;
  185219. }
  185220. if (unit_type != NULL)
  185221. {
  185222. *unit_type = (int)info_ptr->phys_unit_type;
  185223. retval |= PNG_INFO_pHYs;
  185224. if(*unit_type == 1)
  185225. {
  185226. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185227. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185228. }
  185229. }
  185230. }
  185231. return (retval);
  185232. }
  185233. #endif /* PNG_pHYs_SUPPORTED */
  185234. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185235. /* png_get_channels really belongs in here, too, but it's been around longer */
  185236. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185237. png_byte PNGAPI
  185238. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185239. {
  185240. if (png_ptr != NULL && info_ptr != NULL)
  185241. return(info_ptr->channels);
  185242. else
  185243. return (0);
  185244. }
  185245. png_bytep PNGAPI
  185246. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185247. {
  185248. if (png_ptr != NULL && info_ptr != NULL)
  185249. return(info_ptr->signature);
  185250. else
  185251. return (NULL);
  185252. }
  185253. #if defined(PNG_bKGD_SUPPORTED)
  185254. png_uint_32 PNGAPI
  185255. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185256. png_color_16p *background)
  185257. {
  185258. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185259. && background != NULL)
  185260. {
  185261. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185262. *background = &(info_ptr->background);
  185263. return (PNG_INFO_bKGD);
  185264. }
  185265. return (0);
  185266. }
  185267. #endif
  185268. #if defined(PNG_cHRM_SUPPORTED)
  185269. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185270. png_uint_32 PNGAPI
  185271. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185272. double *white_x, double *white_y, double *red_x, double *red_y,
  185273. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185274. {
  185275. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185276. {
  185277. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185278. if (white_x != NULL)
  185279. *white_x = (double)info_ptr->x_white;
  185280. if (white_y != NULL)
  185281. *white_y = (double)info_ptr->y_white;
  185282. if (red_x != NULL)
  185283. *red_x = (double)info_ptr->x_red;
  185284. if (red_y != NULL)
  185285. *red_y = (double)info_ptr->y_red;
  185286. if (green_x != NULL)
  185287. *green_x = (double)info_ptr->x_green;
  185288. if (green_y != NULL)
  185289. *green_y = (double)info_ptr->y_green;
  185290. if (blue_x != NULL)
  185291. *blue_x = (double)info_ptr->x_blue;
  185292. if (blue_y != NULL)
  185293. *blue_y = (double)info_ptr->y_blue;
  185294. return (PNG_INFO_cHRM);
  185295. }
  185296. return (0);
  185297. }
  185298. #endif
  185299. #ifdef PNG_FIXED_POINT_SUPPORTED
  185300. png_uint_32 PNGAPI
  185301. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185302. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185303. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185304. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185305. {
  185306. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185307. {
  185308. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185309. if (white_x != NULL)
  185310. *white_x = info_ptr->int_x_white;
  185311. if (white_y != NULL)
  185312. *white_y = info_ptr->int_y_white;
  185313. if (red_x != NULL)
  185314. *red_x = info_ptr->int_x_red;
  185315. if (red_y != NULL)
  185316. *red_y = info_ptr->int_y_red;
  185317. if (green_x != NULL)
  185318. *green_x = info_ptr->int_x_green;
  185319. if (green_y != NULL)
  185320. *green_y = info_ptr->int_y_green;
  185321. if (blue_x != NULL)
  185322. *blue_x = info_ptr->int_x_blue;
  185323. if (blue_y != NULL)
  185324. *blue_y = info_ptr->int_y_blue;
  185325. return (PNG_INFO_cHRM);
  185326. }
  185327. return (0);
  185328. }
  185329. #endif
  185330. #endif
  185331. #if defined(PNG_gAMA_SUPPORTED)
  185332. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185333. png_uint_32 PNGAPI
  185334. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185335. {
  185336. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185337. && file_gamma != NULL)
  185338. {
  185339. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185340. *file_gamma = (double)info_ptr->gamma;
  185341. return (PNG_INFO_gAMA);
  185342. }
  185343. return (0);
  185344. }
  185345. #endif
  185346. #ifdef PNG_FIXED_POINT_SUPPORTED
  185347. png_uint_32 PNGAPI
  185348. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185349. png_fixed_point *int_file_gamma)
  185350. {
  185351. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185352. && int_file_gamma != NULL)
  185353. {
  185354. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185355. *int_file_gamma = info_ptr->int_gamma;
  185356. return (PNG_INFO_gAMA);
  185357. }
  185358. return (0);
  185359. }
  185360. #endif
  185361. #endif
  185362. #if defined(PNG_sRGB_SUPPORTED)
  185363. png_uint_32 PNGAPI
  185364. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185365. {
  185366. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185367. && file_srgb_intent != NULL)
  185368. {
  185369. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185370. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185371. return (PNG_INFO_sRGB);
  185372. }
  185373. return (0);
  185374. }
  185375. #endif
  185376. #if defined(PNG_iCCP_SUPPORTED)
  185377. png_uint_32 PNGAPI
  185378. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185379. png_charpp name, int *compression_type,
  185380. png_charpp profile, png_uint_32 *proflen)
  185381. {
  185382. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185383. && name != NULL && profile != NULL && proflen != NULL)
  185384. {
  185385. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185386. *name = info_ptr->iccp_name;
  185387. *profile = info_ptr->iccp_profile;
  185388. /* compression_type is a dummy so the API won't have to change
  185389. if we introduce multiple compression types later. */
  185390. *proflen = (int)info_ptr->iccp_proflen;
  185391. *compression_type = (int)info_ptr->iccp_compression;
  185392. return (PNG_INFO_iCCP);
  185393. }
  185394. return (0);
  185395. }
  185396. #endif
  185397. #if defined(PNG_sPLT_SUPPORTED)
  185398. png_uint_32 PNGAPI
  185399. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185400. png_sPLT_tpp spalettes)
  185401. {
  185402. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185403. {
  185404. *spalettes = info_ptr->splt_palettes;
  185405. return ((png_uint_32)info_ptr->splt_palettes_num);
  185406. }
  185407. return (0);
  185408. }
  185409. #endif
  185410. #if defined(PNG_hIST_SUPPORTED)
  185411. png_uint_32 PNGAPI
  185412. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185413. {
  185414. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185415. && hist != NULL)
  185416. {
  185417. png_debug1(1, "in %s retrieval function\n", "hIST");
  185418. *hist = info_ptr->hist;
  185419. return (PNG_INFO_hIST);
  185420. }
  185421. return (0);
  185422. }
  185423. #endif
  185424. png_uint_32 PNGAPI
  185425. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185426. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185427. int *color_type, int *interlace_type, int *compression_type,
  185428. int *filter_type)
  185429. {
  185430. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185431. bit_depth != NULL && color_type != NULL)
  185432. {
  185433. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185434. *width = info_ptr->width;
  185435. *height = info_ptr->height;
  185436. *bit_depth = info_ptr->bit_depth;
  185437. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185438. png_error(png_ptr, "Invalid bit depth");
  185439. *color_type = info_ptr->color_type;
  185440. if (info_ptr->color_type > 6)
  185441. png_error(png_ptr, "Invalid color type");
  185442. if (compression_type != NULL)
  185443. *compression_type = info_ptr->compression_type;
  185444. if (filter_type != NULL)
  185445. *filter_type = info_ptr->filter_type;
  185446. if (interlace_type != NULL)
  185447. *interlace_type = info_ptr->interlace_type;
  185448. /* check for potential overflow of rowbytes */
  185449. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185450. png_error(png_ptr, "Invalid image width");
  185451. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185452. png_error(png_ptr, "Invalid image height");
  185453. if (info_ptr->width > (PNG_UINT_32_MAX
  185454. >> 3) /* 8-byte RGBA pixels */
  185455. - 64 /* bigrowbuf hack */
  185456. - 1 /* filter byte */
  185457. - 7*8 /* rounding of width to multiple of 8 pixels */
  185458. - 8) /* extra max_pixel_depth pad */
  185459. {
  185460. png_warning(png_ptr,
  185461. "Width too large for libpng to process image data.");
  185462. }
  185463. return (1);
  185464. }
  185465. return (0);
  185466. }
  185467. #if defined(PNG_oFFs_SUPPORTED)
  185468. png_uint_32 PNGAPI
  185469. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185470. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185471. {
  185472. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185473. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185474. {
  185475. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185476. *offset_x = info_ptr->x_offset;
  185477. *offset_y = info_ptr->y_offset;
  185478. *unit_type = (int)info_ptr->offset_unit_type;
  185479. return (PNG_INFO_oFFs);
  185480. }
  185481. return (0);
  185482. }
  185483. #endif
  185484. #if defined(PNG_pCAL_SUPPORTED)
  185485. png_uint_32 PNGAPI
  185486. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185487. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185488. png_charp *units, png_charpp *params)
  185489. {
  185490. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185491. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185492. nparams != NULL && units != NULL && params != NULL)
  185493. {
  185494. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185495. *purpose = info_ptr->pcal_purpose;
  185496. *X0 = info_ptr->pcal_X0;
  185497. *X1 = info_ptr->pcal_X1;
  185498. *type = (int)info_ptr->pcal_type;
  185499. *nparams = (int)info_ptr->pcal_nparams;
  185500. *units = info_ptr->pcal_units;
  185501. *params = info_ptr->pcal_params;
  185502. return (PNG_INFO_pCAL);
  185503. }
  185504. return (0);
  185505. }
  185506. #endif
  185507. #if defined(PNG_sCAL_SUPPORTED)
  185508. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185509. png_uint_32 PNGAPI
  185510. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185511. int *unit, double *width, double *height)
  185512. {
  185513. if (png_ptr != NULL && info_ptr != NULL &&
  185514. (info_ptr->valid & PNG_INFO_sCAL))
  185515. {
  185516. *unit = info_ptr->scal_unit;
  185517. *width = info_ptr->scal_pixel_width;
  185518. *height = info_ptr->scal_pixel_height;
  185519. return (PNG_INFO_sCAL);
  185520. }
  185521. return(0);
  185522. }
  185523. #else
  185524. #ifdef PNG_FIXED_POINT_SUPPORTED
  185525. png_uint_32 PNGAPI
  185526. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185527. int *unit, png_charpp width, png_charpp height)
  185528. {
  185529. if (png_ptr != NULL && info_ptr != NULL &&
  185530. (info_ptr->valid & PNG_INFO_sCAL))
  185531. {
  185532. *unit = info_ptr->scal_unit;
  185533. *width = info_ptr->scal_s_width;
  185534. *height = info_ptr->scal_s_height;
  185535. return (PNG_INFO_sCAL);
  185536. }
  185537. return(0);
  185538. }
  185539. #endif
  185540. #endif
  185541. #endif
  185542. #if defined(PNG_pHYs_SUPPORTED)
  185543. png_uint_32 PNGAPI
  185544. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185545. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185546. {
  185547. png_uint_32 retval = 0;
  185548. if (png_ptr != NULL && info_ptr != NULL &&
  185549. (info_ptr->valid & PNG_INFO_pHYs))
  185550. {
  185551. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185552. if (res_x != NULL)
  185553. {
  185554. *res_x = info_ptr->x_pixels_per_unit;
  185555. retval |= PNG_INFO_pHYs;
  185556. }
  185557. if (res_y != NULL)
  185558. {
  185559. *res_y = info_ptr->y_pixels_per_unit;
  185560. retval |= PNG_INFO_pHYs;
  185561. }
  185562. if (unit_type != NULL)
  185563. {
  185564. *unit_type = (int)info_ptr->phys_unit_type;
  185565. retval |= PNG_INFO_pHYs;
  185566. }
  185567. }
  185568. return (retval);
  185569. }
  185570. #endif
  185571. png_uint_32 PNGAPI
  185572. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185573. int *num_palette)
  185574. {
  185575. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185576. && palette != NULL)
  185577. {
  185578. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185579. *palette = info_ptr->palette;
  185580. *num_palette = info_ptr->num_palette;
  185581. png_debug1(3, "num_palette = %d\n", *num_palette);
  185582. return (PNG_INFO_PLTE);
  185583. }
  185584. return (0);
  185585. }
  185586. #if defined(PNG_sBIT_SUPPORTED)
  185587. png_uint_32 PNGAPI
  185588. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185589. {
  185590. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185591. && sig_bit != NULL)
  185592. {
  185593. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185594. *sig_bit = &(info_ptr->sig_bit);
  185595. return (PNG_INFO_sBIT);
  185596. }
  185597. return (0);
  185598. }
  185599. #endif
  185600. #if defined(PNG_TEXT_SUPPORTED)
  185601. png_uint_32 PNGAPI
  185602. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185603. int *num_text)
  185604. {
  185605. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185606. {
  185607. png_debug1(1, "in %s retrieval function\n",
  185608. (png_ptr->chunk_name[0] == '\0' ? "text"
  185609. : (png_const_charp)png_ptr->chunk_name));
  185610. if (text_ptr != NULL)
  185611. *text_ptr = info_ptr->text;
  185612. if (num_text != NULL)
  185613. *num_text = info_ptr->num_text;
  185614. return ((png_uint_32)info_ptr->num_text);
  185615. }
  185616. if (num_text != NULL)
  185617. *num_text = 0;
  185618. return(0);
  185619. }
  185620. #endif
  185621. #if defined(PNG_tIME_SUPPORTED)
  185622. png_uint_32 PNGAPI
  185623. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185624. {
  185625. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185626. && mod_time != NULL)
  185627. {
  185628. png_debug1(1, "in %s retrieval function\n", "tIME");
  185629. *mod_time = &(info_ptr->mod_time);
  185630. return (PNG_INFO_tIME);
  185631. }
  185632. return (0);
  185633. }
  185634. #endif
  185635. #if defined(PNG_tRNS_SUPPORTED)
  185636. png_uint_32 PNGAPI
  185637. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185638. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185639. {
  185640. png_uint_32 retval = 0;
  185641. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185642. {
  185643. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185644. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185645. {
  185646. if (trans != NULL)
  185647. {
  185648. *trans = info_ptr->trans;
  185649. retval |= PNG_INFO_tRNS;
  185650. }
  185651. if (trans_values != NULL)
  185652. *trans_values = &(info_ptr->trans_values);
  185653. }
  185654. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185655. {
  185656. if (trans_values != NULL)
  185657. {
  185658. *trans_values = &(info_ptr->trans_values);
  185659. retval |= PNG_INFO_tRNS;
  185660. }
  185661. if(trans != NULL)
  185662. *trans = NULL;
  185663. }
  185664. if(num_trans != NULL)
  185665. {
  185666. *num_trans = info_ptr->num_trans;
  185667. retval |= PNG_INFO_tRNS;
  185668. }
  185669. }
  185670. return (retval);
  185671. }
  185672. #endif
  185673. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185674. png_uint_32 PNGAPI
  185675. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185676. png_unknown_chunkpp unknowns)
  185677. {
  185678. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185679. {
  185680. *unknowns = info_ptr->unknown_chunks;
  185681. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185682. }
  185683. return (0);
  185684. }
  185685. #endif
  185686. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185687. png_byte PNGAPI
  185688. png_get_rgb_to_gray_status (png_structp png_ptr)
  185689. {
  185690. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185691. }
  185692. #endif
  185693. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185694. png_voidp PNGAPI
  185695. png_get_user_chunk_ptr(png_structp png_ptr)
  185696. {
  185697. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185698. }
  185699. #endif
  185700. #ifdef PNG_WRITE_SUPPORTED
  185701. png_uint_32 PNGAPI
  185702. png_get_compression_buffer_size(png_structp png_ptr)
  185703. {
  185704. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185705. }
  185706. #endif
  185707. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185708. #ifndef PNG_1_0_X
  185709. /* this function was added to libpng 1.2.0 and should exist by default */
  185710. png_uint_32 PNGAPI
  185711. png_get_asm_flags (png_structp png_ptr)
  185712. {
  185713. /* obsolete, to be removed from libpng-1.4.0 */
  185714. return (png_ptr? 0L: 0L);
  185715. }
  185716. /* this function was added to libpng 1.2.0 and should exist by default */
  185717. png_uint_32 PNGAPI
  185718. png_get_asm_flagmask (int flag_select)
  185719. {
  185720. /* obsolete, to be removed from libpng-1.4.0 */
  185721. flag_select=flag_select;
  185722. return 0L;
  185723. }
  185724. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185725. /* this function was added to libpng 1.2.0 */
  185726. png_uint_32 PNGAPI
  185727. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185728. {
  185729. /* obsolete, to be removed from libpng-1.4.0 */
  185730. flag_select=flag_select;
  185731. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185732. return 0L;
  185733. }
  185734. /* this function was added to libpng 1.2.0 */
  185735. png_byte PNGAPI
  185736. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185737. {
  185738. /* obsolete, to be removed from libpng-1.4.0 */
  185739. return (png_ptr? 0: 0);
  185740. }
  185741. /* this function was added to libpng 1.2.0 */
  185742. png_uint_32 PNGAPI
  185743. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185744. {
  185745. /* obsolete, to be removed from libpng-1.4.0 */
  185746. return (png_ptr? 0L: 0L);
  185747. }
  185748. #endif /* ?PNG_1_0_X */
  185749. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185750. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185751. /* these functions were added to libpng 1.2.6 */
  185752. png_uint_32 PNGAPI
  185753. png_get_user_width_max (png_structp png_ptr)
  185754. {
  185755. return (png_ptr? png_ptr->user_width_max : 0);
  185756. }
  185757. png_uint_32 PNGAPI
  185758. png_get_user_height_max (png_structp png_ptr)
  185759. {
  185760. return (png_ptr? png_ptr->user_height_max : 0);
  185761. }
  185762. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185763. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185764. /*** End of inlined file: pngget.c ***/
  185765. /*** Start of inlined file: pngmem.c ***/
  185766. /* pngmem.c - stub functions for memory allocation
  185767. *
  185768. * Last changed in libpng 1.2.13 November 13, 2006
  185769. * For conditions of distribution and use, see copyright notice in png.h
  185770. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185771. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185772. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185773. *
  185774. * This file provides a location for all memory allocation. Users who
  185775. * need special memory handling are expected to supply replacement
  185776. * functions for png_malloc() and png_free(), and to use
  185777. * png_create_read_struct_2() and png_create_write_struct_2() to
  185778. * identify the replacement functions.
  185779. */
  185780. #define PNG_INTERNAL
  185781. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185782. /* Borland DOS special memory handler */
  185783. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185784. /* if you change this, be sure to change the one in png.h also */
  185785. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185786. by a single call to calloc() if this is thought to improve performance. */
  185787. png_voidp /* PRIVATE */
  185788. png_create_struct(int type)
  185789. {
  185790. #ifdef PNG_USER_MEM_SUPPORTED
  185791. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185792. }
  185793. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185794. png_voidp /* PRIVATE */
  185795. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185796. {
  185797. #endif /* PNG_USER_MEM_SUPPORTED */
  185798. png_size_t size;
  185799. png_voidp struct_ptr;
  185800. if (type == PNG_STRUCT_INFO)
  185801. size = png_sizeof(png_info);
  185802. else if (type == PNG_STRUCT_PNG)
  185803. size = png_sizeof(png_struct);
  185804. else
  185805. return (png_get_copyright(NULL));
  185806. #ifdef PNG_USER_MEM_SUPPORTED
  185807. if(malloc_fn != NULL)
  185808. {
  185809. png_struct dummy_struct;
  185810. png_structp png_ptr = &dummy_struct;
  185811. png_ptr->mem_ptr=mem_ptr;
  185812. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185813. }
  185814. else
  185815. #endif /* PNG_USER_MEM_SUPPORTED */
  185816. struct_ptr = (png_voidp)farmalloc(size);
  185817. if (struct_ptr != NULL)
  185818. png_memset(struct_ptr, 0, size);
  185819. return (struct_ptr);
  185820. }
  185821. /* Free memory allocated by a png_create_struct() call */
  185822. void /* PRIVATE */
  185823. png_destroy_struct(png_voidp struct_ptr)
  185824. {
  185825. #ifdef PNG_USER_MEM_SUPPORTED
  185826. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185827. }
  185828. /* Free memory allocated by a png_create_struct() call */
  185829. void /* PRIVATE */
  185830. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185831. png_voidp mem_ptr)
  185832. {
  185833. #endif
  185834. if (struct_ptr != NULL)
  185835. {
  185836. #ifdef PNG_USER_MEM_SUPPORTED
  185837. if(free_fn != NULL)
  185838. {
  185839. png_struct dummy_struct;
  185840. png_structp png_ptr = &dummy_struct;
  185841. png_ptr->mem_ptr=mem_ptr;
  185842. (*(free_fn))(png_ptr, struct_ptr);
  185843. return;
  185844. }
  185845. #endif /* PNG_USER_MEM_SUPPORTED */
  185846. farfree (struct_ptr);
  185847. }
  185848. }
  185849. /* Allocate memory. For reasonable files, size should never exceed
  185850. * 64K. However, zlib may allocate more then 64K if you don't tell
  185851. * it not to. See zconf.h and png.h for more information. zlib does
  185852. * need to allocate exactly 64K, so whatever you call here must
  185853. * have the ability to do that.
  185854. *
  185855. * Borland seems to have a problem in DOS mode for exactly 64K.
  185856. * It gives you a segment with an offset of 8 (perhaps to store its
  185857. * memory stuff). zlib doesn't like this at all, so we have to
  185858. * detect and deal with it. This code should not be needed in
  185859. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  185860. * been updated by Alexander Lehmann for version 0.89 to waste less
  185861. * memory.
  185862. *
  185863. * Note that we can't use png_size_t for the "size" declaration,
  185864. * since on some systems a png_size_t is a 16-bit quantity, and as a
  185865. * result, we would be truncating potentially larger memory requests
  185866. * (which should cause a fatal error) and introducing major problems.
  185867. */
  185868. png_voidp PNGAPI
  185869. png_malloc(png_structp png_ptr, png_uint_32 size)
  185870. {
  185871. png_voidp ret;
  185872. if (png_ptr == NULL || size == 0)
  185873. return (NULL);
  185874. #ifdef PNG_USER_MEM_SUPPORTED
  185875. if(png_ptr->malloc_fn != NULL)
  185876. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185877. else
  185878. ret = (png_malloc_default(png_ptr, size));
  185879. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185880. png_error(png_ptr, "Out of memory!");
  185881. return (ret);
  185882. }
  185883. png_voidp PNGAPI
  185884. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185885. {
  185886. png_voidp ret;
  185887. #endif /* PNG_USER_MEM_SUPPORTED */
  185888. if (png_ptr == NULL || size == 0)
  185889. return (NULL);
  185890. #ifdef PNG_MAX_MALLOC_64K
  185891. if (size > (png_uint_32)65536L)
  185892. {
  185893. png_warning(png_ptr, "Cannot Allocate > 64K");
  185894. ret = NULL;
  185895. }
  185896. else
  185897. #endif
  185898. if (size != (size_t)size)
  185899. ret = NULL;
  185900. else if (size == (png_uint_32)65536L)
  185901. {
  185902. if (png_ptr->offset_table == NULL)
  185903. {
  185904. /* try to see if we need to do any of this fancy stuff */
  185905. ret = farmalloc(size);
  185906. if (ret == NULL || ((png_size_t)ret & 0xffff))
  185907. {
  185908. int num_blocks;
  185909. png_uint_32 total_size;
  185910. png_bytep table;
  185911. int i;
  185912. png_byte huge * hptr;
  185913. if (ret != NULL)
  185914. {
  185915. farfree(ret);
  185916. ret = NULL;
  185917. }
  185918. if(png_ptr->zlib_window_bits > 14)
  185919. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  185920. else
  185921. num_blocks = 1;
  185922. if (png_ptr->zlib_mem_level >= 7)
  185923. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  185924. else
  185925. num_blocks++;
  185926. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  185927. table = farmalloc(total_size);
  185928. if (table == NULL)
  185929. {
  185930. #ifndef PNG_USER_MEM_SUPPORTED
  185931. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185932. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  185933. else
  185934. png_warning(png_ptr, "Out Of Memory.");
  185935. #endif
  185936. return (NULL);
  185937. }
  185938. if ((png_size_t)table & 0xfff0)
  185939. {
  185940. #ifndef PNG_USER_MEM_SUPPORTED
  185941. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185942. png_error(png_ptr,
  185943. "Farmalloc didn't return normalized pointer");
  185944. else
  185945. png_warning(png_ptr,
  185946. "Farmalloc didn't return normalized pointer");
  185947. #endif
  185948. return (NULL);
  185949. }
  185950. png_ptr->offset_table = table;
  185951. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  185952. png_sizeof (png_bytep));
  185953. if (png_ptr->offset_table_ptr == NULL)
  185954. {
  185955. #ifndef PNG_USER_MEM_SUPPORTED
  185956. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185957. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  185958. else
  185959. png_warning(png_ptr, "Out Of memory.");
  185960. #endif
  185961. return (NULL);
  185962. }
  185963. hptr = (png_byte huge *)table;
  185964. if ((png_size_t)hptr & 0xf)
  185965. {
  185966. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  185967. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  185968. }
  185969. for (i = 0; i < num_blocks; i++)
  185970. {
  185971. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  185972. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  185973. }
  185974. png_ptr->offset_table_number = num_blocks;
  185975. png_ptr->offset_table_count = 0;
  185976. png_ptr->offset_table_count_free = 0;
  185977. }
  185978. }
  185979. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  185980. {
  185981. #ifndef PNG_USER_MEM_SUPPORTED
  185982. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185983. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  185984. else
  185985. png_warning(png_ptr, "Out of Memory.");
  185986. #endif
  185987. return (NULL);
  185988. }
  185989. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  185990. }
  185991. else
  185992. ret = farmalloc(size);
  185993. #ifndef PNG_USER_MEM_SUPPORTED
  185994. if (ret == NULL)
  185995. {
  185996. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185997. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185998. else
  185999. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186000. }
  186001. #endif
  186002. return (ret);
  186003. }
  186004. /* free a pointer allocated by png_malloc(). In the default
  186005. configuration, png_ptr is not used, but is passed in case it
  186006. is needed. If ptr is NULL, return without taking any action. */
  186007. void PNGAPI
  186008. png_free(png_structp png_ptr, png_voidp ptr)
  186009. {
  186010. if (png_ptr == NULL || ptr == NULL)
  186011. return;
  186012. #ifdef PNG_USER_MEM_SUPPORTED
  186013. if (png_ptr->free_fn != NULL)
  186014. {
  186015. (*(png_ptr->free_fn))(png_ptr, ptr);
  186016. return;
  186017. }
  186018. else png_free_default(png_ptr, ptr);
  186019. }
  186020. void PNGAPI
  186021. png_free_default(png_structp png_ptr, png_voidp ptr)
  186022. {
  186023. #endif /* PNG_USER_MEM_SUPPORTED */
  186024. if(png_ptr == NULL) return;
  186025. if (png_ptr->offset_table != NULL)
  186026. {
  186027. int i;
  186028. for (i = 0; i < png_ptr->offset_table_count; i++)
  186029. {
  186030. if (ptr == png_ptr->offset_table_ptr[i])
  186031. {
  186032. ptr = NULL;
  186033. png_ptr->offset_table_count_free++;
  186034. break;
  186035. }
  186036. }
  186037. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186038. {
  186039. farfree(png_ptr->offset_table);
  186040. farfree(png_ptr->offset_table_ptr);
  186041. png_ptr->offset_table = NULL;
  186042. png_ptr->offset_table_ptr = NULL;
  186043. }
  186044. }
  186045. if (ptr != NULL)
  186046. {
  186047. farfree(ptr);
  186048. }
  186049. }
  186050. #else /* Not the Borland DOS special memory handler */
  186051. /* Allocate memory for a png_struct or a png_info. The malloc and
  186052. memset can be replaced by a single call to calloc() if this is thought
  186053. to improve performance noticably. */
  186054. png_voidp /* PRIVATE */
  186055. png_create_struct(int type)
  186056. {
  186057. #ifdef PNG_USER_MEM_SUPPORTED
  186058. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186059. }
  186060. /* Allocate memory for a png_struct or a png_info. The malloc and
  186061. memset can be replaced by a single call to calloc() if this is thought
  186062. to improve performance noticably. */
  186063. png_voidp /* PRIVATE */
  186064. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186065. {
  186066. #endif /* PNG_USER_MEM_SUPPORTED */
  186067. png_size_t size;
  186068. png_voidp struct_ptr;
  186069. if (type == PNG_STRUCT_INFO)
  186070. size = png_sizeof(png_info);
  186071. else if (type == PNG_STRUCT_PNG)
  186072. size = png_sizeof(png_struct);
  186073. else
  186074. return (NULL);
  186075. #ifdef PNG_USER_MEM_SUPPORTED
  186076. if(malloc_fn != NULL)
  186077. {
  186078. png_struct dummy_struct;
  186079. png_structp png_ptr = &dummy_struct;
  186080. png_ptr->mem_ptr=mem_ptr;
  186081. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186082. if (struct_ptr != NULL)
  186083. png_memset(struct_ptr, 0, size);
  186084. return (struct_ptr);
  186085. }
  186086. #endif /* PNG_USER_MEM_SUPPORTED */
  186087. #if defined(__TURBOC__) && !defined(__FLAT__)
  186088. struct_ptr = (png_voidp)farmalloc(size);
  186089. #else
  186090. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186091. struct_ptr = (png_voidp)halloc(size,1);
  186092. # else
  186093. struct_ptr = (png_voidp)malloc(size);
  186094. # endif
  186095. #endif
  186096. if (struct_ptr != NULL)
  186097. png_memset(struct_ptr, 0, size);
  186098. return (struct_ptr);
  186099. }
  186100. /* Free memory allocated by a png_create_struct() call */
  186101. void /* PRIVATE */
  186102. png_destroy_struct(png_voidp struct_ptr)
  186103. {
  186104. #ifdef PNG_USER_MEM_SUPPORTED
  186105. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186106. }
  186107. /* Free memory allocated by a png_create_struct() call */
  186108. void /* PRIVATE */
  186109. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186110. png_voidp mem_ptr)
  186111. {
  186112. #endif /* PNG_USER_MEM_SUPPORTED */
  186113. if (struct_ptr != NULL)
  186114. {
  186115. #ifdef PNG_USER_MEM_SUPPORTED
  186116. if(free_fn != NULL)
  186117. {
  186118. png_struct dummy_struct;
  186119. png_structp png_ptr = &dummy_struct;
  186120. png_ptr->mem_ptr=mem_ptr;
  186121. (*(free_fn))(png_ptr, struct_ptr);
  186122. return;
  186123. }
  186124. #endif /* PNG_USER_MEM_SUPPORTED */
  186125. #if defined(__TURBOC__) && !defined(__FLAT__)
  186126. farfree(struct_ptr);
  186127. #else
  186128. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186129. hfree(struct_ptr);
  186130. # else
  186131. free(struct_ptr);
  186132. # endif
  186133. #endif
  186134. }
  186135. }
  186136. /* Allocate memory. For reasonable files, size should never exceed
  186137. 64K. However, zlib may allocate more then 64K if you don't tell
  186138. it not to. See zconf.h and png.h for more information. zlib does
  186139. need to allocate exactly 64K, so whatever you call here must
  186140. have the ability to do that. */
  186141. png_voidp PNGAPI
  186142. png_malloc(png_structp png_ptr, png_uint_32 size)
  186143. {
  186144. png_voidp ret;
  186145. #ifdef PNG_USER_MEM_SUPPORTED
  186146. if (png_ptr == NULL || size == 0)
  186147. return (NULL);
  186148. if(png_ptr->malloc_fn != NULL)
  186149. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186150. else
  186151. ret = (png_malloc_default(png_ptr, size));
  186152. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186153. png_error(png_ptr, "Out of Memory!");
  186154. return (ret);
  186155. }
  186156. png_voidp PNGAPI
  186157. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186158. {
  186159. png_voidp ret;
  186160. #endif /* PNG_USER_MEM_SUPPORTED */
  186161. if (png_ptr == NULL || size == 0)
  186162. return (NULL);
  186163. #ifdef PNG_MAX_MALLOC_64K
  186164. if (size > (png_uint_32)65536L)
  186165. {
  186166. #ifndef PNG_USER_MEM_SUPPORTED
  186167. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186168. png_error(png_ptr, "Cannot Allocate > 64K");
  186169. else
  186170. #endif
  186171. return NULL;
  186172. }
  186173. #endif
  186174. /* Check for overflow */
  186175. #if defined(__TURBOC__) && !defined(__FLAT__)
  186176. if (size != (unsigned long)size)
  186177. ret = NULL;
  186178. else
  186179. ret = farmalloc(size);
  186180. #else
  186181. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186182. if (size != (unsigned long)size)
  186183. ret = NULL;
  186184. else
  186185. ret = halloc(size, 1);
  186186. # else
  186187. if (size != (size_t)size)
  186188. ret = NULL;
  186189. else
  186190. ret = malloc((size_t)size);
  186191. # endif
  186192. #endif
  186193. #ifndef PNG_USER_MEM_SUPPORTED
  186194. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186195. png_error(png_ptr, "Out of Memory");
  186196. #endif
  186197. return (ret);
  186198. }
  186199. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186200. without taking any action. */
  186201. void PNGAPI
  186202. png_free(png_structp png_ptr, png_voidp ptr)
  186203. {
  186204. if (png_ptr == NULL || ptr == NULL)
  186205. return;
  186206. #ifdef PNG_USER_MEM_SUPPORTED
  186207. if (png_ptr->free_fn != NULL)
  186208. {
  186209. (*(png_ptr->free_fn))(png_ptr, ptr);
  186210. return;
  186211. }
  186212. else png_free_default(png_ptr, ptr);
  186213. }
  186214. void PNGAPI
  186215. png_free_default(png_structp png_ptr, png_voidp ptr)
  186216. {
  186217. if (png_ptr == NULL || ptr == NULL)
  186218. return;
  186219. #endif /* PNG_USER_MEM_SUPPORTED */
  186220. #if defined(__TURBOC__) && !defined(__FLAT__)
  186221. farfree(ptr);
  186222. #else
  186223. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186224. hfree(ptr);
  186225. # else
  186226. free(ptr);
  186227. # endif
  186228. #endif
  186229. }
  186230. #endif /* Not Borland DOS special memory handler */
  186231. #if defined(PNG_1_0_X)
  186232. # define png_malloc_warn png_malloc
  186233. #else
  186234. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186235. * function will set up png_malloc() to issue a png_warning and return NULL
  186236. * instead of issuing a png_error, if it fails to allocate the requested
  186237. * memory.
  186238. */
  186239. png_voidp PNGAPI
  186240. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186241. {
  186242. png_voidp ptr;
  186243. png_uint_32 save_flags;
  186244. if(png_ptr == NULL) return (NULL);
  186245. save_flags=png_ptr->flags;
  186246. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186247. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186248. png_ptr->flags=save_flags;
  186249. return(ptr);
  186250. }
  186251. #endif
  186252. png_voidp PNGAPI
  186253. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186254. png_uint_32 length)
  186255. {
  186256. png_size_t size;
  186257. size = (png_size_t)length;
  186258. if ((png_uint_32)size != length)
  186259. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186260. return(png_memcpy (s1, s2, size));
  186261. }
  186262. png_voidp PNGAPI
  186263. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186264. png_uint_32 length)
  186265. {
  186266. png_size_t size;
  186267. size = (png_size_t)length;
  186268. if ((png_uint_32)size != length)
  186269. png_error(png_ptr,"Overflow in png_memset_check.");
  186270. return (png_memset (s1, value, size));
  186271. }
  186272. #ifdef PNG_USER_MEM_SUPPORTED
  186273. /* This function is called when the application wants to use another method
  186274. * of allocating and freeing memory.
  186275. */
  186276. void PNGAPI
  186277. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186278. malloc_fn, png_free_ptr free_fn)
  186279. {
  186280. if(png_ptr != NULL) {
  186281. png_ptr->mem_ptr = mem_ptr;
  186282. png_ptr->malloc_fn = malloc_fn;
  186283. png_ptr->free_fn = free_fn;
  186284. }
  186285. }
  186286. /* This function returns a pointer to the mem_ptr associated with the user
  186287. * functions. The application should free any memory associated with this
  186288. * pointer before png_write_destroy and png_read_destroy are called.
  186289. */
  186290. png_voidp PNGAPI
  186291. png_get_mem_ptr(png_structp png_ptr)
  186292. {
  186293. if(png_ptr == NULL) return (NULL);
  186294. return ((png_voidp)png_ptr->mem_ptr);
  186295. }
  186296. #endif /* PNG_USER_MEM_SUPPORTED */
  186297. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186298. /*** End of inlined file: pngmem.c ***/
  186299. /*** Start of inlined file: pngread.c ***/
  186300. /* pngread.c - read a PNG file
  186301. *
  186302. * Last changed in libpng 1.2.20 September 7, 2007
  186303. * For conditions of distribution and use, see copyright notice in png.h
  186304. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186305. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186306. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186307. *
  186308. * This file contains routines that an application calls directly to
  186309. * read a PNG file or stream.
  186310. */
  186311. #define PNG_INTERNAL
  186312. #if defined(PNG_READ_SUPPORTED)
  186313. /* Create a PNG structure for reading, and allocate any memory needed. */
  186314. png_structp PNGAPI
  186315. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186316. png_error_ptr error_fn, png_error_ptr warn_fn)
  186317. {
  186318. #ifdef PNG_USER_MEM_SUPPORTED
  186319. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186320. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186321. }
  186322. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186323. png_structp PNGAPI
  186324. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186325. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186326. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186327. {
  186328. #endif /* PNG_USER_MEM_SUPPORTED */
  186329. png_structp png_ptr;
  186330. #ifdef PNG_SETJMP_SUPPORTED
  186331. #ifdef USE_FAR_KEYWORD
  186332. jmp_buf jmpbuf;
  186333. #endif
  186334. #endif
  186335. int i;
  186336. png_debug(1, "in png_create_read_struct\n");
  186337. #ifdef PNG_USER_MEM_SUPPORTED
  186338. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186339. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186340. #else
  186341. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186342. #endif
  186343. if (png_ptr == NULL)
  186344. return (NULL);
  186345. /* added at libpng-1.2.6 */
  186346. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186347. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186348. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186349. #endif
  186350. #ifdef PNG_SETJMP_SUPPORTED
  186351. #ifdef USE_FAR_KEYWORD
  186352. if (setjmp(jmpbuf))
  186353. #else
  186354. if (setjmp(png_ptr->jmpbuf))
  186355. #endif
  186356. {
  186357. png_free(png_ptr, png_ptr->zbuf);
  186358. png_ptr->zbuf=NULL;
  186359. #ifdef PNG_USER_MEM_SUPPORTED
  186360. png_destroy_struct_2((png_voidp)png_ptr,
  186361. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186362. #else
  186363. png_destroy_struct((png_voidp)png_ptr);
  186364. #endif
  186365. return (NULL);
  186366. }
  186367. #ifdef USE_FAR_KEYWORD
  186368. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186369. #endif
  186370. #endif
  186371. #ifdef PNG_USER_MEM_SUPPORTED
  186372. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186373. #endif
  186374. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186375. i=0;
  186376. do
  186377. {
  186378. if(user_png_ver[i] != png_libpng_ver[i])
  186379. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186380. } while (png_libpng_ver[i++]);
  186381. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186382. {
  186383. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186384. * we must recompile any applications that use any older library version.
  186385. * For versions after libpng 1.0, we will be compatible, so we need
  186386. * only check the first digit.
  186387. */
  186388. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186389. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186390. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186391. {
  186392. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186393. char msg[80];
  186394. if (user_png_ver)
  186395. {
  186396. png_snprintf(msg, 80,
  186397. "Application was compiled with png.h from libpng-%.20s",
  186398. user_png_ver);
  186399. png_warning(png_ptr, msg);
  186400. }
  186401. png_snprintf(msg, 80,
  186402. "Application is running with png.c from libpng-%.20s",
  186403. png_libpng_ver);
  186404. png_warning(png_ptr, msg);
  186405. #endif
  186406. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186407. png_ptr->flags=0;
  186408. #endif
  186409. png_error(png_ptr,
  186410. "Incompatible libpng version in application and library");
  186411. }
  186412. }
  186413. /* initialize zbuf - compression buffer */
  186414. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186415. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186416. (png_uint_32)png_ptr->zbuf_size);
  186417. png_ptr->zstream.zalloc = png_zalloc;
  186418. png_ptr->zstream.zfree = png_zfree;
  186419. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186420. switch (inflateInit(&png_ptr->zstream))
  186421. {
  186422. case Z_OK: /* Do nothing */ break;
  186423. case Z_MEM_ERROR:
  186424. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186425. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186426. default: png_error(png_ptr, "Unknown zlib error");
  186427. }
  186428. png_ptr->zstream.next_out = png_ptr->zbuf;
  186429. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186430. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186431. #ifdef PNG_SETJMP_SUPPORTED
  186432. /* Applications that neglect to set up their own setjmp() and then encounter
  186433. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186434. abort instead of returning. */
  186435. #ifdef USE_FAR_KEYWORD
  186436. if (setjmp(jmpbuf))
  186437. PNG_ABORT();
  186438. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186439. #else
  186440. if (setjmp(png_ptr->jmpbuf))
  186441. PNG_ABORT();
  186442. #endif
  186443. #endif
  186444. return (png_ptr);
  186445. }
  186446. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186447. /* Initialize PNG structure for reading, and allocate any memory needed.
  186448. This interface is deprecated in favour of the png_create_read_struct(),
  186449. and it will disappear as of libpng-1.3.0. */
  186450. #undef png_read_init
  186451. void PNGAPI
  186452. png_read_init(png_structp png_ptr)
  186453. {
  186454. /* We only come here via pre-1.0.7-compiled applications */
  186455. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186456. }
  186457. void PNGAPI
  186458. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186459. png_size_t png_struct_size, png_size_t png_info_size)
  186460. {
  186461. /* We only come here via pre-1.0.12-compiled applications */
  186462. if(png_ptr == NULL) return;
  186463. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186464. if(png_sizeof(png_struct) > png_struct_size ||
  186465. png_sizeof(png_info) > png_info_size)
  186466. {
  186467. char msg[80];
  186468. png_ptr->warning_fn=NULL;
  186469. if (user_png_ver)
  186470. {
  186471. png_snprintf(msg, 80,
  186472. "Application was compiled with png.h from libpng-%.20s",
  186473. user_png_ver);
  186474. png_warning(png_ptr, msg);
  186475. }
  186476. png_snprintf(msg, 80,
  186477. "Application is running with png.c from libpng-%.20s",
  186478. png_libpng_ver);
  186479. png_warning(png_ptr, msg);
  186480. }
  186481. #endif
  186482. if(png_sizeof(png_struct) > png_struct_size)
  186483. {
  186484. png_ptr->error_fn=NULL;
  186485. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186486. png_ptr->flags=0;
  186487. #endif
  186488. png_error(png_ptr,
  186489. "The png struct allocated by the application for reading is too small.");
  186490. }
  186491. if(png_sizeof(png_info) > png_info_size)
  186492. {
  186493. png_ptr->error_fn=NULL;
  186494. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186495. png_ptr->flags=0;
  186496. #endif
  186497. png_error(png_ptr,
  186498. "The info struct allocated by application for reading is too small.");
  186499. }
  186500. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186501. }
  186502. #endif /* PNG_1_0_X || PNG_1_2_X */
  186503. void PNGAPI
  186504. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186505. png_size_t png_struct_size)
  186506. {
  186507. #ifdef PNG_SETJMP_SUPPORTED
  186508. jmp_buf tmp_jmp; /* to save current jump buffer */
  186509. #endif
  186510. int i=0;
  186511. png_structp png_ptr=*ptr_ptr;
  186512. if(png_ptr == NULL) return;
  186513. do
  186514. {
  186515. if(user_png_ver[i] != png_libpng_ver[i])
  186516. {
  186517. #ifdef PNG_LEGACY_SUPPORTED
  186518. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186519. #else
  186520. png_ptr->warning_fn=NULL;
  186521. png_warning(png_ptr,
  186522. "Application uses deprecated png_read_init() and should be recompiled.");
  186523. break;
  186524. #endif
  186525. }
  186526. } while (png_libpng_ver[i++]);
  186527. png_debug(1, "in png_read_init_3\n");
  186528. #ifdef PNG_SETJMP_SUPPORTED
  186529. /* save jump buffer and error functions */
  186530. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186531. #endif
  186532. if(png_sizeof(png_struct) > png_struct_size)
  186533. {
  186534. png_destroy_struct(png_ptr);
  186535. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186536. png_ptr = *ptr_ptr;
  186537. }
  186538. /* reset all variables to 0 */
  186539. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186540. #ifdef PNG_SETJMP_SUPPORTED
  186541. /* restore jump buffer */
  186542. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186543. #endif
  186544. /* added at libpng-1.2.6 */
  186545. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186546. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186547. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186548. #endif
  186549. /* initialize zbuf - compression buffer */
  186550. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186551. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186552. (png_uint_32)png_ptr->zbuf_size);
  186553. png_ptr->zstream.zalloc = png_zalloc;
  186554. png_ptr->zstream.zfree = png_zfree;
  186555. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186556. switch (inflateInit(&png_ptr->zstream))
  186557. {
  186558. case Z_OK: /* Do nothing */ break;
  186559. case Z_MEM_ERROR:
  186560. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186561. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186562. default: png_error(png_ptr, "Unknown zlib error");
  186563. }
  186564. png_ptr->zstream.next_out = png_ptr->zbuf;
  186565. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186566. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186567. }
  186568. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186569. /* Read the information before the actual image data. This has been
  186570. * changed in v0.90 to allow reading a file that already has the magic
  186571. * bytes read from the stream. You can tell libpng how many bytes have
  186572. * been read from the beginning of the stream (up to the maximum of 8)
  186573. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186574. * here. The application can then have access to the signature bytes we
  186575. * read if it is determined that this isn't a valid PNG file.
  186576. */
  186577. void PNGAPI
  186578. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186579. {
  186580. if(png_ptr == NULL) return;
  186581. png_debug(1, "in png_read_info\n");
  186582. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186583. if (png_ptr->sig_bytes < 8)
  186584. {
  186585. png_size_t num_checked = png_ptr->sig_bytes,
  186586. num_to_check = 8 - num_checked;
  186587. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186588. png_ptr->sig_bytes = 8;
  186589. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186590. {
  186591. if (num_checked < 4 &&
  186592. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186593. png_error(png_ptr, "Not a PNG file");
  186594. else
  186595. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186596. }
  186597. if (num_checked < 3)
  186598. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186599. }
  186600. for(;;)
  186601. {
  186602. #ifdef PNG_USE_LOCAL_ARRAYS
  186603. PNG_CONST PNG_IHDR;
  186604. PNG_CONST PNG_IDAT;
  186605. PNG_CONST PNG_IEND;
  186606. PNG_CONST PNG_PLTE;
  186607. #if defined(PNG_READ_bKGD_SUPPORTED)
  186608. PNG_CONST PNG_bKGD;
  186609. #endif
  186610. #if defined(PNG_READ_cHRM_SUPPORTED)
  186611. PNG_CONST PNG_cHRM;
  186612. #endif
  186613. #if defined(PNG_READ_gAMA_SUPPORTED)
  186614. PNG_CONST PNG_gAMA;
  186615. #endif
  186616. #if defined(PNG_READ_hIST_SUPPORTED)
  186617. PNG_CONST PNG_hIST;
  186618. #endif
  186619. #if defined(PNG_READ_iCCP_SUPPORTED)
  186620. PNG_CONST PNG_iCCP;
  186621. #endif
  186622. #if defined(PNG_READ_iTXt_SUPPORTED)
  186623. PNG_CONST PNG_iTXt;
  186624. #endif
  186625. #if defined(PNG_READ_oFFs_SUPPORTED)
  186626. PNG_CONST PNG_oFFs;
  186627. #endif
  186628. #if defined(PNG_READ_pCAL_SUPPORTED)
  186629. PNG_CONST PNG_pCAL;
  186630. #endif
  186631. #if defined(PNG_READ_pHYs_SUPPORTED)
  186632. PNG_CONST PNG_pHYs;
  186633. #endif
  186634. #if defined(PNG_READ_sBIT_SUPPORTED)
  186635. PNG_CONST PNG_sBIT;
  186636. #endif
  186637. #if defined(PNG_READ_sCAL_SUPPORTED)
  186638. PNG_CONST PNG_sCAL;
  186639. #endif
  186640. #if defined(PNG_READ_sPLT_SUPPORTED)
  186641. PNG_CONST PNG_sPLT;
  186642. #endif
  186643. #if defined(PNG_READ_sRGB_SUPPORTED)
  186644. PNG_CONST PNG_sRGB;
  186645. #endif
  186646. #if defined(PNG_READ_tEXt_SUPPORTED)
  186647. PNG_CONST PNG_tEXt;
  186648. #endif
  186649. #if defined(PNG_READ_tIME_SUPPORTED)
  186650. PNG_CONST PNG_tIME;
  186651. #endif
  186652. #if defined(PNG_READ_tRNS_SUPPORTED)
  186653. PNG_CONST PNG_tRNS;
  186654. #endif
  186655. #if defined(PNG_READ_zTXt_SUPPORTED)
  186656. PNG_CONST PNG_zTXt;
  186657. #endif
  186658. #endif /* PNG_USE_LOCAL_ARRAYS */
  186659. png_byte chunk_length[4];
  186660. png_uint_32 length;
  186661. png_read_data(png_ptr, chunk_length, 4);
  186662. length = png_get_uint_31(png_ptr,chunk_length);
  186663. png_reset_crc(png_ptr);
  186664. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186665. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186666. length);
  186667. /* This should be a binary subdivision search or a hash for
  186668. * matching the chunk name rather than a linear search.
  186669. */
  186670. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186671. if(png_ptr->mode & PNG_AFTER_IDAT)
  186672. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186673. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186674. png_handle_IHDR(png_ptr, info_ptr, length);
  186675. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186676. png_handle_IEND(png_ptr, info_ptr, length);
  186677. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186678. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186679. {
  186680. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186681. png_ptr->mode |= PNG_HAVE_IDAT;
  186682. png_handle_unknown(png_ptr, info_ptr, length);
  186683. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186684. png_ptr->mode |= PNG_HAVE_PLTE;
  186685. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186686. {
  186687. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186688. png_error(png_ptr, "Missing IHDR before IDAT");
  186689. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186690. !(png_ptr->mode & PNG_HAVE_PLTE))
  186691. png_error(png_ptr, "Missing PLTE before IDAT");
  186692. break;
  186693. }
  186694. }
  186695. #endif
  186696. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186697. png_handle_PLTE(png_ptr, info_ptr, length);
  186698. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186699. {
  186700. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186701. png_error(png_ptr, "Missing IHDR before IDAT");
  186702. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186703. !(png_ptr->mode & PNG_HAVE_PLTE))
  186704. png_error(png_ptr, "Missing PLTE before IDAT");
  186705. png_ptr->idat_size = length;
  186706. png_ptr->mode |= PNG_HAVE_IDAT;
  186707. break;
  186708. }
  186709. #if defined(PNG_READ_bKGD_SUPPORTED)
  186710. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186711. png_handle_bKGD(png_ptr, info_ptr, length);
  186712. #endif
  186713. #if defined(PNG_READ_cHRM_SUPPORTED)
  186714. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186715. png_handle_cHRM(png_ptr, info_ptr, length);
  186716. #endif
  186717. #if defined(PNG_READ_gAMA_SUPPORTED)
  186718. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186719. png_handle_gAMA(png_ptr, info_ptr, length);
  186720. #endif
  186721. #if defined(PNG_READ_hIST_SUPPORTED)
  186722. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186723. png_handle_hIST(png_ptr, info_ptr, length);
  186724. #endif
  186725. #if defined(PNG_READ_oFFs_SUPPORTED)
  186726. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186727. png_handle_oFFs(png_ptr, info_ptr, length);
  186728. #endif
  186729. #if defined(PNG_READ_pCAL_SUPPORTED)
  186730. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186731. png_handle_pCAL(png_ptr, info_ptr, length);
  186732. #endif
  186733. #if defined(PNG_READ_sCAL_SUPPORTED)
  186734. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186735. png_handle_sCAL(png_ptr, info_ptr, length);
  186736. #endif
  186737. #if defined(PNG_READ_pHYs_SUPPORTED)
  186738. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186739. png_handle_pHYs(png_ptr, info_ptr, length);
  186740. #endif
  186741. #if defined(PNG_READ_sBIT_SUPPORTED)
  186742. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186743. png_handle_sBIT(png_ptr, info_ptr, length);
  186744. #endif
  186745. #if defined(PNG_READ_sRGB_SUPPORTED)
  186746. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186747. png_handle_sRGB(png_ptr, info_ptr, length);
  186748. #endif
  186749. #if defined(PNG_READ_iCCP_SUPPORTED)
  186750. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186751. png_handle_iCCP(png_ptr, info_ptr, length);
  186752. #endif
  186753. #if defined(PNG_READ_sPLT_SUPPORTED)
  186754. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186755. png_handle_sPLT(png_ptr, info_ptr, length);
  186756. #endif
  186757. #if defined(PNG_READ_tEXt_SUPPORTED)
  186758. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186759. png_handle_tEXt(png_ptr, info_ptr, length);
  186760. #endif
  186761. #if defined(PNG_READ_tIME_SUPPORTED)
  186762. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186763. png_handle_tIME(png_ptr, info_ptr, length);
  186764. #endif
  186765. #if defined(PNG_READ_tRNS_SUPPORTED)
  186766. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186767. png_handle_tRNS(png_ptr, info_ptr, length);
  186768. #endif
  186769. #if defined(PNG_READ_zTXt_SUPPORTED)
  186770. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186771. png_handle_zTXt(png_ptr, info_ptr, length);
  186772. #endif
  186773. #if defined(PNG_READ_iTXt_SUPPORTED)
  186774. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186775. png_handle_iTXt(png_ptr, info_ptr, length);
  186776. #endif
  186777. else
  186778. png_handle_unknown(png_ptr, info_ptr, length);
  186779. }
  186780. }
  186781. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186782. /* optional call to update the users info_ptr structure */
  186783. void PNGAPI
  186784. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186785. {
  186786. png_debug(1, "in png_read_update_info\n");
  186787. if(png_ptr == NULL) return;
  186788. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186789. png_read_start_row(png_ptr);
  186790. else
  186791. png_warning(png_ptr,
  186792. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186793. png_read_transform_info(png_ptr, info_ptr);
  186794. }
  186795. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186796. /* Initialize palette, background, etc, after transformations
  186797. * are set, but before any reading takes place. This allows
  186798. * the user to obtain a gamma-corrected palette, for example.
  186799. * If the user doesn't call this, we will do it ourselves.
  186800. */
  186801. void PNGAPI
  186802. png_start_read_image(png_structp png_ptr)
  186803. {
  186804. png_debug(1, "in png_start_read_image\n");
  186805. if(png_ptr == NULL) return;
  186806. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186807. png_read_start_row(png_ptr);
  186808. }
  186809. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186810. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186811. void PNGAPI
  186812. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186813. {
  186814. #ifdef PNG_USE_LOCAL_ARRAYS
  186815. PNG_CONST PNG_IDAT;
  186816. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186817. 0xff};
  186818. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186819. #endif
  186820. int ret;
  186821. if(png_ptr == NULL) return;
  186822. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  186823. png_ptr->row_number, png_ptr->pass);
  186824. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186825. png_read_start_row(png_ptr);
  186826. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  186827. {
  186828. /* check for transforms that have been set but were defined out */
  186829. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  186830. if (png_ptr->transformations & PNG_INVERT_MONO)
  186831. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  186832. #endif
  186833. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  186834. if (png_ptr->transformations & PNG_FILLER)
  186835. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  186836. #endif
  186837. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  186838. if (png_ptr->transformations & PNG_PACKSWAP)
  186839. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  186840. #endif
  186841. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  186842. if (png_ptr->transformations & PNG_PACK)
  186843. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  186844. #endif
  186845. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  186846. if (png_ptr->transformations & PNG_SHIFT)
  186847. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  186848. #endif
  186849. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  186850. if (png_ptr->transformations & PNG_BGR)
  186851. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  186852. #endif
  186853. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  186854. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186855. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  186856. #endif
  186857. }
  186858. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186859. /* if interlaced and we do not need a new row, combine row and return */
  186860. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186861. {
  186862. switch (png_ptr->pass)
  186863. {
  186864. case 0:
  186865. if (png_ptr->row_number & 0x07)
  186866. {
  186867. if (dsp_row != NULL)
  186868. png_combine_row(png_ptr, dsp_row,
  186869. png_pass_dsp_mask[png_ptr->pass]);
  186870. png_read_finish_row(png_ptr);
  186871. return;
  186872. }
  186873. break;
  186874. case 1:
  186875. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  186876. {
  186877. if (dsp_row != NULL)
  186878. png_combine_row(png_ptr, dsp_row,
  186879. png_pass_dsp_mask[png_ptr->pass]);
  186880. png_read_finish_row(png_ptr);
  186881. return;
  186882. }
  186883. break;
  186884. case 2:
  186885. if ((png_ptr->row_number & 0x07) != 4)
  186886. {
  186887. if (dsp_row != NULL && (png_ptr->row_number & 4))
  186888. png_combine_row(png_ptr, dsp_row,
  186889. png_pass_dsp_mask[png_ptr->pass]);
  186890. png_read_finish_row(png_ptr);
  186891. return;
  186892. }
  186893. break;
  186894. case 3:
  186895. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  186896. {
  186897. if (dsp_row != NULL)
  186898. png_combine_row(png_ptr, dsp_row,
  186899. png_pass_dsp_mask[png_ptr->pass]);
  186900. png_read_finish_row(png_ptr);
  186901. return;
  186902. }
  186903. break;
  186904. case 4:
  186905. if ((png_ptr->row_number & 3) != 2)
  186906. {
  186907. if (dsp_row != NULL && (png_ptr->row_number & 2))
  186908. png_combine_row(png_ptr, dsp_row,
  186909. png_pass_dsp_mask[png_ptr->pass]);
  186910. png_read_finish_row(png_ptr);
  186911. return;
  186912. }
  186913. break;
  186914. case 5:
  186915. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  186916. {
  186917. if (dsp_row != NULL)
  186918. png_combine_row(png_ptr, dsp_row,
  186919. png_pass_dsp_mask[png_ptr->pass]);
  186920. png_read_finish_row(png_ptr);
  186921. return;
  186922. }
  186923. break;
  186924. case 6:
  186925. if (!(png_ptr->row_number & 1))
  186926. {
  186927. png_read_finish_row(png_ptr);
  186928. return;
  186929. }
  186930. break;
  186931. }
  186932. }
  186933. #endif
  186934. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  186935. png_error(png_ptr, "Invalid attempt to read row data");
  186936. png_ptr->zstream.next_out = png_ptr->row_buf;
  186937. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186938. do
  186939. {
  186940. if (!(png_ptr->zstream.avail_in))
  186941. {
  186942. while (!png_ptr->idat_size)
  186943. {
  186944. png_byte chunk_length[4];
  186945. png_crc_finish(png_ptr, 0);
  186946. png_read_data(png_ptr, chunk_length, 4);
  186947. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  186948. png_reset_crc(png_ptr);
  186949. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186950. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186951. png_error(png_ptr, "Not enough image data");
  186952. }
  186953. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  186954. png_ptr->zstream.next_in = png_ptr->zbuf;
  186955. if (png_ptr->zbuf_size > png_ptr->idat_size)
  186956. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  186957. png_crc_read(png_ptr, png_ptr->zbuf,
  186958. (png_size_t)png_ptr->zstream.avail_in);
  186959. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  186960. }
  186961. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186962. if (ret == Z_STREAM_END)
  186963. {
  186964. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  186965. png_ptr->idat_size)
  186966. png_error(png_ptr, "Extra compressed data");
  186967. png_ptr->mode |= PNG_AFTER_IDAT;
  186968. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186969. break;
  186970. }
  186971. if (ret != Z_OK)
  186972. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  186973. "Decompression error");
  186974. } while (png_ptr->zstream.avail_out);
  186975. png_ptr->row_info.color_type = png_ptr->color_type;
  186976. png_ptr->row_info.width = png_ptr->iwidth;
  186977. png_ptr->row_info.channels = png_ptr->channels;
  186978. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186979. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186980. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186981. png_ptr->row_info.width);
  186982. if(png_ptr->row_buf[0])
  186983. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186984. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186985. (int)(png_ptr->row_buf[0]));
  186986. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186987. png_ptr->rowbytes + 1);
  186988. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  186989. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  186990. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  186991. {
  186992. /* Intrapixel differencing */
  186993. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186994. }
  186995. #endif
  186996. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186997. png_do_read_transformations(png_ptr);
  186998. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186999. /* blow up interlaced rows to full size */
  187000. if (png_ptr->interlaced &&
  187001. (png_ptr->transformations & PNG_INTERLACE))
  187002. {
  187003. if (png_ptr->pass < 6)
  187004. /* old interface (pre-1.0.9):
  187005. png_do_read_interlace(&(png_ptr->row_info),
  187006. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187007. */
  187008. png_do_read_interlace(png_ptr);
  187009. if (dsp_row != NULL)
  187010. png_combine_row(png_ptr, dsp_row,
  187011. png_pass_dsp_mask[png_ptr->pass]);
  187012. if (row != NULL)
  187013. png_combine_row(png_ptr, row,
  187014. png_pass_mask[png_ptr->pass]);
  187015. }
  187016. else
  187017. #endif
  187018. {
  187019. if (row != NULL)
  187020. png_combine_row(png_ptr, row, 0xff);
  187021. if (dsp_row != NULL)
  187022. png_combine_row(png_ptr, dsp_row, 0xff);
  187023. }
  187024. png_read_finish_row(png_ptr);
  187025. if (png_ptr->read_row_fn != NULL)
  187026. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187027. }
  187028. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187029. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187030. /* Read one or more rows of image data. If the image is interlaced,
  187031. * and png_set_interlace_handling() has been called, the rows need to
  187032. * contain the contents of the rows from the previous pass. If the
  187033. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187034. * called, the rows contents must be initialized to the contents of the
  187035. * screen.
  187036. *
  187037. * "row" holds the actual image, and pixels are placed in it
  187038. * as they arrive. If the image is displayed after each pass, it will
  187039. * appear to "sparkle" in. "display_row" can be used to display a
  187040. * "chunky" progressive image, with finer detail added as it becomes
  187041. * available. If you do not want this "chunky" display, you may pass
  187042. * NULL for display_row. If you do not want the sparkle display, and
  187043. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187044. * If you have called png_handle_alpha(), and the image has either an
  187045. * alpha channel or a transparency chunk, you must provide a buffer for
  187046. * rows. In this case, you do not have to provide a display_row buffer
  187047. * also, but you may. If the image is not interlaced, or if you have
  187048. * not called png_set_interlace_handling(), the display_row buffer will
  187049. * be ignored, so pass NULL to it.
  187050. *
  187051. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187052. */
  187053. void PNGAPI
  187054. png_read_rows(png_structp png_ptr, png_bytepp row,
  187055. png_bytepp display_row, png_uint_32 num_rows)
  187056. {
  187057. png_uint_32 i;
  187058. png_bytepp rp;
  187059. png_bytepp dp;
  187060. png_debug(1, "in png_read_rows\n");
  187061. if(png_ptr == NULL) return;
  187062. rp = row;
  187063. dp = display_row;
  187064. if (rp != NULL && dp != NULL)
  187065. for (i = 0; i < num_rows; i++)
  187066. {
  187067. png_bytep rptr = *rp++;
  187068. png_bytep dptr = *dp++;
  187069. png_read_row(png_ptr, rptr, dptr);
  187070. }
  187071. else if(rp != NULL)
  187072. for (i = 0; i < num_rows; i++)
  187073. {
  187074. png_bytep rptr = *rp;
  187075. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187076. rp++;
  187077. }
  187078. else if(dp != NULL)
  187079. for (i = 0; i < num_rows; i++)
  187080. {
  187081. png_bytep dptr = *dp;
  187082. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187083. dp++;
  187084. }
  187085. }
  187086. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187087. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187088. /* Read the entire image. If the image has an alpha channel or a tRNS
  187089. * chunk, and you have called png_handle_alpha()[*], you will need to
  187090. * initialize the image to the current image that PNG will be overlaying.
  187091. * We set the num_rows again here, in case it was incorrectly set in
  187092. * png_read_start_row() by a call to png_read_update_info() or
  187093. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187094. * prior to either of these functions like it should have been. You can
  187095. * only call this function once. If you desire to have an image for
  187096. * each pass of a interlaced image, use png_read_rows() instead.
  187097. *
  187098. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187099. */
  187100. void PNGAPI
  187101. png_read_image(png_structp png_ptr, png_bytepp image)
  187102. {
  187103. png_uint_32 i,image_height;
  187104. int pass, j;
  187105. png_bytepp rp;
  187106. png_debug(1, "in png_read_image\n");
  187107. if(png_ptr == NULL) return;
  187108. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187109. pass = png_set_interlace_handling(png_ptr);
  187110. #else
  187111. if (png_ptr->interlaced)
  187112. png_error(png_ptr,
  187113. "Cannot read interlaced image -- interlace handler disabled.");
  187114. pass = 1;
  187115. #endif
  187116. image_height=png_ptr->height;
  187117. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187118. for (j = 0; j < pass; j++)
  187119. {
  187120. rp = image;
  187121. for (i = 0; i < image_height; i++)
  187122. {
  187123. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187124. rp++;
  187125. }
  187126. }
  187127. }
  187128. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187129. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187130. /* Read the end of the PNG file. Will not read past the end of the
  187131. * file, will verify the end is accurate, and will read any comments
  187132. * or time information at the end of the file, if info is not NULL.
  187133. */
  187134. void PNGAPI
  187135. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187136. {
  187137. png_byte chunk_length[4];
  187138. png_uint_32 length;
  187139. png_debug(1, "in png_read_end\n");
  187140. if(png_ptr == NULL) return;
  187141. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187142. do
  187143. {
  187144. #ifdef PNG_USE_LOCAL_ARRAYS
  187145. PNG_CONST PNG_IHDR;
  187146. PNG_CONST PNG_IDAT;
  187147. PNG_CONST PNG_IEND;
  187148. PNG_CONST PNG_PLTE;
  187149. #if defined(PNG_READ_bKGD_SUPPORTED)
  187150. PNG_CONST PNG_bKGD;
  187151. #endif
  187152. #if defined(PNG_READ_cHRM_SUPPORTED)
  187153. PNG_CONST PNG_cHRM;
  187154. #endif
  187155. #if defined(PNG_READ_gAMA_SUPPORTED)
  187156. PNG_CONST PNG_gAMA;
  187157. #endif
  187158. #if defined(PNG_READ_hIST_SUPPORTED)
  187159. PNG_CONST PNG_hIST;
  187160. #endif
  187161. #if defined(PNG_READ_iCCP_SUPPORTED)
  187162. PNG_CONST PNG_iCCP;
  187163. #endif
  187164. #if defined(PNG_READ_iTXt_SUPPORTED)
  187165. PNG_CONST PNG_iTXt;
  187166. #endif
  187167. #if defined(PNG_READ_oFFs_SUPPORTED)
  187168. PNG_CONST PNG_oFFs;
  187169. #endif
  187170. #if defined(PNG_READ_pCAL_SUPPORTED)
  187171. PNG_CONST PNG_pCAL;
  187172. #endif
  187173. #if defined(PNG_READ_pHYs_SUPPORTED)
  187174. PNG_CONST PNG_pHYs;
  187175. #endif
  187176. #if defined(PNG_READ_sBIT_SUPPORTED)
  187177. PNG_CONST PNG_sBIT;
  187178. #endif
  187179. #if defined(PNG_READ_sCAL_SUPPORTED)
  187180. PNG_CONST PNG_sCAL;
  187181. #endif
  187182. #if defined(PNG_READ_sPLT_SUPPORTED)
  187183. PNG_CONST PNG_sPLT;
  187184. #endif
  187185. #if defined(PNG_READ_sRGB_SUPPORTED)
  187186. PNG_CONST PNG_sRGB;
  187187. #endif
  187188. #if defined(PNG_READ_tEXt_SUPPORTED)
  187189. PNG_CONST PNG_tEXt;
  187190. #endif
  187191. #if defined(PNG_READ_tIME_SUPPORTED)
  187192. PNG_CONST PNG_tIME;
  187193. #endif
  187194. #if defined(PNG_READ_tRNS_SUPPORTED)
  187195. PNG_CONST PNG_tRNS;
  187196. #endif
  187197. #if defined(PNG_READ_zTXt_SUPPORTED)
  187198. PNG_CONST PNG_zTXt;
  187199. #endif
  187200. #endif /* PNG_USE_LOCAL_ARRAYS */
  187201. png_read_data(png_ptr, chunk_length, 4);
  187202. length = png_get_uint_31(png_ptr,chunk_length);
  187203. png_reset_crc(png_ptr);
  187204. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187205. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187206. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187207. png_handle_IHDR(png_ptr, info_ptr, length);
  187208. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187209. png_handle_IEND(png_ptr, info_ptr, length);
  187210. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187211. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187212. {
  187213. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187214. {
  187215. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187216. png_error(png_ptr, "Too many IDAT's found");
  187217. }
  187218. png_handle_unknown(png_ptr, info_ptr, length);
  187219. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187220. png_ptr->mode |= PNG_HAVE_PLTE;
  187221. }
  187222. #endif
  187223. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187224. {
  187225. /* Zero length IDATs are legal after the last IDAT has been
  187226. * read, but not after other chunks have been read.
  187227. */
  187228. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187229. png_error(png_ptr, "Too many IDAT's found");
  187230. png_crc_finish(png_ptr, length);
  187231. }
  187232. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187233. png_handle_PLTE(png_ptr, info_ptr, length);
  187234. #if defined(PNG_READ_bKGD_SUPPORTED)
  187235. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187236. png_handle_bKGD(png_ptr, info_ptr, length);
  187237. #endif
  187238. #if defined(PNG_READ_cHRM_SUPPORTED)
  187239. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187240. png_handle_cHRM(png_ptr, info_ptr, length);
  187241. #endif
  187242. #if defined(PNG_READ_gAMA_SUPPORTED)
  187243. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187244. png_handle_gAMA(png_ptr, info_ptr, length);
  187245. #endif
  187246. #if defined(PNG_READ_hIST_SUPPORTED)
  187247. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187248. png_handle_hIST(png_ptr, info_ptr, length);
  187249. #endif
  187250. #if defined(PNG_READ_oFFs_SUPPORTED)
  187251. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187252. png_handle_oFFs(png_ptr, info_ptr, length);
  187253. #endif
  187254. #if defined(PNG_READ_pCAL_SUPPORTED)
  187255. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187256. png_handle_pCAL(png_ptr, info_ptr, length);
  187257. #endif
  187258. #if defined(PNG_READ_sCAL_SUPPORTED)
  187259. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187260. png_handle_sCAL(png_ptr, info_ptr, length);
  187261. #endif
  187262. #if defined(PNG_READ_pHYs_SUPPORTED)
  187263. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187264. png_handle_pHYs(png_ptr, info_ptr, length);
  187265. #endif
  187266. #if defined(PNG_READ_sBIT_SUPPORTED)
  187267. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187268. png_handle_sBIT(png_ptr, info_ptr, length);
  187269. #endif
  187270. #if defined(PNG_READ_sRGB_SUPPORTED)
  187271. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187272. png_handle_sRGB(png_ptr, info_ptr, length);
  187273. #endif
  187274. #if defined(PNG_READ_iCCP_SUPPORTED)
  187275. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187276. png_handle_iCCP(png_ptr, info_ptr, length);
  187277. #endif
  187278. #if defined(PNG_READ_sPLT_SUPPORTED)
  187279. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187280. png_handle_sPLT(png_ptr, info_ptr, length);
  187281. #endif
  187282. #if defined(PNG_READ_tEXt_SUPPORTED)
  187283. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187284. png_handle_tEXt(png_ptr, info_ptr, length);
  187285. #endif
  187286. #if defined(PNG_READ_tIME_SUPPORTED)
  187287. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187288. png_handle_tIME(png_ptr, info_ptr, length);
  187289. #endif
  187290. #if defined(PNG_READ_tRNS_SUPPORTED)
  187291. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187292. png_handle_tRNS(png_ptr, info_ptr, length);
  187293. #endif
  187294. #if defined(PNG_READ_zTXt_SUPPORTED)
  187295. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187296. png_handle_zTXt(png_ptr, info_ptr, length);
  187297. #endif
  187298. #if defined(PNG_READ_iTXt_SUPPORTED)
  187299. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187300. png_handle_iTXt(png_ptr, info_ptr, length);
  187301. #endif
  187302. else
  187303. png_handle_unknown(png_ptr, info_ptr, length);
  187304. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187305. }
  187306. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187307. /* free all memory used by the read */
  187308. void PNGAPI
  187309. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187310. png_infopp end_info_ptr_ptr)
  187311. {
  187312. png_structp png_ptr = NULL;
  187313. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187314. #ifdef PNG_USER_MEM_SUPPORTED
  187315. png_free_ptr free_fn;
  187316. png_voidp mem_ptr;
  187317. #endif
  187318. png_debug(1, "in png_destroy_read_struct\n");
  187319. if (png_ptr_ptr != NULL)
  187320. png_ptr = *png_ptr_ptr;
  187321. if (info_ptr_ptr != NULL)
  187322. info_ptr = *info_ptr_ptr;
  187323. if (end_info_ptr_ptr != NULL)
  187324. end_info_ptr = *end_info_ptr_ptr;
  187325. #ifdef PNG_USER_MEM_SUPPORTED
  187326. free_fn = png_ptr->free_fn;
  187327. mem_ptr = png_ptr->mem_ptr;
  187328. #endif
  187329. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187330. if (info_ptr != NULL)
  187331. {
  187332. #if defined(PNG_TEXT_SUPPORTED)
  187333. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187334. #endif
  187335. #ifdef PNG_USER_MEM_SUPPORTED
  187336. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187337. (png_voidp)mem_ptr);
  187338. #else
  187339. png_destroy_struct((png_voidp)info_ptr);
  187340. #endif
  187341. *info_ptr_ptr = NULL;
  187342. }
  187343. if (end_info_ptr != NULL)
  187344. {
  187345. #if defined(PNG_READ_TEXT_SUPPORTED)
  187346. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187347. #endif
  187348. #ifdef PNG_USER_MEM_SUPPORTED
  187349. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187350. (png_voidp)mem_ptr);
  187351. #else
  187352. png_destroy_struct((png_voidp)end_info_ptr);
  187353. #endif
  187354. *end_info_ptr_ptr = NULL;
  187355. }
  187356. if (png_ptr != NULL)
  187357. {
  187358. #ifdef PNG_USER_MEM_SUPPORTED
  187359. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187360. (png_voidp)mem_ptr);
  187361. #else
  187362. png_destroy_struct((png_voidp)png_ptr);
  187363. #endif
  187364. *png_ptr_ptr = NULL;
  187365. }
  187366. }
  187367. /* free all memory used by the read (old method) */
  187368. void /* PRIVATE */
  187369. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187370. {
  187371. #ifdef PNG_SETJMP_SUPPORTED
  187372. jmp_buf tmp_jmp;
  187373. #endif
  187374. png_error_ptr error_fn;
  187375. png_error_ptr warning_fn;
  187376. png_voidp error_ptr;
  187377. #ifdef PNG_USER_MEM_SUPPORTED
  187378. png_free_ptr free_fn;
  187379. #endif
  187380. png_debug(1, "in png_read_destroy\n");
  187381. if (info_ptr != NULL)
  187382. png_info_destroy(png_ptr, info_ptr);
  187383. if (end_info_ptr != NULL)
  187384. png_info_destroy(png_ptr, end_info_ptr);
  187385. png_free(png_ptr, png_ptr->zbuf);
  187386. png_free(png_ptr, png_ptr->big_row_buf);
  187387. png_free(png_ptr, png_ptr->prev_row);
  187388. #if defined(PNG_READ_DITHER_SUPPORTED)
  187389. png_free(png_ptr, png_ptr->palette_lookup);
  187390. png_free(png_ptr, png_ptr->dither_index);
  187391. #endif
  187392. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187393. png_free(png_ptr, png_ptr->gamma_table);
  187394. #endif
  187395. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187396. png_free(png_ptr, png_ptr->gamma_from_1);
  187397. png_free(png_ptr, png_ptr->gamma_to_1);
  187398. #endif
  187399. #ifdef PNG_FREE_ME_SUPPORTED
  187400. if (png_ptr->free_me & PNG_FREE_PLTE)
  187401. png_zfree(png_ptr, png_ptr->palette);
  187402. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187403. #else
  187404. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187405. png_zfree(png_ptr, png_ptr->palette);
  187406. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187407. #endif
  187408. #if defined(PNG_tRNS_SUPPORTED) || \
  187409. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187410. #ifdef PNG_FREE_ME_SUPPORTED
  187411. if (png_ptr->free_me & PNG_FREE_TRNS)
  187412. png_free(png_ptr, png_ptr->trans);
  187413. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187414. #else
  187415. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187416. png_free(png_ptr, png_ptr->trans);
  187417. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187418. #endif
  187419. #endif
  187420. #if defined(PNG_READ_hIST_SUPPORTED)
  187421. #ifdef PNG_FREE_ME_SUPPORTED
  187422. if (png_ptr->free_me & PNG_FREE_HIST)
  187423. png_free(png_ptr, png_ptr->hist);
  187424. png_ptr->free_me &= ~PNG_FREE_HIST;
  187425. #else
  187426. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187427. png_free(png_ptr, png_ptr->hist);
  187428. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187429. #endif
  187430. #endif
  187431. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187432. if (png_ptr->gamma_16_table != NULL)
  187433. {
  187434. int i;
  187435. int istop = (1 << (8 - png_ptr->gamma_shift));
  187436. for (i = 0; i < istop; i++)
  187437. {
  187438. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187439. }
  187440. png_free(png_ptr, png_ptr->gamma_16_table);
  187441. }
  187442. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187443. if (png_ptr->gamma_16_from_1 != NULL)
  187444. {
  187445. int i;
  187446. int istop = (1 << (8 - png_ptr->gamma_shift));
  187447. for (i = 0; i < istop; i++)
  187448. {
  187449. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187450. }
  187451. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187452. }
  187453. if (png_ptr->gamma_16_to_1 != NULL)
  187454. {
  187455. int i;
  187456. int istop = (1 << (8 - png_ptr->gamma_shift));
  187457. for (i = 0; i < istop; i++)
  187458. {
  187459. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187460. }
  187461. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187462. }
  187463. #endif
  187464. #endif
  187465. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187466. png_free(png_ptr, png_ptr->time_buffer);
  187467. #endif
  187468. inflateEnd(&png_ptr->zstream);
  187469. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187470. png_free(png_ptr, png_ptr->save_buffer);
  187471. #endif
  187472. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187473. #ifdef PNG_TEXT_SUPPORTED
  187474. png_free(png_ptr, png_ptr->current_text);
  187475. #endif /* PNG_TEXT_SUPPORTED */
  187476. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187477. /* Save the important info out of the png_struct, in case it is
  187478. * being used again.
  187479. */
  187480. #ifdef PNG_SETJMP_SUPPORTED
  187481. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187482. #endif
  187483. error_fn = png_ptr->error_fn;
  187484. warning_fn = png_ptr->warning_fn;
  187485. error_ptr = png_ptr->error_ptr;
  187486. #ifdef PNG_USER_MEM_SUPPORTED
  187487. free_fn = png_ptr->free_fn;
  187488. #endif
  187489. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187490. png_ptr->error_fn = error_fn;
  187491. png_ptr->warning_fn = warning_fn;
  187492. png_ptr->error_ptr = error_ptr;
  187493. #ifdef PNG_USER_MEM_SUPPORTED
  187494. png_ptr->free_fn = free_fn;
  187495. #endif
  187496. #ifdef PNG_SETJMP_SUPPORTED
  187497. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187498. #endif
  187499. }
  187500. void PNGAPI
  187501. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187502. {
  187503. if(png_ptr == NULL) return;
  187504. png_ptr->read_row_fn = read_row_fn;
  187505. }
  187506. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187507. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187508. void PNGAPI
  187509. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187510. int transforms,
  187511. voidp params)
  187512. {
  187513. int row;
  187514. if(png_ptr == NULL) return;
  187515. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187516. /* invert the alpha channel from opacity to transparency
  187517. */
  187518. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187519. png_set_invert_alpha(png_ptr);
  187520. #endif
  187521. /* png_read_info() gives us all of the information from the
  187522. * PNG file before the first IDAT (image data chunk).
  187523. */
  187524. png_read_info(png_ptr, info_ptr);
  187525. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187526. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187527. /* -------------- image transformations start here ------------------- */
  187528. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187529. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187530. */
  187531. if (transforms & PNG_TRANSFORM_STRIP_16)
  187532. png_set_strip_16(png_ptr);
  187533. #endif
  187534. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187535. /* Strip alpha bytes from the input data without combining with
  187536. * the background (not recommended).
  187537. */
  187538. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187539. png_set_strip_alpha(png_ptr);
  187540. #endif
  187541. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187542. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187543. * byte into separate bytes (useful for paletted and grayscale images).
  187544. */
  187545. if (transforms & PNG_TRANSFORM_PACKING)
  187546. png_set_packing(png_ptr);
  187547. #endif
  187548. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187549. /* Change the order of packed pixels to least significant bit first
  187550. * (not useful if you are using png_set_packing).
  187551. */
  187552. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187553. png_set_packswap(png_ptr);
  187554. #endif
  187555. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187556. /* Expand paletted colors into true RGB triplets
  187557. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187558. * Expand paletted or RGB images with transparency to full alpha
  187559. * channels so the data will be available as RGBA quartets.
  187560. */
  187561. if (transforms & PNG_TRANSFORM_EXPAND)
  187562. if ((png_ptr->bit_depth < 8) ||
  187563. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187564. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187565. png_set_expand(png_ptr);
  187566. #endif
  187567. /* We don't handle background color or gamma transformation or dithering.
  187568. */
  187569. #if defined(PNG_READ_INVERT_SUPPORTED)
  187570. /* invert monochrome files to have 0 as white and 1 as black
  187571. */
  187572. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187573. png_set_invert_mono(png_ptr);
  187574. #endif
  187575. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187576. /* If you want to shift the pixel values from the range [0,255] or
  187577. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187578. * colors were originally in:
  187579. */
  187580. if ((transforms & PNG_TRANSFORM_SHIFT)
  187581. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187582. {
  187583. png_color_8p sig_bit;
  187584. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187585. png_set_shift(png_ptr, sig_bit);
  187586. }
  187587. #endif
  187588. #if defined(PNG_READ_BGR_SUPPORTED)
  187589. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187590. */
  187591. if (transforms & PNG_TRANSFORM_BGR)
  187592. png_set_bgr(png_ptr);
  187593. #endif
  187594. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187595. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187596. */
  187597. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187598. png_set_swap_alpha(png_ptr);
  187599. #endif
  187600. #if defined(PNG_READ_SWAP_SUPPORTED)
  187601. /* swap bytes of 16 bit files to least significant byte first
  187602. */
  187603. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187604. png_set_swap(png_ptr);
  187605. #endif
  187606. /* We don't handle adding filler bytes */
  187607. /* Optional call to gamma correct and add the background to the palette
  187608. * and update info structure. REQUIRED if you are expecting libpng to
  187609. * update the palette for you (i.e., you selected such a transform above).
  187610. */
  187611. png_read_update_info(png_ptr, info_ptr);
  187612. /* -------------- image transformations end here ------------------- */
  187613. #ifdef PNG_FREE_ME_SUPPORTED
  187614. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187615. #endif
  187616. if(info_ptr->row_pointers == NULL)
  187617. {
  187618. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187619. info_ptr->height * png_sizeof(png_bytep));
  187620. #ifdef PNG_FREE_ME_SUPPORTED
  187621. info_ptr->free_me |= PNG_FREE_ROWS;
  187622. #endif
  187623. for (row = 0; row < (int)info_ptr->height; row++)
  187624. {
  187625. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187626. png_get_rowbytes(png_ptr, info_ptr));
  187627. }
  187628. }
  187629. png_read_image(png_ptr, info_ptr->row_pointers);
  187630. info_ptr->valid |= PNG_INFO_IDAT;
  187631. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187632. png_read_end(png_ptr, info_ptr);
  187633. transforms = transforms; /* quiet compiler warnings */
  187634. params = params;
  187635. }
  187636. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187637. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187638. #endif /* PNG_READ_SUPPORTED */
  187639. /*** End of inlined file: pngread.c ***/
  187640. /*** Start of inlined file: pngpread.c ***/
  187641. /* pngpread.c - read a png file in push mode
  187642. *
  187643. * Last changed in libpng 1.2.21 October 4, 2007
  187644. * For conditions of distribution and use, see copyright notice in png.h
  187645. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187646. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187647. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187648. */
  187649. #define PNG_INTERNAL
  187650. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187651. /* push model modes */
  187652. #define PNG_READ_SIG_MODE 0
  187653. #define PNG_READ_CHUNK_MODE 1
  187654. #define PNG_READ_IDAT_MODE 2
  187655. #define PNG_SKIP_MODE 3
  187656. #define PNG_READ_tEXt_MODE 4
  187657. #define PNG_READ_zTXt_MODE 5
  187658. #define PNG_READ_DONE_MODE 6
  187659. #define PNG_READ_iTXt_MODE 7
  187660. #define PNG_ERROR_MODE 8
  187661. void PNGAPI
  187662. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187663. png_bytep buffer, png_size_t buffer_size)
  187664. {
  187665. if(png_ptr == NULL) return;
  187666. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187667. while (png_ptr->buffer_size)
  187668. {
  187669. png_process_some_data(png_ptr, info_ptr);
  187670. }
  187671. }
  187672. /* What we do with the incoming data depends on what we were previously
  187673. * doing before we ran out of data...
  187674. */
  187675. void /* PRIVATE */
  187676. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187677. {
  187678. if(png_ptr == NULL) return;
  187679. switch (png_ptr->process_mode)
  187680. {
  187681. case PNG_READ_SIG_MODE:
  187682. {
  187683. png_push_read_sig(png_ptr, info_ptr);
  187684. break;
  187685. }
  187686. case PNG_READ_CHUNK_MODE:
  187687. {
  187688. png_push_read_chunk(png_ptr, info_ptr);
  187689. break;
  187690. }
  187691. case PNG_READ_IDAT_MODE:
  187692. {
  187693. png_push_read_IDAT(png_ptr);
  187694. break;
  187695. }
  187696. #if defined(PNG_READ_tEXt_SUPPORTED)
  187697. case PNG_READ_tEXt_MODE:
  187698. {
  187699. png_push_read_tEXt(png_ptr, info_ptr);
  187700. break;
  187701. }
  187702. #endif
  187703. #if defined(PNG_READ_zTXt_SUPPORTED)
  187704. case PNG_READ_zTXt_MODE:
  187705. {
  187706. png_push_read_zTXt(png_ptr, info_ptr);
  187707. break;
  187708. }
  187709. #endif
  187710. #if defined(PNG_READ_iTXt_SUPPORTED)
  187711. case PNG_READ_iTXt_MODE:
  187712. {
  187713. png_push_read_iTXt(png_ptr, info_ptr);
  187714. break;
  187715. }
  187716. #endif
  187717. case PNG_SKIP_MODE:
  187718. {
  187719. png_push_crc_finish(png_ptr);
  187720. break;
  187721. }
  187722. default:
  187723. {
  187724. png_ptr->buffer_size = 0;
  187725. break;
  187726. }
  187727. }
  187728. }
  187729. /* Read any remaining signature bytes from the stream and compare them with
  187730. * the correct PNG signature. It is possible that this routine is called
  187731. * with bytes already read from the signature, either because they have been
  187732. * checked by the calling application, or because of multiple calls to this
  187733. * routine.
  187734. */
  187735. void /* PRIVATE */
  187736. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187737. {
  187738. png_size_t num_checked = png_ptr->sig_bytes,
  187739. num_to_check = 8 - num_checked;
  187740. if (png_ptr->buffer_size < num_to_check)
  187741. {
  187742. num_to_check = png_ptr->buffer_size;
  187743. }
  187744. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187745. num_to_check);
  187746. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187747. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187748. {
  187749. if (num_checked < 4 &&
  187750. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187751. png_error(png_ptr, "Not a PNG file");
  187752. else
  187753. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187754. }
  187755. else
  187756. {
  187757. if (png_ptr->sig_bytes >= 8)
  187758. {
  187759. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187760. }
  187761. }
  187762. }
  187763. void /* PRIVATE */
  187764. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187765. {
  187766. #ifdef PNG_USE_LOCAL_ARRAYS
  187767. PNG_CONST PNG_IHDR;
  187768. PNG_CONST PNG_IDAT;
  187769. PNG_CONST PNG_IEND;
  187770. PNG_CONST PNG_PLTE;
  187771. #if defined(PNG_READ_bKGD_SUPPORTED)
  187772. PNG_CONST PNG_bKGD;
  187773. #endif
  187774. #if defined(PNG_READ_cHRM_SUPPORTED)
  187775. PNG_CONST PNG_cHRM;
  187776. #endif
  187777. #if defined(PNG_READ_gAMA_SUPPORTED)
  187778. PNG_CONST PNG_gAMA;
  187779. #endif
  187780. #if defined(PNG_READ_hIST_SUPPORTED)
  187781. PNG_CONST PNG_hIST;
  187782. #endif
  187783. #if defined(PNG_READ_iCCP_SUPPORTED)
  187784. PNG_CONST PNG_iCCP;
  187785. #endif
  187786. #if defined(PNG_READ_iTXt_SUPPORTED)
  187787. PNG_CONST PNG_iTXt;
  187788. #endif
  187789. #if defined(PNG_READ_oFFs_SUPPORTED)
  187790. PNG_CONST PNG_oFFs;
  187791. #endif
  187792. #if defined(PNG_READ_pCAL_SUPPORTED)
  187793. PNG_CONST PNG_pCAL;
  187794. #endif
  187795. #if defined(PNG_READ_pHYs_SUPPORTED)
  187796. PNG_CONST PNG_pHYs;
  187797. #endif
  187798. #if defined(PNG_READ_sBIT_SUPPORTED)
  187799. PNG_CONST PNG_sBIT;
  187800. #endif
  187801. #if defined(PNG_READ_sCAL_SUPPORTED)
  187802. PNG_CONST PNG_sCAL;
  187803. #endif
  187804. #if defined(PNG_READ_sRGB_SUPPORTED)
  187805. PNG_CONST PNG_sRGB;
  187806. #endif
  187807. #if defined(PNG_READ_sPLT_SUPPORTED)
  187808. PNG_CONST PNG_sPLT;
  187809. #endif
  187810. #if defined(PNG_READ_tEXt_SUPPORTED)
  187811. PNG_CONST PNG_tEXt;
  187812. #endif
  187813. #if defined(PNG_READ_tIME_SUPPORTED)
  187814. PNG_CONST PNG_tIME;
  187815. #endif
  187816. #if defined(PNG_READ_tRNS_SUPPORTED)
  187817. PNG_CONST PNG_tRNS;
  187818. #endif
  187819. #if defined(PNG_READ_zTXt_SUPPORTED)
  187820. PNG_CONST PNG_zTXt;
  187821. #endif
  187822. #endif /* PNG_USE_LOCAL_ARRAYS */
  187823. /* First we make sure we have enough data for the 4 byte chunk name
  187824. * and the 4 byte chunk length before proceeding with decoding the
  187825. * chunk data. To fully decode each of these chunks, we also make
  187826. * sure we have enough data in the buffer for the 4 byte CRC at the
  187827. * end of every chunk (except IDAT, which is handled separately).
  187828. */
  187829. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187830. {
  187831. png_byte chunk_length[4];
  187832. if (png_ptr->buffer_size < 8)
  187833. {
  187834. png_push_save_buffer(png_ptr);
  187835. return;
  187836. }
  187837. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187838. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187839. png_reset_crc(png_ptr);
  187840. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187841. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187842. }
  187843. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187844. if(png_ptr->mode & PNG_AFTER_IDAT)
  187845. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187846. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187847. {
  187848. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187849. {
  187850. png_push_save_buffer(png_ptr);
  187851. return;
  187852. }
  187853. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  187854. }
  187855. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187856. {
  187857. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187858. {
  187859. png_push_save_buffer(png_ptr);
  187860. return;
  187861. }
  187862. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  187863. png_ptr->process_mode = PNG_READ_DONE_MODE;
  187864. png_push_have_end(png_ptr, info_ptr);
  187865. }
  187866. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187867. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187868. {
  187869. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187870. {
  187871. png_push_save_buffer(png_ptr);
  187872. return;
  187873. }
  187874. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187875. png_ptr->mode |= PNG_HAVE_IDAT;
  187876. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187877. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187878. png_ptr->mode |= PNG_HAVE_PLTE;
  187879. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187880. {
  187881. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187882. png_error(png_ptr, "Missing IHDR before IDAT");
  187883. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187884. !(png_ptr->mode & PNG_HAVE_PLTE))
  187885. png_error(png_ptr, "Missing PLTE before IDAT");
  187886. }
  187887. }
  187888. #endif
  187889. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187890. {
  187891. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187892. {
  187893. png_push_save_buffer(png_ptr);
  187894. return;
  187895. }
  187896. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  187897. }
  187898. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187899. {
  187900. /* If we reach an IDAT chunk, this means we have read all of the
  187901. * header chunks, and we can start reading the image (or if this
  187902. * is called after the image has been read - we have an error).
  187903. */
  187904. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187905. png_error(png_ptr, "Missing IHDR before IDAT");
  187906. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187907. !(png_ptr->mode & PNG_HAVE_PLTE))
  187908. png_error(png_ptr, "Missing PLTE before IDAT");
  187909. if (png_ptr->mode & PNG_HAVE_IDAT)
  187910. {
  187911. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187912. if (png_ptr->push_length == 0)
  187913. return;
  187914. if (png_ptr->mode & PNG_AFTER_IDAT)
  187915. png_error(png_ptr, "Too many IDAT's found");
  187916. }
  187917. png_ptr->idat_size = png_ptr->push_length;
  187918. png_ptr->mode |= PNG_HAVE_IDAT;
  187919. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  187920. png_push_have_info(png_ptr, info_ptr);
  187921. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187922. png_ptr->zstream.next_out = png_ptr->row_buf;
  187923. return;
  187924. }
  187925. #if defined(PNG_READ_gAMA_SUPPORTED)
  187926. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187927. {
  187928. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187929. {
  187930. png_push_save_buffer(png_ptr);
  187931. return;
  187932. }
  187933. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  187934. }
  187935. #endif
  187936. #if defined(PNG_READ_sBIT_SUPPORTED)
  187937. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187938. {
  187939. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187940. {
  187941. png_push_save_buffer(png_ptr);
  187942. return;
  187943. }
  187944. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  187945. }
  187946. #endif
  187947. #if defined(PNG_READ_cHRM_SUPPORTED)
  187948. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187949. {
  187950. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187951. {
  187952. png_push_save_buffer(png_ptr);
  187953. return;
  187954. }
  187955. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  187956. }
  187957. #endif
  187958. #if defined(PNG_READ_sRGB_SUPPORTED)
  187959. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187960. {
  187961. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187962. {
  187963. png_push_save_buffer(png_ptr);
  187964. return;
  187965. }
  187966. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  187967. }
  187968. #endif
  187969. #if defined(PNG_READ_iCCP_SUPPORTED)
  187970. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187971. {
  187972. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187973. {
  187974. png_push_save_buffer(png_ptr);
  187975. return;
  187976. }
  187977. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  187978. }
  187979. #endif
  187980. #if defined(PNG_READ_sPLT_SUPPORTED)
  187981. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187982. {
  187983. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187984. {
  187985. png_push_save_buffer(png_ptr);
  187986. return;
  187987. }
  187988. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  187989. }
  187990. #endif
  187991. #if defined(PNG_READ_tRNS_SUPPORTED)
  187992. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187993. {
  187994. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187995. {
  187996. png_push_save_buffer(png_ptr);
  187997. return;
  187998. }
  187999. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188000. }
  188001. #endif
  188002. #if defined(PNG_READ_bKGD_SUPPORTED)
  188003. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188004. {
  188005. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188006. {
  188007. png_push_save_buffer(png_ptr);
  188008. return;
  188009. }
  188010. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188011. }
  188012. #endif
  188013. #if defined(PNG_READ_hIST_SUPPORTED)
  188014. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188015. {
  188016. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188017. {
  188018. png_push_save_buffer(png_ptr);
  188019. return;
  188020. }
  188021. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188022. }
  188023. #endif
  188024. #if defined(PNG_READ_pHYs_SUPPORTED)
  188025. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188026. {
  188027. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188028. {
  188029. png_push_save_buffer(png_ptr);
  188030. return;
  188031. }
  188032. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188033. }
  188034. #endif
  188035. #if defined(PNG_READ_oFFs_SUPPORTED)
  188036. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188037. {
  188038. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188039. {
  188040. png_push_save_buffer(png_ptr);
  188041. return;
  188042. }
  188043. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188044. }
  188045. #endif
  188046. #if defined(PNG_READ_pCAL_SUPPORTED)
  188047. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188048. {
  188049. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188050. {
  188051. png_push_save_buffer(png_ptr);
  188052. return;
  188053. }
  188054. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188055. }
  188056. #endif
  188057. #if defined(PNG_READ_sCAL_SUPPORTED)
  188058. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188059. {
  188060. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188061. {
  188062. png_push_save_buffer(png_ptr);
  188063. return;
  188064. }
  188065. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188066. }
  188067. #endif
  188068. #if defined(PNG_READ_tIME_SUPPORTED)
  188069. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188070. {
  188071. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188072. {
  188073. png_push_save_buffer(png_ptr);
  188074. return;
  188075. }
  188076. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188077. }
  188078. #endif
  188079. #if defined(PNG_READ_tEXt_SUPPORTED)
  188080. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188081. {
  188082. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188083. {
  188084. png_push_save_buffer(png_ptr);
  188085. return;
  188086. }
  188087. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188088. }
  188089. #endif
  188090. #if defined(PNG_READ_zTXt_SUPPORTED)
  188091. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188092. {
  188093. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188094. {
  188095. png_push_save_buffer(png_ptr);
  188096. return;
  188097. }
  188098. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188099. }
  188100. #endif
  188101. #if defined(PNG_READ_iTXt_SUPPORTED)
  188102. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188103. {
  188104. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188105. {
  188106. png_push_save_buffer(png_ptr);
  188107. return;
  188108. }
  188109. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188110. }
  188111. #endif
  188112. else
  188113. {
  188114. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188115. {
  188116. png_push_save_buffer(png_ptr);
  188117. return;
  188118. }
  188119. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188120. }
  188121. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188122. }
  188123. void /* PRIVATE */
  188124. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188125. {
  188126. png_ptr->process_mode = PNG_SKIP_MODE;
  188127. png_ptr->skip_length = skip;
  188128. }
  188129. void /* PRIVATE */
  188130. png_push_crc_finish(png_structp png_ptr)
  188131. {
  188132. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188133. {
  188134. png_size_t save_size;
  188135. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188136. save_size = (png_size_t)png_ptr->skip_length;
  188137. else
  188138. save_size = png_ptr->save_buffer_size;
  188139. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188140. png_ptr->skip_length -= save_size;
  188141. png_ptr->buffer_size -= save_size;
  188142. png_ptr->save_buffer_size -= save_size;
  188143. png_ptr->save_buffer_ptr += save_size;
  188144. }
  188145. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188146. {
  188147. png_size_t save_size;
  188148. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188149. save_size = (png_size_t)png_ptr->skip_length;
  188150. else
  188151. save_size = png_ptr->current_buffer_size;
  188152. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188153. png_ptr->skip_length -= save_size;
  188154. png_ptr->buffer_size -= save_size;
  188155. png_ptr->current_buffer_size -= save_size;
  188156. png_ptr->current_buffer_ptr += save_size;
  188157. }
  188158. if (!png_ptr->skip_length)
  188159. {
  188160. if (png_ptr->buffer_size < 4)
  188161. {
  188162. png_push_save_buffer(png_ptr);
  188163. return;
  188164. }
  188165. png_crc_finish(png_ptr, 0);
  188166. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188167. }
  188168. }
  188169. void PNGAPI
  188170. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188171. {
  188172. png_bytep ptr;
  188173. if(png_ptr == NULL) return;
  188174. ptr = buffer;
  188175. if (png_ptr->save_buffer_size)
  188176. {
  188177. png_size_t save_size;
  188178. if (length < png_ptr->save_buffer_size)
  188179. save_size = length;
  188180. else
  188181. save_size = png_ptr->save_buffer_size;
  188182. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188183. length -= save_size;
  188184. ptr += save_size;
  188185. png_ptr->buffer_size -= save_size;
  188186. png_ptr->save_buffer_size -= save_size;
  188187. png_ptr->save_buffer_ptr += save_size;
  188188. }
  188189. if (length && png_ptr->current_buffer_size)
  188190. {
  188191. png_size_t save_size;
  188192. if (length < png_ptr->current_buffer_size)
  188193. save_size = length;
  188194. else
  188195. save_size = png_ptr->current_buffer_size;
  188196. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188197. png_ptr->buffer_size -= save_size;
  188198. png_ptr->current_buffer_size -= save_size;
  188199. png_ptr->current_buffer_ptr += save_size;
  188200. }
  188201. }
  188202. void /* PRIVATE */
  188203. png_push_save_buffer(png_structp png_ptr)
  188204. {
  188205. if (png_ptr->save_buffer_size)
  188206. {
  188207. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188208. {
  188209. png_size_t i,istop;
  188210. png_bytep sp;
  188211. png_bytep dp;
  188212. istop = png_ptr->save_buffer_size;
  188213. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188214. i < istop; i++, sp++, dp++)
  188215. {
  188216. *dp = *sp;
  188217. }
  188218. }
  188219. }
  188220. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188221. png_ptr->save_buffer_max)
  188222. {
  188223. png_size_t new_max;
  188224. png_bytep old_buffer;
  188225. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188226. (png_ptr->current_buffer_size + 256))
  188227. {
  188228. png_error(png_ptr, "Potential overflow of save_buffer");
  188229. }
  188230. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188231. old_buffer = png_ptr->save_buffer;
  188232. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188233. (png_uint_32)new_max);
  188234. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188235. png_free(png_ptr, old_buffer);
  188236. png_ptr->save_buffer_max = new_max;
  188237. }
  188238. if (png_ptr->current_buffer_size)
  188239. {
  188240. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188241. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188242. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188243. png_ptr->current_buffer_size = 0;
  188244. }
  188245. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188246. png_ptr->buffer_size = 0;
  188247. }
  188248. void /* PRIVATE */
  188249. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188250. png_size_t buffer_length)
  188251. {
  188252. png_ptr->current_buffer = buffer;
  188253. png_ptr->current_buffer_size = buffer_length;
  188254. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188255. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188256. }
  188257. void /* PRIVATE */
  188258. png_push_read_IDAT(png_structp png_ptr)
  188259. {
  188260. #ifdef PNG_USE_LOCAL_ARRAYS
  188261. PNG_CONST PNG_IDAT;
  188262. #endif
  188263. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188264. {
  188265. png_byte chunk_length[4];
  188266. if (png_ptr->buffer_size < 8)
  188267. {
  188268. png_push_save_buffer(png_ptr);
  188269. return;
  188270. }
  188271. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188272. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188273. png_reset_crc(png_ptr);
  188274. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188275. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188276. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188277. {
  188278. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188279. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188280. png_error(png_ptr, "Not enough compressed data");
  188281. return;
  188282. }
  188283. png_ptr->idat_size = png_ptr->push_length;
  188284. }
  188285. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188286. {
  188287. png_size_t save_size;
  188288. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188289. {
  188290. save_size = (png_size_t)png_ptr->idat_size;
  188291. /* check for overflow */
  188292. if((png_uint_32)save_size != png_ptr->idat_size)
  188293. png_error(png_ptr, "save_size overflowed in pngpread");
  188294. }
  188295. else
  188296. save_size = png_ptr->save_buffer_size;
  188297. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188298. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188299. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188300. png_ptr->idat_size -= save_size;
  188301. png_ptr->buffer_size -= save_size;
  188302. png_ptr->save_buffer_size -= save_size;
  188303. png_ptr->save_buffer_ptr += save_size;
  188304. }
  188305. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188306. {
  188307. png_size_t save_size;
  188308. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188309. {
  188310. save_size = (png_size_t)png_ptr->idat_size;
  188311. /* check for overflow */
  188312. if((png_uint_32)save_size != png_ptr->idat_size)
  188313. png_error(png_ptr, "save_size overflowed in pngpread");
  188314. }
  188315. else
  188316. save_size = png_ptr->current_buffer_size;
  188317. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188318. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188319. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188320. png_ptr->idat_size -= save_size;
  188321. png_ptr->buffer_size -= save_size;
  188322. png_ptr->current_buffer_size -= save_size;
  188323. png_ptr->current_buffer_ptr += save_size;
  188324. }
  188325. if (!png_ptr->idat_size)
  188326. {
  188327. if (png_ptr->buffer_size < 4)
  188328. {
  188329. png_push_save_buffer(png_ptr);
  188330. return;
  188331. }
  188332. png_crc_finish(png_ptr, 0);
  188333. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188334. png_ptr->mode |= PNG_AFTER_IDAT;
  188335. }
  188336. }
  188337. void /* PRIVATE */
  188338. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188339. png_size_t buffer_length)
  188340. {
  188341. int ret;
  188342. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188343. png_error(png_ptr, "Extra compression data");
  188344. png_ptr->zstream.next_in = buffer;
  188345. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188346. for(;;)
  188347. {
  188348. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188349. if (ret != Z_OK)
  188350. {
  188351. if (ret == Z_STREAM_END)
  188352. {
  188353. if (png_ptr->zstream.avail_in)
  188354. png_error(png_ptr, "Extra compressed data");
  188355. if (!(png_ptr->zstream.avail_out))
  188356. {
  188357. png_push_process_row(png_ptr);
  188358. }
  188359. png_ptr->mode |= PNG_AFTER_IDAT;
  188360. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188361. break;
  188362. }
  188363. else if (ret == Z_BUF_ERROR)
  188364. break;
  188365. else
  188366. png_error(png_ptr, "Decompression Error");
  188367. }
  188368. if (!(png_ptr->zstream.avail_out))
  188369. {
  188370. if ((
  188371. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188372. png_ptr->interlaced && png_ptr->pass > 6) ||
  188373. (!png_ptr->interlaced &&
  188374. #endif
  188375. png_ptr->row_number == png_ptr->num_rows))
  188376. {
  188377. if (png_ptr->zstream.avail_in)
  188378. {
  188379. png_warning(png_ptr, "Too much data in IDAT chunks");
  188380. }
  188381. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188382. break;
  188383. }
  188384. png_push_process_row(png_ptr);
  188385. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188386. png_ptr->zstream.next_out = png_ptr->row_buf;
  188387. }
  188388. else
  188389. break;
  188390. }
  188391. }
  188392. void /* PRIVATE */
  188393. png_push_process_row(png_structp png_ptr)
  188394. {
  188395. png_ptr->row_info.color_type = png_ptr->color_type;
  188396. png_ptr->row_info.width = png_ptr->iwidth;
  188397. png_ptr->row_info.channels = png_ptr->channels;
  188398. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188399. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188400. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188401. png_ptr->row_info.width);
  188402. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188403. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188404. (int)(png_ptr->row_buf[0]));
  188405. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188406. png_ptr->rowbytes + 1);
  188407. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188408. png_do_read_transformations(png_ptr);
  188409. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188410. /* blow up interlaced rows to full size */
  188411. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188412. {
  188413. if (png_ptr->pass < 6)
  188414. /* old interface (pre-1.0.9):
  188415. png_do_read_interlace(&(png_ptr->row_info),
  188416. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188417. */
  188418. png_do_read_interlace(png_ptr);
  188419. switch (png_ptr->pass)
  188420. {
  188421. case 0:
  188422. {
  188423. int i;
  188424. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188425. {
  188426. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188427. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188428. }
  188429. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188430. {
  188431. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188432. {
  188433. png_push_have_row(png_ptr, png_bytep_NULL);
  188434. png_read_push_finish_row(png_ptr);
  188435. }
  188436. }
  188437. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188438. {
  188439. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188440. {
  188441. png_push_have_row(png_ptr, png_bytep_NULL);
  188442. png_read_push_finish_row(png_ptr);
  188443. }
  188444. }
  188445. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188446. {
  188447. png_push_have_row(png_ptr, png_bytep_NULL);
  188448. png_read_push_finish_row(png_ptr);
  188449. }
  188450. break;
  188451. }
  188452. case 1:
  188453. {
  188454. int i;
  188455. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188456. {
  188457. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188458. png_read_push_finish_row(png_ptr);
  188459. }
  188460. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188461. {
  188462. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188463. {
  188464. png_push_have_row(png_ptr, png_bytep_NULL);
  188465. png_read_push_finish_row(png_ptr);
  188466. }
  188467. }
  188468. break;
  188469. }
  188470. case 2:
  188471. {
  188472. int i;
  188473. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188474. {
  188475. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188476. png_read_push_finish_row(png_ptr);
  188477. }
  188478. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188479. {
  188480. png_push_have_row(png_ptr, png_bytep_NULL);
  188481. png_read_push_finish_row(png_ptr);
  188482. }
  188483. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188484. {
  188485. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188486. {
  188487. png_push_have_row(png_ptr, png_bytep_NULL);
  188488. png_read_push_finish_row(png_ptr);
  188489. }
  188490. }
  188491. break;
  188492. }
  188493. case 3:
  188494. {
  188495. int i;
  188496. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188497. {
  188498. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188499. png_read_push_finish_row(png_ptr);
  188500. }
  188501. if (png_ptr->pass == 4) /* skip top two generated rows */
  188502. {
  188503. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188504. {
  188505. png_push_have_row(png_ptr, png_bytep_NULL);
  188506. png_read_push_finish_row(png_ptr);
  188507. }
  188508. }
  188509. break;
  188510. }
  188511. case 4:
  188512. {
  188513. int i;
  188514. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188515. {
  188516. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188517. png_read_push_finish_row(png_ptr);
  188518. }
  188519. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188520. {
  188521. png_push_have_row(png_ptr, png_bytep_NULL);
  188522. png_read_push_finish_row(png_ptr);
  188523. }
  188524. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188525. {
  188526. png_push_have_row(png_ptr, png_bytep_NULL);
  188527. png_read_push_finish_row(png_ptr);
  188528. }
  188529. break;
  188530. }
  188531. case 5:
  188532. {
  188533. int i;
  188534. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188535. {
  188536. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188537. png_read_push_finish_row(png_ptr);
  188538. }
  188539. if (png_ptr->pass == 6) /* skip top generated row */
  188540. {
  188541. png_push_have_row(png_ptr, png_bytep_NULL);
  188542. png_read_push_finish_row(png_ptr);
  188543. }
  188544. break;
  188545. }
  188546. case 6:
  188547. {
  188548. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188549. png_read_push_finish_row(png_ptr);
  188550. if (png_ptr->pass != 6)
  188551. break;
  188552. png_push_have_row(png_ptr, png_bytep_NULL);
  188553. png_read_push_finish_row(png_ptr);
  188554. }
  188555. }
  188556. }
  188557. else
  188558. #endif
  188559. {
  188560. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188561. png_read_push_finish_row(png_ptr);
  188562. }
  188563. }
  188564. void /* PRIVATE */
  188565. png_read_push_finish_row(png_structp png_ptr)
  188566. {
  188567. #ifdef PNG_USE_LOCAL_ARRAYS
  188568. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188569. /* start of interlace block */
  188570. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188571. /* offset to next interlace block */
  188572. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188573. /* start of interlace block in the y direction */
  188574. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188575. /* offset to next interlace block in the y direction */
  188576. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188577. /* Height of interlace block. This is not currently used - if you need
  188578. * it, uncomment it here and in png.h
  188579. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188580. */
  188581. #endif
  188582. png_ptr->row_number++;
  188583. if (png_ptr->row_number < png_ptr->num_rows)
  188584. return;
  188585. if (png_ptr->interlaced)
  188586. {
  188587. png_ptr->row_number = 0;
  188588. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188589. png_ptr->rowbytes + 1);
  188590. do
  188591. {
  188592. png_ptr->pass++;
  188593. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188594. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188595. (png_ptr->pass == 5 && png_ptr->width < 2))
  188596. png_ptr->pass++;
  188597. if (png_ptr->pass > 7)
  188598. png_ptr->pass--;
  188599. if (png_ptr->pass >= 7)
  188600. break;
  188601. png_ptr->iwidth = (png_ptr->width +
  188602. png_pass_inc[png_ptr->pass] - 1 -
  188603. png_pass_start[png_ptr->pass]) /
  188604. png_pass_inc[png_ptr->pass];
  188605. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188606. png_ptr->iwidth) + 1;
  188607. if (png_ptr->transformations & PNG_INTERLACE)
  188608. break;
  188609. png_ptr->num_rows = (png_ptr->height +
  188610. png_pass_yinc[png_ptr->pass] - 1 -
  188611. png_pass_ystart[png_ptr->pass]) /
  188612. png_pass_yinc[png_ptr->pass];
  188613. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188614. }
  188615. }
  188616. #if defined(PNG_READ_tEXt_SUPPORTED)
  188617. void /* PRIVATE */
  188618. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188619. length)
  188620. {
  188621. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188622. {
  188623. png_error(png_ptr, "Out of place tEXt");
  188624. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188625. }
  188626. #ifdef PNG_MAX_MALLOC_64K
  188627. png_ptr->skip_length = 0; /* This may not be necessary */
  188628. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188629. {
  188630. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188631. png_ptr->skip_length = length - (png_uint_32)65535L;
  188632. length = (png_uint_32)65535L;
  188633. }
  188634. #endif
  188635. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188636. (png_uint_32)(length+1));
  188637. png_ptr->current_text[length] = '\0';
  188638. png_ptr->current_text_ptr = png_ptr->current_text;
  188639. png_ptr->current_text_size = (png_size_t)length;
  188640. png_ptr->current_text_left = (png_size_t)length;
  188641. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188642. }
  188643. void /* PRIVATE */
  188644. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188645. {
  188646. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188647. {
  188648. png_size_t text_size;
  188649. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188650. text_size = png_ptr->buffer_size;
  188651. else
  188652. text_size = png_ptr->current_text_left;
  188653. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188654. png_ptr->current_text_left -= text_size;
  188655. png_ptr->current_text_ptr += text_size;
  188656. }
  188657. if (!(png_ptr->current_text_left))
  188658. {
  188659. png_textp text_ptr;
  188660. png_charp text;
  188661. png_charp key;
  188662. int ret;
  188663. if (png_ptr->buffer_size < 4)
  188664. {
  188665. png_push_save_buffer(png_ptr);
  188666. return;
  188667. }
  188668. png_push_crc_finish(png_ptr);
  188669. #if defined(PNG_MAX_MALLOC_64K)
  188670. if (png_ptr->skip_length)
  188671. return;
  188672. #endif
  188673. key = png_ptr->current_text;
  188674. for (text = key; *text; text++)
  188675. /* empty loop */ ;
  188676. if (text < key + png_ptr->current_text_size)
  188677. text++;
  188678. text_ptr = (png_textp)png_malloc(png_ptr,
  188679. (png_uint_32)png_sizeof(png_text));
  188680. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188681. text_ptr->key = key;
  188682. #ifdef PNG_iTXt_SUPPORTED
  188683. text_ptr->lang = NULL;
  188684. text_ptr->lang_key = NULL;
  188685. #endif
  188686. text_ptr->text = text;
  188687. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188688. png_free(png_ptr, key);
  188689. png_free(png_ptr, text_ptr);
  188690. png_ptr->current_text = NULL;
  188691. if (ret)
  188692. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188693. }
  188694. }
  188695. #endif
  188696. #if defined(PNG_READ_zTXt_SUPPORTED)
  188697. void /* PRIVATE */
  188698. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188699. length)
  188700. {
  188701. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188702. {
  188703. png_error(png_ptr, "Out of place zTXt");
  188704. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188705. }
  188706. #ifdef PNG_MAX_MALLOC_64K
  188707. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188708. * to be able to store the uncompressed data. Actually, the threshold
  188709. * is probably around 32K, but it isn't as definite as 64K is.
  188710. */
  188711. if (length > (png_uint_32)65535L)
  188712. {
  188713. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188714. png_push_crc_skip(png_ptr, length);
  188715. return;
  188716. }
  188717. #endif
  188718. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188719. (png_uint_32)(length+1));
  188720. png_ptr->current_text[length] = '\0';
  188721. png_ptr->current_text_ptr = png_ptr->current_text;
  188722. png_ptr->current_text_size = (png_size_t)length;
  188723. png_ptr->current_text_left = (png_size_t)length;
  188724. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188725. }
  188726. void /* PRIVATE */
  188727. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188728. {
  188729. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188730. {
  188731. png_size_t text_size;
  188732. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188733. text_size = png_ptr->buffer_size;
  188734. else
  188735. text_size = png_ptr->current_text_left;
  188736. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188737. png_ptr->current_text_left -= text_size;
  188738. png_ptr->current_text_ptr += text_size;
  188739. }
  188740. if (!(png_ptr->current_text_left))
  188741. {
  188742. png_textp text_ptr;
  188743. png_charp text;
  188744. png_charp key;
  188745. int ret;
  188746. png_size_t text_size, key_size;
  188747. if (png_ptr->buffer_size < 4)
  188748. {
  188749. png_push_save_buffer(png_ptr);
  188750. return;
  188751. }
  188752. png_push_crc_finish(png_ptr);
  188753. key = png_ptr->current_text;
  188754. for (text = key; *text; text++)
  188755. /* empty loop */ ;
  188756. /* zTXt can't have zero text */
  188757. if (text >= key + png_ptr->current_text_size)
  188758. {
  188759. png_ptr->current_text = NULL;
  188760. png_free(png_ptr, key);
  188761. return;
  188762. }
  188763. text++;
  188764. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188765. {
  188766. png_ptr->current_text = NULL;
  188767. png_free(png_ptr, key);
  188768. return;
  188769. }
  188770. text++;
  188771. png_ptr->zstream.next_in = (png_bytep )text;
  188772. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188773. (text - key));
  188774. png_ptr->zstream.next_out = png_ptr->zbuf;
  188775. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188776. key_size = text - key;
  188777. text_size = 0;
  188778. text = NULL;
  188779. ret = Z_STREAM_END;
  188780. while (png_ptr->zstream.avail_in)
  188781. {
  188782. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188783. if (ret != Z_OK && ret != Z_STREAM_END)
  188784. {
  188785. inflateReset(&png_ptr->zstream);
  188786. png_ptr->zstream.avail_in = 0;
  188787. png_ptr->current_text = NULL;
  188788. png_free(png_ptr, key);
  188789. png_free(png_ptr, text);
  188790. return;
  188791. }
  188792. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188793. {
  188794. if (text == NULL)
  188795. {
  188796. text = (png_charp)png_malloc(png_ptr,
  188797. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188798. + key_size + 1));
  188799. png_memcpy(text + key_size, png_ptr->zbuf,
  188800. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188801. png_memcpy(text, key, key_size);
  188802. text_size = key_size + png_ptr->zbuf_size -
  188803. png_ptr->zstream.avail_out;
  188804. *(text + text_size) = '\0';
  188805. }
  188806. else
  188807. {
  188808. png_charp tmp;
  188809. tmp = text;
  188810. text = (png_charp)png_malloc(png_ptr, text_size +
  188811. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188812. + 1));
  188813. png_memcpy(text, tmp, text_size);
  188814. png_free(png_ptr, tmp);
  188815. png_memcpy(text + text_size, png_ptr->zbuf,
  188816. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188817. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188818. *(text + text_size) = '\0';
  188819. }
  188820. if (ret != Z_STREAM_END)
  188821. {
  188822. png_ptr->zstream.next_out = png_ptr->zbuf;
  188823. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188824. }
  188825. }
  188826. else
  188827. {
  188828. break;
  188829. }
  188830. if (ret == Z_STREAM_END)
  188831. break;
  188832. }
  188833. inflateReset(&png_ptr->zstream);
  188834. png_ptr->zstream.avail_in = 0;
  188835. if (ret != Z_STREAM_END)
  188836. {
  188837. png_ptr->current_text = NULL;
  188838. png_free(png_ptr, key);
  188839. png_free(png_ptr, text);
  188840. return;
  188841. }
  188842. png_ptr->current_text = NULL;
  188843. png_free(png_ptr, key);
  188844. key = text;
  188845. text += key_size;
  188846. text_ptr = (png_textp)png_malloc(png_ptr,
  188847. (png_uint_32)png_sizeof(png_text));
  188848. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  188849. text_ptr->key = key;
  188850. #ifdef PNG_iTXt_SUPPORTED
  188851. text_ptr->lang = NULL;
  188852. text_ptr->lang_key = NULL;
  188853. #endif
  188854. text_ptr->text = text;
  188855. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188856. png_free(png_ptr, key);
  188857. png_free(png_ptr, text_ptr);
  188858. if (ret)
  188859. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188860. }
  188861. }
  188862. #endif
  188863. #if defined(PNG_READ_iTXt_SUPPORTED)
  188864. void /* PRIVATE */
  188865. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188866. length)
  188867. {
  188868. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188869. {
  188870. png_error(png_ptr, "Out of place iTXt");
  188871. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188872. }
  188873. #ifdef PNG_MAX_MALLOC_64K
  188874. png_ptr->skip_length = 0; /* This may not be necessary */
  188875. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188876. {
  188877. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  188878. png_ptr->skip_length = length - (png_uint_32)65535L;
  188879. length = (png_uint_32)65535L;
  188880. }
  188881. #endif
  188882. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188883. (png_uint_32)(length+1));
  188884. png_ptr->current_text[length] = '\0';
  188885. png_ptr->current_text_ptr = png_ptr->current_text;
  188886. png_ptr->current_text_size = (png_size_t)length;
  188887. png_ptr->current_text_left = (png_size_t)length;
  188888. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  188889. }
  188890. void /* PRIVATE */
  188891. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  188892. {
  188893. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188894. {
  188895. png_size_t text_size;
  188896. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188897. text_size = png_ptr->buffer_size;
  188898. else
  188899. text_size = png_ptr->current_text_left;
  188900. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188901. png_ptr->current_text_left -= text_size;
  188902. png_ptr->current_text_ptr += text_size;
  188903. }
  188904. if (!(png_ptr->current_text_left))
  188905. {
  188906. png_textp text_ptr;
  188907. png_charp key;
  188908. int comp_flag;
  188909. png_charp lang;
  188910. png_charp lang_key;
  188911. png_charp text;
  188912. int ret;
  188913. if (png_ptr->buffer_size < 4)
  188914. {
  188915. png_push_save_buffer(png_ptr);
  188916. return;
  188917. }
  188918. png_push_crc_finish(png_ptr);
  188919. #if defined(PNG_MAX_MALLOC_64K)
  188920. if (png_ptr->skip_length)
  188921. return;
  188922. #endif
  188923. key = png_ptr->current_text;
  188924. for (lang = key; *lang; lang++)
  188925. /* empty loop */ ;
  188926. if (lang < key + png_ptr->current_text_size - 3)
  188927. lang++;
  188928. comp_flag = *lang++;
  188929. lang++; /* skip comp_type, always zero */
  188930. for (lang_key = lang; *lang_key; lang_key++)
  188931. /* empty loop */ ;
  188932. lang_key++; /* skip NUL separator */
  188933. text=lang_key;
  188934. if (lang_key < key + png_ptr->current_text_size - 1)
  188935. {
  188936. for (; *text; text++)
  188937. /* empty loop */ ;
  188938. }
  188939. if (text < key + png_ptr->current_text_size)
  188940. text++;
  188941. text_ptr = (png_textp)png_malloc(png_ptr,
  188942. (png_uint_32)png_sizeof(png_text));
  188943. text_ptr->compression = comp_flag + 2;
  188944. text_ptr->key = key;
  188945. text_ptr->lang = lang;
  188946. text_ptr->lang_key = lang_key;
  188947. text_ptr->text = text;
  188948. text_ptr->text_length = 0;
  188949. text_ptr->itxt_length = png_strlen(text);
  188950. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188951. png_ptr->current_text = NULL;
  188952. png_free(png_ptr, text_ptr);
  188953. if (ret)
  188954. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  188955. }
  188956. }
  188957. #endif
  188958. /* This function is called when we haven't found a handler for this
  188959. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  188960. * name or a critical chunk), the chunk is (currently) silently ignored.
  188961. */
  188962. void /* PRIVATE */
  188963. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188964. length)
  188965. {
  188966. png_uint_32 skip=0;
  188967. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  188968. if (!(png_ptr->chunk_name[0] & 0x20))
  188969. {
  188970. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188971. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188972. PNG_HANDLE_CHUNK_ALWAYS
  188973. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188974. && png_ptr->read_user_chunk_fn == NULL
  188975. #endif
  188976. )
  188977. #endif
  188978. png_chunk_error(png_ptr, "unknown critical chunk");
  188979. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188980. }
  188981. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188982. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  188983. {
  188984. #ifdef PNG_MAX_MALLOC_64K
  188985. if (length > (png_uint_32)65535L)
  188986. {
  188987. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  188988. skip = length - (png_uint_32)65535L;
  188989. length = (png_uint_32)65535L;
  188990. }
  188991. #endif
  188992. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  188993. (png_charp)png_ptr->chunk_name, 5);
  188994. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  188995. png_ptr->unknown_chunk.size = (png_size_t)length;
  188996. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  188997. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188998. if(png_ptr->read_user_chunk_fn != NULL)
  188999. {
  189000. /* callback to user unknown chunk handler */
  189001. int ret;
  189002. ret = (*(png_ptr->read_user_chunk_fn))
  189003. (png_ptr, &png_ptr->unknown_chunk);
  189004. if (ret < 0)
  189005. png_chunk_error(png_ptr, "error in user chunk");
  189006. if (ret == 0)
  189007. {
  189008. if (!(png_ptr->chunk_name[0] & 0x20))
  189009. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189010. PNG_HANDLE_CHUNK_ALWAYS)
  189011. png_chunk_error(png_ptr, "unknown critical chunk");
  189012. png_set_unknown_chunks(png_ptr, info_ptr,
  189013. &png_ptr->unknown_chunk, 1);
  189014. }
  189015. }
  189016. #else
  189017. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189018. #endif
  189019. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189020. png_ptr->unknown_chunk.data = NULL;
  189021. }
  189022. else
  189023. #endif
  189024. skip=length;
  189025. png_push_crc_skip(png_ptr, skip);
  189026. }
  189027. void /* PRIVATE */
  189028. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189029. {
  189030. if (png_ptr->info_fn != NULL)
  189031. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189032. }
  189033. void /* PRIVATE */
  189034. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189035. {
  189036. if (png_ptr->end_fn != NULL)
  189037. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189038. }
  189039. void /* PRIVATE */
  189040. png_push_have_row(png_structp png_ptr, png_bytep row)
  189041. {
  189042. if (png_ptr->row_fn != NULL)
  189043. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189044. (int)png_ptr->pass);
  189045. }
  189046. void PNGAPI
  189047. png_progressive_combine_row (png_structp png_ptr,
  189048. png_bytep old_row, png_bytep new_row)
  189049. {
  189050. #ifdef PNG_USE_LOCAL_ARRAYS
  189051. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189052. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189053. #endif
  189054. if(png_ptr == NULL) return;
  189055. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189056. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189057. }
  189058. void PNGAPI
  189059. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189060. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189061. png_progressive_end_ptr end_fn)
  189062. {
  189063. if(png_ptr == NULL) return;
  189064. png_ptr->info_fn = info_fn;
  189065. png_ptr->row_fn = row_fn;
  189066. png_ptr->end_fn = end_fn;
  189067. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189068. }
  189069. png_voidp PNGAPI
  189070. png_get_progressive_ptr(png_structp png_ptr)
  189071. {
  189072. if(png_ptr == NULL) return (NULL);
  189073. return png_ptr->io_ptr;
  189074. }
  189075. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189076. /*** End of inlined file: pngpread.c ***/
  189077. /*** Start of inlined file: pngrio.c ***/
  189078. /* pngrio.c - functions for data input
  189079. *
  189080. * Last changed in libpng 1.2.13 November 13, 2006
  189081. * For conditions of distribution and use, see copyright notice in png.h
  189082. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189083. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189084. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189085. *
  189086. * This file provides a location for all input. Users who need
  189087. * special handling are expected to write a function that has the same
  189088. * arguments as this and performs a similar function, but that possibly
  189089. * has a different input method. Note that you shouldn't change this
  189090. * function, but rather write a replacement function and then make
  189091. * libpng use it at run time with png_set_read_fn(...).
  189092. */
  189093. #define PNG_INTERNAL
  189094. #if defined(PNG_READ_SUPPORTED)
  189095. /* Read the data from whatever input you are using. The default routine
  189096. reads from a file pointer. Note that this routine sometimes gets called
  189097. with very small lengths, so you should implement some kind of simple
  189098. buffering if you are using unbuffered reads. This should never be asked
  189099. to read more then 64K on a 16 bit machine. */
  189100. void /* PRIVATE */
  189101. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189102. {
  189103. png_debug1(4,"reading %d bytes\n", (int)length);
  189104. if (png_ptr->read_data_fn != NULL)
  189105. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189106. else
  189107. png_error(png_ptr, "Call to NULL read function");
  189108. }
  189109. #if !defined(PNG_NO_STDIO)
  189110. /* This is the function that does the actual reading of data. If you are
  189111. not reading from a standard C stream, you should create a replacement
  189112. read_data function and use it at run time with png_set_read_fn(), rather
  189113. than changing the library. */
  189114. #ifndef USE_FAR_KEYWORD
  189115. void PNGAPI
  189116. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189117. {
  189118. png_size_t check;
  189119. if(png_ptr == NULL) return;
  189120. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189121. * instead of an int, which is what fread() actually returns.
  189122. */
  189123. #if defined(_WIN32_WCE)
  189124. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189125. check = 0;
  189126. #else
  189127. check = (png_size_t)fread(data, (png_size_t)1, length,
  189128. (png_FILE_p)png_ptr->io_ptr);
  189129. #endif
  189130. if (check != length)
  189131. png_error(png_ptr, "Read Error");
  189132. }
  189133. #else
  189134. /* this is the model-independent version. Since the standard I/O library
  189135. can't handle far buffers in the medium and small models, we have to copy
  189136. the data.
  189137. */
  189138. #define NEAR_BUF_SIZE 1024
  189139. #define MIN(a,b) (a <= b ? a : b)
  189140. static void PNGAPI
  189141. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189142. {
  189143. int check;
  189144. png_byte *n_data;
  189145. png_FILE_p io_ptr;
  189146. if(png_ptr == NULL) return;
  189147. /* Check if data really is near. If so, use usual code. */
  189148. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189149. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189150. if ((png_bytep)n_data == data)
  189151. {
  189152. #if defined(_WIN32_WCE)
  189153. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189154. check = 0;
  189155. #else
  189156. check = fread(n_data, 1, length, io_ptr);
  189157. #endif
  189158. }
  189159. else
  189160. {
  189161. png_byte buf[NEAR_BUF_SIZE];
  189162. png_size_t read, remaining, err;
  189163. check = 0;
  189164. remaining = length;
  189165. do
  189166. {
  189167. read = MIN(NEAR_BUF_SIZE, remaining);
  189168. #if defined(_WIN32_WCE)
  189169. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189170. err = 0;
  189171. #else
  189172. err = fread(buf, (png_size_t)1, read, io_ptr);
  189173. #endif
  189174. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189175. if(err != read)
  189176. break;
  189177. else
  189178. check += err;
  189179. data += read;
  189180. remaining -= read;
  189181. }
  189182. while (remaining != 0);
  189183. }
  189184. if ((png_uint_32)check != (png_uint_32)length)
  189185. png_error(png_ptr, "read Error");
  189186. }
  189187. #endif
  189188. #endif
  189189. /* This function allows the application to supply a new input function
  189190. for libpng if standard C streams aren't being used.
  189191. This function takes as its arguments:
  189192. png_ptr - pointer to a png input data structure
  189193. io_ptr - pointer to user supplied structure containing info about
  189194. the input functions. May be NULL.
  189195. read_data_fn - pointer to a new input function that takes as its
  189196. arguments a pointer to a png_struct, a pointer to
  189197. a location where input data can be stored, and a 32-bit
  189198. unsigned int that is the number of bytes to be read.
  189199. To exit and output any fatal error messages the new write
  189200. function should call png_error(png_ptr, "Error msg"). */
  189201. void PNGAPI
  189202. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189203. png_rw_ptr read_data_fn)
  189204. {
  189205. if(png_ptr == NULL) return;
  189206. png_ptr->io_ptr = io_ptr;
  189207. #if !defined(PNG_NO_STDIO)
  189208. if (read_data_fn != NULL)
  189209. png_ptr->read_data_fn = read_data_fn;
  189210. else
  189211. png_ptr->read_data_fn = png_default_read_data;
  189212. #else
  189213. png_ptr->read_data_fn = read_data_fn;
  189214. #endif
  189215. /* It is an error to write to a read device */
  189216. if (png_ptr->write_data_fn != NULL)
  189217. {
  189218. png_ptr->write_data_fn = NULL;
  189219. png_warning(png_ptr,
  189220. "It's an error to set both read_data_fn and write_data_fn in the ");
  189221. png_warning(png_ptr,
  189222. "same structure. Resetting write_data_fn to NULL.");
  189223. }
  189224. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189225. png_ptr->output_flush_fn = NULL;
  189226. #endif
  189227. }
  189228. #endif /* PNG_READ_SUPPORTED */
  189229. /*** End of inlined file: pngrio.c ***/
  189230. /*** Start of inlined file: pngrtran.c ***/
  189231. /* pngrtran.c - transforms the data in a row for PNG readers
  189232. *
  189233. * Last changed in libpng 1.2.21 [October 4, 2007]
  189234. * For conditions of distribution and use, see copyright notice in png.h
  189235. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189236. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189237. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189238. *
  189239. * This file contains functions optionally called by an application
  189240. * in order to tell libpng how to handle data when reading a PNG.
  189241. * Transformations that are used in both reading and writing are
  189242. * in pngtrans.c.
  189243. */
  189244. #define PNG_INTERNAL
  189245. #if defined(PNG_READ_SUPPORTED)
  189246. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189247. void PNGAPI
  189248. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189249. {
  189250. png_debug(1, "in png_set_crc_action\n");
  189251. /* Tell libpng how we react to CRC errors in critical chunks */
  189252. if(png_ptr == NULL) return;
  189253. switch (crit_action)
  189254. {
  189255. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189256. break;
  189257. case PNG_CRC_WARN_USE: /* warn/use data */
  189258. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189259. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189260. break;
  189261. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189262. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189263. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189264. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189265. break;
  189266. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189267. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189268. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189269. case PNG_CRC_DEFAULT:
  189270. default:
  189271. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189272. break;
  189273. }
  189274. switch (ancil_action)
  189275. {
  189276. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189277. break;
  189278. case PNG_CRC_WARN_USE: /* warn/use data */
  189279. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189280. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189281. break;
  189282. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189283. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189284. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189285. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189286. break;
  189287. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189288. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189289. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189290. break;
  189291. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189292. case PNG_CRC_DEFAULT:
  189293. default:
  189294. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189295. break;
  189296. }
  189297. }
  189298. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189299. defined(PNG_FLOATING_POINT_SUPPORTED)
  189300. /* handle alpha and tRNS via a background color */
  189301. void PNGAPI
  189302. png_set_background(png_structp png_ptr,
  189303. png_color_16p background_color, int background_gamma_code,
  189304. int need_expand, double background_gamma)
  189305. {
  189306. png_debug(1, "in png_set_background\n");
  189307. if(png_ptr == NULL) return;
  189308. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189309. {
  189310. png_warning(png_ptr, "Application must supply a known background gamma");
  189311. return;
  189312. }
  189313. png_ptr->transformations |= PNG_BACKGROUND;
  189314. png_memcpy(&(png_ptr->background), background_color,
  189315. png_sizeof(png_color_16));
  189316. png_ptr->background_gamma = (float)background_gamma;
  189317. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189318. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189319. }
  189320. #endif
  189321. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189322. /* strip 16 bit depth files to 8 bit depth */
  189323. void PNGAPI
  189324. png_set_strip_16(png_structp png_ptr)
  189325. {
  189326. png_debug(1, "in png_set_strip_16\n");
  189327. if(png_ptr == NULL) return;
  189328. png_ptr->transformations |= PNG_16_TO_8;
  189329. }
  189330. #endif
  189331. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189332. void PNGAPI
  189333. png_set_strip_alpha(png_structp png_ptr)
  189334. {
  189335. png_debug(1, "in png_set_strip_alpha\n");
  189336. if(png_ptr == NULL) return;
  189337. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189338. }
  189339. #endif
  189340. #if defined(PNG_READ_DITHER_SUPPORTED)
  189341. /* Dither file to 8 bit. Supply a palette, the current number
  189342. * of elements in the palette, the maximum number of elements
  189343. * allowed, and a histogram if possible. If the current number
  189344. * of colors is greater then the maximum number, the palette will be
  189345. * modified to fit in the maximum number. "full_dither" indicates
  189346. * whether we need a dithering cube set up for RGB images, or if we
  189347. * simply are reducing the number of colors in a paletted image.
  189348. */
  189349. typedef struct png_dsort_struct
  189350. {
  189351. struct png_dsort_struct FAR * next;
  189352. png_byte left;
  189353. png_byte right;
  189354. } png_dsort;
  189355. typedef png_dsort FAR * png_dsortp;
  189356. typedef png_dsort FAR * FAR * png_dsortpp;
  189357. void PNGAPI
  189358. png_set_dither(png_structp png_ptr, png_colorp palette,
  189359. int num_palette, int maximum_colors, png_uint_16p histogram,
  189360. int full_dither)
  189361. {
  189362. png_debug(1, "in png_set_dither\n");
  189363. if(png_ptr == NULL) return;
  189364. png_ptr->transformations |= PNG_DITHER;
  189365. if (!full_dither)
  189366. {
  189367. int i;
  189368. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189369. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189370. for (i = 0; i < num_palette; i++)
  189371. png_ptr->dither_index[i] = (png_byte)i;
  189372. }
  189373. if (num_palette > maximum_colors)
  189374. {
  189375. if (histogram != NULL)
  189376. {
  189377. /* This is easy enough, just throw out the least used colors.
  189378. Perhaps not the best solution, but good enough. */
  189379. int i;
  189380. /* initialize an array to sort colors */
  189381. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189382. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189383. /* initialize the dither_sort array */
  189384. for (i = 0; i < num_palette; i++)
  189385. png_ptr->dither_sort[i] = (png_byte)i;
  189386. /* Find the least used palette entries by starting a
  189387. bubble sort, and running it until we have sorted
  189388. out enough colors. Note that we don't care about
  189389. sorting all the colors, just finding which are
  189390. least used. */
  189391. for (i = num_palette - 1; i >= maximum_colors; i--)
  189392. {
  189393. int done; /* to stop early if the list is pre-sorted */
  189394. int j;
  189395. done = 1;
  189396. for (j = 0; j < i; j++)
  189397. {
  189398. if (histogram[png_ptr->dither_sort[j]]
  189399. < histogram[png_ptr->dither_sort[j + 1]])
  189400. {
  189401. png_byte t;
  189402. t = png_ptr->dither_sort[j];
  189403. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189404. png_ptr->dither_sort[j + 1] = t;
  189405. done = 0;
  189406. }
  189407. }
  189408. if (done)
  189409. break;
  189410. }
  189411. /* swap the palette around, and set up a table, if necessary */
  189412. if (full_dither)
  189413. {
  189414. int j = num_palette;
  189415. /* put all the useful colors within the max, but don't
  189416. move the others */
  189417. for (i = 0; i < maximum_colors; i++)
  189418. {
  189419. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189420. {
  189421. do
  189422. j--;
  189423. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189424. palette[i] = palette[j];
  189425. }
  189426. }
  189427. }
  189428. else
  189429. {
  189430. int j = num_palette;
  189431. /* move all the used colors inside the max limit, and
  189432. develop a translation table */
  189433. for (i = 0; i < maximum_colors; i++)
  189434. {
  189435. /* only move the colors we need to */
  189436. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189437. {
  189438. png_color tmp_color;
  189439. do
  189440. j--;
  189441. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189442. tmp_color = palette[j];
  189443. palette[j] = palette[i];
  189444. palette[i] = tmp_color;
  189445. /* indicate where the color went */
  189446. png_ptr->dither_index[j] = (png_byte)i;
  189447. png_ptr->dither_index[i] = (png_byte)j;
  189448. }
  189449. }
  189450. /* find closest color for those colors we are not using */
  189451. for (i = 0; i < num_palette; i++)
  189452. {
  189453. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189454. {
  189455. int min_d, k, min_k, d_index;
  189456. /* find the closest color to one we threw out */
  189457. d_index = png_ptr->dither_index[i];
  189458. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189459. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189460. {
  189461. int d;
  189462. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189463. if (d < min_d)
  189464. {
  189465. min_d = d;
  189466. min_k = k;
  189467. }
  189468. }
  189469. /* point to closest color */
  189470. png_ptr->dither_index[i] = (png_byte)min_k;
  189471. }
  189472. }
  189473. }
  189474. png_free(png_ptr, png_ptr->dither_sort);
  189475. png_ptr->dither_sort=NULL;
  189476. }
  189477. else
  189478. {
  189479. /* This is much harder to do simply (and quickly). Perhaps
  189480. we need to go through a median cut routine, but those
  189481. don't always behave themselves with only a few colors
  189482. as input. So we will just find the closest two colors,
  189483. and throw out one of them (chosen somewhat randomly).
  189484. [We don't understand this at all, so if someone wants to
  189485. work on improving it, be our guest - AED, GRP]
  189486. */
  189487. int i;
  189488. int max_d;
  189489. int num_new_palette;
  189490. png_dsortp t;
  189491. png_dsortpp hash;
  189492. t=NULL;
  189493. /* initialize palette index arrays */
  189494. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189495. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189496. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189497. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189498. /* initialize the sort array */
  189499. for (i = 0; i < num_palette; i++)
  189500. {
  189501. png_ptr->index_to_palette[i] = (png_byte)i;
  189502. png_ptr->palette_to_index[i] = (png_byte)i;
  189503. }
  189504. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189505. png_sizeof (png_dsortp)));
  189506. for (i = 0; i < 769; i++)
  189507. hash[i] = NULL;
  189508. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189509. num_new_palette = num_palette;
  189510. /* initial wild guess at how far apart the farthest pixel
  189511. pair we will be eliminating will be. Larger
  189512. numbers mean more areas will be allocated, Smaller
  189513. numbers run the risk of not saving enough data, and
  189514. having to do this all over again.
  189515. I have not done extensive checking on this number.
  189516. */
  189517. max_d = 96;
  189518. while (num_new_palette > maximum_colors)
  189519. {
  189520. for (i = 0; i < num_new_palette - 1; i++)
  189521. {
  189522. int j;
  189523. for (j = i + 1; j < num_new_palette; j++)
  189524. {
  189525. int d;
  189526. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189527. if (d <= max_d)
  189528. {
  189529. t = (png_dsortp)png_malloc_warn(png_ptr,
  189530. (png_uint_32)(png_sizeof(png_dsort)));
  189531. if (t == NULL)
  189532. break;
  189533. t->next = hash[d];
  189534. t->left = (png_byte)i;
  189535. t->right = (png_byte)j;
  189536. hash[d] = t;
  189537. }
  189538. }
  189539. if (t == NULL)
  189540. break;
  189541. }
  189542. if (t != NULL)
  189543. for (i = 0; i <= max_d; i++)
  189544. {
  189545. if (hash[i] != NULL)
  189546. {
  189547. png_dsortp p;
  189548. for (p = hash[i]; p; p = p->next)
  189549. {
  189550. if ((int)png_ptr->index_to_palette[p->left]
  189551. < num_new_palette &&
  189552. (int)png_ptr->index_to_palette[p->right]
  189553. < num_new_palette)
  189554. {
  189555. int j, next_j;
  189556. if (num_new_palette & 0x01)
  189557. {
  189558. j = p->left;
  189559. next_j = p->right;
  189560. }
  189561. else
  189562. {
  189563. j = p->right;
  189564. next_j = p->left;
  189565. }
  189566. num_new_palette--;
  189567. palette[png_ptr->index_to_palette[j]]
  189568. = palette[num_new_palette];
  189569. if (!full_dither)
  189570. {
  189571. int k;
  189572. for (k = 0; k < num_palette; k++)
  189573. {
  189574. if (png_ptr->dither_index[k] ==
  189575. png_ptr->index_to_palette[j])
  189576. png_ptr->dither_index[k] =
  189577. png_ptr->index_to_palette[next_j];
  189578. if ((int)png_ptr->dither_index[k] ==
  189579. num_new_palette)
  189580. png_ptr->dither_index[k] =
  189581. png_ptr->index_to_palette[j];
  189582. }
  189583. }
  189584. png_ptr->index_to_palette[png_ptr->palette_to_index
  189585. [num_new_palette]] = png_ptr->index_to_palette[j];
  189586. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189587. = png_ptr->palette_to_index[num_new_palette];
  189588. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189589. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189590. }
  189591. if (num_new_palette <= maximum_colors)
  189592. break;
  189593. }
  189594. if (num_new_palette <= maximum_colors)
  189595. break;
  189596. }
  189597. }
  189598. for (i = 0; i < 769; i++)
  189599. {
  189600. if (hash[i] != NULL)
  189601. {
  189602. png_dsortp p = hash[i];
  189603. while (p)
  189604. {
  189605. t = p->next;
  189606. png_free(png_ptr, p);
  189607. p = t;
  189608. }
  189609. }
  189610. hash[i] = 0;
  189611. }
  189612. max_d += 96;
  189613. }
  189614. png_free(png_ptr, hash);
  189615. png_free(png_ptr, png_ptr->palette_to_index);
  189616. png_free(png_ptr, png_ptr->index_to_palette);
  189617. png_ptr->palette_to_index=NULL;
  189618. png_ptr->index_to_palette=NULL;
  189619. }
  189620. num_palette = maximum_colors;
  189621. }
  189622. if (png_ptr->palette == NULL)
  189623. {
  189624. png_ptr->palette = palette;
  189625. }
  189626. png_ptr->num_palette = (png_uint_16)num_palette;
  189627. if (full_dither)
  189628. {
  189629. int i;
  189630. png_bytep distance;
  189631. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189632. PNG_DITHER_BLUE_BITS;
  189633. int num_red = (1 << PNG_DITHER_RED_BITS);
  189634. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189635. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189636. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189637. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189638. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189639. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189640. png_sizeof (png_byte));
  189641. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189642. png_sizeof(png_byte)));
  189643. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189644. for (i = 0; i < num_palette; i++)
  189645. {
  189646. int ir, ig, ib;
  189647. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189648. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189649. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189650. for (ir = 0; ir < num_red; ir++)
  189651. {
  189652. /* int dr = abs(ir - r); */
  189653. int dr = ((ir > r) ? ir - r : r - ir);
  189654. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189655. for (ig = 0; ig < num_green; ig++)
  189656. {
  189657. /* int dg = abs(ig - g); */
  189658. int dg = ((ig > g) ? ig - g : g - ig);
  189659. int dt = dr + dg;
  189660. int dm = ((dr > dg) ? dr : dg);
  189661. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189662. for (ib = 0; ib < num_blue; ib++)
  189663. {
  189664. int d_index = index_g | ib;
  189665. /* int db = abs(ib - b); */
  189666. int db = ((ib > b) ? ib - b : b - ib);
  189667. int dmax = ((dm > db) ? dm : db);
  189668. int d = dmax + dt + db;
  189669. if (d < (int)distance[d_index])
  189670. {
  189671. distance[d_index] = (png_byte)d;
  189672. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189673. }
  189674. }
  189675. }
  189676. }
  189677. }
  189678. png_free(png_ptr, distance);
  189679. }
  189680. }
  189681. #endif
  189682. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189683. /* Transform the image from the file_gamma to the screen_gamma. We
  189684. * only do transformations on images where the file_gamma and screen_gamma
  189685. * are not close reciprocals, otherwise it slows things down slightly, and
  189686. * also needlessly introduces small errors.
  189687. *
  189688. * We will turn off gamma transformation later if no semitransparent entries
  189689. * are present in the tRNS array for palette images. We can't do it here
  189690. * because we don't necessarily have the tRNS chunk yet.
  189691. */
  189692. void PNGAPI
  189693. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189694. {
  189695. png_debug(1, "in png_set_gamma\n");
  189696. if(png_ptr == NULL) return;
  189697. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189698. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189699. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189700. png_ptr->transformations |= PNG_GAMMA;
  189701. png_ptr->gamma = (float)file_gamma;
  189702. png_ptr->screen_gamma = (float)scrn_gamma;
  189703. }
  189704. #endif
  189705. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189706. /* Expand paletted images to RGB, expand grayscale images of
  189707. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189708. * to alpha channels.
  189709. */
  189710. void PNGAPI
  189711. png_set_expand(png_structp png_ptr)
  189712. {
  189713. png_debug(1, "in png_set_expand\n");
  189714. if(png_ptr == NULL) return;
  189715. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189716. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189717. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189718. #endif
  189719. }
  189720. /* GRR 19990627: the following three functions currently are identical
  189721. * to png_set_expand(). However, it is entirely reasonable that someone
  189722. * might wish to expand an indexed image to RGB but *not* expand a single,
  189723. * fully transparent palette entry to a full alpha channel--perhaps instead
  189724. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189725. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189726. * IOW, a future version of the library may make the transformations flag
  189727. * a bit more fine-grained, with separate bits for each of these three
  189728. * functions.
  189729. *
  189730. * More to the point, these functions make it obvious what libpng will be
  189731. * doing, whereas "expand" can (and does) mean any number of things.
  189732. *
  189733. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189734. * to expand only the sample depth but not to expand the tRNS to alpha.
  189735. */
  189736. /* Expand paletted images to RGB. */
  189737. void PNGAPI
  189738. png_set_palette_to_rgb(png_structp png_ptr)
  189739. {
  189740. png_debug(1, "in png_set_palette_to_rgb\n");
  189741. if(png_ptr == NULL) return;
  189742. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189743. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189744. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189745. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189746. #endif
  189747. }
  189748. #if !defined(PNG_1_0_X)
  189749. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189750. void PNGAPI
  189751. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189752. {
  189753. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189754. if(png_ptr == NULL) return;
  189755. png_ptr->transformations |= PNG_EXPAND;
  189756. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189757. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189758. #endif
  189759. }
  189760. #endif
  189761. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189762. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189763. /* Deprecated as of libpng-1.2.9 */
  189764. void PNGAPI
  189765. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189766. {
  189767. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189768. if(png_ptr == NULL) return;
  189769. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189770. }
  189771. #endif
  189772. /* Expand tRNS chunks to alpha channels. */
  189773. void PNGAPI
  189774. png_set_tRNS_to_alpha(png_structp png_ptr)
  189775. {
  189776. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189777. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189778. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189779. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189780. #endif
  189781. }
  189782. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189783. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189784. void PNGAPI
  189785. png_set_gray_to_rgb(png_structp png_ptr)
  189786. {
  189787. png_debug(1, "in png_set_gray_to_rgb\n");
  189788. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189789. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189790. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189791. #endif
  189792. }
  189793. #endif
  189794. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189795. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189796. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189797. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189798. */
  189799. void PNGAPI
  189800. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189801. double green)
  189802. {
  189803. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189804. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189805. if(png_ptr == NULL) return;
  189806. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189807. }
  189808. #endif
  189809. void PNGAPI
  189810. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189811. png_fixed_point red, png_fixed_point green)
  189812. {
  189813. png_debug(1, "in png_set_rgb_to_gray\n");
  189814. if(png_ptr == NULL) return;
  189815. switch(error_action)
  189816. {
  189817. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189818. break;
  189819. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  189820. break;
  189821. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  189822. }
  189823. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189824. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189825. png_ptr->transformations |= PNG_EXPAND;
  189826. #else
  189827. {
  189828. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  189829. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  189830. }
  189831. #endif
  189832. {
  189833. png_uint_16 red_int, green_int;
  189834. if(red < 0 || green < 0)
  189835. {
  189836. red_int = 6968; /* .212671 * 32768 + .5 */
  189837. green_int = 23434; /* .715160 * 32768 + .5 */
  189838. }
  189839. else if(red + green < 100000L)
  189840. {
  189841. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  189842. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  189843. }
  189844. else
  189845. {
  189846. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  189847. red_int = 6968;
  189848. green_int = 23434;
  189849. }
  189850. png_ptr->rgb_to_gray_red_coeff = red_int;
  189851. png_ptr->rgb_to_gray_green_coeff = green_int;
  189852. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  189853. }
  189854. }
  189855. #endif
  189856. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  189857. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  189858. defined(PNG_LEGACY_SUPPORTED)
  189859. void PNGAPI
  189860. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  189861. read_user_transform_fn)
  189862. {
  189863. png_debug(1, "in png_set_read_user_transform_fn\n");
  189864. if(png_ptr == NULL) return;
  189865. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  189866. png_ptr->transformations |= PNG_USER_TRANSFORM;
  189867. png_ptr->read_user_transform_fn = read_user_transform_fn;
  189868. #endif
  189869. #ifdef PNG_LEGACY_SUPPORTED
  189870. if(read_user_transform_fn)
  189871. png_warning(png_ptr,
  189872. "This version of libpng does not support user transforms");
  189873. #endif
  189874. }
  189875. #endif
  189876. /* Initialize everything needed for the read. This includes modifying
  189877. * the palette.
  189878. */
  189879. void /* PRIVATE */
  189880. png_init_read_transformations(png_structp png_ptr)
  189881. {
  189882. png_debug(1, "in png_init_read_transformations\n");
  189883. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189884. if(png_ptr != NULL)
  189885. #endif
  189886. {
  189887. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  189888. || defined(PNG_READ_GAMMA_SUPPORTED)
  189889. int color_type = png_ptr->color_type;
  189890. #endif
  189891. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  189892. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189893. /* Detect gray background and attempt to enable optimization
  189894. * for gray --> RGB case */
  189895. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  189896. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  189897. * background color might actually be gray yet not be flagged as such.
  189898. * This is not a problem for the current code, which uses
  189899. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  189900. * png_do_gray_to_rgb() transformation.
  189901. */
  189902. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189903. !(color_type & PNG_COLOR_MASK_COLOR))
  189904. {
  189905. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189906. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189907. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189908. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  189909. png_ptr->background.red == png_ptr->background.green &&
  189910. png_ptr->background.red == png_ptr->background.blue)
  189911. {
  189912. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189913. png_ptr->background.gray = png_ptr->background.red;
  189914. }
  189915. #endif
  189916. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189917. (png_ptr->transformations & PNG_EXPAND))
  189918. {
  189919. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  189920. {
  189921. /* expand background and tRNS chunks */
  189922. switch (png_ptr->bit_depth)
  189923. {
  189924. case 1:
  189925. png_ptr->background.gray *= (png_uint_16)0xff;
  189926. png_ptr->background.red = png_ptr->background.green
  189927. = png_ptr->background.blue = png_ptr->background.gray;
  189928. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189929. {
  189930. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  189931. png_ptr->trans_values.red = png_ptr->trans_values.green
  189932. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189933. }
  189934. break;
  189935. case 2:
  189936. png_ptr->background.gray *= (png_uint_16)0x55;
  189937. png_ptr->background.red = png_ptr->background.green
  189938. = png_ptr->background.blue = png_ptr->background.gray;
  189939. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189940. {
  189941. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  189942. png_ptr->trans_values.red = png_ptr->trans_values.green
  189943. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189944. }
  189945. break;
  189946. case 4:
  189947. png_ptr->background.gray *= (png_uint_16)0x11;
  189948. png_ptr->background.red = png_ptr->background.green
  189949. = png_ptr->background.blue = png_ptr->background.gray;
  189950. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189951. {
  189952. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  189953. png_ptr->trans_values.red = png_ptr->trans_values.green
  189954. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189955. }
  189956. break;
  189957. case 8:
  189958. case 16:
  189959. png_ptr->background.red = png_ptr->background.green
  189960. = png_ptr->background.blue = png_ptr->background.gray;
  189961. break;
  189962. }
  189963. }
  189964. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  189965. {
  189966. png_ptr->background.red =
  189967. png_ptr->palette[png_ptr->background.index].red;
  189968. png_ptr->background.green =
  189969. png_ptr->palette[png_ptr->background.index].green;
  189970. png_ptr->background.blue =
  189971. png_ptr->palette[png_ptr->background.index].blue;
  189972. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  189973. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  189974. {
  189975. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189976. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189977. #endif
  189978. {
  189979. /* invert the alpha channel (in tRNS) unless the pixels are
  189980. going to be expanded, in which case leave it for later */
  189981. int i,istop;
  189982. istop=(int)png_ptr->num_trans;
  189983. for (i=0; i<istop; i++)
  189984. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  189985. }
  189986. }
  189987. #endif
  189988. }
  189989. }
  189990. #endif
  189991. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189992. png_ptr->background_1 = png_ptr->background;
  189993. #endif
  189994. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189995. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  189996. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  189997. < PNG_GAMMA_THRESHOLD))
  189998. {
  189999. int i,k;
  190000. k=0;
  190001. for (i=0; i<png_ptr->num_trans; i++)
  190002. {
  190003. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190004. k=1; /* partial transparency is present */
  190005. }
  190006. if (k == 0)
  190007. png_ptr->transformations &= (~PNG_GAMMA);
  190008. }
  190009. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190010. png_ptr->gamma != 0.0)
  190011. {
  190012. png_build_gamma_table(png_ptr);
  190013. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190014. if (png_ptr->transformations & PNG_BACKGROUND)
  190015. {
  190016. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190017. {
  190018. /* could skip if no transparency and
  190019. */
  190020. png_color back, back_1;
  190021. png_colorp palette = png_ptr->palette;
  190022. int num_palette = png_ptr->num_palette;
  190023. int i;
  190024. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190025. {
  190026. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190027. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190028. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190029. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190030. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190031. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190032. }
  190033. else
  190034. {
  190035. double g, gs;
  190036. switch (png_ptr->background_gamma_type)
  190037. {
  190038. case PNG_BACKGROUND_GAMMA_SCREEN:
  190039. g = (png_ptr->screen_gamma);
  190040. gs = 1.0;
  190041. break;
  190042. case PNG_BACKGROUND_GAMMA_FILE:
  190043. g = 1.0 / (png_ptr->gamma);
  190044. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190045. break;
  190046. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190047. g = 1.0 / (png_ptr->background_gamma);
  190048. gs = 1.0 / (png_ptr->background_gamma *
  190049. png_ptr->screen_gamma);
  190050. break;
  190051. default:
  190052. g = 1.0; /* back_1 */
  190053. gs = 1.0; /* back */
  190054. }
  190055. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190056. {
  190057. back.red = (png_byte)png_ptr->background.red;
  190058. back.green = (png_byte)png_ptr->background.green;
  190059. back.blue = (png_byte)png_ptr->background.blue;
  190060. }
  190061. else
  190062. {
  190063. back.red = (png_byte)(pow(
  190064. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190065. back.green = (png_byte)(pow(
  190066. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190067. back.blue = (png_byte)(pow(
  190068. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190069. }
  190070. back_1.red = (png_byte)(pow(
  190071. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190072. back_1.green = (png_byte)(pow(
  190073. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190074. back_1.blue = (png_byte)(pow(
  190075. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190076. }
  190077. for (i = 0; i < num_palette; i++)
  190078. {
  190079. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190080. {
  190081. if (png_ptr->trans[i] == 0)
  190082. {
  190083. palette[i] = back;
  190084. }
  190085. else /* if (png_ptr->trans[i] != 0xff) */
  190086. {
  190087. png_byte v, w;
  190088. v = png_ptr->gamma_to_1[palette[i].red];
  190089. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190090. palette[i].red = png_ptr->gamma_from_1[w];
  190091. v = png_ptr->gamma_to_1[palette[i].green];
  190092. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190093. palette[i].green = png_ptr->gamma_from_1[w];
  190094. v = png_ptr->gamma_to_1[palette[i].blue];
  190095. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190096. palette[i].blue = png_ptr->gamma_from_1[w];
  190097. }
  190098. }
  190099. else
  190100. {
  190101. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190102. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190103. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190104. }
  190105. }
  190106. }
  190107. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190108. else
  190109. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190110. {
  190111. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190112. double g = 1.0;
  190113. double gs = 1.0;
  190114. switch (png_ptr->background_gamma_type)
  190115. {
  190116. case PNG_BACKGROUND_GAMMA_SCREEN:
  190117. g = (png_ptr->screen_gamma);
  190118. gs = 1.0;
  190119. break;
  190120. case PNG_BACKGROUND_GAMMA_FILE:
  190121. g = 1.0 / (png_ptr->gamma);
  190122. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190123. break;
  190124. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190125. g = 1.0 / (png_ptr->background_gamma);
  190126. gs = 1.0 / (png_ptr->background_gamma *
  190127. png_ptr->screen_gamma);
  190128. break;
  190129. }
  190130. png_ptr->background_1.gray = (png_uint_16)(pow(
  190131. (double)png_ptr->background.gray / m, g) * m + .5);
  190132. png_ptr->background.gray = (png_uint_16)(pow(
  190133. (double)png_ptr->background.gray / m, gs) * m + .5);
  190134. if ((png_ptr->background.red != png_ptr->background.green) ||
  190135. (png_ptr->background.red != png_ptr->background.blue) ||
  190136. (png_ptr->background.red != png_ptr->background.gray))
  190137. {
  190138. /* RGB or RGBA with color background */
  190139. png_ptr->background_1.red = (png_uint_16)(pow(
  190140. (double)png_ptr->background.red / m, g) * m + .5);
  190141. png_ptr->background_1.green = (png_uint_16)(pow(
  190142. (double)png_ptr->background.green / m, g) * m + .5);
  190143. png_ptr->background_1.blue = (png_uint_16)(pow(
  190144. (double)png_ptr->background.blue / m, g) * m + .5);
  190145. png_ptr->background.red = (png_uint_16)(pow(
  190146. (double)png_ptr->background.red / m, gs) * m + .5);
  190147. png_ptr->background.green = (png_uint_16)(pow(
  190148. (double)png_ptr->background.green / m, gs) * m + .5);
  190149. png_ptr->background.blue = (png_uint_16)(pow(
  190150. (double)png_ptr->background.blue / m, gs) * m + .5);
  190151. }
  190152. else
  190153. {
  190154. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190155. png_ptr->background_1.red = png_ptr->background_1.green
  190156. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190157. png_ptr->background.red = png_ptr->background.green
  190158. = png_ptr->background.blue = png_ptr->background.gray;
  190159. }
  190160. }
  190161. }
  190162. else
  190163. /* transformation does not include PNG_BACKGROUND */
  190164. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190165. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190166. {
  190167. png_colorp palette = png_ptr->palette;
  190168. int num_palette = png_ptr->num_palette;
  190169. int i;
  190170. for (i = 0; i < num_palette; i++)
  190171. {
  190172. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190173. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190174. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190175. }
  190176. }
  190177. }
  190178. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190179. else
  190180. #endif
  190181. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190182. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190183. /* No GAMMA transformation */
  190184. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190185. (color_type == PNG_COLOR_TYPE_PALETTE))
  190186. {
  190187. int i;
  190188. int istop = (int)png_ptr->num_trans;
  190189. png_color back;
  190190. png_colorp palette = png_ptr->palette;
  190191. back.red = (png_byte)png_ptr->background.red;
  190192. back.green = (png_byte)png_ptr->background.green;
  190193. back.blue = (png_byte)png_ptr->background.blue;
  190194. for (i = 0; i < istop; i++)
  190195. {
  190196. if (png_ptr->trans[i] == 0)
  190197. {
  190198. palette[i] = back;
  190199. }
  190200. else if (png_ptr->trans[i] != 0xff)
  190201. {
  190202. /* The png_composite() macro is defined in png.h */
  190203. png_composite(palette[i].red, palette[i].red,
  190204. png_ptr->trans[i], back.red);
  190205. png_composite(palette[i].green, palette[i].green,
  190206. png_ptr->trans[i], back.green);
  190207. png_composite(palette[i].blue, palette[i].blue,
  190208. png_ptr->trans[i], back.blue);
  190209. }
  190210. }
  190211. }
  190212. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190213. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190214. if ((png_ptr->transformations & PNG_SHIFT) &&
  190215. (color_type == PNG_COLOR_TYPE_PALETTE))
  190216. {
  190217. png_uint_16 i;
  190218. png_uint_16 istop = png_ptr->num_palette;
  190219. int sr = 8 - png_ptr->sig_bit.red;
  190220. int sg = 8 - png_ptr->sig_bit.green;
  190221. int sb = 8 - png_ptr->sig_bit.blue;
  190222. if (sr < 0 || sr > 8)
  190223. sr = 0;
  190224. if (sg < 0 || sg > 8)
  190225. sg = 0;
  190226. if (sb < 0 || sb > 8)
  190227. sb = 0;
  190228. for (i = 0; i < istop; i++)
  190229. {
  190230. png_ptr->palette[i].red >>= sr;
  190231. png_ptr->palette[i].green >>= sg;
  190232. png_ptr->palette[i].blue >>= sb;
  190233. }
  190234. }
  190235. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190236. }
  190237. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190238. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190239. if(png_ptr)
  190240. return;
  190241. #endif
  190242. }
  190243. /* Modify the info structure to reflect the transformations. The
  190244. * info should be updated so a PNG file could be written with it,
  190245. * assuming the transformations result in valid PNG data.
  190246. */
  190247. void /* PRIVATE */
  190248. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190249. {
  190250. png_debug(1, "in png_read_transform_info\n");
  190251. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190252. if (png_ptr->transformations & PNG_EXPAND)
  190253. {
  190254. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190255. {
  190256. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190257. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190258. else
  190259. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190260. info_ptr->bit_depth = 8;
  190261. info_ptr->num_trans = 0;
  190262. }
  190263. else
  190264. {
  190265. if (png_ptr->num_trans)
  190266. {
  190267. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190268. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190269. else
  190270. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190271. }
  190272. if (info_ptr->bit_depth < 8)
  190273. info_ptr->bit_depth = 8;
  190274. info_ptr->num_trans = 0;
  190275. }
  190276. }
  190277. #endif
  190278. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190279. if (png_ptr->transformations & PNG_BACKGROUND)
  190280. {
  190281. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190282. info_ptr->num_trans = 0;
  190283. info_ptr->background = png_ptr->background;
  190284. }
  190285. #endif
  190286. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190287. if (png_ptr->transformations & PNG_GAMMA)
  190288. {
  190289. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190290. info_ptr->gamma = png_ptr->gamma;
  190291. #endif
  190292. #ifdef PNG_FIXED_POINT_SUPPORTED
  190293. info_ptr->int_gamma = png_ptr->int_gamma;
  190294. #endif
  190295. }
  190296. #endif
  190297. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190298. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190299. info_ptr->bit_depth = 8;
  190300. #endif
  190301. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190302. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190303. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190304. #endif
  190305. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190306. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190307. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190308. #endif
  190309. #if defined(PNG_READ_DITHER_SUPPORTED)
  190310. if (png_ptr->transformations & PNG_DITHER)
  190311. {
  190312. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190313. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190314. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190315. {
  190316. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190317. }
  190318. }
  190319. #endif
  190320. #if defined(PNG_READ_PACK_SUPPORTED)
  190321. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190322. info_ptr->bit_depth = 8;
  190323. #endif
  190324. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190325. info_ptr->channels = 1;
  190326. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190327. info_ptr->channels = 3;
  190328. else
  190329. info_ptr->channels = 1;
  190330. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190331. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190332. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190333. #endif
  190334. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190335. info_ptr->channels++;
  190336. #if defined(PNG_READ_FILLER_SUPPORTED)
  190337. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190338. if ((png_ptr->transformations & PNG_FILLER) &&
  190339. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190340. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190341. {
  190342. info_ptr->channels++;
  190343. /* if adding a true alpha channel not just filler */
  190344. #if !defined(PNG_1_0_X)
  190345. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190346. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190347. #endif
  190348. }
  190349. #endif
  190350. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190351. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190352. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190353. {
  190354. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190355. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190356. if(info_ptr->channels < png_ptr->user_transform_channels)
  190357. info_ptr->channels = png_ptr->user_transform_channels;
  190358. }
  190359. #endif
  190360. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190361. info_ptr->bit_depth);
  190362. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190363. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190364. if(png_ptr)
  190365. return;
  190366. #endif
  190367. }
  190368. /* Transform the row. The order of transformations is significant,
  190369. * and is very touchy. If you add a transformation, take care to
  190370. * decide how it fits in with the other transformations here.
  190371. */
  190372. void /* PRIVATE */
  190373. png_do_read_transformations(png_structp png_ptr)
  190374. {
  190375. png_debug(1, "in png_do_read_transformations\n");
  190376. if (png_ptr->row_buf == NULL)
  190377. {
  190378. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190379. char msg[50];
  190380. png_snprintf2(msg, 50,
  190381. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190382. png_ptr->pass);
  190383. png_error(png_ptr, msg);
  190384. #else
  190385. png_error(png_ptr, "NULL row buffer");
  190386. #endif
  190387. }
  190388. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190389. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190390. /* Application has failed to call either png_read_start_image()
  190391. * or png_read_update_info() after setting transforms that expand
  190392. * pixels. This check added to libpng-1.2.19 */
  190393. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190394. png_error(png_ptr, "Uninitialized row");
  190395. #else
  190396. png_warning(png_ptr, "Uninitialized row");
  190397. #endif
  190398. #endif
  190399. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190400. if (png_ptr->transformations & PNG_EXPAND)
  190401. {
  190402. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190403. {
  190404. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190405. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190406. }
  190407. else
  190408. {
  190409. if (png_ptr->num_trans &&
  190410. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190411. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190412. &(png_ptr->trans_values));
  190413. else
  190414. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190415. NULL);
  190416. }
  190417. }
  190418. #endif
  190419. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190420. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190421. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190422. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190423. #endif
  190424. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190425. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190426. {
  190427. int rgb_error =
  190428. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190429. if(rgb_error)
  190430. {
  190431. png_ptr->rgb_to_gray_status=1;
  190432. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190433. PNG_RGB_TO_GRAY_WARN)
  190434. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190435. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190436. PNG_RGB_TO_GRAY_ERR)
  190437. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190438. }
  190439. }
  190440. #endif
  190441. /*
  190442. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190443. In most cases, the "simple transparency" should be done prior to doing
  190444. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190445. pixel is transparent. You would also need to make sure that the
  190446. transparency information is upgraded to RGB.
  190447. To summarize, the current flow is:
  190448. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190449. with background "in place" if transparent,
  190450. convert to RGB if necessary
  190451. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190452. convert to RGB if necessary
  190453. To support RGB backgrounds for gray images we need:
  190454. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190455. 3 or 6 bytes and composite with background
  190456. "in place" if transparent (3x compare/pixel
  190457. compared to doing composite with gray bkgrnd)
  190458. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190459. remove alpha bytes (3x float operations/pixel
  190460. compared with composite on gray background)
  190461. Greg's change will do this. The reason it wasn't done before is for
  190462. performance, as this increases the per-pixel operations. If we would check
  190463. in advance if the background was gray or RGB, and position the gray-to-RGB
  190464. transform appropriately, then it would save a lot of work/time.
  190465. */
  190466. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190467. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190468. * for performance reasons */
  190469. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190470. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190471. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190472. #endif
  190473. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190474. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190475. ((png_ptr->num_trans != 0 ) ||
  190476. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190477. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190478. &(png_ptr->trans_values), &(png_ptr->background)
  190479. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190480. , &(png_ptr->background_1),
  190481. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190482. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190483. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190484. png_ptr->gamma_shift
  190485. #endif
  190486. );
  190487. #endif
  190488. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190489. if ((png_ptr->transformations & PNG_GAMMA) &&
  190490. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190491. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190492. ((png_ptr->num_trans != 0) ||
  190493. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190494. #endif
  190495. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190496. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190497. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190498. png_ptr->gamma_shift);
  190499. #endif
  190500. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190501. if (png_ptr->transformations & PNG_16_TO_8)
  190502. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190503. #endif
  190504. #if defined(PNG_READ_DITHER_SUPPORTED)
  190505. if (png_ptr->transformations & PNG_DITHER)
  190506. {
  190507. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190508. png_ptr->palette_lookup, png_ptr->dither_index);
  190509. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190510. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190511. }
  190512. #endif
  190513. #if defined(PNG_READ_INVERT_SUPPORTED)
  190514. if (png_ptr->transformations & PNG_INVERT_MONO)
  190515. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190516. #endif
  190517. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190518. if (png_ptr->transformations & PNG_SHIFT)
  190519. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190520. &(png_ptr->shift));
  190521. #endif
  190522. #if defined(PNG_READ_PACK_SUPPORTED)
  190523. if (png_ptr->transformations & PNG_PACK)
  190524. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190525. #endif
  190526. #if defined(PNG_READ_BGR_SUPPORTED)
  190527. if (png_ptr->transformations & PNG_BGR)
  190528. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190529. #endif
  190530. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190531. if (png_ptr->transformations & PNG_PACKSWAP)
  190532. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190533. #endif
  190534. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190535. /* if gray -> RGB, do so now only if we did not do so above */
  190536. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190537. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190538. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190539. #endif
  190540. #if defined(PNG_READ_FILLER_SUPPORTED)
  190541. if (png_ptr->transformations & PNG_FILLER)
  190542. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190543. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190544. #endif
  190545. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190546. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190547. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190548. #endif
  190549. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190550. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190551. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190552. #endif
  190553. #if defined(PNG_READ_SWAP_SUPPORTED)
  190554. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190555. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190556. #endif
  190557. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190558. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190559. {
  190560. if(png_ptr->read_user_transform_fn != NULL)
  190561. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190562. (png_ptr, /* png_ptr */
  190563. &(png_ptr->row_info), /* row_info: */
  190564. /* png_uint_32 width; width of row */
  190565. /* png_uint_32 rowbytes; number of bytes in row */
  190566. /* png_byte color_type; color type of pixels */
  190567. /* png_byte bit_depth; bit depth of samples */
  190568. /* png_byte channels; number of channels (1-4) */
  190569. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190570. png_ptr->row_buf + 1); /* start of pixel data for row */
  190571. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190572. if(png_ptr->user_transform_depth)
  190573. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190574. if(png_ptr->user_transform_channels)
  190575. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190576. #endif
  190577. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190578. png_ptr->row_info.channels);
  190579. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190580. png_ptr->row_info.width);
  190581. }
  190582. #endif
  190583. }
  190584. #if defined(PNG_READ_PACK_SUPPORTED)
  190585. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190586. * without changing the actual values. Thus, if you had a row with
  190587. * a bit depth of 1, you would end up with bytes that only contained
  190588. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190589. * png_do_shift() after this.
  190590. */
  190591. void /* PRIVATE */
  190592. png_do_unpack(png_row_infop row_info, png_bytep row)
  190593. {
  190594. png_debug(1, "in png_do_unpack\n");
  190595. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190596. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190597. #else
  190598. if (row_info->bit_depth < 8)
  190599. #endif
  190600. {
  190601. png_uint_32 i;
  190602. png_uint_32 row_width=row_info->width;
  190603. switch (row_info->bit_depth)
  190604. {
  190605. case 1:
  190606. {
  190607. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190608. png_bytep dp = row + (png_size_t)row_width - 1;
  190609. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190610. for (i = 0; i < row_width; i++)
  190611. {
  190612. *dp = (png_byte)((*sp >> shift) & 0x01);
  190613. if (shift == 7)
  190614. {
  190615. shift = 0;
  190616. sp--;
  190617. }
  190618. else
  190619. shift++;
  190620. dp--;
  190621. }
  190622. break;
  190623. }
  190624. case 2:
  190625. {
  190626. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190627. png_bytep dp = row + (png_size_t)row_width - 1;
  190628. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190629. for (i = 0; i < row_width; i++)
  190630. {
  190631. *dp = (png_byte)((*sp >> shift) & 0x03);
  190632. if (shift == 6)
  190633. {
  190634. shift = 0;
  190635. sp--;
  190636. }
  190637. else
  190638. shift += 2;
  190639. dp--;
  190640. }
  190641. break;
  190642. }
  190643. case 4:
  190644. {
  190645. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190646. png_bytep dp = row + (png_size_t)row_width - 1;
  190647. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190648. for (i = 0; i < row_width; i++)
  190649. {
  190650. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190651. if (shift == 4)
  190652. {
  190653. shift = 0;
  190654. sp--;
  190655. }
  190656. else
  190657. shift = 4;
  190658. dp--;
  190659. }
  190660. break;
  190661. }
  190662. }
  190663. row_info->bit_depth = 8;
  190664. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190665. row_info->rowbytes = row_width * row_info->channels;
  190666. }
  190667. }
  190668. #endif
  190669. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190670. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190671. * pixels back to their significant bits values. Thus, if you have
  190672. * a row of bit depth 8, but only 5 are significant, this will shift
  190673. * the values back to 0 through 31.
  190674. */
  190675. void /* PRIVATE */
  190676. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190677. {
  190678. png_debug(1, "in png_do_unshift\n");
  190679. if (
  190680. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190681. row != NULL && row_info != NULL && sig_bits != NULL &&
  190682. #endif
  190683. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190684. {
  190685. int shift[4];
  190686. int channels = 0;
  190687. int c;
  190688. png_uint_16 value = 0;
  190689. png_uint_32 row_width = row_info->width;
  190690. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190691. {
  190692. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190693. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190694. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190695. }
  190696. else
  190697. {
  190698. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190699. }
  190700. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190701. {
  190702. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190703. }
  190704. for (c = 0; c < channels; c++)
  190705. {
  190706. if (shift[c] <= 0)
  190707. shift[c] = 0;
  190708. else
  190709. value = 1;
  190710. }
  190711. if (!value)
  190712. return;
  190713. switch (row_info->bit_depth)
  190714. {
  190715. case 2:
  190716. {
  190717. png_bytep bp;
  190718. png_uint_32 i;
  190719. png_uint_32 istop = row_info->rowbytes;
  190720. for (bp = row, i = 0; i < istop; i++)
  190721. {
  190722. *bp >>= 1;
  190723. *bp++ &= 0x55;
  190724. }
  190725. break;
  190726. }
  190727. case 4:
  190728. {
  190729. png_bytep bp = row;
  190730. png_uint_32 i;
  190731. png_uint_32 istop = row_info->rowbytes;
  190732. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190733. (png_byte)((int)0xf >> shift[0]));
  190734. for (i = 0; i < istop; i++)
  190735. {
  190736. *bp >>= shift[0];
  190737. *bp++ &= mask;
  190738. }
  190739. break;
  190740. }
  190741. case 8:
  190742. {
  190743. png_bytep bp = row;
  190744. png_uint_32 i;
  190745. png_uint_32 istop = row_width * channels;
  190746. for (i = 0; i < istop; i++)
  190747. {
  190748. *bp++ >>= shift[i%channels];
  190749. }
  190750. break;
  190751. }
  190752. case 16:
  190753. {
  190754. png_bytep bp = row;
  190755. png_uint_32 i;
  190756. png_uint_32 istop = channels * row_width;
  190757. for (i = 0; i < istop; i++)
  190758. {
  190759. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190760. value >>= shift[i%channels];
  190761. *bp++ = (png_byte)(value >> 8);
  190762. *bp++ = (png_byte)(value & 0xff);
  190763. }
  190764. break;
  190765. }
  190766. }
  190767. }
  190768. }
  190769. #endif
  190770. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190771. /* chop rows of bit depth 16 down to 8 */
  190772. void /* PRIVATE */
  190773. png_do_chop(png_row_infop row_info, png_bytep row)
  190774. {
  190775. png_debug(1, "in png_do_chop\n");
  190776. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190777. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190778. #else
  190779. if (row_info->bit_depth == 16)
  190780. #endif
  190781. {
  190782. png_bytep sp = row;
  190783. png_bytep dp = row;
  190784. png_uint_32 i;
  190785. png_uint_32 istop = row_info->width * row_info->channels;
  190786. for (i = 0; i<istop; i++, sp += 2, dp++)
  190787. {
  190788. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190789. /* This does a more accurate scaling of the 16-bit color
  190790. * value, rather than a simple low-byte truncation.
  190791. *
  190792. * What the ideal calculation should be:
  190793. * *dp = (((((png_uint_32)(*sp) << 8) |
  190794. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190795. *
  190796. * GRR: no, I think this is what it really should be:
  190797. * *dp = (((((png_uint_32)(*sp) << 8) |
  190798. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190799. *
  190800. * GRR: here's the exact calculation with shifts:
  190801. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190802. * *dp = (temp - (temp >> 8)) >> 8;
  190803. *
  190804. * Approximate calculation with shift/add instead of multiply/divide:
  190805. * *dp = ((((png_uint_32)(*sp) << 8) |
  190806. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190807. *
  190808. * What we actually do to avoid extra shifting and conversion:
  190809. */
  190810. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190811. #else
  190812. /* Simply discard the low order byte */
  190813. *dp = *sp;
  190814. #endif
  190815. }
  190816. row_info->bit_depth = 8;
  190817. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190818. row_info->rowbytes = row_info->width * row_info->channels;
  190819. }
  190820. }
  190821. #endif
  190822. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190823. void /* PRIVATE */
  190824. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  190825. {
  190826. png_debug(1, "in png_do_read_swap_alpha\n");
  190827. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190828. if (row != NULL && row_info != NULL)
  190829. #endif
  190830. {
  190831. png_uint_32 row_width = row_info->width;
  190832. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190833. {
  190834. /* This converts from RGBA to ARGB */
  190835. if (row_info->bit_depth == 8)
  190836. {
  190837. png_bytep sp = row + row_info->rowbytes;
  190838. png_bytep dp = sp;
  190839. png_byte save;
  190840. png_uint_32 i;
  190841. for (i = 0; i < row_width; i++)
  190842. {
  190843. save = *(--sp);
  190844. *(--dp) = *(--sp);
  190845. *(--dp) = *(--sp);
  190846. *(--dp) = *(--sp);
  190847. *(--dp) = save;
  190848. }
  190849. }
  190850. /* This converts from RRGGBBAA to AARRGGBB */
  190851. else
  190852. {
  190853. png_bytep sp = row + row_info->rowbytes;
  190854. png_bytep dp = sp;
  190855. png_byte save[2];
  190856. png_uint_32 i;
  190857. for (i = 0; i < row_width; i++)
  190858. {
  190859. save[0] = *(--sp);
  190860. save[1] = *(--sp);
  190861. *(--dp) = *(--sp);
  190862. *(--dp) = *(--sp);
  190863. *(--dp) = *(--sp);
  190864. *(--dp) = *(--sp);
  190865. *(--dp) = *(--sp);
  190866. *(--dp) = *(--sp);
  190867. *(--dp) = save[0];
  190868. *(--dp) = save[1];
  190869. }
  190870. }
  190871. }
  190872. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190873. {
  190874. /* This converts from GA to AG */
  190875. if (row_info->bit_depth == 8)
  190876. {
  190877. png_bytep sp = row + row_info->rowbytes;
  190878. png_bytep dp = sp;
  190879. png_byte save;
  190880. png_uint_32 i;
  190881. for (i = 0; i < row_width; i++)
  190882. {
  190883. save = *(--sp);
  190884. *(--dp) = *(--sp);
  190885. *(--dp) = save;
  190886. }
  190887. }
  190888. /* This converts from GGAA to AAGG */
  190889. else
  190890. {
  190891. png_bytep sp = row + row_info->rowbytes;
  190892. png_bytep dp = sp;
  190893. png_byte save[2];
  190894. png_uint_32 i;
  190895. for (i = 0; i < row_width; i++)
  190896. {
  190897. save[0] = *(--sp);
  190898. save[1] = *(--sp);
  190899. *(--dp) = *(--sp);
  190900. *(--dp) = *(--sp);
  190901. *(--dp) = save[0];
  190902. *(--dp) = save[1];
  190903. }
  190904. }
  190905. }
  190906. }
  190907. }
  190908. #endif
  190909. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190910. void /* PRIVATE */
  190911. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  190912. {
  190913. png_debug(1, "in png_do_read_invert_alpha\n");
  190914. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190915. if (row != NULL && row_info != NULL)
  190916. #endif
  190917. {
  190918. png_uint_32 row_width = row_info->width;
  190919. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190920. {
  190921. /* This inverts the alpha channel in RGBA */
  190922. if (row_info->bit_depth == 8)
  190923. {
  190924. png_bytep sp = row + row_info->rowbytes;
  190925. png_bytep dp = sp;
  190926. png_uint_32 i;
  190927. for (i = 0; i < row_width; i++)
  190928. {
  190929. *(--dp) = (png_byte)(255 - *(--sp));
  190930. /* This does nothing:
  190931. *(--dp) = *(--sp);
  190932. *(--dp) = *(--sp);
  190933. *(--dp) = *(--sp);
  190934. We can replace it with:
  190935. */
  190936. sp-=3;
  190937. dp=sp;
  190938. }
  190939. }
  190940. /* This inverts the alpha channel in RRGGBBAA */
  190941. else
  190942. {
  190943. png_bytep sp = row + row_info->rowbytes;
  190944. png_bytep dp = sp;
  190945. png_uint_32 i;
  190946. for (i = 0; i < row_width; i++)
  190947. {
  190948. *(--dp) = (png_byte)(255 - *(--sp));
  190949. *(--dp) = (png_byte)(255 - *(--sp));
  190950. /* This does nothing:
  190951. *(--dp) = *(--sp);
  190952. *(--dp) = *(--sp);
  190953. *(--dp) = *(--sp);
  190954. *(--dp) = *(--sp);
  190955. *(--dp) = *(--sp);
  190956. *(--dp) = *(--sp);
  190957. We can replace it with:
  190958. */
  190959. sp-=6;
  190960. dp=sp;
  190961. }
  190962. }
  190963. }
  190964. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190965. {
  190966. /* This inverts the alpha channel in GA */
  190967. if (row_info->bit_depth == 8)
  190968. {
  190969. png_bytep sp = row + row_info->rowbytes;
  190970. png_bytep dp = sp;
  190971. png_uint_32 i;
  190972. for (i = 0; i < row_width; i++)
  190973. {
  190974. *(--dp) = (png_byte)(255 - *(--sp));
  190975. *(--dp) = *(--sp);
  190976. }
  190977. }
  190978. /* This inverts the alpha channel in GGAA */
  190979. else
  190980. {
  190981. png_bytep sp = row + row_info->rowbytes;
  190982. png_bytep dp = sp;
  190983. png_uint_32 i;
  190984. for (i = 0; i < row_width; i++)
  190985. {
  190986. *(--dp) = (png_byte)(255 - *(--sp));
  190987. *(--dp) = (png_byte)(255 - *(--sp));
  190988. /*
  190989. *(--dp) = *(--sp);
  190990. *(--dp) = *(--sp);
  190991. */
  190992. sp-=2;
  190993. dp=sp;
  190994. }
  190995. }
  190996. }
  190997. }
  190998. }
  190999. #endif
  191000. #if defined(PNG_READ_FILLER_SUPPORTED)
  191001. /* Add filler channel if we have RGB color */
  191002. void /* PRIVATE */
  191003. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191004. png_uint_32 filler, png_uint_32 flags)
  191005. {
  191006. png_uint_32 i;
  191007. png_uint_32 row_width = row_info->width;
  191008. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191009. png_byte lo_filler = (png_byte)(filler & 0xff);
  191010. png_debug(1, "in png_do_read_filler\n");
  191011. if (
  191012. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191013. row != NULL && row_info != NULL &&
  191014. #endif
  191015. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191016. {
  191017. if(row_info->bit_depth == 8)
  191018. {
  191019. /* This changes the data from G to GX */
  191020. if (flags & PNG_FLAG_FILLER_AFTER)
  191021. {
  191022. png_bytep sp = row + (png_size_t)row_width;
  191023. png_bytep dp = sp + (png_size_t)row_width;
  191024. for (i = 1; i < row_width; i++)
  191025. {
  191026. *(--dp) = lo_filler;
  191027. *(--dp) = *(--sp);
  191028. }
  191029. *(--dp) = lo_filler;
  191030. row_info->channels = 2;
  191031. row_info->pixel_depth = 16;
  191032. row_info->rowbytes = row_width * 2;
  191033. }
  191034. /* This changes the data from G to XG */
  191035. else
  191036. {
  191037. png_bytep sp = row + (png_size_t)row_width;
  191038. png_bytep dp = sp + (png_size_t)row_width;
  191039. for (i = 0; i < row_width; i++)
  191040. {
  191041. *(--dp) = *(--sp);
  191042. *(--dp) = lo_filler;
  191043. }
  191044. row_info->channels = 2;
  191045. row_info->pixel_depth = 16;
  191046. row_info->rowbytes = row_width * 2;
  191047. }
  191048. }
  191049. else if(row_info->bit_depth == 16)
  191050. {
  191051. /* This changes the data from GG to GGXX */
  191052. if (flags & PNG_FLAG_FILLER_AFTER)
  191053. {
  191054. png_bytep sp = row + (png_size_t)row_width * 2;
  191055. png_bytep dp = sp + (png_size_t)row_width * 2;
  191056. for (i = 1; i < row_width; i++)
  191057. {
  191058. *(--dp) = hi_filler;
  191059. *(--dp) = lo_filler;
  191060. *(--dp) = *(--sp);
  191061. *(--dp) = *(--sp);
  191062. }
  191063. *(--dp) = hi_filler;
  191064. *(--dp) = lo_filler;
  191065. row_info->channels = 2;
  191066. row_info->pixel_depth = 32;
  191067. row_info->rowbytes = row_width * 4;
  191068. }
  191069. /* This changes the data from GG to XXGG */
  191070. else
  191071. {
  191072. png_bytep sp = row + (png_size_t)row_width * 2;
  191073. png_bytep dp = sp + (png_size_t)row_width * 2;
  191074. for (i = 0; i < row_width; i++)
  191075. {
  191076. *(--dp) = *(--sp);
  191077. *(--dp) = *(--sp);
  191078. *(--dp) = hi_filler;
  191079. *(--dp) = lo_filler;
  191080. }
  191081. row_info->channels = 2;
  191082. row_info->pixel_depth = 32;
  191083. row_info->rowbytes = row_width * 4;
  191084. }
  191085. }
  191086. } /* COLOR_TYPE == GRAY */
  191087. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191088. {
  191089. if(row_info->bit_depth == 8)
  191090. {
  191091. /* This changes the data from RGB to RGBX */
  191092. if (flags & PNG_FLAG_FILLER_AFTER)
  191093. {
  191094. png_bytep sp = row + (png_size_t)row_width * 3;
  191095. png_bytep dp = sp + (png_size_t)row_width;
  191096. for (i = 1; i < row_width; i++)
  191097. {
  191098. *(--dp) = lo_filler;
  191099. *(--dp) = *(--sp);
  191100. *(--dp) = *(--sp);
  191101. *(--dp) = *(--sp);
  191102. }
  191103. *(--dp) = lo_filler;
  191104. row_info->channels = 4;
  191105. row_info->pixel_depth = 32;
  191106. row_info->rowbytes = row_width * 4;
  191107. }
  191108. /* This changes the data from RGB to XRGB */
  191109. else
  191110. {
  191111. png_bytep sp = row + (png_size_t)row_width * 3;
  191112. png_bytep dp = sp + (png_size_t)row_width;
  191113. for (i = 0; i < row_width; i++)
  191114. {
  191115. *(--dp) = *(--sp);
  191116. *(--dp) = *(--sp);
  191117. *(--dp) = *(--sp);
  191118. *(--dp) = lo_filler;
  191119. }
  191120. row_info->channels = 4;
  191121. row_info->pixel_depth = 32;
  191122. row_info->rowbytes = row_width * 4;
  191123. }
  191124. }
  191125. else if(row_info->bit_depth == 16)
  191126. {
  191127. /* This changes the data from RRGGBB to RRGGBBXX */
  191128. if (flags & PNG_FLAG_FILLER_AFTER)
  191129. {
  191130. png_bytep sp = row + (png_size_t)row_width * 6;
  191131. png_bytep dp = sp + (png_size_t)row_width * 2;
  191132. for (i = 1; i < row_width; i++)
  191133. {
  191134. *(--dp) = hi_filler;
  191135. *(--dp) = lo_filler;
  191136. *(--dp) = *(--sp);
  191137. *(--dp) = *(--sp);
  191138. *(--dp) = *(--sp);
  191139. *(--dp) = *(--sp);
  191140. *(--dp) = *(--sp);
  191141. *(--dp) = *(--sp);
  191142. }
  191143. *(--dp) = hi_filler;
  191144. *(--dp) = lo_filler;
  191145. row_info->channels = 4;
  191146. row_info->pixel_depth = 64;
  191147. row_info->rowbytes = row_width * 8;
  191148. }
  191149. /* This changes the data from RRGGBB to XXRRGGBB */
  191150. else
  191151. {
  191152. png_bytep sp = row + (png_size_t)row_width * 6;
  191153. png_bytep dp = sp + (png_size_t)row_width * 2;
  191154. for (i = 0; i < row_width; i++)
  191155. {
  191156. *(--dp) = *(--sp);
  191157. *(--dp) = *(--sp);
  191158. *(--dp) = *(--sp);
  191159. *(--dp) = *(--sp);
  191160. *(--dp) = *(--sp);
  191161. *(--dp) = *(--sp);
  191162. *(--dp) = hi_filler;
  191163. *(--dp) = lo_filler;
  191164. }
  191165. row_info->channels = 4;
  191166. row_info->pixel_depth = 64;
  191167. row_info->rowbytes = row_width * 8;
  191168. }
  191169. }
  191170. } /* COLOR_TYPE == RGB */
  191171. }
  191172. #endif
  191173. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191174. /* expand grayscale files to RGB, with or without alpha */
  191175. void /* PRIVATE */
  191176. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191177. {
  191178. png_uint_32 i;
  191179. png_uint_32 row_width = row_info->width;
  191180. png_debug(1, "in png_do_gray_to_rgb\n");
  191181. if (row_info->bit_depth >= 8 &&
  191182. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191183. row != NULL && row_info != NULL &&
  191184. #endif
  191185. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191186. {
  191187. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191188. {
  191189. if (row_info->bit_depth == 8)
  191190. {
  191191. png_bytep sp = row + (png_size_t)row_width - 1;
  191192. png_bytep dp = sp + (png_size_t)row_width * 2;
  191193. for (i = 0; i < row_width; i++)
  191194. {
  191195. *(dp--) = *sp;
  191196. *(dp--) = *sp;
  191197. *(dp--) = *(sp--);
  191198. }
  191199. }
  191200. else
  191201. {
  191202. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191203. png_bytep dp = sp + (png_size_t)row_width * 4;
  191204. for (i = 0; i < row_width; i++)
  191205. {
  191206. *(dp--) = *sp;
  191207. *(dp--) = *(sp - 1);
  191208. *(dp--) = *sp;
  191209. *(dp--) = *(sp - 1);
  191210. *(dp--) = *(sp--);
  191211. *(dp--) = *(sp--);
  191212. }
  191213. }
  191214. }
  191215. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191216. {
  191217. if (row_info->bit_depth == 8)
  191218. {
  191219. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191220. png_bytep dp = sp + (png_size_t)row_width * 2;
  191221. for (i = 0; i < row_width; i++)
  191222. {
  191223. *(dp--) = *(sp--);
  191224. *(dp--) = *sp;
  191225. *(dp--) = *sp;
  191226. *(dp--) = *(sp--);
  191227. }
  191228. }
  191229. else
  191230. {
  191231. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191232. png_bytep dp = sp + (png_size_t)row_width * 4;
  191233. for (i = 0; i < row_width; i++)
  191234. {
  191235. *(dp--) = *(sp--);
  191236. *(dp--) = *(sp--);
  191237. *(dp--) = *sp;
  191238. *(dp--) = *(sp - 1);
  191239. *(dp--) = *sp;
  191240. *(dp--) = *(sp - 1);
  191241. *(dp--) = *(sp--);
  191242. *(dp--) = *(sp--);
  191243. }
  191244. }
  191245. }
  191246. row_info->channels += (png_byte)2;
  191247. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191248. row_info->pixel_depth = (png_byte)(row_info->channels *
  191249. row_info->bit_depth);
  191250. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191251. }
  191252. }
  191253. #endif
  191254. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191255. /* reduce RGB files to grayscale, with or without alpha
  191256. * using the equation given in Poynton's ColorFAQ at
  191257. * <http://www.inforamp.net/~poynton/>
  191258. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191259. *
  191260. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191261. *
  191262. * We approximate this with
  191263. *
  191264. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191265. *
  191266. * which can be expressed with integers as
  191267. *
  191268. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191269. *
  191270. * The calculation is to be done in a linear colorspace.
  191271. *
  191272. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191273. */
  191274. int /* PRIVATE */
  191275. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191276. {
  191277. png_uint_32 i;
  191278. png_uint_32 row_width = row_info->width;
  191279. int rgb_error = 0;
  191280. png_debug(1, "in png_do_rgb_to_gray\n");
  191281. if (
  191282. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191283. row != NULL && row_info != NULL &&
  191284. #endif
  191285. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191286. {
  191287. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191288. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191289. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191290. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191291. {
  191292. if (row_info->bit_depth == 8)
  191293. {
  191294. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191295. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191296. {
  191297. png_bytep sp = row;
  191298. png_bytep dp = row;
  191299. for (i = 0; i < row_width; i++)
  191300. {
  191301. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191302. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191303. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191304. if(red != green || red != blue)
  191305. {
  191306. rgb_error |= 1;
  191307. *(dp++) = png_ptr->gamma_from_1[
  191308. (rc*red+gc*green+bc*blue)>>15];
  191309. }
  191310. else
  191311. *(dp++) = *(sp-1);
  191312. }
  191313. }
  191314. else
  191315. #endif
  191316. {
  191317. png_bytep sp = row;
  191318. png_bytep dp = row;
  191319. for (i = 0; i < row_width; i++)
  191320. {
  191321. png_byte red = *(sp++);
  191322. png_byte green = *(sp++);
  191323. png_byte blue = *(sp++);
  191324. if(red != green || red != blue)
  191325. {
  191326. rgb_error |= 1;
  191327. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191328. }
  191329. else
  191330. *(dp++) = *(sp-1);
  191331. }
  191332. }
  191333. }
  191334. else /* RGB bit_depth == 16 */
  191335. {
  191336. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191337. if (png_ptr->gamma_16_to_1 != NULL &&
  191338. png_ptr->gamma_16_from_1 != NULL)
  191339. {
  191340. png_bytep sp = row;
  191341. png_bytep dp = row;
  191342. for (i = 0; i < row_width; i++)
  191343. {
  191344. png_uint_16 red, green, blue, w;
  191345. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191346. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191347. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191348. if(red == green && red == blue)
  191349. w = red;
  191350. else
  191351. {
  191352. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191353. png_ptr->gamma_shift][red>>8];
  191354. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191355. png_ptr->gamma_shift][green>>8];
  191356. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191357. png_ptr->gamma_shift][blue>>8];
  191358. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191359. + bc*blue_1)>>15);
  191360. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191361. png_ptr->gamma_shift][gray16 >> 8];
  191362. rgb_error |= 1;
  191363. }
  191364. *(dp++) = (png_byte)((w>>8) & 0xff);
  191365. *(dp++) = (png_byte)(w & 0xff);
  191366. }
  191367. }
  191368. else
  191369. #endif
  191370. {
  191371. png_bytep sp = row;
  191372. png_bytep dp = row;
  191373. for (i = 0; i < row_width; i++)
  191374. {
  191375. png_uint_16 red, green, blue, gray16;
  191376. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191377. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191378. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191379. if(red != green || red != blue)
  191380. rgb_error |= 1;
  191381. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191382. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191383. *(dp++) = (png_byte)(gray16 & 0xff);
  191384. }
  191385. }
  191386. }
  191387. }
  191388. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191389. {
  191390. if (row_info->bit_depth == 8)
  191391. {
  191392. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191393. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191394. {
  191395. png_bytep sp = row;
  191396. png_bytep dp = row;
  191397. for (i = 0; i < row_width; i++)
  191398. {
  191399. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191400. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191401. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191402. if(red != green || red != blue)
  191403. rgb_error |= 1;
  191404. *(dp++) = png_ptr->gamma_from_1
  191405. [(rc*red + gc*green + bc*blue)>>15];
  191406. *(dp++) = *(sp++); /* alpha */
  191407. }
  191408. }
  191409. else
  191410. #endif
  191411. {
  191412. png_bytep sp = row;
  191413. png_bytep dp = row;
  191414. for (i = 0; i < row_width; i++)
  191415. {
  191416. png_byte red = *(sp++);
  191417. png_byte green = *(sp++);
  191418. png_byte blue = *(sp++);
  191419. if(red != green || red != blue)
  191420. rgb_error |= 1;
  191421. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191422. *(dp++) = *(sp++); /* alpha */
  191423. }
  191424. }
  191425. }
  191426. else /* RGBA bit_depth == 16 */
  191427. {
  191428. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191429. if (png_ptr->gamma_16_to_1 != NULL &&
  191430. png_ptr->gamma_16_from_1 != NULL)
  191431. {
  191432. png_bytep sp = row;
  191433. png_bytep dp = row;
  191434. for (i = 0; i < row_width; i++)
  191435. {
  191436. png_uint_16 red, green, blue, w;
  191437. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191438. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191439. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191440. if(red == green && red == blue)
  191441. w = red;
  191442. else
  191443. {
  191444. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191445. png_ptr->gamma_shift][red>>8];
  191446. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191447. png_ptr->gamma_shift][green>>8];
  191448. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191449. png_ptr->gamma_shift][blue>>8];
  191450. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191451. + gc * green_1 + bc * blue_1)>>15);
  191452. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191453. png_ptr->gamma_shift][gray16 >> 8];
  191454. rgb_error |= 1;
  191455. }
  191456. *(dp++) = (png_byte)((w>>8) & 0xff);
  191457. *(dp++) = (png_byte)(w & 0xff);
  191458. *(dp++) = *(sp++); /* alpha */
  191459. *(dp++) = *(sp++);
  191460. }
  191461. }
  191462. else
  191463. #endif
  191464. {
  191465. png_bytep sp = row;
  191466. png_bytep dp = row;
  191467. for (i = 0; i < row_width; i++)
  191468. {
  191469. png_uint_16 red, green, blue, gray16;
  191470. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191471. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191472. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191473. if(red != green || red != blue)
  191474. rgb_error |= 1;
  191475. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191476. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191477. *(dp++) = (png_byte)(gray16 & 0xff);
  191478. *(dp++) = *(sp++); /* alpha */
  191479. *(dp++) = *(sp++);
  191480. }
  191481. }
  191482. }
  191483. }
  191484. row_info->channels -= (png_byte)2;
  191485. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191486. row_info->pixel_depth = (png_byte)(row_info->channels *
  191487. row_info->bit_depth);
  191488. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191489. }
  191490. return rgb_error;
  191491. }
  191492. #endif
  191493. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191494. * large of png_color. This lets grayscale images be treated as
  191495. * paletted. Most useful for gamma correction and simplification
  191496. * of code.
  191497. */
  191498. void PNGAPI
  191499. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191500. {
  191501. int num_palette;
  191502. int color_inc;
  191503. int i;
  191504. int v;
  191505. png_debug(1, "in png_do_build_grayscale_palette\n");
  191506. if (palette == NULL)
  191507. return;
  191508. switch (bit_depth)
  191509. {
  191510. case 1:
  191511. num_palette = 2;
  191512. color_inc = 0xff;
  191513. break;
  191514. case 2:
  191515. num_palette = 4;
  191516. color_inc = 0x55;
  191517. break;
  191518. case 4:
  191519. num_palette = 16;
  191520. color_inc = 0x11;
  191521. break;
  191522. case 8:
  191523. num_palette = 256;
  191524. color_inc = 1;
  191525. break;
  191526. default:
  191527. num_palette = 0;
  191528. color_inc = 0;
  191529. break;
  191530. }
  191531. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191532. {
  191533. palette[i].red = (png_byte)v;
  191534. palette[i].green = (png_byte)v;
  191535. palette[i].blue = (png_byte)v;
  191536. }
  191537. }
  191538. /* This function is currently unused. Do we really need it? */
  191539. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191540. void /* PRIVATE */
  191541. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191542. int num_palette)
  191543. {
  191544. png_debug(1, "in png_correct_palette\n");
  191545. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191546. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191547. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191548. {
  191549. png_color back, back_1;
  191550. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191551. {
  191552. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191553. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191554. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191555. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191556. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191557. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191558. }
  191559. else
  191560. {
  191561. double g;
  191562. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191563. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191564. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191565. {
  191566. back.red = png_ptr->background.red;
  191567. back.green = png_ptr->background.green;
  191568. back.blue = png_ptr->background.blue;
  191569. }
  191570. else
  191571. {
  191572. back.red =
  191573. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191574. 255.0 + 0.5);
  191575. back.green =
  191576. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191577. 255.0 + 0.5);
  191578. back.blue =
  191579. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191580. 255.0 + 0.5);
  191581. }
  191582. g = 1.0 / png_ptr->background_gamma;
  191583. back_1.red =
  191584. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191585. 255.0 + 0.5);
  191586. back_1.green =
  191587. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191588. 255.0 + 0.5);
  191589. back_1.blue =
  191590. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191591. 255.0 + 0.5);
  191592. }
  191593. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191594. {
  191595. png_uint_32 i;
  191596. for (i = 0; i < (png_uint_32)num_palette; i++)
  191597. {
  191598. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191599. {
  191600. palette[i] = back;
  191601. }
  191602. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191603. {
  191604. png_byte v, w;
  191605. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191606. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191607. palette[i].red = png_ptr->gamma_from_1[w];
  191608. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191609. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191610. palette[i].green = png_ptr->gamma_from_1[w];
  191611. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191612. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191613. palette[i].blue = png_ptr->gamma_from_1[w];
  191614. }
  191615. else
  191616. {
  191617. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191618. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191619. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191620. }
  191621. }
  191622. }
  191623. else
  191624. {
  191625. int i;
  191626. for (i = 0; i < num_palette; i++)
  191627. {
  191628. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191629. {
  191630. palette[i] = back;
  191631. }
  191632. else
  191633. {
  191634. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191635. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191636. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191637. }
  191638. }
  191639. }
  191640. }
  191641. else
  191642. #endif
  191643. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191644. if (png_ptr->transformations & PNG_GAMMA)
  191645. {
  191646. int i;
  191647. for (i = 0; i < num_palette; i++)
  191648. {
  191649. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191650. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191651. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191652. }
  191653. }
  191654. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191655. else
  191656. #endif
  191657. #endif
  191658. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191659. if (png_ptr->transformations & PNG_BACKGROUND)
  191660. {
  191661. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191662. {
  191663. png_color back;
  191664. back.red = (png_byte)png_ptr->background.red;
  191665. back.green = (png_byte)png_ptr->background.green;
  191666. back.blue = (png_byte)png_ptr->background.blue;
  191667. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191668. {
  191669. if (png_ptr->trans[i] == 0)
  191670. {
  191671. palette[i].red = back.red;
  191672. palette[i].green = back.green;
  191673. palette[i].blue = back.blue;
  191674. }
  191675. else if (png_ptr->trans[i] != 0xff)
  191676. {
  191677. png_composite(palette[i].red, png_ptr->palette[i].red,
  191678. png_ptr->trans[i], back.red);
  191679. png_composite(palette[i].green, png_ptr->palette[i].green,
  191680. png_ptr->trans[i], back.green);
  191681. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191682. png_ptr->trans[i], back.blue);
  191683. }
  191684. }
  191685. }
  191686. else /* assume grayscale palette (what else could it be?) */
  191687. {
  191688. int i;
  191689. for (i = 0; i < num_palette; i++)
  191690. {
  191691. if (i == (png_byte)png_ptr->trans_values.gray)
  191692. {
  191693. palette[i].red = (png_byte)png_ptr->background.red;
  191694. palette[i].green = (png_byte)png_ptr->background.green;
  191695. palette[i].blue = (png_byte)png_ptr->background.blue;
  191696. }
  191697. }
  191698. }
  191699. }
  191700. #endif
  191701. }
  191702. #endif
  191703. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191704. /* Replace any alpha or transparency with the supplied background color.
  191705. * "background" is already in the screen gamma, while "background_1" is
  191706. * at a gamma of 1.0. Paletted files have already been taken care of.
  191707. */
  191708. void /* PRIVATE */
  191709. png_do_background(png_row_infop row_info, png_bytep row,
  191710. png_color_16p trans_values, png_color_16p background
  191711. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191712. , png_color_16p background_1,
  191713. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191714. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191715. png_uint_16pp gamma_16_to_1, int gamma_shift
  191716. #endif
  191717. )
  191718. {
  191719. png_bytep sp, dp;
  191720. png_uint_32 i;
  191721. png_uint_32 row_width=row_info->width;
  191722. int shift;
  191723. png_debug(1, "in png_do_background\n");
  191724. if (background != NULL &&
  191725. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191726. row != NULL && row_info != NULL &&
  191727. #endif
  191728. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191729. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191730. {
  191731. switch (row_info->color_type)
  191732. {
  191733. case PNG_COLOR_TYPE_GRAY:
  191734. {
  191735. switch (row_info->bit_depth)
  191736. {
  191737. case 1:
  191738. {
  191739. sp = row;
  191740. shift = 7;
  191741. for (i = 0; i < row_width; i++)
  191742. {
  191743. if ((png_uint_16)((*sp >> shift) & 0x01)
  191744. == trans_values->gray)
  191745. {
  191746. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191747. *sp |= (png_byte)(background->gray << shift);
  191748. }
  191749. if (!shift)
  191750. {
  191751. shift = 7;
  191752. sp++;
  191753. }
  191754. else
  191755. shift--;
  191756. }
  191757. break;
  191758. }
  191759. case 2:
  191760. {
  191761. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191762. if (gamma_table != NULL)
  191763. {
  191764. sp = row;
  191765. shift = 6;
  191766. for (i = 0; i < row_width; i++)
  191767. {
  191768. if ((png_uint_16)((*sp >> shift) & 0x03)
  191769. == trans_values->gray)
  191770. {
  191771. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191772. *sp |= (png_byte)(background->gray << shift);
  191773. }
  191774. else
  191775. {
  191776. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191777. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191778. (p << 4) | (p << 6)] >> 6) & 0x03);
  191779. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191780. *sp |= (png_byte)(g << shift);
  191781. }
  191782. if (!shift)
  191783. {
  191784. shift = 6;
  191785. sp++;
  191786. }
  191787. else
  191788. shift -= 2;
  191789. }
  191790. }
  191791. else
  191792. #endif
  191793. {
  191794. sp = row;
  191795. shift = 6;
  191796. for (i = 0; i < row_width; i++)
  191797. {
  191798. if ((png_uint_16)((*sp >> shift) & 0x03)
  191799. == trans_values->gray)
  191800. {
  191801. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191802. *sp |= (png_byte)(background->gray << shift);
  191803. }
  191804. if (!shift)
  191805. {
  191806. shift = 6;
  191807. sp++;
  191808. }
  191809. else
  191810. shift -= 2;
  191811. }
  191812. }
  191813. break;
  191814. }
  191815. case 4:
  191816. {
  191817. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191818. if (gamma_table != NULL)
  191819. {
  191820. sp = row;
  191821. shift = 4;
  191822. for (i = 0; i < row_width; i++)
  191823. {
  191824. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191825. == trans_values->gray)
  191826. {
  191827. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191828. *sp |= (png_byte)(background->gray << shift);
  191829. }
  191830. else
  191831. {
  191832. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  191833. png_byte g = (png_byte)((gamma_table[p |
  191834. (p << 4)] >> 4) & 0x0f);
  191835. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191836. *sp |= (png_byte)(g << shift);
  191837. }
  191838. if (!shift)
  191839. {
  191840. shift = 4;
  191841. sp++;
  191842. }
  191843. else
  191844. shift -= 4;
  191845. }
  191846. }
  191847. else
  191848. #endif
  191849. {
  191850. sp = row;
  191851. shift = 4;
  191852. for (i = 0; i < row_width; i++)
  191853. {
  191854. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191855. == trans_values->gray)
  191856. {
  191857. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191858. *sp |= (png_byte)(background->gray << shift);
  191859. }
  191860. if (!shift)
  191861. {
  191862. shift = 4;
  191863. sp++;
  191864. }
  191865. else
  191866. shift -= 4;
  191867. }
  191868. }
  191869. break;
  191870. }
  191871. case 8:
  191872. {
  191873. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191874. if (gamma_table != NULL)
  191875. {
  191876. sp = row;
  191877. for (i = 0; i < row_width; i++, sp++)
  191878. {
  191879. if (*sp == trans_values->gray)
  191880. {
  191881. *sp = (png_byte)background->gray;
  191882. }
  191883. else
  191884. {
  191885. *sp = gamma_table[*sp];
  191886. }
  191887. }
  191888. }
  191889. else
  191890. #endif
  191891. {
  191892. sp = row;
  191893. for (i = 0; i < row_width; i++, sp++)
  191894. {
  191895. if (*sp == trans_values->gray)
  191896. {
  191897. *sp = (png_byte)background->gray;
  191898. }
  191899. }
  191900. }
  191901. break;
  191902. }
  191903. case 16:
  191904. {
  191905. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191906. if (gamma_16 != NULL)
  191907. {
  191908. sp = row;
  191909. for (i = 0; i < row_width; i++, sp += 2)
  191910. {
  191911. png_uint_16 v;
  191912. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191913. if (v == trans_values->gray)
  191914. {
  191915. /* background is already in screen gamma */
  191916. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191917. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191918. }
  191919. else
  191920. {
  191921. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191922. *sp = (png_byte)((v >> 8) & 0xff);
  191923. *(sp + 1) = (png_byte)(v & 0xff);
  191924. }
  191925. }
  191926. }
  191927. else
  191928. #endif
  191929. {
  191930. sp = row;
  191931. for (i = 0; i < row_width; i++, sp += 2)
  191932. {
  191933. png_uint_16 v;
  191934. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191935. if (v == trans_values->gray)
  191936. {
  191937. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191938. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191939. }
  191940. }
  191941. }
  191942. break;
  191943. }
  191944. }
  191945. break;
  191946. }
  191947. case PNG_COLOR_TYPE_RGB:
  191948. {
  191949. if (row_info->bit_depth == 8)
  191950. {
  191951. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191952. if (gamma_table != NULL)
  191953. {
  191954. sp = row;
  191955. for (i = 0; i < row_width; i++, sp += 3)
  191956. {
  191957. if (*sp == trans_values->red &&
  191958. *(sp + 1) == trans_values->green &&
  191959. *(sp + 2) == trans_values->blue)
  191960. {
  191961. *sp = (png_byte)background->red;
  191962. *(sp + 1) = (png_byte)background->green;
  191963. *(sp + 2) = (png_byte)background->blue;
  191964. }
  191965. else
  191966. {
  191967. *sp = gamma_table[*sp];
  191968. *(sp + 1) = gamma_table[*(sp + 1)];
  191969. *(sp + 2) = gamma_table[*(sp + 2)];
  191970. }
  191971. }
  191972. }
  191973. else
  191974. #endif
  191975. {
  191976. sp = row;
  191977. for (i = 0; i < row_width; i++, sp += 3)
  191978. {
  191979. if (*sp == trans_values->red &&
  191980. *(sp + 1) == trans_values->green &&
  191981. *(sp + 2) == trans_values->blue)
  191982. {
  191983. *sp = (png_byte)background->red;
  191984. *(sp + 1) = (png_byte)background->green;
  191985. *(sp + 2) = (png_byte)background->blue;
  191986. }
  191987. }
  191988. }
  191989. }
  191990. else /* if (row_info->bit_depth == 16) */
  191991. {
  191992. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191993. if (gamma_16 != NULL)
  191994. {
  191995. sp = row;
  191996. for (i = 0; i < row_width; i++, sp += 6)
  191997. {
  191998. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191999. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192000. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192001. if (r == trans_values->red && g == trans_values->green &&
  192002. b == trans_values->blue)
  192003. {
  192004. /* background is already in screen gamma */
  192005. *sp = (png_byte)((background->red >> 8) & 0xff);
  192006. *(sp + 1) = (png_byte)(background->red & 0xff);
  192007. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192008. *(sp + 3) = (png_byte)(background->green & 0xff);
  192009. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192010. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192011. }
  192012. else
  192013. {
  192014. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192015. *sp = (png_byte)((v >> 8) & 0xff);
  192016. *(sp + 1) = (png_byte)(v & 0xff);
  192017. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192018. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192019. *(sp + 3) = (png_byte)(v & 0xff);
  192020. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192021. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192022. *(sp + 5) = (png_byte)(v & 0xff);
  192023. }
  192024. }
  192025. }
  192026. else
  192027. #endif
  192028. {
  192029. sp = row;
  192030. for (i = 0; i < row_width; i++, sp += 6)
  192031. {
  192032. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192033. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192034. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192035. if (r == trans_values->red && g == trans_values->green &&
  192036. b == trans_values->blue)
  192037. {
  192038. *sp = (png_byte)((background->red >> 8) & 0xff);
  192039. *(sp + 1) = (png_byte)(background->red & 0xff);
  192040. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192041. *(sp + 3) = (png_byte)(background->green & 0xff);
  192042. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192043. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192044. }
  192045. }
  192046. }
  192047. }
  192048. break;
  192049. }
  192050. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192051. {
  192052. if (row_info->bit_depth == 8)
  192053. {
  192054. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192055. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192056. gamma_table != NULL)
  192057. {
  192058. sp = row;
  192059. dp = row;
  192060. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192061. {
  192062. png_uint_16 a = *(sp + 1);
  192063. if (a == 0xff)
  192064. {
  192065. *dp = gamma_table[*sp];
  192066. }
  192067. else if (a == 0)
  192068. {
  192069. /* background is already in screen gamma */
  192070. *dp = (png_byte)background->gray;
  192071. }
  192072. else
  192073. {
  192074. png_byte v, w;
  192075. v = gamma_to_1[*sp];
  192076. png_composite(w, v, a, background_1->gray);
  192077. *dp = gamma_from_1[w];
  192078. }
  192079. }
  192080. }
  192081. else
  192082. #endif
  192083. {
  192084. sp = row;
  192085. dp = row;
  192086. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192087. {
  192088. png_byte a = *(sp + 1);
  192089. if (a == 0xff)
  192090. {
  192091. *dp = *sp;
  192092. }
  192093. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192094. else if (a == 0)
  192095. {
  192096. *dp = (png_byte)background->gray;
  192097. }
  192098. else
  192099. {
  192100. png_composite(*dp, *sp, a, background_1->gray);
  192101. }
  192102. #else
  192103. *dp = (png_byte)background->gray;
  192104. #endif
  192105. }
  192106. }
  192107. }
  192108. else /* if (png_ptr->bit_depth == 16) */
  192109. {
  192110. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192111. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192112. gamma_16_to_1 != NULL)
  192113. {
  192114. sp = row;
  192115. dp = row;
  192116. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192117. {
  192118. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192119. if (a == (png_uint_16)0xffff)
  192120. {
  192121. png_uint_16 v;
  192122. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192123. *dp = (png_byte)((v >> 8) & 0xff);
  192124. *(dp + 1) = (png_byte)(v & 0xff);
  192125. }
  192126. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192127. else if (a == 0)
  192128. #else
  192129. else
  192130. #endif
  192131. {
  192132. /* background is already in screen gamma */
  192133. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192134. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192135. }
  192136. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192137. else
  192138. {
  192139. png_uint_16 g, v, w;
  192140. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192141. png_composite_16(v, g, a, background_1->gray);
  192142. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192143. *dp = (png_byte)((w >> 8) & 0xff);
  192144. *(dp + 1) = (png_byte)(w & 0xff);
  192145. }
  192146. #endif
  192147. }
  192148. }
  192149. else
  192150. #endif
  192151. {
  192152. sp = row;
  192153. dp = row;
  192154. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192155. {
  192156. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192157. if (a == (png_uint_16)0xffff)
  192158. {
  192159. png_memcpy(dp, sp, 2);
  192160. }
  192161. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192162. else if (a == 0)
  192163. #else
  192164. else
  192165. #endif
  192166. {
  192167. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192168. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192169. }
  192170. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192171. else
  192172. {
  192173. png_uint_16 g, v;
  192174. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192175. png_composite_16(v, g, a, background_1->gray);
  192176. *dp = (png_byte)((v >> 8) & 0xff);
  192177. *(dp + 1) = (png_byte)(v & 0xff);
  192178. }
  192179. #endif
  192180. }
  192181. }
  192182. }
  192183. break;
  192184. }
  192185. case PNG_COLOR_TYPE_RGB_ALPHA:
  192186. {
  192187. if (row_info->bit_depth == 8)
  192188. {
  192189. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192190. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192191. gamma_table != NULL)
  192192. {
  192193. sp = row;
  192194. dp = row;
  192195. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192196. {
  192197. png_byte a = *(sp + 3);
  192198. if (a == 0xff)
  192199. {
  192200. *dp = gamma_table[*sp];
  192201. *(dp + 1) = gamma_table[*(sp + 1)];
  192202. *(dp + 2) = gamma_table[*(sp + 2)];
  192203. }
  192204. else if (a == 0)
  192205. {
  192206. /* background is already in screen gamma */
  192207. *dp = (png_byte)background->red;
  192208. *(dp + 1) = (png_byte)background->green;
  192209. *(dp + 2) = (png_byte)background->blue;
  192210. }
  192211. else
  192212. {
  192213. png_byte v, w;
  192214. v = gamma_to_1[*sp];
  192215. png_composite(w, v, a, background_1->red);
  192216. *dp = gamma_from_1[w];
  192217. v = gamma_to_1[*(sp + 1)];
  192218. png_composite(w, v, a, background_1->green);
  192219. *(dp + 1) = gamma_from_1[w];
  192220. v = gamma_to_1[*(sp + 2)];
  192221. png_composite(w, v, a, background_1->blue);
  192222. *(dp + 2) = gamma_from_1[w];
  192223. }
  192224. }
  192225. }
  192226. else
  192227. #endif
  192228. {
  192229. sp = row;
  192230. dp = row;
  192231. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192232. {
  192233. png_byte a = *(sp + 3);
  192234. if (a == 0xff)
  192235. {
  192236. *dp = *sp;
  192237. *(dp + 1) = *(sp + 1);
  192238. *(dp + 2) = *(sp + 2);
  192239. }
  192240. else if (a == 0)
  192241. {
  192242. *dp = (png_byte)background->red;
  192243. *(dp + 1) = (png_byte)background->green;
  192244. *(dp + 2) = (png_byte)background->blue;
  192245. }
  192246. else
  192247. {
  192248. png_composite(*dp, *sp, a, background->red);
  192249. png_composite(*(dp + 1), *(sp + 1), a,
  192250. background->green);
  192251. png_composite(*(dp + 2), *(sp + 2), a,
  192252. background->blue);
  192253. }
  192254. }
  192255. }
  192256. }
  192257. else /* if (row_info->bit_depth == 16) */
  192258. {
  192259. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192260. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192261. gamma_16_to_1 != NULL)
  192262. {
  192263. sp = row;
  192264. dp = row;
  192265. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192266. {
  192267. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192268. << 8) + (png_uint_16)(*(sp + 7)));
  192269. if (a == (png_uint_16)0xffff)
  192270. {
  192271. png_uint_16 v;
  192272. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192273. *dp = (png_byte)((v >> 8) & 0xff);
  192274. *(dp + 1) = (png_byte)(v & 0xff);
  192275. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192276. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192277. *(dp + 3) = (png_byte)(v & 0xff);
  192278. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192279. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192280. *(dp + 5) = (png_byte)(v & 0xff);
  192281. }
  192282. else if (a == 0)
  192283. {
  192284. /* background is already in screen gamma */
  192285. *dp = (png_byte)((background->red >> 8) & 0xff);
  192286. *(dp + 1) = (png_byte)(background->red & 0xff);
  192287. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192288. *(dp + 3) = (png_byte)(background->green & 0xff);
  192289. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192290. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192291. }
  192292. else
  192293. {
  192294. png_uint_16 v, w, x;
  192295. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192296. png_composite_16(w, v, a, background_1->red);
  192297. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192298. *dp = (png_byte)((x >> 8) & 0xff);
  192299. *(dp + 1) = (png_byte)(x & 0xff);
  192300. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192301. png_composite_16(w, v, a, background_1->green);
  192302. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192303. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192304. *(dp + 3) = (png_byte)(x & 0xff);
  192305. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192306. png_composite_16(w, v, a, background_1->blue);
  192307. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192308. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192309. *(dp + 5) = (png_byte)(x & 0xff);
  192310. }
  192311. }
  192312. }
  192313. else
  192314. #endif
  192315. {
  192316. sp = row;
  192317. dp = row;
  192318. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192319. {
  192320. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192321. << 8) + (png_uint_16)(*(sp + 7)));
  192322. if (a == (png_uint_16)0xffff)
  192323. {
  192324. png_memcpy(dp, sp, 6);
  192325. }
  192326. else if (a == 0)
  192327. {
  192328. *dp = (png_byte)((background->red >> 8) & 0xff);
  192329. *(dp + 1) = (png_byte)(background->red & 0xff);
  192330. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192331. *(dp + 3) = (png_byte)(background->green & 0xff);
  192332. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192333. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192334. }
  192335. else
  192336. {
  192337. png_uint_16 v;
  192338. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192339. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192340. + *(sp + 3));
  192341. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192342. + *(sp + 5));
  192343. png_composite_16(v, r, a, background->red);
  192344. *dp = (png_byte)((v >> 8) & 0xff);
  192345. *(dp + 1) = (png_byte)(v & 0xff);
  192346. png_composite_16(v, g, a, background->green);
  192347. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192348. *(dp + 3) = (png_byte)(v & 0xff);
  192349. png_composite_16(v, b, a, background->blue);
  192350. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192351. *(dp + 5) = (png_byte)(v & 0xff);
  192352. }
  192353. }
  192354. }
  192355. }
  192356. break;
  192357. }
  192358. }
  192359. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192360. {
  192361. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192362. row_info->channels--;
  192363. row_info->pixel_depth = (png_byte)(row_info->channels *
  192364. row_info->bit_depth);
  192365. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192366. }
  192367. }
  192368. }
  192369. #endif
  192370. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192371. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192372. * you do this after you deal with the transparency issue on grayscale
  192373. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192374. * is 16, use gamma_16_table and gamma_shift. Build these with
  192375. * build_gamma_table().
  192376. */
  192377. void /* PRIVATE */
  192378. png_do_gamma(png_row_infop row_info, png_bytep row,
  192379. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192380. int gamma_shift)
  192381. {
  192382. png_bytep sp;
  192383. png_uint_32 i;
  192384. png_uint_32 row_width=row_info->width;
  192385. png_debug(1, "in png_do_gamma\n");
  192386. if (
  192387. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192388. row != NULL && row_info != NULL &&
  192389. #endif
  192390. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192391. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192392. {
  192393. switch (row_info->color_type)
  192394. {
  192395. case PNG_COLOR_TYPE_RGB:
  192396. {
  192397. if (row_info->bit_depth == 8)
  192398. {
  192399. sp = row;
  192400. for (i = 0; i < row_width; i++)
  192401. {
  192402. *sp = gamma_table[*sp];
  192403. sp++;
  192404. *sp = gamma_table[*sp];
  192405. sp++;
  192406. *sp = gamma_table[*sp];
  192407. sp++;
  192408. }
  192409. }
  192410. else /* if (row_info->bit_depth == 16) */
  192411. {
  192412. sp = row;
  192413. for (i = 0; i < row_width; i++)
  192414. {
  192415. png_uint_16 v;
  192416. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192417. *sp = (png_byte)((v >> 8) & 0xff);
  192418. *(sp + 1) = (png_byte)(v & 0xff);
  192419. sp += 2;
  192420. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192421. *sp = (png_byte)((v >> 8) & 0xff);
  192422. *(sp + 1) = (png_byte)(v & 0xff);
  192423. sp += 2;
  192424. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192425. *sp = (png_byte)((v >> 8) & 0xff);
  192426. *(sp + 1) = (png_byte)(v & 0xff);
  192427. sp += 2;
  192428. }
  192429. }
  192430. break;
  192431. }
  192432. case PNG_COLOR_TYPE_RGB_ALPHA:
  192433. {
  192434. if (row_info->bit_depth == 8)
  192435. {
  192436. sp = row;
  192437. for (i = 0; i < row_width; i++)
  192438. {
  192439. *sp = gamma_table[*sp];
  192440. sp++;
  192441. *sp = gamma_table[*sp];
  192442. sp++;
  192443. *sp = gamma_table[*sp];
  192444. sp++;
  192445. sp++;
  192446. }
  192447. }
  192448. else /* if (row_info->bit_depth == 16) */
  192449. {
  192450. sp = row;
  192451. for (i = 0; i < row_width; i++)
  192452. {
  192453. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192454. *sp = (png_byte)((v >> 8) & 0xff);
  192455. *(sp + 1) = (png_byte)(v & 0xff);
  192456. sp += 2;
  192457. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192458. *sp = (png_byte)((v >> 8) & 0xff);
  192459. *(sp + 1) = (png_byte)(v & 0xff);
  192460. sp += 2;
  192461. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192462. *sp = (png_byte)((v >> 8) & 0xff);
  192463. *(sp + 1) = (png_byte)(v & 0xff);
  192464. sp += 4;
  192465. }
  192466. }
  192467. break;
  192468. }
  192469. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192470. {
  192471. if (row_info->bit_depth == 8)
  192472. {
  192473. sp = row;
  192474. for (i = 0; i < row_width; i++)
  192475. {
  192476. *sp = gamma_table[*sp];
  192477. sp += 2;
  192478. }
  192479. }
  192480. else /* if (row_info->bit_depth == 16) */
  192481. {
  192482. sp = row;
  192483. for (i = 0; i < row_width; i++)
  192484. {
  192485. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192486. *sp = (png_byte)((v >> 8) & 0xff);
  192487. *(sp + 1) = (png_byte)(v & 0xff);
  192488. sp += 4;
  192489. }
  192490. }
  192491. break;
  192492. }
  192493. case PNG_COLOR_TYPE_GRAY:
  192494. {
  192495. if (row_info->bit_depth == 2)
  192496. {
  192497. sp = row;
  192498. for (i = 0; i < row_width; i += 4)
  192499. {
  192500. int a = *sp & 0xc0;
  192501. int b = *sp & 0x30;
  192502. int c = *sp & 0x0c;
  192503. int d = *sp & 0x03;
  192504. *sp = (png_byte)(
  192505. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192506. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192507. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192508. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192509. sp++;
  192510. }
  192511. }
  192512. if (row_info->bit_depth == 4)
  192513. {
  192514. sp = row;
  192515. for (i = 0; i < row_width; i += 2)
  192516. {
  192517. int msb = *sp & 0xf0;
  192518. int lsb = *sp & 0x0f;
  192519. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192520. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192521. sp++;
  192522. }
  192523. }
  192524. else if (row_info->bit_depth == 8)
  192525. {
  192526. sp = row;
  192527. for (i = 0; i < row_width; i++)
  192528. {
  192529. *sp = gamma_table[*sp];
  192530. sp++;
  192531. }
  192532. }
  192533. else if (row_info->bit_depth == 16)
  192534. {
  192535. sp = row;
  192536. for (i = 0; i < row_width; i++)
  192537. {
  192538. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192539. *sp = (png_byte)((v >> 8) & 0xff);
  192540. *(sp + 1) = (png_byte)(v & 0xff);
  192541. sp += 2;
  192542. }
  192543. }
  192544. break;
  192545. }
  192546. }
  192547. }
  192548. }
  192549. #endif
  192550. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192551. /* Expands a palette row to an RGB or RGBA row depending
  192552. * upon whether you supply trans and num_trans.
  192553. */
  192554. void /* PRIVATE */
  192555. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192556. png_colorp palette, png_bytep trans, int num_trans)
  192557. {
  192558. int shift, value;
  192559. png_bytep sp, dp;
  192560. png_uint_32 i;
  192561. png_uint_32 row_width=row_info->width;
  192562. png_debug(1, "in png_do_expand_palette\n");
  192563. if (
  192564. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192565. row != NULL && row_info != NULL &&
  192566. #endif
  192567. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192568. {
  192569. if (row_info->bit_depth < 8)
  192570. {
  192571. switch (row_info->bit_depth)
  192572. {
  192573. case 1:
  192574. {
  192575. sp = row + (png_size_t)((row_width - 1) >> 3);
  192576. dp = row + (png_size_t)row_width - 1;
  192577. shift = 7 - (int)((row_width + 7) & 0x07);
  192578. for (i = 0; i < row_width; i++)
  192579. {
  192580. if ((*sp >> shift) & 0x01)
  192581. *dp = 1;
  192582. else
  192583. *dp = 0;
  192584. if (shift == 7)
  192585. {
  192586. shift = 0;
  192587. sp--;
  192588. }
  192589. else
  192590. shift++;
  192591. dp--;
  192592. }
  192593. break;
  192594. }
  192595. case 2:
  192596. {
  192597. sp = row + (png_size_t)((row_width - 1) >> 2);
  192598. dp = row + (png_size_t)row_width - 1;
  192599. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192600. for (i = 0; i < row_width; i++)
  192601. {
  192602. value = (*sp >> shift) & 0x03;
  192603. *dp = (png_byte)value;
  192604. if (shift == 6)
  192605. {
  192606. shift = 0;
  192607. sp--;
  192608. }
  192609. else
  192610. shift += 2;
  192611. dp--;
  192612. }
  192613. break;
  192614. }
  192615. case 4:
  192616. {
  192617. sp = row + (png_size_t)((row_width - 1) >> 1);
  192618. dp = row + (png_size_t)row_width - 1;
  192619. shift = (int)((row_width & 0x01) << 2);
  192620. for (i = 0; i < row_width; i++)
  192621. {
  192622. value = (*sp >> shift) & 0x0f;
  192623. *dp = (png_byte)value;
  192624. if (shift == 4)
  192625. {
  192626. shift = 0;
  192627. sp--;
  192628. }
  192629. else
  192630. shift += 4;
  192631. dp--;
  192632. }
  192633. break;
  192634. }
  192635. }
  192636. row_info->bit_depth = 8;
  192637. row_info->pixel_depth = 8;
  192638. row_info->rowbytes = row_width;
  192639. }
  192640. switch (row_info->bit_depth)
  192641. {
  192642. case 8:
  192643. {
  192644. if (trans != NULL)
  192645. {
  192646. sp = row + (png_size_t)row_width - 1;
  192647. dp = row + (png_size_t)(row_width << 2) - 1;
  192648. for (i = 0; i < row_width; i++)
  192649. {
  192650. if ((int)(*sp) >= num_trans)
  192651. *dp-- = 0xff;
  192652. else
  192653. *dp-- = trans[*sp];
  192654. *dp-- = palette[*sp].blue;
  192655. *dp-- = palette[*sp].green;
  192656. *dp-- = palette[*sp].red;
  192657. sp--;
  192658. }
  192659. row_info->bit_depth = 8;
  192660. row_info->pixel_depth = 32;
  192661. row_info->rowbytes = row_width * 4;
  192662. row_info->color_type = 6;
  192663. row_info->channels = 4;
  192664. }
  192665. else
  192666. {
  192667. sp = row + (png_size_t)row_width - 1;
  192668. dp = row + (png_size_t)(row_width * 3) - 1;
  192669. for (i = 0; i < row_width; i++)
  192670. {
  192671. *dp-- = palette[*sp].blue;
  192672. *dp-- = palette[*sp].green;
  192673. *dp-- = palette[*sp].red;
  192674. sp--;
  192675. }
  192676. row_info->bit_depth = 8;
  192677. row_info->pixel_depth = 24;
  192678. row_info->rowbytes = row_width * 3;
  192679. row_info->color_type = 2;
  192680. row_info->channels = 3;
  192681. }
  192682. break;
  192683. }
  192684. }
  192685. }
  192686. }
  192687. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192688. * expanded transparency value is supplied, an alpha channel is built.
  192689. */
  192690. void /* PRIVATE */
  192691. png_do_expand(png_row_infop row_info, png_bytep row,
  192692. png_color_16p trans_value)
  192693. {
  192694. int shift, value;
  192695. png_bytep sp, dp;
  192696. png_uint_32 i;
  192697. png_uint_32 row_width=row_info->width;
  192698. png_debug(1, "in png_do_expand\n");
  192699. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192700. if (row != NULL && row_info != NULL)
  192701. #endif
  192702. {
  192703. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192704. {
  192705. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192706. if (row_info->bit_depth < 8)
  192707. {
  192708. switch (row_info->bit_depth)
  192709. {
  192710. case 1:
  192711. {
  192712. gray = (png_uint_16)((gray&0x01)*0xff);
  192713. sp = row + (png_size_t)((row_width - 1) >> 3);
  192714. dp = row + (png_size_t)row_width - 1;
  192715. shift = 7 - (int)((row_width + 7) & 0x07);
  192716. for (i = 0; i < row_width; i++)
  192717. {
  192718. if ((*sp >> shift) & 0x01)
  192719. *dp = 0xff;
  192720. else
  192721. *dp = 0;
  192722. if (shift == 7)
  192723. {
  192724. shift = 0;
  192725. sp--;
  192726. }
  192727. else
  192728. shift++;
  192729. dp--;
  192730. }
  192731. break;
  192732. }
  192733. case 2:
  192734. {
  192735. gray = (png_uint_16)((gray&0x03)*0x55);
  192736. sp = row + (png_size_t)((row_width - 1) >> 2);
  192737. dp = row + (png_size_t)row_width - 1;
  192738. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192739. for (i = 0; i < row_width; i++)
  192740. {
  192741. value = (*sp >> shift) & 0x03;
  192742. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192743. (value << 6));
  192744. if (shift == 6)
  192745. {
  192746. shift = 0;
  192747. sp--;
  192748. }
  192749. else
  192750. shift += 2;
  192751. dp--;
  192752. }
  192753. break;
  192754. }
  192755. case 4:
  192756. {
  192757. gray = (png_uint_16)((gray&0x0f)*0x11);
  192758. sp = row + (png_size_t)((row_width - 1) >> 1);
  192759. dp = row + (png_size_t)row_width - 1;
  192760. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192761. for (i = 0; i < row_width; i++)
  192762. {
  192763. value = (*sp >> shift) & 0x0f;
  192764. *dp = (png_byte)(value | (value << 4));
  192765. if (shift == 4)
  192766. {
  192767. shift = 0;
  192768. sp--;
  192769. }
  192770. else
  192771. shift = 4;
  192772. dp--;
  192773. }
  192774. break;
  192775. }
  192776. }
  192777. row_info->bit_depth = 8;
  192778. row_info->pixel_depth = 8;
  192779. row_info->rowbytes = row_width;
  192780. }
  192781. if (trans_value != NULL)
  192782. {
  192783. if (row_info->bit_depth == 8)
  192784. {
  192785. gray = gray & 0xff;
  192786. sp = row + (png_size_t)row_width - 1;
  192787. dp = row + (png_size_t)(row_width << 1) - 1;
  192788. for (i = 0; i < row_width; i++)
  192789. {
  192790. if (*sp == gray)
  192791. *dp-- = 0;
  192792. else
  192793. *dp-- = 0xff;
  192794. *dp-- = *sp--;
  192795. }
  192796. }
  192797. else if (row_info->bit_depth == 16)
  192798. {
  192799. png_byte gray_high = (gray >> 8) & 0xff;
  192800. png_byte gray_low = gray & 0xff;
  192801. sp = row + row_info->rowbytes - 1;
  192802. dp = row + (row_info->rowbytes << 1) - 1;
  192803. for (i = 0; i < row_width; i++)
  192804. {
  192805. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192806. {
  192807. *dp-- = 0;
  192808. *dp-- = 0;
  192809. }
  192810. else
  192811. {
  192812. *dp-- = 0xff;
  192813. *dp-- = 0xff;
  192814. }
  192815. *dp-- = *sp--;
  192816. *dp-- = *sp--;
  192817. }
  192818. }
  192819. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  192820. row_info->channels = 2;
  192821. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  192822. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  192823. row_width);
  192824. }
  192825. }
  192826. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  192827. {
  192828. if (row_info->bit_depth == 8)
  192829. {
  192830. png_byte red = trans_value->red & 0xff;
  192831. png_byte green = trans_value->green & 0xff;
  192832. png_byte blue = trans_value->blue & 0xff;
  192833. sp = row + (png_size_t)row_info->rowbytes - 1;
  192834. dp = row + (png_size_t)(row_width << 2) - 1;
  192835. for (i = 0; i < row_width; i++)
  192836. {
  192837. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  192838. *dp-- = 0;
  192839. else
  192840. *dp-- = 0xff;
  192841. *dp-- = *sp--;
  192842. *dp-- = *sp--;
  192843. *dp-- = *sp--;
  192844. }
  192845. }
  192846. else if (row_info->bit_depth == 16)
  192847. {
  192848. png_byte red_high = (trans_value->red >> 8) & 0xff;
  192849. png_byte green_high = (trans_value->green >> 8) & 0xff;
  192850. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  192851. png_byte red_low = trans_value->red & 0xff;
  192852. png_byte green_low = trans_value->green & 0xff;
  192853. png_byte blue_low = trans_value->blue & 0xff;
  192854. sp = row + row_info->rowbytes - 1;
  192855. dp = row + (png_size_t)(row_width << 3) - 1;
  192856. for (i = 0; i < row_width; i++)
  192857. {
  192858. if (*(sp - 5) == red_high &&
  192859. *(sp - 4) == red_low &&
  192860. *(sp - 3) == green_high &&
  192861. *(sp - 2) == green_low &&
  192862. *(sp - 1) == blue_high &&
  192863. *(sp ) == blue_low)
  192864. {
  192865. *dp-- = 0;
  192866. *dp-- = 0;
  192867. }
  192868. else
  192869. {
  192870. *dp-- = 0xff;
  192871. *dp-- = 0xff;
  192872. }
  192873. *dp-- = *sp--;
  192874. *dp-- = *sp--;
  192875. *dp-- = *sp--;
  192876. *dp-- = *sp--;
  192877. *dp-- = *sp--;
  192878. *dp-- = *sp--;
  192879. }
  192880. }
  192881. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  192882. row_info->channels = 4;
  192883. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  192884. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192885. }
  192886. }
  192887. }
  192888. #endif
  192889. #if defined(PNG_READ_DITHER_SUPPORTED)
  192890. void /* PRIVATE */
  192891. png_do_dither(png_row_infop row_info, png_bytep row,
  192892. png_bytep palette_lookup, png_bytep dither_lookup)
  192893. {
  192894. png_bytep sp, dp;
  192895. png_uint_32 i;
  192896. png_uint_32 row_width=row_info->width;
  192897. png_debug(1, "in png_do_dither\n");
  192898. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192899. if (row != NULL && row_info != NULL)
  192900. #endif
  192901. {
  192902. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  192903. palette_lookup && row_info->bit_depth == 8)
  192904. {
  192905. int r, g, b, p;
  192906. sp = row;
  192907. dp = row;
  192908. for (i = 0; i < row_width; i++)
  192909. {
  192910. r = *sp++;
  192911. g = *sp++;
  192912. b = *sp++;
  192913. /* this looks real messy, but the compiler will reduce
  192914. it down to a reasonable formula. For example, with
  192915. 5 bits per color, we get:
  192916. p = (((r >> 3) & 0x1f) << 10) |
  192917. (((g >> 3) & 0x1f) << 5) |
  192918. ((b >> 3) & 0x1f);
  192919. */
  192920. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192921. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192922. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192923. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192924. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192925. (PNG_DITHER_BLUE_BITS)) |
  192926. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192927. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192928. *dp++ = palette_lookup[p];
  192929. }
  192930. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192931. row_info->channels = 1;
  192932. row_info->pixel_depth = row_info->bit_depth;
  192933. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192934. }
  192935. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192936. palette_lookup != NULL && row_info->bit_depth == 8)
  192937. {
  192938. int r, g, b, p;
  192939. sp = row;
  192940. dp = row;
  192941. for (i = 0; i < row_width; i++)
  192942. {
  192943. r = *sp++;
  192944. g = *sp++;
  192945. b = *sp++;
  192946. sp++;
  192947. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192948. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192949. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192950. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192951. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192952. (PNG_DITHER_BLUE_BITS)) |
  192953. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192954. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192955. *dp++ = palette_lookup[p];
  192956. }
  192957. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192958. row_info->channels = 1;
  192959. row_info->pixel_depth = row_info->bit_depth;
  192960. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192961. }
  192962. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  192963. dither_lookup && row_info->bit_depth == 8)
  192964. {
  192965. sp = row;
  192966. for (i = 0; i < row_width; i++, sp++)
  192967. {
  192968. *sp = dither_lookup[*sp];
  192969. }
  192970. }
  192971. }
  192972. }
  192973. #endif
  192974. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192975. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192976. static PNG_CONST int png_gamma_shift[] =
  192977. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  192978. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  192979. * tables, we don't make a full table if we are reducing to 8-bit in
  192980. * the future. Note also how the gamma_16 tables are segmented so that
  192981. * we don't need to allocate > 64K chunks for a full 16-bit table.
  192982. */
  192983. void /* PRIVATE */
  192984. png_build_gamma_table(png_structp png_ptr)
  192985. {
  192986. png_debug(1, "in png_build_gamma_table\n");
  192987. if (png_ptr->bit_depth <= 8)
  192988. {
  192989. int i;
  192990. double g;
  192991. if (png_ptr->screen_gamma > .000001)
  192992. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192993. else
  192994. g = 1.0;
  192995. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  192996. (png_uint_32)256);
  192997. for (i = 0; i < 256; i++)
  192998. {
  192999. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193000. g) * 255.0 + .5);
  193001. }
  193002. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193003. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193004. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193005. {
  193006. g = 1.0 / (png_ptr->gamma);
  193007. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193008. (png_uint_32)256);
  193009. for (i = 0; i < 256; i++)
  193010. {
  193011. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193012. g) * 255.0 + .5);
  193013. }
  193014. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193015. (png_uint_32)256);
  193016. if(png_ptr->screen_gamma > 0.000001)
  193017. g = 1.0 / png_ptr->screen_gamma;
  193018. else
  193019. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193020. for (i = 0; i < 256; i++)
  193021. {
  193022. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193023. g) * 255.0 + .5);
  193024. }
  193025. }
  193026. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193027. }
  193028. else
  193029. {
  193030. double g;
  193031. int i, j, shift, num;
  193032. int sig_bit;
  193033. png_uint_32 ig;
  193034. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193035. {
  193036. sig_bit = (int)png_ptr->sig_bit.red;
  193037. if ((int)png_ptr->sig_bit.green > sig_bit)
  193038. sig_bit = png_ptr->sig_bit.green;
  193039. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193040. sig_bit = png_ptr->sig_bit.blue;
  193041. }
  193042. else
  193043. {
  193044. sig_bit = (int)png_ptr->sig_bit.gray;
  193045. }
  193046. if (sig_bit > 0)
  193047. shift = 16 - sig_bit;
  193048. else
  193049. shift = 0;
  193050. if (png_ptr->transformations & PNG_16_TO_8)
  193051. {
  193052. if (shift < (16 - PNG_MAX_GAMMA_8))
  193053. shift = (16 - PNG_MAX_GAMMA_8);
  193054. }
  193055. if (shift > 8)
  193056. shift = 8;
  193057. if (shift < 0)
  193058. shift = 0;
  193059. png_ptr->gamma_shift = (png_byte)shift;
  193060. num = (1 << (8 - shift));
  193061. if (png_ptr->screen_gamma > .000001)
  193062. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193063. else
  193064. g = 1.0;
  193065. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193066. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193067. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193068. {
  193069. double fin, fout;
  193070. png_uint_32 last, max;
  193071. for (i = 0; i < num; i++)
  193072. {
  193073. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193074. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193075. }
  193076. g = 1.0 / g;
  193077. last = 0;
  193078. for (i = 0; i < 256; i++)
  193079. {
  193080. fout = ((double)i + 0.5) / 256.0;
  193081. fin = pow(fout, g);
  193082. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193083. while (last <= max)
  193084. {
  193085. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193086. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193087. (png_uint_16)i | ((png_uint_16)i << 8));
  193088. last++;
  193089. }
  193090. }
  193091. while (last < ((png_uint_32)num << 8))
  193092. {
  193093. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193094. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193095. last++;
  193096. }
  193097. }
  193098. else
  193099. {
  193100. for (i = 0; i < num; i++)
  193101. {
  193102. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193103. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193104. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193105. for (j = 0; j < 256; j++)
  193106. {
  193107. png_ptr->gamma_16_table[i][j] =
  193108. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193109. 65535.0, g) * 65535.0 + .5);
  193110. }
  193111. }
  193112. }
  193113. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193114. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193115. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193116. {
  193117. g = 1.0 / (png_ptr->gamma);
  193118. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193119. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193120. for (i = 0; i < num; i++)
  193121. {
  193122. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193123. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193124. ig = (((png_uint_32)i *
  193125. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193126. for (j = 0; j < 256; j++)
  193127. {
  193128. png_ptr->gamma_16_to_1[i][j] =
  193129. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193130. 65535.0, g) * 65535.0 + .5);
  193131. }
  193132. }
  193133. if(png_ptr->screen_gamma > 0.000001)
  193134. g = 1.0 / png_ptr->screen_gamma;
  193135. else
  193136. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193137. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193138. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193139. for (i = 0; i < num; i++)
  193140. {
  193141. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193142. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193143. ig = (((png_uint_32)i *
  193144. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193145. for (j = 0; j < 256; j++)
  193146. {
  193147. png_ptr->gamma_16_from_1[i][j] =
  193148. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193149. 65535.0, g) * 65535.0 + .5);
  193150. }
  193151. }
  193152. }
  193153. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193154. }
  193155. }
  193156. #endif
  193157. /* To do: install integer version of png_build_gamma_table here */
  193158. #endif
  193159. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193160. /* undoes intrapixel differencing */
  193161. void /* PRIVATE */
  193162. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193163. {
  193164. png_debug(1, "in png_do_read_intrapixel\n");
  193165. if (
  193166. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193167. row != NULL && row_info != NULL &&
  193168. #endif
  193169. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193170. {
  193171. int bytes_per_pixel;
  193172. png_uint_32 row_width = row_info->width;
  193173. if (row_info->bit_depth == 8)
  193174. {
  193175. png_bytep rp;
  193176. png_uint_32 i;
  193177. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193178. bytes_per_pixel = 3;
  193179. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193180. bytes_per_pixel = 4;
  193181. else
  193182. return;
  193183. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193184. {
  193185. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193186. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193187. }
  193188. }
  193189. else if (row_info->bit_depth == 16)
  193190. {
  193191. png_bytep rp;
  193192. png_uint_32 i;
  193193. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193194. bytes_per_pixel = 6;
  193195. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193196. bytes_per_pixel = 8;
  193197. else
  193198. return;
  193199. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193200. {
  193201. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193202. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193203. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193204. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193205. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193206. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193207. *(rp+1) = (png_byte)(red & 0xff);
  193208. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193209. *(rp+5) = (png_byte)(blue & 0xff);
  193210. }
  193211. }
  193212. }
  193213. }
  193214. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193215. #endif /* PNG_READ_SUPPORTED */
  193216. /*** End of inlined file: pngrtran.c ***/
  193217. /*** Start of inlined file: pngrutil.c ***/
  193218. /* pngrutil.c - utilities to read a PNG file
  193219. *
  193220. * Last changed in libpng 1.2.21 [October 4, 2007]
  193221. * For conditions of distribution and use, see copyright notice in png.h
  193222. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193223. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193224. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193225. *
  193226. * This file contains routines that are only called from within
  193227. * libpng itself during the course of reading an image.
  193228. */
  193229. #define PNG_INTERNAL
  193230. #if defined(PNG_READ_SUPPORTED)
  193231. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193232. # define WIN32_WCE_OLD
  193233. #endif
  193234. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193235. # if defined(WIN32_WCE_OLD)
  193236. /* strtod() function is not supported on WindowsCE */
  193237. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193238. {
  193239. double result = 0;
  193240. int len;
  193241. wchar_t *str, *end;
  193242. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193243. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193244. if ( NULL != str )
  193245. {
  193246. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193247. result = wcstod(str, &end);
  193248. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193249. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193250. png_free(png_ptr, str);
  193251. }
  193252. return result;
  193253. }
  193254. # else
  193255. # define png_strtod(p,a,b) strtod(a,b)
  193256. # endif
  193257. #endif
  193258. png_uint_32 PNGAPI
  193259. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193260. {
  193261. png_uint_32 i = png_get_uint_32(buf);
  193262. if (i > PNG_UINT_31_MAX)
  193263. png_error(png_ptr, "PNG unsigned integer out of range.");
  193264. return (i);
  193265. }
  193266. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193267. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193268. png_uint_32 PNGAPI
  193269. png_get_uint_32(png_bytep buf)
  193270. {
  193271. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193272. ((png_uint_32)(*(buf + 1)) << 16) +
  193273. ((png_uint_32)(*(buf + 2)) << 8) +
  193274. (png_uint_32)(*(buf + 3));
  193275. return (i);
  193276. }
  193277. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193278. * data is stored in the PNG file in two's complement format, and it is
  193279. * assumed that the machine format for signed integers is the same. */
  193280. png_int_32 PNGAPI
  193281. png_get_int_32(png_bytep buf)
  193282. {
  193283. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193284. ((png_int_32)(*(buf + 1)) << 16) +
  193285. ((png_int_32)(*(buf + 2)) << 8) +
  193286. (png_int_32)(*(buf + 3));
  193287. return (i);
  193288. }
  193289. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193290. png_uint_16 PNGAPI
  193291. png_get_uint_16(png_bytep buf)
  193292. {
  193293. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193294. (png_uint_16)(*(buf + 1)));
  193295. return (i);
  193296. }
  193297. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193298. /* Read data, and (optionally) run it through the CRC. */
  193299. void /* PRIVATE */
  193300. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193301. {
  193302. if(png_ptr == NULL) return;
  193303. png_read_data(png_ptr, buf, length);
  193304. png_calculate_crc(png_ptr, buf, length);
  193305. }
  193306. /* Optionally skip data and then check the CRC. Depending on whether we
  193307. are reading a ancillary or critical chunk, and how the program has set
  193308. things up, we may calculate the CRC on the data and print a message.
  193309. Returns '1' if there was a CRC error, '0' otherwise. */
  193310. int /* PRIVATE */
  193311. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193312. {
  193313. png_size_t i;
  193314. png_size_t istop = png_ptr->zbuf_size;
  193315. for (i = (png_size_t)skip; i > istop; i -= istop)
  193316. {
  193317. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193318. }
  193319. if (i)
  193320. {
  193321. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193322. }
  193323. if (png_crc_error(png_ptr))
  193324. {
  193325. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193326. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193327. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193328. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193329. {
  193330. png_chunk_warning(png_ptr, "CRC error");
  193331. }
  193332. else
  193333. {
  193334. png_chunk_error(png_ptr, "CRC error");
  193335. }
  193336. return (1);
  193337. }
  193338. return (0);
  193339. }
  193340. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193341. the data it has read thus far. */
  193342. int /* PRIVATE */
  193343. png_crc_error(png_structp png_ptr)
  193344. {
  193345. png_byte crc_bytes[4];
  193346. png_uint_32 crc;
  193347. int need_crc = 1;
  193348. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193349. {
  193350. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193351. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193352. need_crc = 0;
  193353. }
  193354. else /* critical */
  193355. {
  193356. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193357. need_crc = 0;
  193358. }
  193359. png_read_data(png_ptr, crc_bytes, 4);
  193360. if (need_crc)
  193361. {
  193362. crc = png_get_uint_32(crc_bytes);
  193363. return ((int)(crc != png_ptr->crc));
  193364. }
  193365. else
  193366. return (0);
  193367. }
  193368. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193369. defined(PNG_READ_iCCP_SUPPORTED)
  193370. /*
  193371. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193372. * points at an allocated area holding the contents of a chunk with a
  193373. * trailing compressed part. What we get back is an allocated area
  193374. * holding the original prefix part and an uncompressed version of the
  193375. * trailing part (the malloc area passed in is freed).
  193376. */
  193377. png_charp /* PRIVATE */
  193378. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193379. png_charp chunkdata, png_size_t chunklength,
  193380. png_size_t prefix_size, png_size_t *newlength)
  193381. {
  193382. static PNG_CONST char msg[] = "Error decoding compressed text";
  193383. png_charp text;
  193384. png_size_t text_size;
  193385. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193386. {
  193387. int ret = Z_OK;
  193388. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193389. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193390. png_ptr->zstream.next_out = png_ptr->zbuf;
  193391. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193392. text_size = 0;
  193393. text = NULL;
  193394. while (png_ptr->zstream.avail_in)
  193395. {
  193396. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193397. if (ret != Z_OK && ret != Z_STREAM_END)
  193398. {
  193399. if (png_ptr->zstream.msg != NULL)
  193400. png_warning(png_ptr, png_ptr->zstream.msg);
  193401. else
  193402. png_warning(png_ptr, msg);
  193403. inflateReset(&png_ptr->zstream);
  193404. png_ptr->zstream.avail_in = 0;
  193405. if (text == NULL)
  193406. {
  193407. text_size = prefix_size + png_sizeof(msg) + 1;
  193408. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193409. if (text == NULL)
  193410. {
  193411. png_free(png_ptr,chunkdata);
  193412. png_error(png_ptr,"Not enough memory to decompress chunk");
  193413. }
  193414. png_memcpy(text, chunkdata, prefix_size);
  193415. }
  193416. text[text_size - 1] = 0x00;
  193417. /* Copy what we can of the error message into the text chunk */
  193418. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193419. text_size = png_sizeof(msg) > text_size ? text_size :
  193420. png_sizeof(msg);
  193421. png_memcpy(text + prefix_size, msg, text_size + 1);
  193422. break;
  193423. }
  193424. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193425. {
  193426. if (text == NULL)
  193427. {
  193428. text_size = prefix_size +
  193429. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193430. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193431. if (text == NULL)
  193432. {
  193433. png_free(png_ptr,chunkdata);
  193434. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193435. }
  193436. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193437. text_size - prefix_size);
  193438. png_memcpy(text, chunkdata, prefix_size);
  193439. *(text + text_size) = 0x00;
  193440. }
  193441. else
  193442. {
  193443. png_charp tmp;
  193444. tmp = text;
  193445. text = (png_charp)png_malloc_warn(png_ptr,
  193446. (png_uint_32)(text_size +
  193447. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193448. if (text == NULL)
  193449. {
  193450. png_free(png_ptr, tmp);
  193451. png_free(png_ptr, chunkdata);
  193452. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193453. }
  193454. png_memcpy(text, tmp, text_size);
  193455. png_free(png_ptr, tmp);
  193456. png_memcpy(text + text_size, png_ptr->zbuf,
  193457. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193458. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193459. *(text + text_size) = 0x00;
  193460. }
  193461. if (ret == Z_STREAM_END)
  193462. break;
  193463. else
  193464. {
  193465. png_ptr->zstream.next_out = png_ptr->zbuf;
  193466. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193467. }
  193468. }
  193469. }
  193470. if (ret != Z_STREAM_END)
  193471. {
  193472. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193473. char umsg[52];
  193474. if (ret == Z_BUF_ERROR)
  193475. png_snprintf(umsg, 52,
  193476. "Buffer error in compressed datastream in %s chunk",
  193477. png_ptr->chunk_name);
  193478. else if (ret == Z_DATA_ERROR)
  193479. png_snprintf(umsg, 52,
  193480. "Data error in compressed datastream in %s chunk",
  193481. png_ptr->chunk_name);
  193482. else
  193483. png_snprintf(umsg, 52,
  193484. "Incomplete compressed datastream in %s chunk",
  193485. png_ptr->chunk_name);
  193486. png_warning(png_ptr, umsg);
  193487. #else
  193488. png_warning(png_ptr,
  193489. "Incomplete compressed datastream in chunk other than IDAT");
  193490. #endif
  193491. text_size=prefix_size;
  193492. if (text == NULL)
  193493. {
  193494. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193495. if (text == NULL)
  193496. {
  193497. png_free(png_ptr, chunkdata);
  193498. png_error(png_ptr,"Not enough memory for text.");
  193499. }
  193500. png_memcpy(text, chunkdata, prefix_size);
  193501. }
  193502. *(text + text_size) = 0x00;
  193503. }
  193504. inflateReset(&png_ptr->zstream);
  193505. png_ptr->zstream.avail_in = 0;
  193506. png_free(png_ptr, chunkdata);
  193507. chunkdata = text;
  193508. *newlength=text_size;
  193509. }
  193510. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193511. {
  193512. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193513. char umsg[50];
  193514. png_snprintf(umsg, 50,
  193515. "Unknown zTXt compression type %d", comp_type);
  193516. png_warning(png_ptr, umsg);
  193517. #else
  193518. png_warning(png_ptr, "Unknown zTXt compression type");
  193519. #endif
  193520. *(chunkdata + prefix_size) = 0x00;
  193521. *newlength=prefix_size;
  193522. }
  193523. return chunkdata;
  193524. }
  193525. #endif
  193526. /* read and check the IDHR chunk */
  193527. void /* PRIVATE */
  193528. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193529. {
  193530. png_byte buf[13];
  193531. png_uint_32 width, height;
  193532. int bit_depth, color_type, compression_type, filter_type;
  193533. int interlace_type;
  193534. png_debug(1, "in png_handle_IHDR\n");
  193535. if (png_ptr->mode & PNG_HAVE_IHDR)
  193536. png_error(png_ptr, "Out of place IHDR");
  193537. /* check the length */
  193538. if (length != 13)
  193539. png_error(png_ptr, "Invalid IHDR chunk");
  193540. png_ptr->mode |= PNG_HAVE_IHDR;
  193541. png_crc_read(png_ptr, buf, 13);
  193542. png_crc_finish(png_ptr, 0);
  193543. width = png_get_uint_31(png_ptr, buf);
  193544. height = png_get_uint_31(png_ptr, buf + 4);
  193545. bit_depth = buf[8];
  193546. color_type = buf[9];
  193547. compression_type = buf[10];
  193548. filter_type = buf[11];
  193549. interlace_type = buf[12];
  193550. /* set internal variables */
  193551. png_ptr->width = width;
  193552. png_ptr->height = height;
  193553. png_ptr->bit_depth = (png_byte)bit_depth;
  193554. png_ptr->interlaced = (png_byte)interlace_type;
  193555. png_ptr->color_type = (png_byte)color_type;
  193556. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193557. png_ptr->filter_type = (png_byte)filter_type;
  193558. #endif
  193559. png_ptr->compression_type = (png_byte)compression_type;
  193560. /* find number of channels */
  193561. switch (png_ptr->color_type)
  193562. {
  193563. case PNG_COLOR_TYPE_GRAY:
  193564. case PNG_COLOR_TYPE_PALETTE:
  193565. png_ptr->channels = 1;
  193566. break;
  193567. case PNG_COLOR_TYPE_RGB:
  193568. png_ptr->channels = 3;
  193569. break;
  193570. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193571. png_ptr->channels = 2;
  193572. break;
  193573. case PNG_COLOR_TYPE_RGB_ALPHA:
  193574. png_ptr->channels = 4;
  193575. break;
  193576. }
  193577. /* set up other useful info */
  193578. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193579. png_ptr->channels);
  193580. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193581. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193582. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193583. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193584. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193585. color_type, interlace_type, compression_type, filter_type);
  193586. }
  193587. /* read and check the palette */
  193588. void /* PRIVATE */
  193589. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193590. {
  193591. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193592. int num, i;
  193593. #ifndef PNG_NO_POINTER_INDEXING
  193594. png_colorp pal_ptr;
  193595. #endif
  193596. png_debug(1, "in png_handle_PLTE\n");
  193597. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193598. png_error(png_ptr, "Missing IHDR before PLTE");
  193599. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193600. {
  193601. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193602. png_crc_finish(png_ptr, length);
  193603. return;
  193604. }
  193605. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193606. png_error(png_ptr, "Duplicate PLTE chunk");
  193607. png_ptr->mode |= PNG_HAVE_PLTE;
  193608. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193609. {
  193610. png_warning(png_ptr,
  193611. "Ignoring PLTE chunk in grayscale PNG");
  193612. png_crc_finish(png_ptr, length);
  193613. return;
  193614. }
  193615. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193616. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193617. {
  193618. png_crc_finish(png_ptr, length);
  193619. return;
  193620. }
  193621. #endif
  193622. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193623. {
  193624. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193625. {
  193626. png_warning(png_ptr, "Invalid palette chunk");
  193627. png_crc_finish(png_ptr, length);
  193628. return;
  193629. }
  193630. else
  193631. {
  193632. png_error(png_ptr, "Invalid palette chunk");
  193633. }
  193634. }
  193635. num = (int)length / 3;
  193636. #ifndef PNG_NO_POINTER_INDEXING
  193637. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193638. {
  193639. png_byte buf[3];
  193640. png_crc_read(png_ptr, buf, 3);
  193641. pal_ptr->red = buf[0];
  193642. pal_ptr->green = buf[1];
  193643. pal_ptr->blue = buf[2];
  193644. }
  193645. #else
  193646. for (i = 0; i < num; i++)
  193647. {
  193648. png_byte buf[3];
  193649. png_crc_read(png_ptr, buf, 3);
  193650. /* don't depend upon png_color being any order */
  193651. palette[i].red = buf[0];
  193652. palette[i].green = buf[1];
  193653. palette[i].blue = buf[2];
  193654. }
  193655. #endif
  193656. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193657. whatever the normal CRC configuration tells us. However, if we
  193658. have an RGB image, the PLTE can be considered ancillary, so
  193659. we will act as though it is. */
  193660. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193661. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193662. #endif
  193663. {
  193664. png_crc_finish(png_ptr, 0);
  193665. }
  193666. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193667. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193668. {
  193669. /* If we don't want to use the data from an ancillary chunk,
  193670. we have two options: an error abort, or a warning and we
  193671. ignore the data in this chunk (which should be OK, since
  193672. it's considered ancillary for a RGB or RGBA image). */
  193673. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193674. {
  193675. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193676. {
  193677. png_chunk_error(png_ptr, "CRC error");
  193678. }
  193679. else
  193680. {
  193681. png_chunk_warning(png_ptr, "CRC error");
  193682. return;
  193683. }
  193684. }
  193685. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193686. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193687. {
  193688. png_chunk_warning(png_ptr, "CRC error");
  193689. }
  193690. }
  193691. #endif
  193692. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193693. #if defined(PNG_READ_tRNS_SUPPORTED)
  193694. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193695. {
  193696. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193697. {
  193698. if (png_ptr->num_trans > (png_uint_16)num)
  193699. {
  193700. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193701. png_ptr->num_trans = (png_uint_16)num;
  193702. }
  193703. if (info_ptr->num_trans > (png_uint_16)num)
  193704. {
  193705. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193706. info_ptr->num_trans = (png_uint_16)num;
  193707. }
  193708. }
  193709. }
  193710. #endif
  193711. }
  193712. void /* PRIVATE */
  193713. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193714. {
  193715. png_debug(1, "in png_handle_IEND\n");
  193716. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193717. {
  193718. png_error(png_ptr, "No image in file");
  193719. }
  193720. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193721. if (length != 0)
  193722. {
  193723. png_warning(png_ptr, "Incorrect IEND chunk length");
  193724. }
  193725. png_crc_finish(png_ptr, length);
  193726. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193727. }
  193728. #if defined(PNG_READ_gAMA_SUPPORTED)
  193729. void /* PRIVATE */
  193730. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193731. {
  193732. png_fixed_point igamma;
  193733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193734. float file_gamma;
  193735. #endif
  193736. png_byte buf[4];
  193737. png_debug(1, "in png_handle_gAMA\n");
  193738. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193739. png_error(png_ptr, "Missing IHDR before gAMA");
  193740. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193741. {
  193742. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193743. png_crc_finish(png_ptr, length);
  193744. return;
  193745. }
  193746. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193747. /* Should be an error, but we can cope with it */
  193748. png_warning(png_ptr, "Out of place gAMA chunk");
  193749. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193750. #if defined(PNG_READ_sRGB_SUPPORTED)
  193751. && !(info_ptr->valid & PNG_INFO_sRGB)
  193752. #endif
  193753. )
  193754. {
  193755. png_warning(png_ptr, "Duplicate gAMA chunk");
  193756. png_crc_finish(png_ptr, length);
  193757. return;
  193758. }
  193759. if (length != 4)
  193760. {
  193761. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193762. png_crc_finish(png_ptr, length);
  193763. return;
  193764. }
  193765. png_crc_read(png_ptr, buf, 4);
  193766. if (png_crc_finish(png_ptr, 0))
  193767. return;
  193768. igamma = (png_fixed_point)png_get_uint_32(buf);
  193769. /* check for zero gamma */
  193770. if (igamma == 0)
  193771. {
  193772. png_warning(png_ptr,
  193773. "Ignoring gAMA chunk with gamma=0");
  193774. return;
  193775. }
  193776. #if defined(PNG_READ_sRGB_SUPPORTED)
  193777. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193778. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193779. {
  193780. png_warning(png_ptr,
  193781. "Ignoring incorrect gAMA value when sRGB is also present");
  193782. #ifndef PNG_NO_CONSOLE_IO
  193783. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193784. #endif
  193785. return;
  193786. }
  193787. #endif /* PNG_READ_sRGB_SUPPORTED */
  193788. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193789. file_gamma = (float)igamma / (float)100000.0;
  193790. # ifdef PNG_READ_GAMMA_SUPPORTED
  193791. png_ptr->gamma = file_gamma;
  193792. # endif
  193793. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193794. #endif
  193795. #ifdef PNG_FIXED_POINT_SUPPORTED
  193796. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193797. #endif
  193798. }
  193799. #endif
  193800. #if defined(PNG_READ_sBIT_SUPPORTED)
  193801. void /* PRIVATE */
  193802. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193803. {
  193804. png_size_t truelen;
  193805. png_byte buf[4];
  193806. png_debug(1, "in png_handle_sBIT\n");
  193807. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193808. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193809. png_error(png_ptr, "Missing IHDR before sBIT");
  193810. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193811. {
  193812. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193813. png_crc_finish(png_ptr, length);
  193814. return;
  193815. }
  193816. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193817. {
  193818. /* Should be an error, but we can cope with it */
  193819. png_warning(png_ptr, "Out of place sBIT chunk");
  193820. }
  193821. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  193822. {
  193823. png_warning(png_ptr, "Duplicate sBIT chunk");
  193824. png_crc_finish(png_ptr, length);
  193825. return;
  193826. }
  193827. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193828. truelen = 3;
  193829. else
  193830. truelen = (png_size_t)png_ptr->channels;
  193831. if (length != truelen || length > 4)
  193832. {
  193833. png_warning(png_ptr, "Incorrect sBIT chunk length");
  193834. png_crc_finish(png_ptr, length);
  193835. return;
  193836. }
  193837. png_crc_read(png_ptr, buf, truelen);
  193838. if (png_crc_finish(png_ptr, 0))
  193839. return;
  193840. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193841. {
  193842. png_ptr->sig_bit.red = buf[0];
  193843. png_ptr->sig_bit.green = buf[1];
  193844. png_ptr->sig_bit.blue = buf[2];
  193845. png_ptr->sig_bit.alpha = buf[3];
  193846. }
  193847. else
  193848. {
  193849. png_ptr->sig_bit.gray = buf[0];
  193850. png_ptr->sig_bit.red = buf[0];
  193851. png_ptr->sig_bit.green = buf[0];
  193852. png_ptr->sig_bit.blue = buf[0];
  193853. png_ptr->sig_bit.alpha = buf[1];
  193854. }
  193855. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  193856. }
  193857. #endif
  193858. #if defined(PNG_READ_cHRM_SUPPORTED)
  193859. void /* PRIVATE */
  193860. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193861. {
  193862. png_byte buf[4];
  193863. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193864. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193865. #endif
  193866. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193867. int_y_green, int_x_blue, int_y_blue;
  193868. png_uint_32 uint_x, uint_y;
  193869. png_debug(1, "in png_handle_cHRM\n");
  193870. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193871. png_error(png_ptr, "Missing IHDR before cHRM");
  193872. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193873. {
  193874. png_warning(png_ptr, "Invalid cHRM after IDAT");
  193875. png_crc_finish(png_ptr, length);
  193876. return;
  193877. }
  193878. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193879. /* Should be an error, but we can cope with it */
  193880. png_warning(png_ptr, "Missing PLTE before cHRM");
  193881. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  193882. #if defined(PNG_READ_sRGB_SUPPORTED)
  193883. && !(info_ptr->valid & PNG_INFO_sRGB)
  193884. #endif
  193885. )
  193886. {
  193887. png_warning(png_ptr, "Duplicate cHRM chunk");
  193888. png_crc_finish(png_ptr, length);
  193889. return;
  193890. }
  193891. if (length != 32)
  193892. {
  193893. png_warning(png_ptr, "Incorrect cHRM chunk length");
  193894. png_crc_finish(png_ptr, length);
  193895. return;
  193896. }
  193897. png_crc_read(png_ptr, buf, 4);
  193898. uint_x = png_get_uint_32(buf);
  193899. png_crc_read(png_ptr, buf, 4);
  193900. uint_y = png_get_uint_32(buf);
  193901. if (uint_x > 80000L || uint_y > 80000L ||
  193902. uint_x + uint_y > 100000L)
  193903. {
  193904. png_warning(png_ptr, "Invalid cHRM white point");
  193905. png_crc_finish(png_ptr, 24);
  193906. return;
  193907. }
  193908. int_x_white = (png_fixed_point)uint_x;
  193909. int_y_white = (png_fixed_point)uint_y;
  193910. png_crc_read(png_ptr, buf, 4);
  193911. uint_x = png_get_uint_32(buf);
  193912. png_crc_read(png_ptr, buf, 4);
  193913. uint_y = png_get_uint_32(buf);
  193914. if (uint_x + uint_y > 100000L)
  193915. {
  193916. png_warning(png_ptr, "Invalid cHRM red point");
  193917. png_crc_finish(png_ptr, 16);
  193918. return;
  193919. }
  193920. int_x_red = (png_fixed_point)uint_x;
  193921. int_y_red = (png_fixed_point)uint_y;
  193922. png_crc_read(png_ptr, buf, 4);
  193923. uint_x = png_get_uint_32(buf);
  193924. png_crc_read(png_ptr, buf, 4);
  193925. uint_y = png_get_uint_32(buf);
  193926. if (uint_x + uint_y > 100000L)
  193927. {
  193928. png_warning(png_ptr, "Invalid cHRM green point");
  193929. png_crc_finish(png_ptr, 8);
  193930. return;
  193931. }
  193932. int_x_green = (png_fixed_point)uint_x;
  193933. int_y_green = (png_fixed_point)uint_y;
  193934. png_crc_read(png_ptr, buf, 4);
  193935. uint_x = png_get_uint_32(buf);
  193936. png_crc_read(png_ptr, buf, 4);
  193937. uint_y = png_get_uint_32(buf);
  193938. if (uint_x + uint_y > 100000L)
  193939. {
  193940. png_warning(png_ptr, "Invalid cHRM blue point");
  193941. png_crc_finish(png_ptr, 0);
  193942. return;
  193943. }
  193944. int_x_blue = (png_fixed_point)uint_x;
  193945. int_y_blue = (png_fixed_point)uint_y;
  193946. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193947. white_x = (float)int_x_white / (float)100000.0;
  193948. white_y = (float)int_y_white / (float)100000.0;
  193949. red_x = (float)int_x_red / (float)100000.0;
  193950. red_y = (float)int_y_red / (float)100000.0;
  193951. green_x = (float)int_x_green / (float)100000.0;
  193952. green_y = (float)int_y_green / (float)100000.0;
  193953. blue_x = (float)int_x_blue / (float)100000.0;
  193954. blue_y = (float)int_y_blue / (float)100000.0;
  193955. #endif
  193956. #if defined(PNG_READ_sRGB_SUPPORTED)
  193957. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  193958. {
  193959. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  193960. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  193961. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  193962. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  193963. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  193964. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  193965. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  193966. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  193967. {
  193968. png_warning(png_ptr,
  193969. "Ignoring incorrect cHRM value when sRGB is also present");
  193970. #ifndef PNG_NO_CONSOLE_IO
  193971. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193972. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  193973. white_x, white_y, red_x, red_y);
  193974. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  193975. green_x, green_y, blue_x, blue_y);
  193976. #else
  193977. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  193978. int_x_white, int_y_white, int_x_red, int_y_red);
  193979. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  193980. int_x_green, int_y_green, int_x_blue, int_y_blue);
  193981. #endif
  193982. #endif /* PNG_NO_CONSOLE_IO */
  193983. }
  193984. png_crc_finish(png_ptr, 0);
  193985. return;
  193986. }
  193987. #endif /* PNG_READ_sRGB_SUPPORTED */
  193988. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193989. png_set_cHRM(png_ptr, info_ptr,
  193990. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193991. #endif
  193992. #ifdef PNG_FIXED_POINT_SUPPORTED
  193993. png_set_cHRM_fixed(png_ptr, info_ptr,
  193994. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193995. int_y_green, int_x_blue, int_y_blue);
  193996. #endif
  193997. if (png_crc_finish(png_ptr, 0))
  193998. return;
  193999. }
  194000. #endif
  194001. #if defined(PNG_READ_sRGB_SUPPORTED)
  194002. void /* PRIVATE */
  194003. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194004. {
  194005. int intent;
  194006. png_byte buf[1];
  194007. png_debug(1, "in png_handle_sRGB\n");
  194008. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194009. png_error(png_ptr, "Missing IHDR before sRGB");
  194010. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194011. {
  194012. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194013. png_crc_finish(png_ptr, length);
  194014. return;
  194015. }
  194016. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194017. /* Should be an error, but we can cope with it */
  194018. png_warning(png_ptr, "Out of place sRGB chunk");
  194019. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194020. {
  194021. png_warning(png_ptr, "Duplicate sRGB chunk");
  194022. png_crc_finish(png_ptr, length);
  194023. return;
  194024. }
  194025. if (length != 1)
  194026. {
  194027. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194028. png_crc_finish(png_ptr, length);
  194029. return;
  194030. }
  194031. png_crc_read(png_ptr, buf, 1);
  194032. if (png_crc_finish(png_ptr, 0))
  194033. return;
  194034. intent = buf[0];
  194035. /* check for bad intent */
  194036. if (intent >= PNG_sRGB_INTENT_LAST)
  194037. {
  194038. png_warning(png_ptr, "Unknown sRGB intent");
  194039. return;
  194040. }
  194041. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194042. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194043. {
  194044. png_fixed_point igamma;
  194045. #ifdef PNG_FIXED_POINT_SUPPORTED
  194046. igamma=info_ptr->int_gamma;
  194047. #else
  194048. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194049. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194050. # endif
  194051. #endif
  194052. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194053. {
  194054. png_warning(png_ptr,
  194055. "Ignoring incorrect gAMA value when sRGB is also present");
  194056. #ifndef PNG_NO_CONSOLE_IO
  194057. # ifdef PNG_FIXED_POINT_SUPPORTED
  194058. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194059. # else
  194060. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194061. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194062. # endif
  194063. # endif
  194064. #endif
  194065. }
  194066. }
  194067. #endif /* PNG_READ_gAMA_SUPPORTED */
  194068. #ifdef PNG_READ_cHRM_SUPPORTED
  194069. #ifdef PNG_FIXED_POINT_SUPPORTED
  194070. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194071. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194072. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194073. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194074. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194075. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194076. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194077. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194078. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194079. {
  194080. png_warning(png_ptr,
  194081. "Ignoring incorrect cHRM value when sRGB is also present");
  194082. }
  194083. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194084. #endif /* PNG_READ_cHRM_SUPPORTED */
  194085. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194086. }
  194087. #endif /* PNG_READ_sRGB_SUPPORTED */
  194088. #if defined(PNG_READ_iCCP_SUPPORTED)
  194089. void /* PRIVATE */
  194090. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194091. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194092. {
  194093. png_charp chunkdata;
  194094. png_byte compression_type;
  194095. png_bytep pC;
  194096. png_charp profile;
  194097. png_uint_32 skip = 0;
  194098. png_uint_32 profile_size, profile_length;
  194099. png_size_t slength, prefix_length, data_length;
  194100. png_debug(1, "in png_handle_iCCP\n");
  194101. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194102. png_error(png_ptr, "Missing IHDR before iCCP");
  194103. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194104. {
  194105. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194106. png_crc_finish(png_ptr, length);
  194107. return;
  194108. }
  194109. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194110. /* Should be an error, but we can cope with it */
  194111. png_warning(png_ptr, "Out of place iCCP chunk");
  194112. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194113. {
  194114. png_warning(png_ptr, "Duplicate iCCP chunk");
  194115. png_crc_finish(png_ptr, length);
  194116. return;
  194117. }
  194118. #ifdef PNG_MAX_MALLOC_64K
  194119. if (length > (png_uint_32)65535L)
  194120. {
  194121. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194122. skip = length - (png_uint_32)65535L;
  194123. length = (png_uint_32)65535L;
  194124. }
  194125. #endif
  194126. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194127. slength = (png_size_t)length;
  194128. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194129. if (png_crc_finish(png_ptr, skip))
  194130. {
  194131. png_free(png_ptr, chunkdata);
  194132. return;
  194133. }
  194134. chunkdata[slength] = 0x00;
  194135. for (profile = chunkdata; *profile; profile++)
  194136. /* empty loop to find end of name */ ;
  194137. ++profile;
  194138. /* there should be at least one zero (the compression type byte)
  194139. following the separator, and we should be on it */
  194140. if ( profile >= chunkdata + slength - 1)
  194141. {
  194142. png_free(png_ptr, chunkdata);
  194143. png_warning(png_ptr, "Malformed iCCP chunk");
  194144. return;
  194145. }
  194146. /* compression_type should always be zero */
  194147. compression_type = *profile++;
  194148. if (compression_type)
  194149. {
  194150. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194151. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194152. wrote nonzero) */
  194153. }
  194154. prefix_length = profile - chunkdata;
  194155. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194156. slength, prefix_length, &data_length);
  194157. profile_length = data_length - prefix_length;
  194158. if ( prefix_length > data_length || profile_length < 4)
  194159. {
  194160. png_free(png_ptr, chunkdata);
  194161. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194162. return;
  194163. }
  194164. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194165. pC = (png_bytep)(chunkdata+prefix_length);
  194166. profile_size = ((*(pC ))<<24) |
  194167. ((*(pC+1))<<16) |
  194168. ((*(pC+2))<< 8) |
  194169. ((*(pC+3)) );
  194170. if(profile_size < profile_length)
  194171. profile_length = profile_size;
  194172. if(profile_size > profile_length)
  194173. {
  194174. png_free(png_ptr, chunkdata);
  194175. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194176. return;
  194177. }
  194178. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194179. chunkdata + prefix_length, profile_length);
  194180. png_free(png_ptr, chunkdata);
  194181. }
  194182. #endif /* PNG_READ_iCCP_SUPPORTED */
  194183. #if defined(PNG_READ_sPLT_SUPPORTED)
  194184. void /* PRIVATE */
  194185. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194186. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194187. {
  194188. png_bytep chunkdata;
  194189. png_bytep entry_start;
  194190. png_sPLT_t new_palette;
  194191. #ifdef PNG_NO_POINTER_INDEXING
  194192. png_sPLT_entryp pp;
  194193. #endif
  194194. int data_length, entry_size, i;
  194195. png_uint_32 skip = 0;
  194196. png_size_t slength;
  194197. png_debug(1, "in png_handle_sPLT\n");
  194198. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194199. png_error(png_ptr, "Missing IHDR before sPLT");
  194200. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194201. {
  194202. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194203. png_crc_finish(png_ptr, length);
  194204. return;
  194205. }
  194206. #ifdef PNG_MAX_MALLOC_64K
  194207. if (length > (png_uint_32)65535L)
  194208. {
  194209. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194210. skip = length - (png_uint_32)65535L;
  194211. length = (png_uint_32)65535L;
  194212. }
  194213. #endif
  194214. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194215. slength = (png_size_t)length;
  194216. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194217. if (png_crc_finish(png_ptr, skip))
  194218. {
  194219. png_free(png_ptr, chunkdata);
  194220. return;
  194221. }
  194222. chunkdata[slength] = 0x00;
  194223. for (entry_start = chunkdata; *entry_start; entry_start++)
  194224. /* empty loop to find end of name */ ;
  194225. ++entry_start;
  194226. /* a sample depth should follow the separator, and we should be on it */
  194227. if (entry_start > chunkdata + slength - 2)
  194228. {
  194229. png_free(png_ptr, chunkdata);
  194230. png_warning(png_ptr, "malformed sPLT chunk");
  194231. return;
  194232. }
  194233. new_palette.depth = *entry_start++;
  194234. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194235. data_length = (slength - (entry_start - chunkdata));
  194236. /* integrity-check the data length */
  194237. if (data_length % entry_size)
  194238. {
  194239. png_free(png_ptr, chunkdata);
  194240. png_warning(png_ptr, "sPLT chunk has bad length");
  194241. return;
  194242. }
  194243. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194244. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194245. png_sizeof(png_sPLT_entry)))
  194246. {
  194247. png_warning(png_ptr, "sPLT chunk too long");
  194248. return;
  194249. }
  194250. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194251. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194252. if (new_palette.entries == NULL)
  194253. {
  194254. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194255. return;
  194256. }
  194257. #ifndef PNG_NO_POINTER_INDEXING
  194258. for (i = 0; i < new_palette.nentries; i++)
  194259. {
  194260. png_sPLT_entryp pp = new_palette.entries + i;
  194261. if (new_palette.depth == 8)
  194262. {
  194263. pp->red = *entry_start++;
  194264. pp->green = *entry_start++;
  194265. pp->blue = *entry_start++;
  194266. pp->alpha = *entry_start++;
  194267. }
  194268. else
  194269. {
  194270. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194271. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194272. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194273. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194274. }
  194275. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194276. }
  194277. #else
  194278. pp = new_palette.entries;
  194279. for (i = 0; i < new_palette.nentries; i++)
  194280. {
  194281. if (new_palette.depth == 8)
  194282. {
  194283. pp[i].red = *entry_start++;
  194284. pp[i].green = *entry_start++;
  194285. pp[i].blue = *entry_start++;
  194286. pp[i].alpha = *entry_start++;
  194287. }
  194288. else
  194289. {
  194290. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194291. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194292. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194293. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194294. }
  194295. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194296. }
  194297. #endif
  194298. /* discard all chunk data except the name and stash that */
  194299. new_palette.name = (png_charp)chunkdata;
  194300. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194301. png_free(png_ptr, chunkdata);
  194302. png_free(png_ptr, new_palette.entries);
  194303. }
  194304. #endif /* PNG_READ_sPLT_SUPPORTED */
  194305. #if defined(PNG_READ_tRNS_SUPPORTED)
  194306. void /* PRIVATE */
  194307. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194308. {
  194309. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194310. int bit_mask;
  194311. png_debug(1, "in png_handle_tRNS\n");
  194312. /* For non-indexed color, mask off any bits in the tRNS value that
  194313. * exceed the bit depth. Some creators were writing extra bits there.
  194314. * This is not needed for indexed color. */
  194315. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194316. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194317. png_error(png_ptr, "Missing IHDR before tRNS");
  194318. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194319. {
  194320. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194321. png_crc_finish(png_ptr, length);
  194322. return;
  194323. }
  194324. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194325. {
  194326. png_warning(png_ptr, "Duplicate tRNS chunk");
  194327. png_crc_finish(png_ptr, length);
  194328. return;
  194329. }
  194330. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194331. {
  194332. png_byte buf[2];
  194333. if (length != 2)
  194334. {
  194335. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194336. png_crc_finish(png_ptr, length);
  194337. return;
  194338. }
  194339. png_crc_read(png_ptr, buf, 2);
  194340. png_ptr->num_trans = 1;
  194341. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194342. }
  194343. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194344. {
  194345. png_byte buf[6];
  194346. if (length != 6)
  194347. {
  194348. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194349. png_crc_finish(png_ptr, length);
  194350. return;
  194351. }
  194352. png_crc_read(png_ptr, buf, (png_size_t)length);
  194353. png_ptr->num_trans = 1;
  194354. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194355. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194356. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194357. }
  194358. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194359. {
  194360. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194361. {
  194362. /* Should be an error, but we can cope with it. */
  194363. png_warning(png_ptr, "Missing PLTE before tRNS");
  194364. }
  194365. if (length > (png_uint_32)png_ptr->num_palette ||
  194366. length > PNG_MAX_PALETTE_LENGTH)
  194367. {
  194368. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194369. png_crc_finish(png_ptr, length);
  194370. return;
  194371. }
  194372. if (length == 0)
  194373. {
  194374. png_warning(png_ptr, "Zero length tRNS chunk");
  194375. png_crc_finish(png_ptr, length);
  194376. return;
  194377. }
  194378. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194379. png_ptr->num_trans = (png_uint_16)length;
  194380. }
  194381. else
  194382. {
  194383. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194384. png_crc_finish(png_ptr, length);
  194385. return;
  194386. }
  194387. if (png_crc_finish(png_ptr, 0))
  194388. {
  194389. png_ptr->num_trans = 0;
  194390. return;
  194391. }
  194392. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194393. &(png_ptr->trans_values));
  194394. }
  194395. #endif
  194396. #if defined(PNG_READ_bKGD_SUPPORTED)
  194397. void /* PRIVATE */
  194398. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194399. {
  194400. png_size_t truelen;
  194401. png_byte buf[6];
  194402. png_debug(1, "in png_handle_bKGD\n");
  194403. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194404. png_error(png_ptr, "Missing IHDR before bKGD");
  194405. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194406. {
  194407. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194408. png_crc_finish(png_ptr, length);
  194409. return;
  194410. }
  194411. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194412. !(png_ptr->mode & PNG_HAVE_PLTE))
  194413. {
  194414. png_warning(png_ptr, "Missing PLTE before bKGD");
  194415. png_crc_finish(png_ptr, length);
  194416. return;
  194417. }
  194418. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194419. {
  194420. png_warning(png_ptr, "Duplicate bKGD chunk");
  194421. png_crc_finish(png_ptr, length);
  194422. return;
  194423. }
  194424. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194425. truelen = 1;
  194426. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194427. truelen = 6;
  194428. else
  194429. truelen = 2;
  194430. if (length != truelen)
  194431. {
  194432. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194433. png_crc_finish(png_ptr, length);
  194434. return;
  194435. }
  194436. png_crc_read(png_ptr, buf, truelen);
  194437. if (png_crc_finish(png_ptr, 0))
  194438. return;
  194439. /* We convert the index value into RGB components so that we can allow
  194440. * arbitrary RGB values for background when we have transparency, and
  194441. * so it is easy to determine the RGB values of the background color
  194442. * from the info_ptr struct. */
  194443. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194444. {
  194445. png_ptr->background.index = buf[0];
  194446. if(info_ptr->num_palette)
  194447. {
  194448. if(buf[0] > info_ptr->num_palette)
  194449. {
  194450. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194451. return;
  194452. }
  194453. png_ptr->background.red =
  194454. (png_uint_16)png_ptr->palette[buf[0]].red;
  194455. png_ptr->background.green =
  194456. (png_uint_16)png_ptr->palette[buf[0]].green;
  194457. png_ptr->background.blue =
  194458. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194459. }
  194460. }
  194461. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194462. {
  194463. png_ptr->background.red =
  194464. png_ptr->background.green =
  194465. png_ptr->background.blue =
  194466. png_ptr->background.gray = png_get_uint_16(buf);
  194467. }
  194468. else
  194469. {
  194470. png_ptr->background.red = png_get_uint_16(buf);
  194471. png_ptr->background.green = png_get_uint_16(buf + 2);
  194472. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194473. }
  194474. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194475. }
  194476. #endif
  194477. #if defined(PNG_READ_hIST_SUPPORTED)
  194478. void /* PRIVATE */
  194479. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194480. {
  194481. unsigned int num, i;
  194482. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194483. png_debug(1, "in png_handle_hIST\n");
  194484. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194485. png_error(png_ptr, "Missing IHDR before hIST");
  194486. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194487. {
  194488. png_warning(png_ptr, "Invalid hIST after IDAT");
  194489. png_crc_finish(png_ptr, length);
  194490. return;
  194491. }
  194492. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194493. {
  194494. png_warning(png_ptr, "Missing PLTE before hIST");
  194495. png_crc_finish(png_ptr, length);
  194496. return;
  194497. }
  194498. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194499. {
  194500. png_warning(png_ptr, "Duplicate hIST chunk");
  194501. png_crc_finish(png_ptr, length);
  194502. return;
  194503. }
  194504. num = length / 2 ;
  194505. if (num != (unsigned int) png_ptr->num_palette || num >
  194506. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194507. {
  194508. png_warning(png_ptr, "Incorrect hIST chunk length");
  194509. png_crc_finish(png_ptr, length);
  194510. return;
  194511. }
  194512. for (i = 0; i < num; i++)
  194513. {
  194514. png_byte buf[2];
  194515. png_crc_read(png_ptr, buf, 2);
  194516. readbuf[i] = png_get_uint_16(buf);
  194517. }
  194518. if (png_crc_finish(png_ptr, 0))
  194519. return;
  194520. png_set_hIST(png_ptr, info_ptr, readbuf);
  194521. }
  194522. #endif
  194523. #if defined(PNG_READ_pHYs_SUPPORTED)
  194524. void /* PRIVATE */
  194525. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194526. {
  194527. png_byte buf[9];
  194528. png_uint_32 res_x, res_y;
  194529. int unit_type;
  194530. png_debug(1, "in png_handle_pHYs\n");
  194531. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194532. png_error(png_ptr, "Missing IHDR before pHYs");
  194533. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194534. {
  194535. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194536. png_crc_finish(png_ptr, length);
  194537. return;
  194538. }
  194539. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194540. {
  194541. png_warning(png_ptr, "Duplicate pHYs chunk");
  194542. png_crc_finish(png_ptr, length);
  194543. return;
  194544. }
  194545. if (length != 9)
  194546. {
  194547. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194548. png_crc_finish(png_ptr, length);
  194549. return;
  194550. }
  194551. png_crc_read(png_ptr, buf, 9);
  194552. if (png_crc_finish(png_ptr, 0))
  194553. return;
  194554. res_x = png_get_uint_32(buf);
  194555. res_y = png_get_uint_32(buf + 4);
  194556. unit_type = buf[8];
  194557. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194558. }
  194559. #endif
  194560. #if defined(PNG_READ_oFFs_SUPPORTED)
  194561. void /* PRIVATE */
  194562. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194563. {
  194564. png_byte buf[9];
  194565. png_int_32 offset_x, offset_y;
  194566. int unit_type;
  194567. png_debug(1, "in png_handle_oFFs\n");
  194568. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194569. png_error(png_ptr, "Missing IHDR before oFFs");
  194570. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194571. {
  194572. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194573. png_crc_finish(png_ptr, length);
  194574. return;
  194575. }
  194576. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194577. {
  194578. png_warning(png_ptr, "Duplicate oFFs chunk");
  194579. png_crc_finish(png_ptr, length);
  194580. return;
  194581. }
  194582. if (length != 9)
  194583. {
  194584. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194585. png_crc_finish(png_ptr, length);
  194586. return;
  194587. }
  194588. png_crc_read(png_ptr, buf, 9);
  194589. if (png_crc_finish(png_ptr, 0))
  194590. return;
  194591. offset_x = png_get_int_32(buf);
  194592. offset_y = png_get_int_32(buf + 4);
  194593. unit_type = buf[8];
  194594. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194595. }
  194596. #endif
  194597. #if defined(PNG_READ_pCAL_SUPPORTED)
  194598. /* read the pCAL chunk (described in the PNG Extensions document) */
  194599. void /* PRIVATE */
  194600. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194601. {
  194602. png_charp purpose;
  194603. png_int_32 X0, X1;
  194604. png_byte type, nparams;
  194605. png_charp buf, units, endptr;
  194606. png_charpp params;
  194607. png_size_t slength;
  194608. int i;
  194609. png_debug(1, "in png_handle_pCAL\n");
  194610. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194611. png_error(png_ptr, "Missing IHDR before pCAL");
  194612. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194613. {
  194614. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194615. png_crc_finish(png_ptr, length);
  194616. return;
  194617. }
  194618. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194619. {
  194620. png_warning(png_ptr, "Duplicate pCAL chunk");
  194621. png_crc_finish(png_ptr, length);
  194622. return;
  194623. }
  194624. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194625. length + 1);
  194626. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194627. if (purpose == NULL)
  194628. {
  194629. png_warning(png_ptr, "No memory for pCAL purpose.");
  194630. return;
  194631. }
  194632. slength = (png_size_t)length;
  194633. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194634. if (png_crc_finish(png_ptr, 0))
  194635. {
  194636. png_free(png_ptr, purpose);
  194637. return;
  194638. }
  194639. purpose[slength] = 0x00; /* null terminate the last string */
  194640. png_debug(3, "Finding end of pCAL purpose string\n");
  194641. for (buf = purpose; *buf; buf++)
  194642. /* empty loop */ ;
  194643. endptr = purpose + slength;
  194644. /* We need to have at least 12 bytes after the purpose string
  194645. in order to get the parameter information. */
  194646. if (endptr <= buf + 12)
  194647. {
  194648. png_warning(png_ptr, "Invalid pCAL data");
  194649. png_free(png_ptr, purpose);
  194650. return;
  194651. }
  194652. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194653. X0 = png_get_int_32((png_bytep)buf+1);
  194654. X1 = png_get_int_32((png_bytep)buf+5);
  194655. type = buf[9];
  194656. nparams = buf[10];
  194657. units = buf + 11;
  194658. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194659. /* Check that we have the right number of parameters for known
  194660. equation types. */
  194661. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194662. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194663. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194664. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194665. {
  194666. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194667. png_free(png_ptr, purpose);
  194668. return;
  194669. }
  194670. else if (type >= PNG_EQUATION_LAST)
  194671. {
  194672. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194673. }
  194674. for (buf = units; *buf; buf++)
  194675. /* Empty loop to move past the units string. */ ;
  194676. png_debug(3, "Allocating pCAL parameters array\n");
  194677. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194678. *png_sizeof(png_charp))) ;
  194679. if (params == NULL)
  194680. {
  194681. png_free(png_ptr, purpose);
  194682. png_warning(png_ptr, "No memory for pCAL params.");
  194683. return;
  194684. }
  194685. /* Get pointers to the start of each parameter string. */
  194686. for (i = 0; i < (int)nparams; i++)
  194687. {
  194688. buf++; /* Skip the null string terminator from previous parameter. */
  194689. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194690. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194691. /* Empty loop to move past each parameter string */ ;
  194692. /* Make sure we haven't run out of data yet */
  194693. if (buf > endptr)
  194694. {
  194695. png_warning(png_ptr, "Invalid pCAL data");
  194696. png_free(png_ptr, purpose);
  194697. png_free(png_ptr, params);
  194698. return;
  194699. }
  194700. }
  194701. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194702. units, params);
  194703. png_free(png_ptr, purpose);
  194704. png_free(png_ptr, params);
  194705. }
  194706. #endif
  194707. #if defined(PNG_READ_sCAL_SUPPORTED)
  194708. /* read the sCAL chunk */
  194709. void /* PRIVATE */
  194710. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194711. {
  194712. png_charp buffer, ep;
  194713. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194714. double width, height;
  194715. png_charp vp;
  194716. #else
  194717. #ifdef PNG_FIXED_POINT_SUPPORTED
  194718. png_charp swidth, sheight;
  194719. #endif
  194720. #endif
  194721. png_size_t slength;
  194722. png_debug(1, "in png_handle_sCAL\n");
  194723. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194724. png_error(png_ptr, "Missing IHDR before sCAL");
  194725. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194726. {
  194727. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194728. png_crc_finish(png_ptr, length);
  194729. return;
  194730. }
  194731. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194732. {
  194733. png_warning(png_ptr, "Duplicate sCAL chunk");
  194734. png_crc_finish(png_ptr, length);
  194735. return;
  194736. }
  194737. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194738. length + 1);
  194739. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194740. if (buffer == NULL)
  194741. {
  194742. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194743. return;
  194744. }
  194745. slength = (png_size_t)length;
  194746. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194747. if (png_crc_finish(png_ptr, 0))
  194748. {
  194749. png_free(png_ptr, buffer);
  194750. return;
  194751. }
  194752. buffer[slength] = 0x00; /* null terminate the last string */
  194753. ep = buffer + 1; /* skip unit byte */
  194754. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194755. width = png_strtod(png_ptr, ep, &vp);
  194756. if (*vp)
  194757. {
  194758. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194759. return;
  194760. }
  194761. #else
  194762. #ifdef PNG_FIXED_POINT_SUPPORTED
  194763. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194764. if (swidth == NULL)
  194765. {
  194766. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194767. return;
  194768. }
  194769. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194770. #endif
  194771. #endif
  194772. for (ep = buffer; *ep; ep++)
  194773. /* empty loop */ ;
  194774. ep++;
  194775. if (buffer + slength < ep)
  194776. {
  194777. png_warning(png_ptr, "Truncated sCAL chunk");
  194778. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194779. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194780. png_free(png_ptr, swidth);
  194781. #endif
  194782. png_free(png_ptr, buffer);
  194783. return;
  194784. }
  194785. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194786. height = png_strtod(png_ptr, ep, &vp);
  194787. if (*vp)
  194788. {
  194789. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194790. return;
  194791. }
  194792. #else
  194793. #ifdef PNG_FIXED_POINT_SUPPORTED
  194794. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194795. if (swidth == NULL)
  194796. {
  194797. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194798. return;
  194799. }
  194800. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194801. #endif
  194802. #endif
  194803. if (buffer + slength < ep
  194804. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194805. || width <= 0. || height <= 0.
  194806. #endif
  194807. )
  194808. {
  194809. png_warning(png_ptr, "Invalid sCAL data");
  194810. png_free(png_ptr, buffer);
  194811. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194812. png_free(png_ptr, swidth);
  194813. png_free(png_ptr, sheight);
  194814. #endif
  194815. return;
  194816. }
  194817. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194818. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194819. #else
  194820. #ifdef PNG_FIXED_POINT_SUPPORTED
  194821. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  194822. #endif
  194823. #endif
  194824. png_free(png_ptr, buffer);
  194825. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194826. png_free(png_ptr, swidth);
  194827. png_free(png_ptr, sheight);
  194828. #endif
  194829. }
  194830. #endif
  194831. #if defined(PNG_READ_tIME_SUPPORTED)
  194832. void /* PRIVATE */
  194833. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194834. {
  194835. png_byte buf[7];
  194836. png_time mod_time;
  194837. png_debug(1, "in png_handle_tIME\n");
  194838. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194839. png_error(png_ptr, "Out of place tIME chunk");
  194840. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  194841. {
  194842. png_warning(png_ptr, "Duplicate tIME chunk");
  194843. png_crc_finish(png_ptr, length);
  194844. return;
  194845. }
  194846. if (png_ptr->mode & PNG_HAVE_IDAT)
  194847. png_ptr->mode |= PNG_AFTER_IDAT;
  194848. if (length != 7)
  194849. {
  194850. png_warning(png_ptr, "Incorrect tIME chunk length");
  194851. png_crc_finish(png_ptr, length);
  194852. return;
  194853. }
  194854. png_crc_read(png_ptr, buf, 7);
  194855. if (png_crc_finish(png_ptr, 0))
  194856. return;
  194857. mod_time.second = buf[6];
  194858. mod_time.minute = buf[5];
  194859. mod_time.hour = buf[4];
  194860. mod_time.day = buf[3];
  194861. mod_time.month = buf[2];
  194862. mod_time.year = png_get_uint_16(buf);
  194863. png_set_tIME(png_ptr, info_ptr, &mod_time);
  194864. }
  194865. #endif
  194866. #if defined(PNG_READ_tEXt_SUPPORTED)
  194867. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194868. void /* PRIVATE */
  194869. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194870. {
  194871. png_textp text_ptr;
  194872. png_charp key;
  194873. png_charp text;
  194874. png_uint_32 skip = 0;
  194875. png_size_t slength;
  194876. int ret;
  194877. png_debug(1, "in png_handle_tEXt\n");
  194878. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194879. png_error(png_ptr, "Missing IHDR before tEXt");
  194880. if (png_ptr->mode & PNG_HAVE_IDAT)
  194881. png_ptr->mode |= PNG_AFTER_IDAT;
  194882. #ifdef PNG_MAX_MALLOC_64K
  194883. if (length > (png_uint_32)65535L)
  194884. {
  194885. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  194886. skip = length - (png_uint_32)65535L;
  194887. length = (png_uint_32)65535L;
  194888. }
  194889. #endif
  194890. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194891. if (key == NULL)
  194892. {
  194893. png_warning(png_ptr, "No memory to process text chunk.");
  194894. return;
  194895. }
  194896. slength = (png_size_t)length;
  194897. png_crc_read(png_ptr, (png_bytep)key, slength);
  194898. if (png_crc_finish(png_ptr, skip))
  194899. {
  194900. png_free(png_ptr, key);
  194901. return;
  194902. }
  194903. key[slength] = 0x00;
  194904. for (text = key; *text; text++)
  194905. /* empty loop to find end of key */ ;
  194906. if (text != key + slength)
  194907. text++;
  194908. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194909. (png_uint_32)png_sizeof(png_text));
  194910. if (text_ptr == NULL)
  194911. {
  194912. png_warning(png_ptr, "Not enough memory to process text chunk.");
  194913. png_free(png_ptr, key);
  194914. return;
  194915. }
  194916. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  194917. text_ptr->key = key;
  194918. #ifdef PNG_iTXt_SUPPORTED
  194919. text_ptr->lang = NULL;
  194920. text_ptr->lang_key = NULL;
  194921. text_ptr->itxt_length = 0;
  194922. #endif
  194923. text_ptr->text = text;
  194924. text_ptr->text_length = png_strlen(text);
  194925. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194926. png_free(png_ptr, key);
  194927. png_free(png_ptr, text_ptr);
  194928. if (ret)
  194929. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  194930. }
  194931. #endif
  194932. #if defined(PNG_READ_zTXt_SUPPORTED)
  194933. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194934. void /* PRIVATE */
  194935. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194936. {
  194937. png_textp text_ptr;
  194938. png_charp chunkdata;
  194939. png_charp text;
  194940. int comp_type;
  194941. int ret;
  194942. png_size_t slength, prefix_len, data_len;
  194943. png_debug(1, "in png_handle_zTXt\n");
  194944. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194945. png_error(png_ptr, "Missing IHDR before zTXt");
  194946. if (png_ptr->mode & PNG_HAVE_IDAT)
  194947. png_ptr->mode |= PNG_AFTER_IDAT;
  194948. #ifdef PNG_MAX_MALLOC_64K
  194949. /* We will no doubt have problems with chunks even half this size, but
  194950. there is no hard and fast rule to tell us where to stop. */
  194951. if (length > (png_uint_32)65535L)
  194952. {
  194953. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  194954. png_crc_finish(png_ptr, length);
  194955. return;
  194956. }
  194957. #endif
  194958. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194959. if (chunkdata == NULL)
  194960. {
  194961. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  194962. return;
  194963. }
  194964. slength = (png_size_t)length;
  194965. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194966. if (png_crc_finish(png_ptr, 0))
  194967. {
  194968. png_free(png_ptr, chunkdata);
  194969. return;
  194970. }
  194971. chunkdata[slength] = 0x00;
  194972. for (text = chunkdata; *text; text++)
  194973. /* empty loop */ ;
  194974. /* zTXt must have some text after the chunkdataword */
  194975. if (text >= chunkdata + slength - 2)
  194976. {
  194977. png_warning(png_ptr, "Truncated zTXt chunk");
  194978. png_free(png_ptr, chunkdata);
  194979. return;
  194980. }
  194981. else
  194982. {
  194983. comp_type = *(++text);
  194984. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  194985. {
  194986. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  194987. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  194988. }
  194989. text++; /* skip the compression_method byte */
  194990. }
  194991. prefix_len = text - chunkdata;
  194992. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194993. (png_size_t)length, prefix_len, &data_len);
  194994. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194995. (png_uint_32)png_sizeof(png_text));
  194996. if (text_ptr == NULL)
  194997. {
  194998. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  194999. png_free(png_ptr, chunkdata);
  195000. return;
  195001. }
  195002. text_ptr->compression = comp_type;
  195003. text_ptr->key = chunkdata;
  195004. #ifdef PNG_iTXt_SUPPORTED
  195005. text_ptr->lang = NULL;
  195006. text_ptr->lang_key = NULL;
  195007. text_ptr->itxt_length = 0;
  195008. #endif
  195009. text_ptr->text = chunkdata + prefix_len;
  195010. text_ptr->text_length = data_len;
  195011. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195012. png_free(png_ptr, text_ptr);
  195013. png_free(png_ptr, chunkdata);
  195014. if (ret)
  195015. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195016. }
  195017. #endif
  195018. #if defined(PNG_READ_iTXt_SUPPORTED)
  195019. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195020. void /* PRIVATE */
  195021. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195022. {
  195023. png_textp text_ptr;
  195024. png_charp chunkdata;
  195025. png_charp key, lang, text, lang_key;
  195026. int comp_flag;
  195027. int comp_type = 0;
  195028. int ret;
  195029. png_size_t slength, prefix_len, data_len;
  195030. png_debug(1, "in png_handle_iTXt\n");
  195031. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195032. png_error(png_ptr, "Missing IHDR before iTXt");
  195033. if (png_ptr->mode & PNG_HAVE_IDAT)
  195034. png_ptr->mode |= PNG_AFTER_IDAT;
  195035. #ifdef PNG_MAX_MALLOC_64K
  195036. /* We will no doubt have problems with chunks even half this size, but
  195037. there is no hard and fast rule to tell us where to stop. */
  195038. if (length > (png_uint_32)65535L)
  195039. {
  195040. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195041. png_crc_finish(png_ptr, length);
  195042. return;
  195043. }
  195044. #endif
  195045. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195046. if (chunkdata == NULL)
  195047. {
  195048. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195049. return;
  195050. }
  195051. slength = (png_size_t)length;
  195052. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195053. if (png_crc_finish(png_ptr, 0))
  195054. {
  195055. png_free(png_ptr, chunkdata);
  195056. return;
  195057. }
  195058. chunkdata[slength] = 0x00;
  195059. for (lang = chunkdata; *lang; lang++)
  195060. /* empty loop */ ;
  195061. lang++; /* skip NUL separator */
  195062. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195063. translated keyword (possibly empty), and possibly some text after the
  195064. keyword */
  195065. if (lang >= chunkdata + slength - 3)
  195066. {
  195067. png_warning(png_ptr, "Truncated iTXt chunk");
  195068. png_free(png_ptr, chunkdata);
  195069. return;
  195070. }
  195071. else
  195072. {
  195073. comp_flag = *lang++;
  195074. comp_type = *lang++;
  195075. }
  195076. for (lang_key = lang; *lang_key; lang_key++)
  195077. /* empty loop */ ;
  195078. lang_key++; /* skip NUL separator */
  195079. if (lang_key >= chunkdata + slength)
  195080. {
  195081. png_warning(png_ptr, "Truncated iTXt chunk");
  195082. png_free(png_ptr, chunkdata);
  195083. return;
  195084. }
  195085. for (text = lang_key; *text; text++)
  195086. /* empty loop */ ;
  195087. text++; /* skip NUL separator */
  195088. if (text >= chunkdata + slength)
  195089. {
  195090. png_warning(png_ptr, "Malformed iTXt chunk");
  195091. png_free(png_ptr, chunkdata);
  195092. return;
  195093. }
  195094. prefix_len = text - chunkdata;
  195095. key=chunkdata;
  195096. if (comp_flag)
  195097. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195098. (size_t)length, prefix_len, &data_len);
  195099. else
  195100. data_len=png_strlen(chunkdata + prefix_len);
  195101. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195102. (png_uint_32)png_sizeof(png_text));
  195103. if (text_ptr == NULL)
  195104. {
  195105. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195106. png_free(png_ptr, chunkdata);
  195107. return;
  195108. }
  195109. text_ptr->compression = (int)comp_flag + 1;
  195110. text_ptr->lang_key = chunkdata+(lang_key-key);
  195111. text_ptr->lang = chunkdata+(lang-key);
  195112. text_ptr->itxt_length = data_len;
  195113. text_ptr->text_length = 0;
  195114. text_ptr->key = chunkdata;
  195115. text_ptr->text = chunkdata + prefix_len;
  195116. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195117. png_free(png_ptr, text_ptr);
  195118. png_free(png_ptr, chunkdata);
  195119. if (ret)
  195120. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195121. }
  195122. #endif
  195123. /* This function is called when we haven't found a handler for a
  195124. chunk. If there isn't a problem with the chunk itself (ie bad
  195125. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195126. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195127. case it will be saved away to be written out later. */
  195128. void /* PRIVATE */
  195129. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195130. {
  195131. png_uint_32 skip = 0;
  195132. png_debug(1, "in png_handle_unknown\n");
  195133. if (png_ptr->mode & PNG_HAVE_IDAT)
  195134. {
  195135. #ifdef PNG_USE_LOCAL_ARRAYS
  195136. PNG_CONST PNG_IDAT;
  195137. #endif
  195138. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195139. png_ptr->mode |= PNG_AFTER_IDAT;
  195140. }
  195141. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195142. if (!(png_ptr->chunk_name[0] & 0x20))
  195143. {
  195144. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195145. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195146. PNG_HANDLE_CHUNK_ALWAYS
  195147. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195148. && png_ptr->read_user_chunk_fn == NULL
  195149. #endif
  195150. )
  195151. #endif
  195152. png_chunk_error(png_ptr, "unknown critical chunk");
  195153. }
  195154. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195155. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195156. (png_ptr->read_user_chunk_fn != NULL))
  195157. {
  195158. #ifdef PNG_MAX_MALLOC_64K
  195159. if (length > (png_uint_32)65535L)
  195160. {
  195161. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195162. skip = length - (png_uint_32)65535L;
  195163. length = (png_uint_32)65535L;
  195164. }
  195165. #endif
  195166. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195167. (png_charp)png_ptr->chunk_name, 5);
  195168. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195169. png_ptr->unknown_chunk.size = (png_size_t)length;
  195170. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195171. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195172. if(png_ptr->read_user_chunk_fn != NULL)
  195173. {
  195174. /* callback to user unknown chunk handler */
  195175. int ret;
  195176. ret = (*(png_ptr->read_user_chunk_fn))
  195177. (png_ptr, &png_ptr->unknown_chunk);
  195178. if (ret < 0)
  195179. png_chunk_error(png_ptr, "error in user chunk");
  195180. if (ret == 0)
  195181. {
  195182. if (!(png_ptr->chunk_name[0] & 0x20))
  195183. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195184. PNG_HANDLE_CHUNK_ALWAYS)
  195185. png_chunk_error(png_ptr, "unknown critical chunk");
  195186. png_set_unknown_chunks(png_ptr, info_ptr,
  195187. &png_ptr->unknown_chunk, 1);
  195188. }
  195189. }
  195190. #else
  195191. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195192. #endif
  195193. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195194. png_ptr->unknown_chunk.data = NULL;
  195195. }
  195196. else
  195197. #endif
  195198. skip = length;
  195199. png_crc_finish(png_ptr, skip);
  195200. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195201. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195202. #endif
  195203. }
  195204. /* This function is called to verify that a chunk name is valid.
  195205. This function can't have the "critical chunk check" incorporated
  195206. into it, since in the future we will need to be able to call user
  195207. functions to handle unknown critical chunks after we check that
  195208. the chunk name itself is valid. */
  195209. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195210. void /* PRIVATE */
  195211. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195212. {
  195213. png_debug(1, "in png_check_chunk_name\n");
  195214. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195215. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195216. {
  195217. png_chunk_error(png_ptr, "invalid chunk type");
  195218. }
  195219. }
  195220. /* Combines the row recently read in with the existing pixels in the
  195221. row. This routine takes care of alpha and transparency if requested.
  195222. This routine also handles the two methods of progressive display
  195223. of interlaced images, depending on the mask value.
  195224. The mask value describes which pixels are to be combined with
  195225. the row. The pattern always repeats every 8 pixels, so just 8
  195226. bits are needed. A one indicates the pixel is to be combined,
  195227. a zero indicates the pixel is to be skipped. This is in addition
  195228. to any alpha or transparency value associated with the pixel. If
  195229. you want all pixels to be combined, pass 0xff (255) in mask. */
  195230. void /* PRIVATE */
  195231. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195232. {
  195233. png_debug(1,"in png_combine_row\n");
  195234. if (mask == 0xff)
  195235. {
  195236. png_memcpy(row, png_ptr->row_buf + 1,
  195237. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195238. }
  195239. else
  195240. {
  195241. switch (png_ptr->row_info.pixel_depth)
  195242. {
  195243. case 1:
  195244. {
  195245. png_bytep sp = png_ptr->row_buf + 1;
  195246. png_bytep dp = row;
  195247. int s_inc, s_start, s_end;
  195248. int m = 0x80;
  195249. int shift;
  195250. png_uint_32 i;
  195251. png_uint_32 row_width = png_ptr->width;
  195252. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195253. if (png_ptr->transformations & PNG_PACKSWAP)
  195254. {
  195255. s_start = 0;
  195256. s_end = 7;
  195257. s_inc = 1;
  195258. }
  195259. else
  195260. #endif
  195261. {
  195262. s_start = 7;
  195263. s_end = 0;
  195264. s_inc = -1;
  195265. }
  195266. shift = s_start;
  195267. for (i = 0; i < row_width; i++)
  195268. {
  195269. if (m & mask)
  195270. {
  195271. int value;
  195272. value = (*sp >> shift) & 0x01;
  195273. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195274. *dp |= (png_byte)(value << shift);
  195275. }
  195276. if (shift == s_end)
  195277. {
  195278. shift = s_start;
  195279. sp++;
  195280. dp++;
  195281. }
  195282. else
  195283. shift += s_inc;
  195284. if (m == 1)
  195285. m = 0x80;
  195286. else
  195287. m >>= 1;
  195288. }
  195289. break;
  195290. }
  195291. case 2:
  195292. {
  195293. png_bytep sp = png_ptr->row_buf + 1;
  195294. png_bytep dp = row;
  195295. int s_start, s_end, s_inc;
  195296. int m = 0x80;
  195297. int shift;
  195298. png_uint_32 i;
  195299. png_uint_32 row_width = png_ptr->width;
  195300. int value;
  195301. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195302. if (png_ptr->transformations & PNG_PACKSWAP)
  195303. {
  195304. s_start = 0;
  195305. s_end = 6;
  195306. s_inc = 2;
  195307. }
  195308. else
  195309. #endif
  195310. {
  195311. s_start = 6;
  195312. s_end = 0;
  195313. s_inc = -2;
  195314. }
  195315. shift = s_start;
  195316. for (i = 0; i < row_width; i++)
  195317. {
  195318. if (m & mask)
  195319. {
  195320. value = (*sp >> shift) & 0x03;
  195321. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195322. *dp |= (png_byte)(value << shift);
  195323. }
  195324. if (shift == s_end)
  195325. {
  195326. shift = s_start;
  195327. sp++;
  195328. dp++;
  195329. }
  195330. else
  195331. shift += s_inc;
  195332. if (m == 1)
  195333. m = 0x80;
  195334. else
  195335. m >>= 1;
  195336. }
  195337. break;
  195338. }
  195339. case 4:
  195340. {
  195341. png_bytep sp = png_ptr->row_buf + 1;
  195342. png_bytep dp = row;
  195343. int s_start, s_end, s_inc;
  195344. int m = 0x80;
  195345. int shift;
  195346. png_uint_32 i;
  195347. png_uint_32 row_width = png_ptr->width;
  195348. int value;
  195349. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195350. if (png_ptr->transformations & PNG_PACKSWAP)
  195351. {
  195352. s_start = 0;
  195353. s_end = 4;
  195354. s_inc = 4;
  195355. }
  195356. else
  195357. #endif
  195358. {
  195359. s_start = 4;
  195360. s_end = 0;
  195361. s_inc = -4;
  195362. }
  195363. shift = s_start;
  195364. for (i = 0; i < row_width; i++)
  195365. {
  195366. if (m & mask)
  195367. {
  195368. value = (*sp >> shift) & 0xf;
  195369. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195370. *dp |= (png_byte)(value << shift);
  195371. }
  195372. if (shift == s_end)
  195373. {
  195374. shift = s_start;
  195375. sp++;
  195376. dp++;
  195377. }
  195378. else
  195379. shift += s_inc;
  195380. if (m == 1)
  195381. m = 0x80;
  195382. else
  195383. m >>= 1;
  195384. }
  195385. break;
  195386. }
  195387. default:
  195388. {
  195389. png_bytep sp = png_ptr->row_buf + 1;
  195390. png_bytep dp = row;
  195391. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195392. png_uint_32 i;
  195393. png_uint_32 row_width = png_ptr->width;
  195394. png_byte m = 0x80;
  195395. for (i = 0; i < row_width; i++)
  195396. {
  195397. if (m & mask)
  195398. {
  195399. png_memcpy(dp, sp, pixel_bytes);
  195400. }
  195401. sp += pixel_bytes;
  195402. dp += pixel_bytes;
  195403. if (m == 1)
  195404. m = 0x80;
  195405. else
  195406. m >>= 1;
  195407. }
  195408. break;
  195409. }
  195410. }
  195411. }
  195412. }
  195413. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195414. /* OLD pre-1.0.9 interface:
  195415. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195416. png_uint_32 transformations)
  195417. */
  195418. void /* PRIVATE */
  195419. png_do_read_interlace(png_structp png_ptr)
  195420. {
  195421. png_row_infop row_info = &(png_ptr->row_info);
  195422. png_bytep row = png_ptr->row_buf + 1;
  195423. int pass = png_ptr->pass;
  195424. png_uint_32 transformations = png_ptr->transformations;
  195425. #ifdef PNG_USE_LOCAL_ARRAYS
  195426. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195427. /* offset to next interlace block */
  195428. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195429. #endif
  195430. png_debug(1,"in png_do_read_interlace\n");
  195431. if (row != NULL && row_info != NULL)
  195432. {
  195433. png_uint_32 final_width;
  195434. final_width = row_info->width * png_pass_inc[pass];
  195435. switch (row_info->pixel_depth)
  195436. {
  195437. case 1:
  195438. {
  195439. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195440. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195441. int sshift, dshift;
  195442. int s_start, s_end, s_inc;
  195443. int jstop = png_pass_inc[pass];
  195444. png_byte v;
  195445. png_uint_32 i;
  195446. int j;
  195447. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195448. if (transformations & PNG_PACKSWAP)
  195449. {
  195450. sshift = (int)((row_info->width + 7) & 0x07);
  195451. dshift = (int)((final_width + 7) & 0x07);
  195452. s_start = 7;
  195453. s_end = 0;
  195454. s_inc = -1;
  195455. }
  195456. else
  195457. #endif
  195458. {
  195459. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195460. dshift = 7 - (int)((final_width + 7) & 0x07);
  195461. s_start = 0;
  195462. s_end = 7;
  195463. s_inc = 1;
  195464. }
  195465. for (i = 0; i < row_info->width; i++)
  195466. {
  195467. v = (png_byte)((*sp >> sshift) & 0x01);
  195468. for (j = 0; j < jstop; j++)
  195469. {
  195470. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195471. *dp |= (png_byte)(v << dshift);
  195472. if (dshift == s_end)
  195473. {
  195474. dshift = s_start;
  195475. dp--;
  195476. }
  195477. else
  195478. dshift += s_inc;
  195479. }
  195480. if (sshift == s_end)
  195481. {
  195482. sshift = s_start;
  195483. sp--;
  195484. }
  195485. else
  195486. sshift += s_inc;
  195487. }
  195488. break;
  195489. }
  195490. case 2:
  195491. {
  195492. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195493. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195494. int sshift, dshift;
  195495. int s_start, s_end, s_inc;
  195496. int jstop = png_pass_inc[pass];
  195497. png_uint_32 i;
  195498. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195499. if (transformations & PNG_PACKSWAP)
  195500. {
  195501. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195502. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195503. s_start = 6;
  195504. s_end = 0;
  195505. s_inc = -2;
  195506. }
  195507. else
  195508. #endif
  195509. {
  195510. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195511. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195512. s_start = 0;
  195513. s_end = 6;
  195514. s_inc = 2;
  195515. }
  195516. for (i = 0; i < row_info->width; i++)
  195517. {
  195518. png_byte v;
  195519. int j;
  195520. v = (png_byte)((*sp >> sshift) & 0x03);
  195521. for (j = 0; j < jstop; j++)
  195522. {
  195523. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195524. *dp |= (png_byte)(v << dshift);
  195525. if (dshift == s_end)
  195526. {
  195527. dshift = s_start;
  195528. dp--;
  195529. }
  195530. else
  195531. dshift += s_inc;
  195532. }
  195533. if (sshift == s_end)
  195534. {
  195535. sshift = s_start;
  195536. sp--;
  195537. }
  195538. else
  195539. sshift += s_inc;
  195540. }
  195541. break;
  195542. }
  195543. case 4:
  195544. {
  195545. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195546. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195547. int sshift, dshift;
  195548. int s_start, s_end, s_inc;
  195549. png_uint_32 i;
  195550. int jstop = png_pass_inc[pass];
  195551. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195552. if (transformations & PNG_PACKSWAP)
  195553. {
  195554. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195555. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195556. s_start = 4;
  195557. s_end = 0;
  195558. s_inc = -4;
  195559. }
  195560. else
  195561. #endif
  195562. {
  195563. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195564. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195565. s_start = 0;
  195566. s_end = 4;
  195567. s_inc = 4;
  195568. }
  195569. for (i = 0; i < row_info->width; i++)
  195570. {
  195571. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195572. int j;
  195573. for (j = 0; j < jstop; j++)
  195574. {
  195575. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195576. *dp |= (png_byte)(v << dshift);
  195577. if (dshift == s_end)
  195578. {
  195579. dshift = s_start;
  195580. dp--;
  195581. }
  195582. else
  195583. dshift += s_inc;
  195584. }
  195585. if (sshift == s_end)
  195586. {
  195587. sshift = s_start;
  195588. sp--;
  195589. }
  195590. else
  195591. sshift += s_inc;
  195592. }
  195593. break;
  195594. }
  195595. default:
  195596. {
  195597. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195598. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195599. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195600. int jstop = png_pass_inc[pass];
  195601. png_uint_32 i;
  195602. for (i = 0; i < row_info->width; i++)
  195603. {
  195604. png_byte v[8];
  195605. int j;
  195606. png_memcpy(v, sp, pixel_bytes);
  195607. for (j = 0; j < jstop; j++)
  195608. {
  195609. png_memcpy(dp, v, pixel_bytes);
  195610. dp -= pixel_bytes;
  195611. }
  195612. sp -= pixel_bytes;
  195613. }
  195614. break;
  195615. }
  195616. }
  195617. row_info->width = final_width;
  195618. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195619. }
  195620. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195621. transformations = transformations; /* silence compiler warning */
  195622. #endif
  195623. }
  195624. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195625. void /* PRIVATE */
  195626. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195627. png_bytep prev_row, int filter)
  195628. {
  195629. png_debug(1, "in png_read_filter_row\n");
  195630. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195631. switch (filter)
  195632. {
  195633. case PNG_FILTER_VALUE_NONE:
  195634. break;
  195635. case PNG_FILTER_VALUE_SUB:
  195636. {
  195637. png_uint_32 i;
  195638. png_uint_32 istop = row_info->rowbytes;
  195639. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195640. png_bytep rp = row + bpp;
  195641. png_bytep lp = row;
  195642. for (i = bpp; i < istop; i++)
  195643. {
  195644. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195645. rp++;
  195646. }
  195647. break;
  195648. }
  195649. case PNG_FILTER_VALUE_UP:
  195650. {
  195651. png_uint_32 i;
  195652. png_uint_32 istop = row_info->rowbytes;
  195653. png_bytep rp = row;
  195654. png_bytep pp = prev_row;
  195655. for (i = 0; i < istop; i++)
  195656. {
  195657. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195658. rp++;
  195659. }
  195660. break;
  195661. }
  195662. case PNG_FILTER_VALUE_AVG:
  195663. {
  195664. png_uint_32 i;
  195665. png_bytep rp = row;
  195666. png_bytep pp = prev_row;
  195667. png_bytep lp = row;
  195668. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195669. png_uint_32 istop = row_info->rowbytes - bpp;
  195670. for (i = 0; i < bpp; i++)
  195671. {
  195672. *rp = (png_byte)(((int)(*rp) +
  195673. ((int)(*pp++) / 2 )) & 0xff);
  195674. rp++;
  195675. }
  195676. for (i = 0; i < istop; i++)
  195677. {
  195678. *rp = (png_byte)(((int)(*rp) +
  195679. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195680. rp++;
  195681. }
  195682. break;
  195683. }
  195684. case PNG_FILTER_VALUE_PAETH:
  195685. {
  195686. png_uint_32 i;
  195687. png_bytep rp = row;
  195688. png_bytep pp = prev_row;
  195689. png_bytep lp = row;
  195690. png_bytep cp = prev_row;
  195691. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195692. png_uint_32 istop=row_info->rowbytes - bpp;
  195693. for (i = 0; i < bpp; i++)
  195694. {
  195695. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195696. rp++;
  195697. }
  195698. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195699. {
  195700. int a, b, c, pa, pb, pc, p;
  195701. a = *lp++;
  195702. b = *pp++;
  195703. c = *cp++;
  195704. p = b - c;
  195705. pc = a - c;
  195706. #ifdef PNG_USE_ABS
  195707. pa = abs(p);
  195708. pb = abs(pc);
  195709. pc = abs(p + pc);
  195710. #else
  195711. pa = p < 0 ? -p : p;
  195712. pb = pc < 0 ? -pc : pc;
  195713. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195714. #endif
  195715. /*
  195716. if (pa <= pb && pa <= pc)
  195717. p = a;
  195718. else if (pb <= pc)
  195719. p = b;
  195720. else
  195721. p = c;
  195722. */
  195723. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195724. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195725. rp++;
  195726. }
  195727. break;
  195728. }
  195729. default:
  195730. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195731. *row=0;
  195732. break;
  195733. }
  195734. }
  195735. void /* PRIVATE */
  195736. png_read_finish_row(png_structp png_ptr)
  195737. {
  195738. #ifdef PNG_USE_LOCAL_ARRAYS
  195739. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195740. /* start of interlace block */
  195741. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195742. /* offset to next interlace block */
  195743. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195744. /* start of interlace block in the y direction */
  195745. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195746. /* offset to next interlace block in the y direction */
  195747. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195748. #endif
  195749. png_debug(1, "in png_read_finish_row\n");
  195750. png_ptr->row_number++;
  195751. if (png_ptr->row_number < png_ptr->num_rows)
  195752. return;
  195753. if (png_ptr->interlaced)
  195754. {
  195755. png_ptr->row_number = 0;
  195756. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195757. png_ptr->rowbytes + 1);
  195758. do
  195759. {
  195760. png_ptr->pass++;
  195761. if (png_ptr->pass >= 7)
  195762. break;
  195763. png_ptr->iwidth = (png_ptr->width +
  195764. png_pass_inc[png_ptr->pass] - 1 -
  195765. png_pass_start[png_ptr->pass]) /
  195766. png_pass_inc[png_ptr->pass];
  195767. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195768. png_ptr->iwidth) + 1;
  195769. if (!(png_ptr->transformations & PNG_INTERLACE))
  195770. {
  195771. png_ptr->num_rows = (png_ptr->height +
  195772. png_pass_yinc[png_ptr->pass] - 1 -
  195773. png_pass_ystart[png_ptr->pass]) /
  195774. png_pass_yinc[png_ptr->pass];
  195775. if (!(png_ptr->num_rows))
  195776. continue;
  195777. }
  195778. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195779. break;
  195780. } while (png_ptr->iwidth == 0);
  195781. if (png_ptr->pass < 7)
  195782. return;
  195783. }
  195784. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195785. {
  195786. #ifdef PNG_USE_LOCAL_ARRAYS
  195787. PNG_CONST PNG_IDAT;
  195788. #endif
  195789. char extra;
  195790. int ret;
  195791. png_ptr->zstream.next_out = (Bytef *)&extra;
  195792. png_ptr->zstream.avail_out = (uInt)1;
  195793. for(;;)
  195794. {
  195795. if (!(png_ptr->zstream.avail_in))
  195796. {
  195797. while (!png_ptr->idat_size)
  195798. {
  195799. png_byte chunk_length[4];
  195800. png_crc_finish(png_ptr, 0);
  195801. png_read_data(png_ptr, chunk_length, 4);
  195802. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195803. png_reset_crc(png_ptr);
  195804. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195805. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195806. png_error(png_ptr, "Not enough image data");
  195807. }
  195808. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195809. png_ptr->zstream.next_in = png_ptr->zbuf;
  195810. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195811. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195812. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195813. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195814. }
  195815. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195816. if (ret == Z_STREAM_END)
  195817. {
  195818. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195819. png_ptr->idat_size)
  195820. png_warning(png_ptr, "Extra compressed data");
  195821. png_ptr->mode |= PNG_AFTER_IDAT;
  195822. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195823. break;
  195824. }
  195825. if (ret != Z_OK)
  195826. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  195827. "Decompression Error");
  195828. if (!(png_ptr->zstream.avail_out))
  195829. {
  195830. png_warning(png_ptr, "Extra compressed data.");
  195831. png_ptr->mode |= PNG_AFTER_IDAT;
  195832. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195833. break;
  195834. }
  195835. }
  195836. png_ptr->zstream.avail_out = 0;
  195837. }
  195838. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  195839. png_warning(png_ptr, "Extra compression data");
  195840. inflateReset(&png_ptr->zstream);
  195841. png_ptr->mode |= PNG_AFTER_IDAT;
  195842. }
  195843. void /* PRIVATE */
  195844. png_read_start_row(png_structp png_ptr)
  195845. {
  195846. #ifdef PNG_USE_LOCAL_ARRAYS
  195847. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195848. /* start of interlace block */
  195849. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195850. /* offset to next interlace block */
  195851. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195852. /* start of interlace block in the y direction */
  195853. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195854. /* offset to next interlace block in the y direction */
  195855. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195856. #endif
  195857. int max_pixel_depth;
  195858. png_uint_32 row_bytes;
  195859. png_debug(1, "in png_read_start_row\n");
  195860. png_ptr->zstream.avail_in = 0;
  195861. png_init_read_transformations(png_ptr);
  195862. if (png_ptr->interlaced)
  195863. {
  195864. if (!(png_ptr->transformations & PNG_INTERLACE))
  195865. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195866. png_pass_ystart[0]) / png_pass_yinc[0];
  195867. else
  195868. png_ptr->num_rows = png_ptr->height;
  195869. png_ptr->iwidth = (png_ptr->width +
  195870. png_pass_inc[png_ptr->pass] - 1 -
  195871. png_pass_start[png_ptr->pass]) /
  195872. png_pass_inc[png_ptr->pass];
  195873. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  195874. png_ptr->irowbytes = (png_size_t)row_bytes;
  195875. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  195876. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  195877. }
  195878. else
  195879. {
  195880. png_ptr->num_rows = png_ptr->height;
  195881. png_ptr->iwidth = png_ptr->width;
  195882. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  195883. }
  195884. max_pixel_depth = png_ptr->pixel_depth;
  195885. #if defined(PNG_READ_PACK_SUPPORTED)
  195886. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  195887. max_pixel_depth = 8;
  195888. #endif
  195889. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195890. if (png_ptr->transformations & PNG_EXPAND)
  195891. {
  195892. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195893. {
  195894. if (png_ptr->num_trans)
  195895. max_pixel_depth = 32;
  195896. else
  195897. max_pixel_depth = 24;
  195898. }
  195899. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195900. {
  195901. if (max_pixel_depth < 8)
  195902. max_pixel_depth = 8;
  195903. if (png_ptr->num_trans)
  195904. max_pixel_depth *= 2;
  195905. }
  195906. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195907. {
  195908. if (png_ptr->num_trans)
  195909. {
  195910. max_pixel_depth *= 4;
  195911. max_pixel_depth /= 3;
  195912. }
  195913. }
  195914. }
  195915. #endif
  195916. #if defined(PNG_READ_FILLER_SUPPORTED)
  195917. if (png_ptr->transformations & (PNG_FILLER))
  195918. {
  195919. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195920. max_pixel_depth = 32;
  195921. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195922. {
  195923. if (max_pixel_depth <= 8)
  195924. max_pixel_depth = 16;
  195925. else
  195926. max_pixel_depth = 32;
  195927. }
  195928. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195929. {
  195930. if (max_pixel_depth <= 32)
  195931. max_pixel_depth = 32;
  195932. else
  195933. max_pixel_depth = 64;
  195934. }
  195935. }
  195936. #endif
  195937. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  195938. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  195939. {
  195940. if (
  195941. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195942. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  195943. #endif
  195944. #if defined(PNG_READ_FILLER_SUPPORTED)
  195945. (png_ptr->transformations & (PNG_FILLER)) ||
  195946. #endif
  195947. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195948. {
  195949. if (max_pixel_depth <= 16)
  195950. max_pixel_depth = 32;
  195951. else
  195952. max_pixel_depth = 64;
  195953. }
  195954. else
  195955. {
  195956. if (max_pixel_depth <= 8)
  195957. {
  195958. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195959. max_pixel_depth = 32;
  195960. else
  195961. max_pixel_depth = 24;
  195962. }
  195963. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195964. max_pixel_depth = 64;
  195965. else
  195966. max_pixel_depth = 48;
  195967. }
  195968. }
  195969. #endif
  195970. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  195971. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195972. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  195973. {
  195974. int user_pixel_depth=png_ptr->user_transform_depth*
  195975. png_ptr->user_transform_channels;
  195976. if(user_pixel_depth > max_pixel_depth)
  195977. max_pixel_depth=user_pixel_depth;
  195978. }
  195979. #endif
  195980. /* align the width on the next larger 8 pixels. Mainly used
  195981. for interlacing */
  195982. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  195983. /* calculate the maximum bytes needed, adding a byte and a pixel
  195984. for safety's sake */
  195985. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  195986. 1 + ((max_pixel_depth + 7) >> 3);
  195987. #ifdef PNG_MAX_MALLOC_64K
  195988. if (row_bytes > (png_uint_32)65536L)
  195989. png_error(png_ptr, "This image requires a row greater than 64KB");
  195990. #endif
  195991. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  195992. png_ptr->row_buf = png_ptr->big_row_buf+32;
  195993. #ifdef PNG_MAX_MALLOC_64K
  195994. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  195995. png_error(png_ptr, "This image requires a row greater than 64KB");
  195996. #endif
  195997. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  195998. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  195999. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196000. png_ptr->rowbytes + 1));
  196001. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196002. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196003. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196004. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196005. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196006. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196007. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196008. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196009. }
  196010. #endif /* PNG_READ_SUPPORTED */
  196011. /*** End of inlined file: pngrutil.c ***/
  196012. /*** Start of inlined file: pngset.c ***/
  196013. /* pngset.c - storage of image information into info struct
  196014. *
  196015. * Last changed in libpng 1.2.21 [October 4, 2007]
  196016. * For conditions of distribution and use, see copyright notice in png.h
  196017. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196018. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196019. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196020. *
  196021. * The functions here are used during reads to store data from the file
  196022. * into the info struct, and during writes to store application data
  196023. * into the info struct for writing into the file. This abstracts the
  196024. * info struct and allows us to change the structure in the future.
  196025. */
  196026. #define PNG_INTERNAL
  196027. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196028. #if defined(PNG_bKGD_SUPPORTED)
  196029. void PNGAPI
  196030. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196031. {
  196032. png_debug1(1, "in %s storage function\n", "bKGD");
  196033. if (png_ptr == NULL || info_ptr == NULL)
  196034. return;
  196035. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196036. info_ptr->valid |= PNG_INFO_bKGD;
  196037. }
  196038. #endif
  196039. #if defined(PNG_cHRM_SUPPORTED)
  196040. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196041. void PNGAPI
  196042. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196043. double white_x, double white_y, double red_x, double red_y,
  196044. double green_x, double green_y, double blue_x, double blue_y)
  196045. {
  196046. png_debug1(1, "in %s storage function\n", "cHRM");
  196047. if (png_ptr == NULL || info_ptr == NULL)
  196048. return;
  196049. if (white_x < 0.0 || white_y < 0.0 ||
  196050. red_x < 0.0 || red_y < 0.0 ||
  196051. green_x < 0.0 || green_y < 0.0 ||
  196052. blue_x < 0.0 || blue_y < 0.0)
  196053. {
  196054. png_warning(png_ptr,
  196055. "Ignoring attempt to set negative chromaticity value");
  196056. return;
  196057. }
  196058. if (white_x > 21474.83 || white_y > 21474.83 ||
  196059. red_x > 21474.83 || red_y > 21474.83 ||
  196060. green_x > 21474.83 || green_y > 21474.83 ||
  196061. blue_x > 21474.83 || blue_y > 21474.83)
  196062. {
  196063. png_warning(png_ptr,
  196064. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196065. return;
  196066. }
  196067. info_ptr->x_white = (float)white_x;
  196068. info_ptr->y_white = (float)white_y;
  196069. info_ptr->x_red = (float)red_x;
  196070. info_ptr->y_red = (float)red_y;
  196071. info_ptr->x_green = (float)green_x;
  196072. info_ptr->y_green = (float)green_y;
  196073. info_ptr->x_blue = (float)blue_x;
  196074. info_ptr->y_blue = (float)blue_y;
  196075. #ifdef PNG_FIXED_POINT_SUPPORTED
  196076. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196077. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196078. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196079. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196080. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196081. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196082. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196083. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196084. #endif
  196085. info_ptr->valid |= PNG_INFO_cHRM;
  196086. }
  196087. #endif
  196088. #ifdef PNG_FIXED_POINT_SUPPORTED
  196089. void PNGAPI
  196090. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196091. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196092. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196093. png_fixed_point blue_x, png_fixed_point blue_y)
  196094. {
  196095. png_debug1(1, "in %s storage function\n", "cHRM");
  196096. if (png_ptr == NULL || info_ptr == NULL)
  196097. return;
  196098. if (white_x < 0 || white_y < 0 ||
  196099. red_x < 0 || red_y < 0 ||
  196100. green_x < 0 || green_y < 0 ||
  196101. blue_x < 0 || blue_y < 0)
  196102. {
  196103. png_warning(png_ptr,
  196104. "Ignoring attempt to set negative chromaticity value");
  196105. return;
  196106. }
  196107. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196108. if (white_x > (double) PNG_UINT_31_MAX ||
  196109. white_y > (double) PNG_UINT_31_MAX ||
  196110. red_x > (double) PNG_UINT_31_MAX ||
  196111. red_y > (double) PNG_UINT_31_MAX ||
  196112. green_x > (double) PNG_UINT_31_MAX ||
  196113. green_y > (double) PNG_UINT_31_MAX ||
  196114. blue_x > (double) PNG_UINT_31_MAX ||
  196115. blue_y > (double) PNG_UINT_31_MAX)
  196116. #else
  196117. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196118. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196119. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196120. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196121. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196122. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196123. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196124. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196125. #endif
  196126. {
  196127. png_warning(png_ptr,
  196128. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196129. return;
  196130. }
  196131. info_ptr->int_x_white = white_x;
  196132. info_ptr->int_y_white = white_y;
  196133. info_ptr->int_x_red = red_x;
  196134. info_ptr->int_y_red = red_y;
  196135. info_ptr->int_x_green = green_x;
  196136. info_ptr->int_y_green = green_y;
  196137. info_ptr->int_x_blue = blue_x;
  196138. info_ptr->int_y_blue = blue_y;
  196139. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196140. info_ptr->x_white = (float)(white_x/100000.);
  196141. info_ptr->y_white = (float)(white_y/100000.);
  196142. info_ptr->x_red = (float)( red_x/100000.);
  196143. info_ptr->y_red = (float)( red_y/100000.);
  196144. info_ptr->x_green = (float)(green_x/100000.);
  196145. info_ptr->y_green = (float)(green_y/100000.);
  196146. info_ptr->x_blue = (float)( blue_x/100000.);
  196147. info_ptr->y_blue = (float)( blue_y/100000.);
  196148. #endif
  196149. info_ptr->valid |= PNG_INFO_cHRM;
  196150. }
  196151. #endif
  196152. #endif
  196153. #if defined(PNG_gAMA_SUPPORTED)
  196154. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196155. void PNGAPI
  196156. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196157. {
  196158. double gamma;
  196159. png_debug1(1, "in %s storage function\n", "gAMA");
  196160. if (png_ptr == NULL || info_ptr == NULL)
  196161. return;
  196162. /* Check for overflow */
  196163. if (file_gamma > 21474.83)
  196164. {
  196165. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196166. gamma=21474.83;
  196167. }
  196168. else
  196169. gamma=file_gamma;
  196170. info_ptr->gamma = (float)gamma;
  196171. #ifdef PNG_FIXED_POINT_SUPPORTED
  196172. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196173. #endif
  196174. info_ptr->valid |= PNG_INFO_gAMA;
  196175. if(gamma == 0.0)
  196176. png_warning(png_ptr, "Setting gamma=0");
  196177. }
  196178. #endif
  196179. void PNGAPI
  196180. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196181. int_gamma)
  196182. {
  196183. png_fixed_point gamma;
  196184. png_debug1(1, "in %s storage function\n", "gAMA");
  196185. if (png_ptr == NULL || info_ptr == NULL)
  196186. return;
  196187. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196188. {
  196189. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196190. gamma=PNG_UINT_31_MAX;
  196191. }
  196192. else
  196193. {
  196194. if (int_gamma < 0)
  196195. {
  196196. png_warning(png_ptr, "Setting negative gamma to zero");
  196197. gamma=0;
  196198. }
  196199. else
  196200. gamma=int_gamma;
  196201. }
  196202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196203. info_ptr->gamma = (float)(gamma/100000.);
  196204. #endif
  196205. #ifdef PNG_FIXED_POINT_SUPPORTED
  196206. info_ptr->int_gamma = gamma;
  196207. #endif
  196208. info_ptr->valid |= PNG_INFO_gAMA;
  196209. if(gamma == 0)
  196210. png_warning(png_ptr, "Setting gamma=0");
  196211. }
  196212. #endif
  196213. #if defined(PNG_hIST_SUPPORTED)
  196214. void PNGAPI
  196215. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196216. {
  196217. int i;
  196218. png_debug1(1, "in %s storage function\n", "hIST");
  196219. if (png_ptr == NULL || info_ptr == NULL)
  196220. return;
  196221. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196222. > PNG_MAX_PALETTE_LENGTH)
  196223. {
  196224. png_warning(png_ptr,
  196225. "Invalid palette size, hIST allocation skipped.");
  196226. return;
  196227. }
  196228. #ifdef PNG_FREE_ME_SUPPORTED
  196229. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196230. #endif
  196231. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196232. 1.2.1 */
  196233. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196234. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196235. if (png_ptr->hist == NULL)
  196236. {
  196237. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196238. return;
  196239. }
  196240. for (i = 0; i < info_ptr->num_palette; i++)
  196241. png_ptr->hist[i] = hist[i];
  196242. info_ptr->hist = png_ptr->hist;
  196243. info_ptr->valid |= PNG_INFO_hIST;
  196244. #ifdef PNG_FREE_ME_SUPPORTED
  196245. info_ptr->free_me |= PNG_FREE_HIST;
  196246. #else
  196247. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196248. #endif
  196249. }
  196250. #endif
  196251. void PNGAPI
  196252. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196253. png_uint_32 width, png_uint_32 height, int bit_depth,
  196254. int color_type, int interlace_type, int compression_type,
  196255. int filter_type)
  196256. {
  196257. png_debug1(1, "in %s storage function\n", "IHDR");
  196258. if (png_ptr == NULL || info_ptr == NULL)
  196259. return;
  196260. /* check for width and height valid values */
  196261. if (width == 0 || height == 0)
  196262. png_error(png_ptr, "Image width or height is zero in IHDR");
  196263. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196264. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196265. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196266. #else
  196267. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196268. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196269. #endif
  196270. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196271. png_error(png_ptr, "Invalid image size in IHDR");
  196272. if ( width > (PNG_UINT_32_MAX
  196273. >> 3) /* 8-byte RGBA pixels */
  196274. - 64 /* bigrowbuf hack */
  196275. - 1 /* filter byte */
  196276. - 7*8 /* rounding of width to multiple of 8 pixels */
  196277. - 8) /* extra max_pixel_depth pad */
  196278. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196279. /* check other values */
  196280. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196281. bit_depth != 8 && bit_depth != 16)
  196282. png_error(png_ptr, "Invalid bit depth in IHDR");
  196283. if (color_type < 0 || color_type == 1 ||
  196284. color_type == 5 || color_type > 6)
  196285. png_error(png_ptr, "Invalid color type in IHDR");
  196286. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196287. ((color_type == PNG_COLOR_TYPE_RGB ||
  196288. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196289. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196290. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196291. if (interlace_type >= PNG_INTERLACE_LAST)
  196292. png_error(png_ptr, "Unknown interlace method in IHDR");
  196293. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196294. png_error(png_ptr, "Unknown compression method in IHDR");
  196295. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196296. /* Accept filter_method 64 (intrapixel differencing) only if
  196297. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196298. * 2. Libpng did not read a PNG signature (this filter_method is only
  196299. * used in PNG datastreams that are embedded in MNG datastreams) and
  196300. * 3. The application called png_permit_mng_features with a mask that
  196301. * included PNG_FLAG_MNG_FILTER_64 and
  196302. * 4. The filter_method is 64 and
  196303. * 5. The color_type is RGB or RGBA
  196304. */
  196305. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196306. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196307. if(filter_type != PNG_FILTER_TYPE_BASE)
  196308. {
  196309. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196310. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196311. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196312. (color_type == PNG_COLOR_TYPE_RGB ||
  196313. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196314. png_error(png_ptr, "Unknown filter method in IHDR");
  196315. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196316. png_warning(png_ptr, "Invalid filter method in IHDR");
  196317. }
  196318. #else
  196319. if(filter_type != PNG_FILTER_TYPE_BASE)
  196320. png_error(png_ptr, "Unknown filter method in IHDR");
  196321. #endif
  196322. info_ptr->width = width;
  196323. info_ptr->height = height;
  196324. info_ptr->bit_depth = (png_byte)bit_depth;
  196325. info_ptr->color_type =(png_byte) color_type;
  196326. info_ptr->compression_type = (png_byte)compression_type;
  196327. info_ptr->filter_type = (png_byte)filter_type;
  196328. info_ptr->interlace_type = (png_byte)interlace_type;
  196329. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196330. info_ptr->channels = 1;
  196331. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196332. info_ptr->channels = 3;
  196333. else
  196334. info_ptr->channels = 1;
  196335. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196336. info_ptr->channels++;
  196337. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196338. /* check for potential overflow */
  196339. if (width > (PNG_UINT_32_MAX
  196340. >> 3) /* 8-byte RGBA pixels */
  196341. - 64 /* bigrowbuf hack */
  196342. - 1 /* filter byte */
  196343. - 7*8 /* rounding of width to multiple of 8 pixels */
  196344. - 8) /* extra max_pixel_depth pad */
  196345. info_ptr->rowbytes = (png_size_t)0;
  196346. else
  196347. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196348. }
  196349. #if defined(PNG_oFFs_SUPPORTED)
  196350. void PNGAPI
  196351. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196352. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196353. {
  196354. png_debug1(1, "in %s storage function\n", "oFFs");
  196355. if (png_ptr == NULL || info_ptr == NULL)
  196356. return;
  196357. info_ptr->x_offset = offset_x;
  196358. info_ptr->y_offset = offset_y;
  196359. info_ptr->offset_unit_type = (png_byte)unit_type;
  196360. info_ptr->valid |= PNG_INFO_oFFs;
  196361. }
  196362. #endif
  196363. #if defined(PNG_pCAL_SUPPORTED)
  196364. void PNGAPI
  196365. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196366. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196367. png_charp units, png_charpp params)
  196368. {
  196369. png_uint_32 length;
  196370. int i;
  196371. png_debug1(1, "in %s storage function\n", "pCAL");
  196372. if (png_ptr == NULL || info_ptr == NULL)
  196373. return;
  196374. length = png_strlen(purpose) + 1;
  196375. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196376. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196377. if (info_ptr->pcal_purpose == NULL)
  196378. {
  196379. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196380. return;
  196381. }
  196382. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196383. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196384. info_ptr->pcal_X0 = X0;
  196385. info_ptr->pcal_X1 = X1;
  196386. info_ptr->pcal_type = (png_byte)type;
  196387. info_ptr->pcal_nparams = (png_byte)nparams;
  196388. length = png_strlen(units) + 1;
  196389. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196390. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196391. if (info_ptr->pcal_units == NULL)
  196392. {
  196393. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196394. return;
  196395. }
  196396. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196397. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196398. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196399. if (info_ptr->pcal_params == NULL)
  196400. {
  196401. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196402. return;
  196403. }
  196404. info_ptr->pcal_params[nparams] = NULL;
  196405. for (i = 0; i < nparams; i++)
  196406. {
  196407. length = png_strlen(params[i]) + 1;
  196408. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196409. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196410. if (info_ptr->pcal_params[i] == NULL)
  196411. {
  196412. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196413. return;
  196414. }
  196415. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196416. }
  196417. info_ptr->valid |= PNG_INFO_pCAL;
  196418. #ifdef PNG_FREE_ME_SUPPORTED
  196419. info_ptr->free_me |= PNG_FREE_PCAL;
  196420. #endif
  196421. }
  196422. #endif
  196423. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196424. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196425. void PNGAPI
  196426. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196427. int unit, double width, double height)
  196428. {
  196429. png_debug1(1, "in %s storage function\n", "sCAL");
  196430. if (png_ptr == NULL || info_ptr == NULL)
  196431. return;
  196432. info_ptr->scal_unit = (png_byte)unit;
  196433. info_ptr->scal_pixel_width = width;
  196434. info_ptr->scal_pixel_height = height;
  196435. info_ptr->valid |= PNG_INFO_sCAL;
  196436. }
  196437. #else
  196438. #ifdef PNG_FIXED_POINT_SUPPORTED
  196439. void PNGAPI
  196440. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196441. int unit, png_charp swidth, png_charp sheight)
  196442. {
  196443. png_uint_32 length;
  196444. png_debug1(1, "in %s storage function\n", "sCAL");
  196445. if (png_ptr == NULL || info_ptr == NULL)
  196446. return;
  196447. info_ptr->scal_unit = (png_byte)unit;
  196448. length = png_strlen(swidth) + 1;
  196449. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196450. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196451. if (info_ptr->scal_s_width == NULL)
  196452. {
  196453. png_warning(png_ptr,
  196454. "Memory allocation failed while processing sCAL.");
  196455. }
  196456. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196457. length = png_strlen(sheight) + 1;
  196458. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196459. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196460. if (info_ptr->scal_s_height == NULL)
  196461. {
  196462. png_free (png_ptr, info_ptr->scal_s_width);
  196463. png_warning(png_ptr,
  196464. "Memory allocation failed while processing sCAL.");
  196465. }
  196466. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196467. info_ptr->valid |= PNG_INFO_sCAL;
  196468. #ifdef PNG_FREE_ME_SUPPORTED
  196469. info_ptr->free_me |= PNG_FREE_SCAL;
  196470. #endif
  196471. }
  196472. #endif
  196473. #endif
  196474. #endif
  196475. #if defined(PNG_pHYs_SUPPORTED)
  196476. void PNGAPI
  196477. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196478. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196479. {
  196480. png_debug1(1, "in %s storage function\n", "pHYs");
  196481. if (png_ptr == NULL || info_ptr == NULL)
  196482. return;
  196483. info_ptr->x_pixels_per_unit = res_x;
  196484. info_ptr->y_pixels_per_unit = res_y;
  196485. info_ptr->phys_unit_type = (png_byte)unit_type;
  196486. info_ptr->valid |= PNG_INFO_pHYs;
  196487. }
  196488. #endif
  196489. void PNGAPI
  196490. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196491. png_colorp palette, int num_palette)
  196492. {
  196493. png_debug1(1, "in %s storage function\n", "PLTE");
  196494. if (png_ptr == NULL || info_ptr == NULL)
  196495. return;
  196496. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196497. {
  196498. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196499. png_error(png_ptr, "Invalid palette length");
  196500. else
  196501. {
  196502. png_warning(png_ptr, "Invalid palette length");
  196503. return;
  196504. }
  196505. }
  196506. /*
  196507. * It may not actually be necessary to set png_ptr->palette here;
  196508. * we do it for backward compatibility with the way the png_handle_tRNS
  196509. * function used to do the allocation.
  196510. */
  196511. #ifdef PNG_FREE_ME_SUPPORTED
  196512. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196513. #endif
  196514. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196515. of num_palette entries,
  196516. in case of an invalid PNG file that has too-large sample values. */
  196517. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196518. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196519. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196520. png_sizeof(png_color));
  196521. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196522. info_ptr->palette = png_ptr->palette;
  196523. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196524. #ifdef PNG_FREE_ME_SUPPORTED
  196525. info_ptr->free_me |= PNG_FREE_PLTE;
  196526. #else
  196527. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196528. #endif
  196529. info_ptr->valid |= PNG_INFO_PLTE;
  196530. }
  196531. #if defined(PNG_sBIT_SUPPORTED)
  196532. void PNGAPI
  196533. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196534. png_color_8p sig_bit)
  196535. {
  196536. png_debug1(1, "in %s storage function\n", "sBIT");
  196537. if (png_ptr == NULL || info_ptr == NULL)
  196538. return;
  196539. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196540. info_ptr->valid |= PNG_INFO_sBIT;
  196541. }
  196542. #endif
  196543. #if defined(PNG_sRGB_SUPPORTED)
  196544. void PNGAPI
  196545. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196546. {
  196547. png_debug1(1, "in %s storage function\n", "sRGB");
  196548. if (png_ptr == NULL || info_ptr == NULL)
  196549. return;
  196550. info_ptr->srgb_intent = (png_byte)intent;
  196551. info_ptr->valid |= PNG_INFO_sRGB;
  196552. }
  196553. void PNGAPI
  196554. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196555. int intent)
  196556. {
  196557. #if defined(PNG_gAMA_SUPPORTED)
  196558. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196559. float file_gamma;
  196560. #endif
  196561. #ifdef PNG_FIXED_POINT_SUPPORTED
  196562. png_fixed_point int_file_gamma;
  196563. #endif
  196564. #endif
  196565. #if defined(PNG_cHRM_SUPPORTED)
  196566. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196567. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196568. #endif
  196569. #ifdef PNG_FIXED_POINT_SUPPORTED
  196570. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196571. int_green_y, int_blue_x, int_blue_y;
  196572. #endif
  196573. #endif
  196574. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196575. if (png_ptr == NULL || info_ptr == NULL)
  196576. return;
  196577. png_set_sRGB(png_ptr, info_ptr, intent);
  196578. #if defined(PNG_gAMA_SUPPORTED)
  196579. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196580. file_gamma = (float).45455;
  196581. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196582. #endif
  196583. #ifdef PNG_FIXED_POINT_SUPPORTED
  196584. int_file_gamma = 45455L;
  196585. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196586. #endif
  196587. #endif
  196588. #if defined(PNG_cHRM_SUPPORTED)
  196589. #ifdef PNG_FIXED_POINT_SUPPORTED
  196590. int_white_x = 31270L;
  196591. int_white_y = 32900L;
  196592. int_red_x = 64000L;
  196593. int_red_y = 33000L;
  196594. int_green_x = 30000L;
  196595. int_green_y = 60000L;
  196596. int_blue_x = 15000L;
  196597. int_blue_y = 6000L;
  196598. png_set_cHRM_fixed(png_ptr, info_ptr,
  196599. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196600. int_blue_x, int_blue_y);
  196601. #endif
  196602. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196603. white_x = (float).3127;
  196604. white_y = (float).3290;
  196605. red_x = (float).64;
  196606. red_y = (float).33;
  196607. green_x = (float).30;
  196608. green_y = (float).60;
  196609. blue_x = (float).15;
  196610. blue_y = (float).06;
  196611. png_set_cHRM(png_ptr, info_ptr,
  196612. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196613. #endif
  196614. #endif
  196615. }
  196616. #endif
  196617. #if defined(PNG_iCCP_SUPPORTED)
  196618. void PNGAPI
  196619. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196620. png_charp name, int compression_type,
  196621. png_charp profile, png_uint_32 proflen)
  196622. {
  196623. png_charp new_iccp_name;
  196624. png_charp new_iccp_profile;
  196625. png_debug1(1, "in %s storage function\n", "iCCP");
  196626. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196627. return;
  196628. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196629. if (new_iccp_name == NULL)
  196630. {
  196631. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196632. return;
  196633. }
  196634. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196635. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196636. if (new_iccp_profile == NULL)
  196637. {
  196638. png_free (png_ptr, new_iccp_name);
  196639. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196640. return;
  196641. }
  196642. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196643. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196644. info_ptr->iccp_proflen = proflen;
  196645. info_ptr->iccp_name = new_iccp_name;
  196646. info_ptr->iccp_profile = new_iccp_profile;
  196647. /* Compression is always zero but is here so the API and info structure
  196648. * does not have to change if we introduce multiple compression types */
  196649. info_ptr->iccp_compression = (png_byte)compression_type;
  196650. #ifdef PNG_FREE_ME_SUPPORTED
  196651. info_ptr->free_me |= PNG_FREE_ICCP;
  196652. #endif
  196653. info_ptr->valid |= PNG_INFO_iCCP;
  196654. }
  196655. #endif
  196656. #if defined(PNG_TEXT_SUPPORTED)
  196657. void PNGAPI
  196658. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196659. int num_text)
  196660. {
  196661. int ret;
  196662. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196663. if (ret)
  196664. png_error(png_ptr, "Insufficient memory to store text");
  196665. }
  196666. int /* PRIVATE */
  196667. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196668. int num_text)
  196669. {
  196670. int i;
  196671. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196672. "text" : (png_const_charp)png_ptr->chunk_name));
  196673. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196674. return(0);
  196675. /* Make sure we have enough space in the "text" array in info_struct
  196676. * to hold all of the incoming text_ptr objects.
  196677. */
  196678. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196679. {
  196680. if (info_ptr->text != NULL)
  196681. {
  196682. png_textp old_text;
  196683. int old_max;
  196684. old_max = info_ptr->max_text;
  196685. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196686. old_text = info_ptr->text;
  196687. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196688. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196689. if (info_ptr->text == NULL)
  196690. {
  196691. png_free(png_ptr, old_text);
  196692. return(1);
  196693. }
  196694. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196695. png_sizeof(png_text)));
  196696. png_free(png_ptr, old_text);
  196697. }
  196698. else
  196699. {
  196700. info_ptr->max_text = num_text + 8;
  196701. info_ptr->num_text = 0;
  196702. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196703. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196704. if (info_ptr->text == NULL)
  196705. return(1);
  196706. #ifdef PNG_FREE_ME_SUPPORTED
  196707. info_ptr->free_me |= PNG_FREE_TEXT;
  196708. #endif
  196709. }
  196710. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196711. info_ptr->max_text);
  196712. }
  196713. for (i = 0; i < num_text; i++)
  196714. {
  196715. png_size_t text_length,key_len;
  196716. png_size_t lang_len,lang_key_len;
  196717. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196718. if (text_ptr[i].key == NULL)
  196719. continue;
  196720. key_len = png_strlen(text_ptr[i].key);
  196721. if(text_ptr[i].compression <= 0)
  196722. {
  196723. lang_len = 0;
  196724. lang_key_len = 0;
  196725. }
  196726. else
  196727. #ifdef PNG_iTXt_SUPPORTED
  196728. {
  196729. /* set iTXt data */
  196730. if (text_ptr[i].lang != NULL)
  196731. lang_len = png_strlen(text_ptr[i].lang);
  196732. else
  196733. lang_len = 0;
  196734. if (text_ptr[i].lang_key != NULL)
  196735. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196736. else
  196737. lang_key_len = 0;
  196738. }
  196739. #else
  196740. {
  196741. png_warning(png_ptr, "iTXt chunk not supported.");
  196742. continue;
  196743. }
  196744. #endif
  196745. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196746. {
  196747. text_length = 0;
  196748. #ifdef PNG_iTXt_SUPPORTED
  196749. if(text_ptr[i].compression > 0)
  196750. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196751. else
  196752. #endif
  196753. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196754. }
  196755. else
  196756. {
  196757. text_length = png_strlen(text_ptr[i].text);
  196758. textp->compression = text_ptr[i].compression;
  196759. }
  196760. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196761. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196762. if (textp->key == NULL)
  196763. return(1);
  196764. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196765. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196766. (int)textp->key);
  196767. png_memcpy(textp->key, text_ptr[i].key,
  196768. (png_size_t)(key_len));
  196769. *(textp->key+key_len) = '\0';
  196770. #ifdef PNG_iTXt_SUPPORTED
  196771. if (text_ptr[i].compression > 0)
  196772. {
  196773. textp->lang=textp->key + key_len + 1;
  196774. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196775. *(textp->lang+lang_len) = '\0';
  196776. textp->lang_key=textp->lang + lang_len + 1;
  196777. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196778. *(textp->lang_key+lang_key_len) = '\0';
  196779. textp->text=textp->lang_key + lang_key_len + 1;
  196780. }
  196781. else
  196782. #endif
  196783. {
  196784. #ifdef PNG_iTXt_SUPPORTED
  196785. textp->lang=NULL;
  196786. textp->lang_key=NULL;
  196787. #endif
  196788. textp->text=textp->key + key_len + 1;
  196789. }
  196790. if(text_length)
  196791. png_memcpy(textp->text, text_ptr[i].text,
  196792. (png_size_t)(text_length));
  196793. *(textp->text+text_length) = '\0';
  196794. #ifdef PNG_iTXt_SUPPORTED
  196795. if(textp->compression > 0)
  196796. {
  196797. textp->text_length = 0;
  196798. textp->itxt_length = text_length;
  196799. }
  196800. else
  196801. #endif
  196802. {
  196803. textp->text_length = text_length;
  196804. #ifdef PNG_iTXt_SUPPORTED
  196805. textp->itxt_length = 0;
  196806. #endif
  196807. }
  196808. info_ptr->num_text++;
  196809. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196810. }
  196811. return(0);
  196812. }
  196813. #endif
  196814. #if defined(PNG_tIME_SUPPORTED)
  196815. void PNGAPI
  196816. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196817. {
  196818. png_debug1(1, "in %s storage function\n", "tIME");
  196819. if (png_ptr == NULL || info_ptr == NULL ||
  196820. (png_ptr->mode & PNG_WROTE_tIME))
  196821. return;
  196822. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  196823. info_ptr->valid |= PNG_INFO_tIME;
  196824. }
  196825. #endif
  196826. #if defined(PNG_tRNS_SUPPORTED)
  196827. void PNGAPI
  196828. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  196829. png_bytep trans, int num_trans, png_color_16p trans_values)
  196830. {
  196831. png_debug1(1, "in %s storage function\n", "tRNS");
  196832. if (png_ptr == NULL || info_ptr == NULL)
  196833. return;
  196834. if (trans != NULL)
  196835. {
  196836. /*
  196837. * It may not actually be necessary to set png_ptr->trans here;
  196838. * we do it for backward compatibility with the way the png_handle_tRNS
  196839. * function used to do the allocation.
  196840. */
  196841. #ifdef PNG_FREE_ME_SUPPORTED
  196842. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  196843. #endif
  196844. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  196845. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  196846. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  196847. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  196848. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  196849. #ifdef PNG_FREE_ME_SUPPORTED
  196850. info_ptr->free_me |= PNG_FREE_TRNS;
  196851. #else
  196852. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  196853. #endif
  196854. }
  196855. if (trans_values != NULL)
  196856. {
  196857. png_memcpy(&(info_ptr->trans_values), trans_values,
  196858. png_sizeof(png_color_16));
  196859. if (num_trans == 0)
  196860. num_trans = 1;
  196861. }
  196862. info_ptr->num_trans = (png_uint_16)num_trans;
  196863. info_ptr->valid |= PNG_INFO_tRNS;
  196864. }
  196865. #endif
  196866. #if defined(PNG_sPLT_SUPPORTED)
  196867. void PNGAPI
  196868. png_set_sPLT(png_structp png_ptr,
  196869. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  196870. {
  196871. png_sPLT_tp np;
  196872. int i;
  196873. if (png_ptr == NULL || info_ptr == NULL)
  196874. return;
  196875. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  196876. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  196877. if (np == NULL)
  196878. {
  196879. png_warning(png_ptr, "No memory for sPLT palettes.");
  196880. return;
  196881. }
  196882. png_memcpy(np, info_ptr->splt_palettes,
  196883. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  196884. png_free(png_ptr, info_ptr->splt_palettes);
  196885. info_ptr->splt_palettes=NULL;
  196886. for (i = 0; i < nentries; i++)
  196887. {
  196888. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  196889. png_sPLT_tp from = entries + i;
  196890. to->name = (png_charp)png_malloc_warn(png_ptr,
  196891. png_strlen(from->name) + 1);
  196892. if (to->name == NULL)
  196893. {
  196894. png_warning(png_ptr,
  196895. "Out of memory while processing sPLT chunk");
  196896. }
  196897. /* TODO: use png_malloc_warn */
  196898. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  196899. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  196900. from->nentries * png_sizeof(png_sPLT_entry));
  196901. /* TODO: use png_malloc_warn */
  196902. png_memcpy(to->entries, from->entries,
  196903. from->nentries * png_sizeof(png_sPLT_entry));
  196904. if (to->entries == NULL)
  196905. {
  196906. png_warning(png_ptr,
  196907. "Out of memory while processing sPLT chunk");
  196908. png_free(png_ptr,to->name);
  196909. to->name = NULL;
  196910. }
  196911. to->nentries = from->nentries;
  196912. to->depth = from->depth;
  196913. }
  196914. info_ptr->splt_palettes = np;
  196915. info_ptr->splt_palettes_num += nentries;
  196916. info_ptr->valid |= PNG_INFO_sPLT;
  196917. #ifdef PNG_FREE_ME_SUPPORTED
  196918. info_ptr->free_me |= PNG_FREE_SPLT;
  196919. #endif
  196920. }
  196921. #endif /* PNG_sPLT_SUPPORTED */
  196922. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196923. void PNGAPI
  196924. png_set_unknown_chunks(png_structp png_ptr,
  196925. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  196926. {
  196927. png_unknown_chunkp np;
  196928. int i;
  196929. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  196930. return;
  196931. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  196932. (info_ptr->unknown_chunks_num + num_unknowns) *
  196933. png_sizeof(png_unknown_chunk));
  196934. if (np == NULL)
  196935. {
  196936. png_warning(png_ptr,
  196937. "Out of memory while processing unknown chunk.");
  196938. return;
  196939. }
  196940. png_memcpy(np, info_ptr->unknown_chunks,
  196941. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  196942. png_free(png_ptr, info_ptr->unknown_chunks);
  196943. info_ptr->unknown_chunks=NULL;
  196944. for (i = 0; i < num_unknowns; i++)
  196945. {
  196946. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  196947. png_unknown_chunkp from = unknowns + i;
  196948. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  196949. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  196950. if (to->data == NULL)
  196951. {
  196952. png_warning(png_ptr,
  196953. "Out of memory while processing unknown chunk.");
  196954. }
  196955. else
  196956. {
  196957. png_memcpy(to->data, from->data, from->size);
  196958. to->size = from->size;
  196959. /* note our location in the read or write sequence */
  196960. to->location = (png_byte)(png_ptr->mode & 0xff);
  196961. }
  196962. }
  196963. info_ptr->unknown_chunks = np;
  196964. info_ptr->unknown_chunks_num += num_unknowns;
  196965. #ifdef PNG_FREE_ME_SUPPORTED
  196966. info_ptr->free_me |= PNG_FREE_UNKN;
  196967. #endif
  196968. }
  196969. void PNGAPI
  196970. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  196971. int chunk, int location)
  196972. {
  196973. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  196974. (int)info_ptr->unknown_chunks_num)
  196975. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  196976. }
  196977. #endif
  196978. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196979. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  196980. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  196981. void PNGAPI
  196982. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  196983. {
  196984. /* This function is deprecated in favor of png_permit_mng_features()
  196985. and will be removed from libpng-1.3.0 */
  196986. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  196987. if (png_ptr == NULL)
  196988. return;
  196989. png_ptr->mng_features_permitted = (png_byte)
  196990. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  196991. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  196992. }
  196993. #endif
  196994. #endif
  196995. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196996. png_uint_32 PNGAPI
  196997. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  196998. {
  196999. png_debug(1, "in png_permit_mng_features\n");
  197000. if (png_ptr == NULL)
  197001. return (png_uint_32)0;
  197002. png_ptr->mng_features_permitted =
  197003. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197004. return (png_uint_32)png_ptr->mng_features_permitted;
  197005. }
  197006. #endif
  197007. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197008. void PNGAPI
  197009. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197010. chunk_list, int num_chunks)
  197011. {
  197012. png_bytep new_list, p;
  197013. int i, old_num_chunks;
  197014. if (png_ptr == NULL)
  197015. return;
  197016. if (num_chunks == 0)
  197017. {
  197018. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197019. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197020. else
  197021. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197022. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197023. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197024. else
  197025. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197026. return;
  197027. }
  197028. if (chunk_list == NULL)
  197029. return;
  197030. old_num_chunks=png_ptr->num_chunk_list;
  197031. new_list=(png_bytep)png_malloc(png_ptr,
  197032. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197033. if(png_ptr->chunk_list != NULL)
  197034. {
  197035. png_memcpy(new_list, png_ptr->chunk_list,
  197036. (png_size_t)(5*old_num_chunks));
  197037. png_free(png_ptr, png_ptr->chunk_list);
  197038. png_ptr->chunk_list=NULL;
  197039. }
  197040. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197041. (png_size_t)(5*num_chunks));
  197042. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197043. *p=(png_byte)keep;
  197044. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197045. png_ptr->chunk_list=new_list;
  197046. #ifdef PNG_FREE_ME_SUPPORTED
  197047. png_ptr->free_me |= PNG_FREE_LIST;
  197048. #endif
  197049. }
  197050. #endif
  197051. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197052. void PNGAPI
  197053. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197054. png_user_chunk_ptr read_user_chunk_fn)
  197055. {
  197056. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197057. if (png_ptr == NULL)
  197058. return;
  197059. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197060. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197061. }
  197062. #endif
  197063. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197064. void PNGAPI
  197065. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197066. {
  197067. png_debug1(1, "in %s storage function\n", "rows");
  197068. if (png_ptr == NULL || info_ptr == NULL)
  197069. return;
  197070. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197071. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197072. info_ptr->row_pointers = row_pointers;
  197073. if(row_pointers)
  197074. info_ptr->valid |= PNG_INFO_IDAT;
  197075. }
  197076. #endif
  197077. #ifdef PNG_WRITE_SUPPORTED
  197078. void PNGAPI
  197079. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197080. {
  197081. if (png_ptr == NULL)
  197082. return;
  197083. if(png_ptr->zbuf)
  197084. png_free(png_ptr, png_ptr->zbuf);
  197085. png_ptr->zbuf_size = (png_size_t)size;
  197086. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197087. png_ptr->zstream.next_out = png_ptr->zbuf;
  197088. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197089. }
  197090. #endif
  197091. void PNGAPI
  197092. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197093. {
  197094. if (png_ptr && info_ptr)
  197095. info_ptr->valid &= ~(mask);
  197096. }
  197097. #ifndef PNG_1_0_X
  197098. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197099. /* function was added to libpng 1.2.0 and should always exist by default */
  197100. void PNGAPI
  197101. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197102. {
  197103. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197104. if (png_ptr != NULL)
  197105. png_ptr->asm_flags = 0;
  197106. }
  197107. /* this function was added to libpng 1.2.0 */
  197108. void PNGAPI
  197109. png_set_mmx_thresholds (png_structp png_ptr,
  197110. png_byte,
  197111. png_uint_32)
  197112. {
  197113. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197114. if (png_ptr == NULL)
  197115. return;
  197116. }
  197117. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197118. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197119. /* this function was added to libpng 1.2.6 */
  197120. void PNGAPI
  197121. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197122. png_uint_32 user_height_max)
  197123. {
  197124. /* Images with dimensions larger than these limits will be
  197125. * rejected by png_set_IHDR(). To accept any PNG datastream
  197126. * regardless of dimensions, set both limits to 0x7ffffffL.
  197127. */
  197128. if(png_ptr == NULL) return;
  197129. png_ptr->user_width_max = user_width_max;
  197130. png_ptr->user_height_max = user_height_max;
  197131. }
  197132. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197133. #endif /* ?PNG_1_0_X */
  197134. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197135. /*** End of inlined file: pngset.c ***/
  197136. /*** Start of inlined file: pngtrans.c ***/
  197137. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197138. *
  197139. * Last changed in libpng 1.2.17 May 15, 2007
  197140. * For conditions of distribution and use, see copyright notice in png.h
  197141. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197142. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197143. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197144. */
  197145. #define PNG_INTERNAL
  197146. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197147. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197148. /* turn on BGR-to-RGB mapping */
  197149. void PNGAPI
  197150. png_set_bgr(png_structp png_ptr)
  197151. {
  197152. png_debug(1, "in png_set_bgr\n");
  197153. if(png_ptr == NULL) return;
  197154. png_ptr->transformations |= PNG_BGR;
  197155. }
  197156. #endif
  197157. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197158. /* turn on 16 bit byte swapping */
  197159. void PNGAPI
  197160. png_set_swap(png_structp png_ptr)
  197161. {
  197162. png_debug(1, "in png_set_swap\n");
  197163. if(png_ptr == NULL) return;
  197164. if (png_ptr->bit_depth == 16)
  197165. png_ptr->transformations |= PNG_SWAP_BYTES;
  197166. }
  197167. #endif
  197168. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197169. /* turn on pixel packing */
  197170. void PNGAPI
  197171. png_set_packing(png_structp png_ptr)
  197172. {
  197173. png_debug(1, "in png_set_packing\n");
  197174. if(png_ptr == NULL) return;
  197175. if (png_ptr->bit_depth < 8)
  197176. {
  197177. png_ptr->transformations |= PNG_PACK;
  197178. png_ptr->usr_bit_depth = 8;
  197179. }
  197180. }
  197181. #endif
  197182. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197183. /* turn on packed pixel swapping */
  197184. void PNGAPI
  197185. png_set_packswap(png_structp png_ptr)
  197186. {
  197187. png_debug(1, "in png_set_packswap\n");
  197188. if(png_ptr == NULL) return;
  197189. if (png_ptr->bit_depth < 8)
  197190. png_ptr->transformations |= PNG_PACKSWAP;
  197191. }
  197192. #endif
  197193. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197194. void PNGAPI
  197195. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197196. {
  197197. png_debug(1, "in png_set_shift\n");
  197198. if(png_ptr == NULL) return;
  197199. png_ptr->transformations |= PNG_SHIFT;
  197200. png_ptr->shift = *true_bits;
  197201. }
  197202. #endif
  197203. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197204. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197205. int PNGAPI
  197206. png_set_interlace_handling(png_structp png_ptr)
  197207. {
  197208. png_debug(1, "in png_set_interlace handling\n");
  197209. if (png_ptr && png_ptr->interlaced)
  197210. {
  197211. png_ptr->transformations |= PNG_INTERLACE;
  197212. return (7);
  197213. }
  197214. return (1);
  197215. }
  197216. #endif
  197217. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197218. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197219. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197220. * for 48-bit input data, as well as to avoid problems with some compilers
  197221. * that don't like bytes as parameters.
  197222. */
  197223. void PNGAPI
  197224. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197225. {
  197226. png_debug(1, "in png_set_filler\n");
  197227. if(png_ptr == NULL) return;
  197228. png_ptr->transformations |= PNG_FILLER;
  197229. png_ptr->filler = (png_byte)filler;
  197230. if (filler_loc == PNG_FILLER_AFTER)
  197231. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197232. else
  197233. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197234. /* This should probably go in the "do_read_filler" routine.
  197235. * I attempted to do that in libpng-1.0.1a but that caused problems
  197236. * so I restored it in libpng-1.0.2a
  197237. */
  197238. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197239. {
  197240. png_ptr->usr_channels = 4;
  197241. }
  197242. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197243. * a less-than-8-bit grayscale to GA? */
  197244. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197245. {
  197246. png_ptr->usr_channels = 2;
  197247. }
  197248. }
  197249. #if !defined(PNG_1_0_X)
  197250. /* Added to libpng-1.2.7 */
  197251. void PNGAPI
  197252. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197253. {
  197254. png_debug(1, "in png_set_add_alpha\n");
  197255. if(png_ptr == NULL) return;
  197256. png_set_filler(png_ptr, filler, filler_loc);
  197257. png_ptr->transformations |= PNG_ADD_ALPHA;
  197258. }
  197259. #endif
  197260. #endif
  197261. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197262. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197263. void PNGAPI
  197264. png_set_swap_alpha(png_structp png_ptr)
  197265. {
  197266. png_debug(1, "in png_set_swap_alpha\n");
  197267. if(png_ptr == NULL) return;
  197268. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197269. }
  197270. #endif
  197271. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197272. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197273. void PNGAPI
  197274. png_set_invert_alpha(png_structp png_ptr)
  197275. {
  197276. png_debug(1, "in png_set_invert_alpha\n");
  197277. if(png_ptr == NULL) return;
  197278. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197279. }
  197280. #endif
  197281. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197282. void PNGAPI
  197283. png_set_invert_mono(png_structp png_ptr)
  197284. {
  197285. png_debug(1, "in png_set_invert_mono\n");
  197286. if(png_ptr == NULL) return;
  197287. png_ptr->transformations |= PNG_INVERT_MONO;
  197288. }
  197289. /* invert monochrome grayscale data */
  197290. void /* PRIVATE */
  197291. png_do_invert(png_row_infop row_info, png_bytep row)
  197292. {
  197293. png_debug(1, "in png_do_invert\n");
  197294. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197295. * if (row_info->bit_depth == 1 &&
  197296. */
  197297. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197298. if (row == NULL || row_info == NULL)
  197299. return;
  197300. #endif
  197301. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197302. {
  197303. png_bytep rp = row;
  197304. png_uint_32 i;
  197305. png_uint_32 istop = row_info->rowbytes;
  197306. for (i = 0; i < istop; i++)
  197307. {
  197308. *rp = (png_byte)(~(*rp));
  197309. rp++;
  197310. }
  197311. }
  197312. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197313. row_info->bit_depth == 8)
  197314. {
  197315. png_bytep rp = row;
  197316. png_uint_32 i;
  197317. png_uint_32 istop = row_info->rowbytes;
  197318. for (i = 0; i < istop; i+=2)
  197319. {
  197320. *rp = (png_byte)(~(*rp));
  197321. rp+=2;
  197322. }
  197323. }
  197324. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197325. row_info->bit_depth == 16)
  197326. {
  197327. png_bytep rp = row;
  197328. png_uint_32 i;
  197329. png_uint_32 istop = row_info->rowbytes;
  197330. for (i = 0; i < istop; i+=4)
  197331. {
  197332. *rp = (png_byte)(~(*rp));
  197333. *(rp+1) = (png_byte)(~(*(rp+1)));
  197334. rp+=4;
  197335. }
  197336. }
  197337. }
  197338. #endif
  197339. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197340. /* swaps byte order on 16 bit depth images */
  197341. void /* PRIVATE */
  197342. png_do_swap(png_row_infop row_info, png_bytep row)
  197343. {
  197344. png_debug(1, "in png_do_swap\n");
  197345. if (
  197346. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197347. row != NULL && row_info != NULL &&
  197348. #endif
  197349. row_info->bit_depth == 16)
  197350. {
  197351. png_bytep rp = row;
  197352. png_uint_32 i;
  197353. png_uint_32 istop= row_info->width * row_info->channels;
  197354. for (i = 0; i < istop; i++, rp += 2)
  197355. {
  197356. png_byte t = *rp;
  197357. *rp = *(rp + 1);
  197358. *(rp + 1) = t;
  197359. }
  197360. }
  197361. }
  197362. #endif
  197363. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197364. static PNG_CONST png_byte onebppswaptable[256] = {
  197365. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197366. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197367. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197368. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197369. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197370. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197371. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197372. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197373. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197374. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197375. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197376. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197377. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197378. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197379. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197380. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197381. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197382. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197383. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197384. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197385. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197386. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197387. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197388. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197389. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197390. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197391. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197392. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197393. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197394. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197395. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197396. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197397. };
  197398. static PNG_CONST png_byte twobppswaptable[256] = {
  197399. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197400. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197401. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197402. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197403. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197404. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197405. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197406. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197407. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197408. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197409. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197410. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197411. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197412. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197413. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197414. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197415. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197416. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197417. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197418. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197419. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197420. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197421. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197422. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197423. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197424. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197425. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197426. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197427. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197428. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197429. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197430. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197431. };
  197432. static PNG_CONST png_byte fourbppswaptable[256] = {
  197433. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197434. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197435. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197436. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197437. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197438. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197439. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197440. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197441. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197442. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197443. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197444. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197445. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197446. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197447. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197448. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197449. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197450. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197451. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197452. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197453. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197454. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197455. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197456. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197457. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197458. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197459. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197460. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197461. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197462. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197463. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197464. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197465. };
  197466. /* swaps pixel packing order within bytes */
  197467. void /* PRIVATE */
  197468. png_do_packswap(png_row_infop row_info, png_bytep row)
  197469. {
  197470. png_debug(1, "in png_do_packswap\n");
  197471. if (
  197472. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197473. row != NULL && row_info != NULL &&
  197474. #endif
  197475. row_info->bit_depth < 8)
  197476. {
  197477. png_bytep rp, end, table;
  197478. end = row + row_info->rowbytes;
  197479. if (row_info->bit_depth == 1)
  197480. table = (png_bytep)onebppswaptable;
  197481. else if (row_info->bit_depth == 2)
  197482. table = (png_bytep)twobppswaptable;
  197483. else if (row_info->bit_depth == 4)
  197484. table = (png_bytep)fourbppswaptable;
  197485. else
  197486. return;
  197487. for (rp = row; rp < end; rp++)
  197488. *rp = table[*rp];
  197489. }
  197490. }
  197491. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197492. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197493. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197494. /* remove filler or alpha byte(s) */
  197495. void /* PRIVATE */
  197496. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197497. {
  197498. png_debug(1, "in png_do_strip_filler\n");
  197499. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197500. if (row != NULL && row_info != NULL)
  197501. #endif
  197502. {
  197503. png_bytep sp=row;
  197504. png_bytep dp=row;
  197505. png_uint_32 row_width=row_info->width;
  197506. png_uint_32 i;
  197507. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197508. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197509. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197510. row_info->channels == 4)
  197511. {
  197512. if (row_info->bit_depth == 8)
  197513. {
  197514. /* This converts from RGBX or RGBA to RGB */
  197515. if (flags & PNG_FLAG_FILLER_AFTER)
  197516. {
  197517. dp+=3; sp+=4;
  197518. for (i = 1; i < row_width; i++)
  197519. {
  197520. *dp++ = *sp++;
  197521. *dp++ = *sp++;
  197522. *dp++ = *sp++;
  197523. sp++;
  197524. }
  197525. }
  197526. /* This converts from XRGB or ARGB to RGB */
  197527. else
  197528. {
  197529. for (i = 0; i < row_width; i++)
  197530. {
  197531. sp++;
  197532. *dp++ = *sp++;
  197533. *dp++ = *sp++;
  197534. *dp++ = *sp++;
  197535. }
  197536. }
  197537. row_info->pixel_depth = 24;
  197538. row_info->rowbytes = row_width * 3;
  197539. }
  197540. else /* if (row_info->bit_depth == 16) */
  197541. {
  197542. if (flags & PNG_FLAG_FILLER_AFTER)
  197543. {
  197544. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197545. sp += 8; dp += 6;
  197546. for (i = 1; i < row_width; i++)
  197547. {
  197548. /* This could be (although png_memcpy is probably slower):
  197549. png_memcpy(dp, sp, 6);
  197550. sp += 8;
  197551. dp += 6;
  197552. */
  197553. *dp++ = *sp++;
  197554. *dp++ = *sp++;
  197555. *dp++ = *sp++;
  197556. *dp++ = *sp++;
  197557. *dp++ = *sp++;
  197558. *dp++ = *sp++;
  197559. sp += 2;
  197560. }
  197561. }
  197562. else
  197563. {
  197564. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197565. for (i = 0; i < row_width; i++)
  197566. {
  197567. /* This could be (although png_memcpy is probably slower):
  197568. png_memcpy(dp, sp, 6);
  197569. sp += 8;
  197570. dp += 6;
  197571. */
  197572. sp+=2;
  197573. *dp++ = *sp++;
  197574. *dp++ = *sp++;
  197575. *dp++ = *sp++;
  197576. *dp++ = *sp++;
  197577. *dp++ = *sp++;
  197578. *dp++ = *sp++;
  197579. }
  197580. }
  197581. row_info->pixel_depth = 48;
  197582. row_info->rowbytes = row_width * 6;
  197583. }
  197584. row_info->channels = 3;
  197585. }
  197586. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197587. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197588. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197589. row_info->channels == 2)
  197590. {
  197591. if (row_info->bit_depth == 8)
  197592. {
  197593. /* This converts from GX or GA to G */
  197594. if (flags & PNG_FLAG_FILLER_AFTER)
  197595. {
  197596. for (i = 0; i < row_width; i++)
  197597. {
  197598. *dp++ = *sp++;
  197599. sp++;
  197600. }
  197601. }
  197602. /* This converts from XG or AG to G */
  197603. else
  197604. {
  197605. for (i = 0; i < row_width; i++)
  197606. {
  197607. sp++;
  197608. *dp++ = *sp++;
  197609. }
  197610. }
  197611. row_info->pixel_depth = 8;
  197612. row_info->rowbytes = row_width;
  197613. }
  197614. else /* if (row_info->bit_depth == 16) */
  197615. {
  197616. if (flags & PNG_FLAG_FILLER_AFTER)
  197617. {
  197618. /* This converts from GGXX or GGAA to GG */
  197619. sp += 4; dp += 2;
  197620. for (i = 1; i < row_width; i++)
  197621. {
  197622. *dp++ = *sp++;
  197623. *dp++ = *sp++;
  197624. sp += 2;
  197625. }
  197626. }
  197627. else
  197628. {
  197629. /* This converts from XXGG or AAGG to GG */
  197630. for (i = 0; i < row_width; i++)
  197631. {
  197632. sp += 2;
  197633. *dp++ = *sp++;
  197634. *dp++ = *sp++;
  197635. }
  197636. }
  197637. row_info->pixel_depth = 16;
  197638. row_info->rowbytes = row_width * 2;
  197639. }
  197640. row_info->channels = 1;
  197641. }
  197642. if (flags & PNG_FLAG_STRIP_ALPHA)
  197643. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197644. }
  197645. }
  197646. #endif
  197647. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197648. /* swaps red and blue bytes within a pixel */
  197649. void /* PRIVATE */
  197650. png_do_bgr(png_row_infop row_info, png_bytep row)
  197651. {
  197652. png_debug(1, "in png_do_bgr\n");
  197653. if (
  197654. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197655. row != NULL && row_info != NULL &&
  197656. #endif
  197657. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197658. {
  197659. png_uint_32 row_width = row_info->width;
  197660. if (row_info->bit_depth == 8)
  197661. {
  197662. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197663. {
  197664. png_bytep rp;
  197665. png_uint_32 i;
  197666. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197667. {
  197668. png_byte save = *rp;
  197669. *rp = *(rp + 2);
  197670. *(rp + 2) = save;
  197671. }
  197672. }
  197673. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197674. {
  197675. png_bytep rp;
  197676. png_uint_32 i;
  197677. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197678. {
  197679. png_byte save = *rp;
  197680. *rp = *(rp + 2);
  197681. *(rp + 2) = save;
  197682. }
  197683. }
  197684. }
  197685. else if (row_info->bit_depth == 16)
  197686. {
  197687. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197688. {
  197689. png_bytep rp;
  197690. png_uint_32 i;
  197691. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197692. {
  197693. png_byte save = *rp;
  197694. *rp = *(rp + 4);
  197695. *(rp + 4) = save;
  197696. save = *(rp + 1);
  197697. *(rp + 1) = *(rp + 5);
  197698. *(rp + 5) = save;
  197699. }
  197700. }
  197701. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197702. {
  197703. png_bytep rp;
  197704. png_uint_32 i;
  197705. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197706. {
  197707. png_byte save = *rp;
  197708. *rp = *(rp + 4);
  197709. *(rp + 4) = save;
  197710. save = *(rp + 1);
  197711. *(rp + 1) = *(rp + 5);
  197712. *(rp + 5) = save;
  197713. }
  197714. }
  197715. }
  197716. }
  197717. }
  197718. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197719. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197720. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197721. defined(PNG_LEGACY_SUPPORTED)
  197722. void PNGAPI
  197723. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197724. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197725. {
  197726. png_debug(1, "in png_set_user_transform_info\n");
  197727. if(png_ptr == NULL) return;
  197728. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197729. png_ptr->user_transform_ptr = user_transform_ptr;
  197730. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197731. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197732. #else
  197733. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197734. png_warning(png_ptr,
  197735. "This version of libpng does not support user transform info");
  197736. #endif
  197737. }
  197738. #endif
  197739. /* This function returns a pointer to the user_transform_ptr associated with
  197740. * the user transform functions. The application should free any memory
  197741. * associated with this pointer before png_write_destroy and png_read_destroy
  197742. * are called.
  197743. */
  197744. png_voidp PNGAPI
  197745. png_get_user_transform_ptr(png_structp png_ptr)
  197746. {
  197747. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197748. if (png_ptr == NULL) return (NULL);
  197749. return ((png_voidp)png_ptr->user_transform_ptr);
  197750. #else
  197751. return (NULL);
  197752. #endif
  197753. }
  197754. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197755. /*** End of inlined file: pngtrans.c ***/
  197756. /*** Start of inlined file: pngwio.c ***/
  197757. /* pngwio.c - functions for data output
  197758. *
  197759. * Last changed in libpng 1.2.13 November 13, 2006
  197760. * For conditions of distribution and use, see copyright notice in png.h
  197761. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197762. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197763. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197764. *
  197765. * This file provides a location for all output. Users who need
  197766. * special handling are expected to write functions that have the same
  197767. * arguments as these and perform similar functions, but that possibly
  197768. * use different output methods. Note that you shouldn't change these
  197769. * functions, but rather write replacement functions and then change
  197770. * them at run time with png_set_write_fn(...).
  197771. */
  197772. #define PNG_INTERNAL
  197773. #ifdef PNG_WRITE_SUPPORTED
  197774. /* Write the data to whatever output you are using. The default routine
  197775. writes to a file pointer. Note that this routine sometimes gets called
  197776. with very small lengths, so you should implement some kind of simple
  197777. buffering if you are using unbuffered writes. This should never be asked
  197778. to write more than 64K on a 16 bit machine. */
  197779. void /* PRIVATE */
  197780. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197781. {
  197782. if (png_ptr->write_data_fn != NULL )
  197783. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197784. else
  197785. png_error(png_ptr, "Call to NULL write function");
  197786. }
  197787. #if !defined(PNG_NO_STDIO)
  197788. /* This is the function that does the actual writing of data. If you are
  197789. not writing to a standard C stream, you should create a replacement
  197790. write_data function and use it at run time with png_set_write_fn(), rather
  197791. than changing the library. */
  197792. #ifndef USE_FAR_KEYWORD
  197793. void PNGAPI
  197794. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197795. {
  197796. png_uint_32 check;
  197797. if(png_ptr == NULL) return;
  197798. #if defined(_WIN32_WCE)
  197799. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197800. check = 0;
  197801. #else
  197802. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197803. #endif
  197804. if (check != length)
  197805. png_error(png_ptr, "Write Error");
  197806. }
  197807. #else
  197808. /* this is the model-independent version. Since the standard I/O library
  197809. can't handle far buffers in the medium and small models, we have to copy
  197810. the data.
  197811. */
  197812. #define NEAR_BUF_SIZE 1024
  197813. #define MIN(a,b) (a <= b ? a : b)
  197814. void PNGAPI
  197815. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197816. {
  197817. png_uint_32 check;
  197818. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197819. png_FILE_p io_ptr;
  197820. if(png_ptr == NULL) return;
  197821. /* Check if data really is near. If so, use usual code. */
  197822. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  197823. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  197824. if ((png_bytep)near_data == data)
  197825. {
  197826. #if defined(_WIN32_WCE)
  197827. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  197828. check = 0;
  197829. #else
  197830. check = fwrite(near_data, 1, length, io_ptr);
  197831. #endif
  197832. }
  197833. else
  197834. {
  197835. png_byte buf[NEAR_BUF_SIZE];
  197836. png_size_t written, remaining, err;
  197837. check = 0;
  197838. remaining = length;
  197839. do
  197840. {
  197841. written = MIN(NEAR_BUF_SIZE, remaining);
  197842. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  197843. #if defined(_WIN32_WCE)
  197844. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  197845. err = 0;
  197846. #else
  197847. err = fwrite(buf, 1, written, io_ptr);
  197848. #endif
  197849. if (err != written)
  197850. break;
  197851. else
  197852. check += err;
  197853. data += written;
  197854. remaining -= written;
  197855. }
  197856. while (remaining != 0);
  197857. }
  197858. if (check != length)
  197859. png_error(png_ptr, "Write Error");
  197860. }
  197861. #endif
  197862. #endif
  197863. /* This function is called to output any data pending writing (normally
  197864. to disk). After png_flush is called, there should be no data pending
  197865. writing in any buffers. */
  197866. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197867. void /* PRIVATE */
  197868. png_flush(png_structp png_ptr)
  197869. {
  197870. if (png_ptr->output_flush_fn != NULL)
  197871. (*(png_ptr->output_flush_fn))(png_ptr);
  197872. }
  197873. #if !defined(PNG_NO_STDIO)
  197874. void PNGAPI
  197875. png_default_flush(png_structp png_ptr)
  197876. {
  197877. #if !defined(_WIN32_WCE)
  197878. png_FILE_p io_ptr;
  197879. #endif
  197880. if(png_ptr == NULL) return;
  197881. #if !defined(_WIN32_WCE)
  197882. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  197883. if (io_ptr != NULL)
  197884. fflush(io_ptr);
  197885. #endif
  197886. }
  197887. #endif
  197888. #endif
  197889. /* This function allows the application to supply new output functions for
  197890. libpng if standard C streams aren't being used.
  197891. This function takes as its arguments:
  197892. png_ptr - pointer to a png output data structure
  197893. io_ptr - pointer to user supplied structure containing info about
  197894. the output functions. May be NULL.
  197895. write_data_fn - pointer to a new output function that takes as its
  197896. arguments a pointer to a png_struct, a pointer to
  197897. data to be written, and a 32-bit unsigned int that is
  197898. the number of bytes to be written. The new write
  197899. function should call png_error(png_ptr, "Error msg")
  197900. to exit and output any fatal error messages.
  197901. flush_data_fn - pointer to a new flush function that takes as its
  197902. arguments a pointer to a png_struct. After a call to
  197903. the flush function, there should be no data in any buffers
  197904. or pending transmission. If the output method doesn't do
  197905. any buffering of ouput, a function prototype must still be
  197906. supplied although it doesn't have to do anything. If
  197907. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  197908. time, output_flush_fn will be ignored, although it must be
  197909. supplied for compatibility. */
  197910. void PNGAPI
  197911. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  197912. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  197913. {
  197914. if(png_ptr == NULL) return;
  197915. png_ptr->io_ptr = io_ptr;
  197916. #if !defined(PNG_NO_STDIO)
  197917. if (write_data_fn != NULL)
  197918. png_ptr->write_data_fn = write_data_fn;
  197919. else
  197920. png_ptr->write_data_fn = png_default_write_data;
  197921. #else
  197922. png_ptr->write_data_fn = write_data_fn;
  197923. #endif
  197924. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197925. #if !defined(PNG_NO_STDIO)
  197926. if (output_flush_fn != NULL)
  197927. png_ptr->output_flush_fn = output_flush_fn;
  197928. else
  197929. png_ptr->output_flush_fn = png_default_flush;
  197930. #else
  197931. png_ptr->output_flush_fn = output_flush_fn;
  197932. #endif
  197933. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  197934. /* It is an error to read while writing a png file */
  197935. if (png_ptr->read_data_fn != NULL)
  197936. {
  197937. png_ptr->read_data_fn = NULL;
  197938. png_warning(png_ptr,
  197939. "Attempted to set both read_data_fn and write_data_fn in");
  197940. png_warning(png_ptr,
  197941. "the same structure. Resetting read_data_fn to NULL.");
  197942. }
  197943. }
  197944. #if defined(USE_FAR_KEYWORD)
  197945. #if defined(_MSC_VER)
  197946. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197947. {
  197948. void *near_ptr;
  197949. void FAR *far_ptr;
  197950. FP_OFF(near_ptr) = FP_OFF(ptr);
  197951. far_ptr = (void FAR *)near_ptr;
  197952. if(check != 0)
  197953. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  197954. png_error(png_ptr,"segment lost in conversion");
  197955. return(near_ptr);
  197956. }
  197957. # else
  197958. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197959. {
  197960. void *near_ptr;
  197961. void FAR *far_ptr;
  197962. near_ptr = (void FAR *)ptr;
  197963. far_ptr = (void FAR *)near_ptr;
  197964. if(check != 0)
  197965. if(far_ptr != ptr)
  197966. png_error(png_ptr,"segment lost in conversion");
  197967. return(near_ptr);
  197968. }
  197969. # endif
  197970. # endif
  197971. #endif /* PNG_WRITE_SUPPORTED */
  197972. /*** End of inlined file: pngwio.c ***/
  197973. /*** Start of inlined file: pngwrite.c ***/
  197974. /* pngwrite.c - general routines to write a PNG file
  197975. *
  197976. * Last changed in libpng 1.2.15 January 5, 2007
  197977. * For conditions of distribution and use, see copyright notice in png.h
  197978. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197979. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197980. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197981. */
  197982. /* get internal access to png.h */
  197983. #define PNG_INTERNAL
  197984. #ifdef PNG_WRITE_SUPPORTED
  197985. /* Writes all the PNG information. This is the suggested way to use the
  197986. * library. If you have a new chunk to add, make a function to write it,
  197987. * and put it in the correct location here. If you want the chunk written
  197988. * after the image data, put it in png_write_end(). I strongly encourage
  197989. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  197990. * the chunk, as that will keep the code from breaking if you want to just
  197991. * write a plain PNG file. If you have long comments, I suggest writing
  197992. * them in png_write_end(), and compressing them.
  197993. */
  197994. void PNGAPI
  197995. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  197996. {
  197997. png_debug(1, "in png_write_info_before_PLTE\n");
  197998. if (png_ptr == NULL || info_ptr == NULL)
  197999. return;
  198000. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198001. {
  198002. png_write_sig(png_ptr); /* write PNG signature */
  198003. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198004. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198005. {
  198006. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198007. png_ptr->mng_features_permitted=0;
  198008. }
  198009. #endif
  198010. /* write IHDR information. */
  198011. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198012. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198013. info_ptr->filter_type,
  198014. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198015. info_ptr->interlace_type);
  198016. #else
  198017. 0);
  198018. #endif
  198019. /* the rest of these check to see if the valid field has the appropriate
  198020. flag set, and if it does, writes the chunk. */
  198021. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198022. if (info_ptr->valid & PNG_INFO_gAMA)
  198023. {
  198024. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198025. png_write_gAMA(png_ptr, info_ptr->gamma);
  198026. #else
  198027. #ifdef PNG_FIXED_POINT_SUPPORTED
  198028. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198029. # endif
  198030. #endif
  198031. }
  198032. #endif
  198033. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198034. if (info_ptr->valid & PNG_INFO_sRGB)
  198035. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198036. #endif
  198037. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198038. if (info_ptr->valid & PNG_INFO_iCCP)
  198039. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198040. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198041. #endif
  198042. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198043. if (info_ptr->valid & PNG_INFO_sBIT)
  198044. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198045. #endif
  198046. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198047. if (info_ptr->valid & PNG_INFO_cHRM)
  198048. {
  198049. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198050. png_write_cHRM(png_ptr,
  198051. info_ptr->x_white, info_ptr->y_white,
  198052. info_ptr->x_red, info_ptr->y_red,
  198053. info_ptr->x_green, info_ptr->y_green,
  198054. info_ptr->x_blue, info_ptr->y_blue);
  198055. #else
  198056. # ifdef PNG_FIXED_POINT_SUPPORTED
  198057. png_write_cHRM_fixed(png_ptr,
  198058. info_ptr->int_x_white, info_ptr->int_y_white,
  198059. info_ptr->int_x_red, info_ptr->int_y_red,
  198060. info_ptr->int_x_green, info_ptr->int_y_green,
  198061. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198062. # endif
  198063. #endif
  198064. }
  198065. #endif
  198066. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198067. if (info_ptr->unknown_chunks_num)
  198068. {
  198069. png_unknown_chunk *up;
  198070. png_debug(5, "writing extra chunks\n");
  198071. for (up = info_ptr->unknown_chunks;
  198072. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198073. up++)
  198074. {
  198075. int keep=png_handle_as_unknown(png_ptr, up->name);
  198076. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198077. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198078. !(up->location & PNG_HAVE_IDAT) &&
  198079. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198080. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198081. {
  198082. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198083. }
  198084. }
  198085. }
  198086. #endif
  198087. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198088. }
  198089. }
  198090. void PNGAPI
  198091. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198092. {
  198093. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198094. int i;
  198095. #endif
  198096. png_debug(1, "in png_write_info\n");
  198097. if (png_ptr == NULL || info_ptr == NULL)
  198098. return;
  198099. png_write_info_before_PLTE(png_ptr, info_ptr);
  198100. if (info_ptr->valid & PNG_INFO_PLTE)
  198101. png_write_PLTE(png_ptr, info_ptr->palette,
  198102. (png_uint_32)info_ptr->num_palette);
  198103. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198104. png_error(png_ptr, "Valid palette required for paletted images");
  198105. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198106. if (info_ptr->valid & PNG_INFO_tRNS)
  198107. {
  198108. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198109. /* invert the alpha channel (in tRNS) */
  198110. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198111. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198112. {
  198113. int j;
  198114. for (j=0; j<(int)info_ptr->num_trans; j++)
  198115. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198116. }
  198117. #endif
  198118. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198119. info_ptr->num_trans, info_ptr->color_type);
  198120. }
  198121. #endif
  198122. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198123. if (info_ptr->valid & PNG_INFO_bKGD)
  198124. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198125. #endif
  198126. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198127. if (info_ptr->valid & PNG_INFO_hIST)
  198128. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198129. #endif
  198130. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198131. if (info_ptr->valid & PNG_INFO_oFFs)
  198132. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198133. info_ptr->offset_unit_type);
  198134. #endif
  198135. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198136. if (info_ptr->valid & PNG_INFO_pCAL)
  198137. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198138. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198139. info_ptr->pcal_units, info_ptr->pcal_params);
  198140. #endif
  198141. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198142. if (info_ptr->valid & PNG_INFO_sCAL)
  198143. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198144. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198145. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198146. #else
  198147. #ifdef PNG_FIXED_POINT_SUPPORTED
  198148. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198149. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198150. #else
  198151. png_warning(png_ptr,
  198152. "png_write_sCAL not supported; sCAL chunk not written.");
  198153. #endif
  198154. #endif
  198155. #endif
  198156. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198157. if (info_ptr->valid & PNG_INFO_pHYs)
  198158. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198159. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198160. #endif
  198161. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198162. if (info_ptr->valid & PNG_INFO_tIME)
  198163. {
  198164. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198165. png_ptr->mode |= PNG_WROTE_tIME;
  198166. }
  198167. #endif
  198168. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198169. if (info_ptr->valid & PNG_INFO_sPLT)
  198170. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198171. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198172. #endif
  198173. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198174. /* Check to see if we need to write text chunks */
  198175. for (i = 0; i < info_ptr->num_text; i++)
  198176. {
  198177. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198178. info_ptr->text[i].compression);
  198179. /* an internationalized chunk? */
  198180. if (info_ptr->text[i].compression > 0)
  198181. {
  198182. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198183. /* write international chunk */
  198184. png_write_iTXt(png_ptr,
  198185. info_ptr->text[i].compression,
  198186. info_ptr->text[i].key,
  198187. info_ptr->text[i].lang,
  198188. info_ptr->text[i].lang_key,
  198189. info_ptr->text[i].text);
  198190. #else
  198191. png_warning(png_ptr, "Unable to write international text");
  198192. #endif
  198193. /* Mark this chunk as written */
  198194. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198195. }
  198196. /* If we want a compressed text chunk */
  198197. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198198. {
  198199. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198200. /* write compressed chunk */
  198201. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198202. info_ptr->text[i].text, 0,
  198203. info_ptr->text[i].compression);
  198204. #else
  198205. png_warning(png_ptr, "Unable to write compressed text");
  198206. #endif
  198207. /* Mark this chunk as written */
  198208. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198209. }
  198210. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198211. {
  198212. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198213. /* write uncompressed chunk */
  198214. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198215. info_ptr->text[i].text,
  198216. 0);
  198217. #else
  198218. png_warning(png_ptr, "Unable to write uncompressed text");
  198219. #endif
  198220. /* Mark this chunk as written */
  198221. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198222. }
  198223. }
  198224. #endif
  198225. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198226. if (info_ptr->unknown_chunks_num)
  198227. {
  198228. png_unknown_chunk *up;
  198229. png_debug(5, "writing extra chunks\n");
  198230. for (up = info_ptr->unknown_chunks;
  198231. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198232. up++)
  198233. {
  198234. int keep=png_handle_as_unknown(png_ptr, up->name);
  198235. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198236. up->location && (up->location & PNG_HAVE_PLTE) &&
  198237. !(up->location & PNG_HAVE_IDAT) &&
  198238. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198239. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198240. {
  198241. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198242. }
  198243. }
  198244. }
  198245. #endif
  198246. }
  198247. /* Writes the end of the PNG file. If you don't want to write comments or
  198248. * time information, you can pass NULL for info. If you already wrote these
  198249. * in png_write_info(), do not write them again here. If you have long
  198250. * comments, I suggest writing them here, and compressing them.
  198251. */
  198252. void PNGAPI
  198253. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198254. {
  198255. png_debug(1, "in png_write_end\n");
  198256. if (png_ptr == NULL)
  198257. return;
  198258. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198259. png_error(png_ptr, "No IDATs written into file");
  198260. /* see if user wants us to write information chunks */
  198261. if (info_ptr != NULL)
  198262. {
  198263. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198264. int i; /* local index variable */
  198265. #endif
  198266. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198267. /* check to see if user has supplied a time chunk */
  198268. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198269. !(png_ptr->mode & PNG_WROTE_tIME))
  198270. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198271. #endif
  198272. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198273. /* loop through comment chunks */
  198274. for (i = 0; i < info_ptr->num_text; i++)
  198275. {
  198276. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198277. info_ptr->text[i].compression);
  198278. /* an internationalized chunk? */
  198279. if (info_ptr->text[i].compression > 0)
  198280. {
  198281. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198282. /* write international chunk */
  198283. png_write_iTXt(png_ptr,
  198284. info_ptr->text[i].compression,
  198285. info_ptr->text[i].key,
  198286. info_ptr->text[i].lang,
  198287. info_ptr->text[i].lang_key,
  198288. info_ptr->text[i].text);
  198289. #else
  198290. png_warning(png_ptr, "Unable to write international text");
  198291. #endif
  198292. /* Mark this chunk as written */
  198293. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198294. }
  198295. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198296. {
  198297. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198298. /* write compressed chunk */
  198299. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198300. info_ptr->text[i].text, 0,
  198301. info_ptr->text[i].compression);
  198302. #else
  198303. png_warning(png_ptr, "Unable to write compressed text");
  198304. #endif
  198305. /* Mark this chunk as written */
  198306. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198307. }
  198308. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198309. {
  198310. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198311. /* write uncompressed chunk */
  198312. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198313. info_ptr->text[i].text, 0);
  198314. #else
  198315. png_warning(png_ptr, "Unable to write uncompressed text");
  198316. #endif
  198317. /* Mark this chunk as written */
  198318. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198319. }
  198320. }
  198321. #endif
  198322. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198323. if (info_ptr->unknown_chunks_num)
  198324. {
  198325. png_unknown_chunk *up;
  198326. png_debug(5, "writing extra chunks\n");
  198327. for (up = info_ptr->unknown_chunks;
  198328. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198329. up++)
  198330. {
  198331. int keep=png_handle_as_unknown(png_ptr, up->name);
  198332. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198333. up->location && (up->location & PNG_AFTER_IDAT) &&
  198334. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198335. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198336. {
  198337. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198338. }
  198339. }
  198340. }
  198341. #endif
  198342. }
  198343. png_ptr->mode |= PNG_AFTER_IDAT;
  198344. /* write end of PNG file */
  198345. png_write_IEND(png_ptr);
  198346. }
  198347. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198348. #if !defined(_WIN32_WCE)
  198349. /* "time.h" functions are not supported on WindowsCE */
  198350. void PNGAPI
  198351. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198352. {
  198353. png_debug(1, "in png_convert_from_struct_tm\n");
  198354. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198355. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198356. ptime->day = (png_byte)ttime->tm_mday;
  198357. ptime->hour = (png_byte)ttime->tm_hour;
  198358. ptime->minute = (png_byte)ttime->tm_min;
  198359. ptime->second = (png_byte)ttime->tm_sec;
  198360. }
  198361. void PNGAPI
  198362. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198363. {
  198364. struct tm *tbuf;
  198365. png_debug(1, "in png_convert_from_time_t\n");
  198366. tbuf = gmtime(&ttime);
  198367. png_convert_from_struct_tm(ptime, tbuf);
  198368. }
  198369. #endif
  198370. #endif
  198371. /* Initialize png_ptr structure, and allocate any memory needed */
  198372. png_structp PNGAPI
  198373. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198374. png_error_ptr error_fn, png_error_ptr warn_fn)
  198375. {
  198376. #ifdef PNG_USER_MEM_SUPPORTED
  198377. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198378. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198379. }
  198380. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198381. png_structp PNGAPI
  198382. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198383. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198384. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198385. {
  198386. #endif /* PNG_USER_MEM_SUPPORTED */
  198387. png_structp png_ptr;
  198388. #ifdef PNG_SETJMP_SUPPORTED
  198389. #ifdef USE_FAR_KEYWORD
  198390. jmp_buf jmpbuf;
  198391. #endif
  198392. #endif
  198393. int i;
  198394. png_debug(1, "in png_create_write_struct\n");
  198395. #ifdef PNG_USER_MEM_SUPPORTED
  198396. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198397. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198398. #else
  198399. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198400. #endif /* PNG_USER_MEM_SUPPORTED */
  198401. if (png_ptr == NULL)
  198402. return (NULL);
  198403. /* added at libpng-1.2.6 */
  198404. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198405. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198406. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198407. #endif
  198408. #ifdef PNG_SETJMP_SUPPORTED
  198409. #ifdef USE_FAR_KEYWORD
  198410. if (setjmp(jmpbuf))
  198411. #else
  198412. if (setjmp(png_ptr->jmpbuf))
  198413. #endif
  198414. {
  198415. png_free(png_ptr, png_ptr->zbuf);
  198416. png_ptr->zbuf=NULL;
  198417. png_destroy_struct(png_ptr);
  198418. return (NULL);
  198419. }
  198420. #ifdef USE_FAR_KEYWORD
  198421. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198422. #endif
  198423. #endif
  198424. #ifdef PNG_USER_MEM_SUPPORTED
  198425. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198426. #endif /* PNG_USER_MEM_SUPPORTED */
  198427. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198428. i=0;
  198429. do
  198430. {
  198431. if(user_png_ver[i] != png_libpng_ver[i])
  198432. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198433. } while (png_libpng_ver[i++]);
  198434. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198435. {
  198436. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198437. * we must recompile any applications that use any older library version.
  198438. * For versions after libpng 1.0, we will be compatible, so we need
  198439. * only check the first digit.
  198440. */
  198441. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198442. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198443. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198444. {
  198445. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198446. char msg[80];
  198447. if (user_png_ver)
  198448. {
  198449. png_snprintf(msg, 80,
  198450. "Application was compiled with png.h from libpng-%.20s",
  198451. user_png_ver);
  198452. png_warning(png_ptr, msg);
  198453. }
  198454. png_snprintf(msg, 80,
  198455. "Application is running with png.c from libpng-%.20s",
  198456. png_libpng_ver);
  198457. png_warning(png_ptr, msg);
  198458. #endif
  198459. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198460. png_ptr->flags=0;
  198461. #endif
  198462. png_error(png_ptr,
  198463. "Incompatible libpng version in application and library");
  198464. }
  198465. }
  198466. /* initialize zbuf - compression buffer */
  198467. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198468. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198469. (png_uint_32)png_ptr->zbuf_size);
  198470. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198471. png_flush_ptr_NULL);
  198472. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198473. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198474. 1, png_doublep_NULL, png_doublep_NULL);
  198475. #endif
  198476. #ifdef PNG_SETJMP_SUPPORTED
  198477. /* Applications that neglect to set up their own setjmp() and then encounter
  198478. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198479. abort instead of returning. */
  198480. #ifdef USE_FAR_KEYWORD
  198481. if (setjmp(jmpbuf))
  198482. PNG_ABORT();
  198483. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198484. #else
  198485. if (setjmp(png_ptr->jmpbuf))
  198486. PNG_ABORT();
  198487. #endif
  198488. #endif
  198489. return (png_ptr);
  198490. }
  198491. /* Initialize png_ptr structure, and allocate any memory needed */
  198492. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198493. /* Deprecated. */
  198494. #undef png_write_init
  198495. void PNGAPI
  198496. png_write_init(png_structp png_ptr)
  198497. {
  198498. /* We only come here via pre-1.0.7-compiled applications */
  198499. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198500. }
  198501. void PNGAPI
  198502. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198503. png_size_t png_struct_size, png_size_t png_info_size)
  198504. {
  198505. /* We only come here via pre-1.0.12-compiled applications */
  198506. if(png_ptr == NULL) return;
  198507. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198508. if(png_sizeof(png_struct) > png_struct_size ||
  198509. png_sizeof(png_info) > png_info_size)
  198510. {
  198511. char msg[80];
  198512. png_ptr->warning_fn=NULL;
  198513. if (user_png_ver)
  198514. {
  198515. png_snprintf(msg, 80,
  198516. "Application was compiled with png.h from libpng-%.20s",
  198517. user_png_ver);
  198518. png_warning(png_ptr, msg);
  198519. }
  198520. png_snprintf(msg, 80,
  198521. "Application is running with png.c from libpng-%.20s",
  198522. png_libpng_ver);
  198523. png_warning(png_ptr, msg);
  198524. }
  198525. #endif
  198526. if(png_sizeof(png_struct) > png_struct_size)
  198527. {
  198528. png_ptr->error_fn=NULL;
  198529. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198530. png_ptr->flags=0;
  198531. #endif
  198532. png_error(png_ptr,
  198533. "The png struct allocated by the application for writing is too small.");
  198534. }
  198535. if(png_sizeof(png_info) > png_info_size)
  198536. {
  198537. png_ptr->error_fn=NULL;
  198538. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198539. png_ptr->flags=0;
  198540. #endif
  198541. png_error(png_ptr,
  198542. "The info struct allocated by the application for writing is too small.");
  198543. }
  198544. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198545. }
  198546. #endif /* PNG_1_0_X || PNG_1_2_X */
  198547. void PNGAPI
  198548. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198549. png_size_t png_struct_size)
  198550. {
  198551. png_structp png_ptr=*ptr_ptr;
  198552. #ifdef PNG_SETJMP_SUPPORTED
  198553. jmp_buf tmp_jmp; /* to save current jump buffer */
  198554. #endif
  198555. int i = 0;
  198556. if (png_ptr == NULL)
  198557. return;
  198558. do
  198559. {
  198560. if (user_png_ver[i] != png_libpng_ver[i])
  198561. {
  198562. #ifdef PNG_LEGACY_SUPPORTED
  198563. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198564. #else
  198565. png_ptr->warning_fn=NULL;
  198566. png_warning(png_ptr,
  198567. "Application uses deprecated png_write_init() and should be recompiled.");
  198568. break;
  198569. #endif
  198570. }
  198571. } while (png_libpng_ver[i++]);
  198572. png_debug(1, "in png_write_init_3\n");
  198573. #ifdef PNG_SETJMP_SUPPORTED
  198574. /* save jump buffer and error functions */
  198575. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198576. #endif
  198577. if (png_sizeof(png_struct) > png_struct_size)
  198578. {
  198579. png_destroy_struct(png_ptr);
  198580. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198581. *ptr_ptr = png_ptr;
  198582. }
  198583. /* reset all variables to 0 */
  198584. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198585. /* added at libpng-1.2.6 */
  198586. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198587. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198588. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198589. #endif
  198590. #ifdef PNG_SETJMP_SUPPORTED
  198591. /* restore jump buffer */
  198592. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198593. #endif
  198594. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198595. png_flush_ptr_NULL);
  198596. /* initialize zbuf - compression buffer */
  198597. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198598. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198599. (png_uint_32)png_ptr->zbuf_size);
  198600. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198601. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198602. 1, png_doublep_NULL, png_doublep_NULL);
  198603. #endif
  198604. }
  198605. /* Write a few rows of image data. If the image is interlaced,
  198606. * either you will have to write the 7 sub images, or, if you
  198607. * have called png_set_interlace_handling(), you will have to
  198608. * "write" the image seven times.
  198609. */
  198610. void PNGAPI
  198611. png_write_rows(png_structp png_ptr, png_bytepp row,
  198612. png_uint_32 num_rows)
  198613. {
  198614. png_uint_32 i; /* row counter */
  198615. png_bytepp rp; /* row pointer */
  198616. png_debug(1, "in png_write_rows\n");
  198617. if (png_ptr == NULL)
  198618. return;
  198619. /* loop through the rows */
  198620. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198621. {
  198622. png_write_row(png_ptr, *rp);
  198623. }
  198624. }
  198625. /* Write the image. You only need to call this function once, even
  198626. * if you are writing an interlaced image.
  198627. */
  198628. void PNGAPI
  198629. png_write_image(png_structp png_ptr, png_bytepp image)
  198630. {
  198631. png_uint_32 i; /* row index */
  198632. int pass, num_pass; /* pass variables */
  198633. png_bytepp rp; /* points to current row */
  198634. if (png_ptr == NULL)
  198635. return;
  198636. png_debug(1, "in png_write_image\n");
  198637. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198638. /* intialize interlace handling. If image is not interlaced,
  198639. this will set pass to 1 */
  198640. num_pass = png_set_interlace_handling(png_ptr);
  198641. #else
  198642. num_pass = 1;
  198643. #endif
  198644. /* loop through passes */
  198645. for (pass = 0; pass < num_pass; pass++)
  198646. {
  198647. /* loop through image */
  198648. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198649. {
  198650. png_write_row(png_ptr, *rp);
  198651. }
  198652. }
  198653. }
  198654. /* called by user to write a row of image data */
  198655. void PNGAPI
  198656. png_write_row(png_structp png_ptr, png_bytep row)
  198657. {
  198658. if (png_ptr == NULL)
  198659. return;
  198660. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198661. png_ptr->row_number, png_ptr->pass);
  198662. /* initialize transformations and other stuff if first time */
  198663. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198664. {
  198665. /* make sure we wrote the header info */
  198666. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198667. png_error(png_ptr,
  198668. "png_write_info was never called before png_write_row.");
  198669. /* check for transforms that have been set but were defined out */
  198670. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198671. if (png_ptr->transformations & PNG_INVERT_MONO)
  198672. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198673. #endif
  198674. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198675. if (png_ptr->transformations & PNG_FILLER)
  198676. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198677. #endif
  198678. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198679. if (png_ptr->transformations & PNG_PACKSWAP)
  198680. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198681. #endif
  198682. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198683. if (png_ptr->transformations & PNG_PACK)
  198684. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198685. #endif
  198686. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198687. if (png_ptr->transformations & PNG_SHIFT)
  198688. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198689. #endif
  198690. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198691. if (png_ptr->transformations & PNG_BGR)
  198692. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198693. #endif
  198694. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198695. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198696. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198697. #endif
  198698. png_write_start_row(png_ptr);
  198699. }
  198700. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198701. /* if interlaced and not interested in row, return */
  198702. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198703. {
  198704. switch (png_ptr->pass)
  198705. {
  198706. case 0:
  198707. if (png_ptr->row_number & 0x07)
  198708. {
  198709. png_write_finish_row(png_ptr);
  198710. return;
  198711. }
  198712. break;
  198713. case 1:
  198714. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198715. {
  198716. png_write_finish_row(png_ptr);
  198717. return;
  198718. }
  198719. break;
  198720. case 2:
  198721. if ((png_ptr->row_number & 0x07) != 4)
  198722. {
  198723. png_write_finish_row(png_ptr);
  198724. return;
  198725. }
  198726. break;
  198727. case 3:
  198728. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198729. {
  198730. png_write_finish_row(png_ptr);
  198731. return;
  198732. }
  198733. break;
  198734. case 4:
  198735. if ((png_ptr->row_number & 0x03) != 2)
  198736. {
  198737. png_write_finish_row(png_ptr);
  198738. return;
  198739. }
  198740. break;
  198741. case 5:
  198742. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198743. {
  198744. png_write_finish_row(png_ptr);
  198745. return;
  198746. }
  198747. break;
  198748. case 6:
  198749. if (!(png_ptr->row_number & 0x01))
  198750. {
  198751. png_write_finish_row(png_ptr);
  198752. return;
  198753. }
  198754. break;
  198755. }
  198756. }
  198757. #endif
  198758. /* set up row info for transformations */
  198759. png_ptr->row_info.color_type = png_ptr->color_type;
  198760. png_ptr->row_info.width = png_ptr->usr_width;
  198761. png_ptr->row_info.channels = png_ptr->usr_channels;
  198762. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198763. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198764. png_ptr->row_info.channels);
  198765. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198766. png_ptr->row_info.width);
  198767. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198768. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198769. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198770. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198771. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198772. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198773. /* Copy user's row into buffer, leaving room for filter byte. */
  198774. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198775. png_ptr->row_info.rowbytes);
  198776. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198777. /* handle interlacing */
  198778. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198779. (png_ptr->transformations & PNG_INTERLACE))
  198780. {
  198781. png_do_write_interlace(&(png_ptr->row_info),
  198782. png_ptr->row_buf + 1, png_ptr->pass);
  198783. /* this should always get caught above, but still ... */
  198784. if (!(png_ptr->row_info.width))
  198785. {
  198786. png_write_finish_row(png_ptr);
  198787. return;
  198788. }
  198789. }
  198790. #endif
  198791. /* handle other transformations */
  198792. if (png_ptr->transformations)
  198793. png_do_write_transformations(png_ptr);
  198794. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198795. /* Write filter_method 64 (intrapixel differencing) only if
  198796. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198797. * 2. Libpng did not write a PNG signature (this filter_method is only
  198798. * used in PNG datastreams that are embedded in MNG datastreams) and
  198799. * 3. The application called png_permit_mng_features with a mask that
  198800. * included PNG_FLAG_MNG_FILTER_64 and
  198801. * 4. The filter_method is 64 and
  198802. * 5. The color_type is RGB or RGBA
  198803. */
  198804. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198805. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198806. {
  198807. /* Intrapixel differencing */
  198808. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198809. }
  198810. #endif
  198811. /* Find a filter if necessary, filter the row and write it out. */
  198812. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198813. if (png_ptr->write_row_fn != NULL)
  198814. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198815. }
  198816. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198817. /* Set the automatic flush interval or 0 to turn flushing off */
  198818. void PNGAPI
  198819. png_set_flush(png_structp png_ptr, int nrows)
  198820. {
  198821. png_debug(1, "in png_set_flush\n");
  198822. if (png_ptr == NULL)
  198823. return;
  198824. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  198825. }
  198826. /* flush the current output buffers now */
  198827. void PNGAPI
  198828. png_write_flush(png_structp png_ptr)
  198829. {
  198830. int wrote_IDAT;
  198831. png_debug(1, "in png_write_flush\n");
  198832. if (png_ptr == NULL)
  198833. return;
  198834. /* We have already written out all of the data */
  198835. if (png_ptr->row_number >= png_ptr->num_rows)
  198836. return;
  198837. do
  198838. {
  198839. int ret;
  198840. /* compress the data */
  198841. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  198842. wrote_IDAT = 0;
  198843. /* check for compression errors */
  198844. if (ret != Z_OK)
  198845. {
  198846. if (png_ptr->zstream.msg != NULL)
  198847. png_error(png_ptr, png_ptr->zstream.msg);
  198848. else
  198849. png_error(png_ptr, "zlib error");
  198850. }
  198851. if (!(png_ptr->zstream.avail_out))
  198852. {
  198853. /* write the IDAT and reset the zlib output buffer */
  198854. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198855. png_ptr->zbuf_size);
  198856. png_ptr->zstream.next_out = png_ptr->zbuf;
  198857. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198858. wrote_IDAT = 1;
  198859. }
  198860. } while(wrote_IDAT == 1);
  198861. /* If there is any data left to be output, write it into a new IDAT */
  198862. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  198863. {
  198864. /* write the IDAT and reset the zlib output buffer */
  198865. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198866. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  198867. png_ptr->zstream.next_out = png_ptr->zbuf;
  198868. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198869. }
  198870. png_ptr->flush_rows = 0;
  198871. png_flush(png_ptr);
  198872. }
  198873. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198874. /* free all memory used by the write */
  198875. void PNGAPI
  198876. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  198877. {
  198878. png_structp png_ptr = NULL;
  198879. png_infop info_ptr = NULL;
  198880. #ifdef PNG_USER_MEM_SUPPORTED
  198881. png_free_ptr free_fn = NULL;
  198882. png_voidp mem_ptr = NULL;
  198883. #endif
  198884. png_debug(1, "in png_destroy_write_struct\n");
  198885. if (png_ptr_ptr != NULL)
  198886. {
  198887. png_ptr = *png_ptr_ptr;
  198888. #ifdef PNG_USER_MEM_SUPPORTED
  198889. free_fn = png_ptr->free_fn;
  198890. mem_ptr = png_ptr->mem_ptr;
  198891. #endif
  198892. }
  198893. if (info_ptr_ptr != NULL)
  198894. info_ptr = *info_ptr_ptr;
  198895. if (info_ptr != NULL)
  198896. {
  198897. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  198898. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198899. if (png_ptr->num_chunk_list)
  198900. {
  198901. png_free(png_ptr, png_ptr->chunk_list);
  198902. png_ptr->chunk_list=NULL;
  198903. png_ptr->num_chunk_list=0;
  198904. }
  198905. #endif
  198906. #ifdef PNG_USER_MEM_SUPPORTED
  198907. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  198908. (png_voidp)mem_ptr);
  198909. #else
  198910. png_destroy_struct((png_voidp)info_ptr);
  198911. #endif
  198912. *info_ptr_ptr = NULL;
  198913. }
  198914. if (png_ptr != NULL)
  198915. {
  198916. png_write_destroy(png_ptr);
  198917. #ifdef PNG_USER_MEM_SUPPORTED
  198918. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  198919. (png_voidp)mem_ptr);
  198920. #else
  198921. png_destroy_struct((png_voidp)png_ptr);
  198922. #endif
  198923. *png_ptr_ptr = NULL;
  198924. }
  198925. }
  198926. /* Free any memory used in png_ptr struct (old method) */
  198927. void /* PRIVATE */
  198928. png_write_destroy(png_structp png_ptr)
  198929. {
  198930. #ifdef PNG_SETJMP_SUPPORTED
  198931. jmp_buf tmp_jmp; /* save jump buffer */
  198932. #endif
  198933. png_error_ptr error_fn;
  198934. png_error_ptr warning_fn;
  198935. png_voidp error_ptr;
  198936. #ifdef PNG_USER_MEM_SUPPORTED
  198937. png_free_ptr free_fn;
  198938. #endif
  198939. png_debug(1, "in png_write_destroy\n");
  198940. /* free any memory zlib uses */
  198941. deflateEnd(&png_ptr->zstream);
  198942. /* free our memory. png_free checks NULL for us. */
  198943. png_free(png_ptr, png_ptr->zbuf);
  198944. png_free(png_ptr, png_ptr->row_buf);
  198945. png_free(png_ptr, png_ptr->prev_row);
  198946. png_free(png_ptr, png_ptr->sub_row);
  198947. png_free(png_ptr, png_ptr->up_row);
  198948. png_free(png_ptr, png_ptr->avg_row);
  198949. png_free(png_ptr, png_ptr->paeth_row);
  198950. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  198951. png_free(png_ptr, png_ptr->time_buffer);
  198952. #endif
  198953. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198954. png_free(png_ptr, png_ptr->prev_filters);
  198955. png_free(png_ptr, png_ptr->filter_weights);
  198956. png_free(png_ptr, png_ptr->inv_filter_weights);
  198957. png_free(png_ptr, png_ptr->filter_costs);
  198958. png_free(png_ptr, png_ptr->inv_filter_costs);
  198959. #endif
  198960. #ifdef PNG_SETJMP_SUPPORTED
  198961. /* reset structure */
  198962. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198963. #endif
  198964. error_fn = png_ptr->error_fn;
  198965. warning_fn = png_ptr->warning_fn;
  198966. error_ptr = png_ptr->error_ptr;
  198967. #ifdef PNG_USER_MEM_SUPPORTED
  198968. free_fn = png_ptr->free_fn;
  198969. #endif
  198970. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198971. png_ptr->error_fn = error_fn;
  198972. png_ptr->warning_fn = warning_fn;
  198973. png_ptr->error_ptr = error_ptr;
  198974. #ifdef PNG_USER_MEM_SUPPORTED
  198975. png_ptr->free_fn = free_fn;
  198976. #endif
  198977. #ifdef PNG_SETJMP_SUPPORTED
  198978. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198979. #endif
  198980. }
  198981. /* Allow the application to select one or more row filters to use. */
  198982. void PNGAPI
  198983. png_set_filter(png_structp png_ptr, int method, int filters)
  198984. {
  198985. png_debug(1, "in png_set_filter\n");
  198986. if (png_ptr == NULL)
  198987. return;
  198988. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198989. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198990. (method == PNG_INTRAPIXEL_DIFFERENCING))
  198991. method = PNG_FILTER_TYPE_BASE;
  198992. #endif
  198993. if (method == PNG_FILTER_TYPE_BASE)
  198994. {
  198995. switch (filters & (PNG_ALL_FILTERS | 0x07))
  198996. {
  198997. #ifndef PNG_NO_WRITE_FILTER
  198998. case 5:
  198999. case 6:
  199000. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199001. #endif /* PNG_NO_WRITE_FILTER */
  199002. case PNG_FILTER_VALUE_NONE:
  199003. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199004. #ifndef PNG_NO_WRITE_FILTER
  199005. case PNG_FILTER_VALUE_SUB:
  199006. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199007. case PNG_FILTER_VALUE_UP:
  199008. png_ptr->do_filter=PNG_FILTER_UP; break;
  199009. case PNG_FILTER_VALUE_AVG:
  199010. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199011. case PNG_FILTER_VALUE_PAETH:
  199012. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199013. default: png_ptr->do_filter = (png_byte)filters; break;
  199014. #else
  199015. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199016. #endif /* PNG_NO_WRITE_FILTER */
  199017. }
  199018. /* If we have allocated the row_buf, this means we have already started
  199019. * with the image and we should have allocated all of the filter buffers
  199020. * that have been selected. If prev_row isn't already allocated, then
  199021. * it is too late to start using the filters that need it, since we
  199022. * will be missing the data in the previous row. If an application
  199023. * wants to start and stop using particular filters during compression,
  199024. * it should start out with all of the filters, and then add and
  199025. * remove them after the start of compression.
  199026. */
  199027. if (png_ptr->row_buf != NULL)
  199028. {
  199029. #ifndef PNG_NO_WRITE_FILTER
  199030. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199031. {
  199032. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199033. (png_ptr->rowbytes + 1));
  199034. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199035. }
  199036. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199037. {
  199038. if (png_ptr->prev_row == NULL)
  199039. {
  199040. png_warning(png_ptr, "Can't add Up filter after starting");
  199041. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199042. }
  199043. else
  199044. {
  199045. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199046. (png_ptr->rowbytes + 1));
  199047. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199048. }
  199049. }
  199050. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199051. {
  199052. if (png_ptr->prev_row == NULL)
  199053. {
  199054. png_warning(png_ptr, "Can't add Average filter after starting");
  199055. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199056. }
  199057. else
  199058. {
  199059. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199060. (png_ptr->rowbytes + 1));
  199061. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199062. }
  199063. }
  199064. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199065. png_ptr->paeth_row == NULL)
  199066. {
  199067. if (png_ptr->prev_row == NULL)
  199068. {
  199069. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199070. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199071. }
  199072. else
  199073. {
  199074. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199075. (png_ptr->rowbytes + 1));
  199076. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199077. }
  199078. }
  199079. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199080. #endif /* PNG_NO_WRITE_FILTER */
  199081. png_ptr->do_filter = PNG_FILTER_NONE;
  199082. }
  199083. }
  199084. else
  199085. png_error(png_ptr, "Unknown custom filter method");
  199086. }
  199087. /* This allows us to influence the way in which libpng chooses the "best"
  199088. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199089. * differences metric is relatively fast and effective, there is some
  199090. * question as to whether it can be improved upon by trying to keep the
  199091. * filtered data going to zlib more consistent, hopefully resulting in
  199092. * better compression.
  199093. */
  199094. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199095. void PNGAPI
  199096. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199097. int num_weights, png_doublep filter_weights,
  199098. png_doublep filter_costs)
  199099. {
  199100. int i;
  199101. png_debug(1, "in png_set_filter_heuristics\n");
  199102. if (png_ptr == NULL)
  199103. return;
  199104. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199105. {
  199106. png_warning(png_ptr, "Unknown filter heuristic method");
  199107. return;
  199108. }
  199109. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199110. {
  199111. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199112. }
  199113. if (num_weights < 0 || filter_weights == NULL ||
  199114. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199115. {
  199116. num_weights = 0;
  199117. }
  199118. png_ptr->num_prev_filters = (png_byte)num_weights;
  199119. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199120. if (num_weights > 0)
  199121. {
  199122. if (png_ptr->prev_filters == NULL)
  199123. {
  199124. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199125. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199126. /* To make sure that the weighting starts out fairly */
  199127. for (i = 0; i < num_weights; i++)
  199128. {
  199129. png_ptr->prev_filters[i] = 255;
  199130. }
  199131. }
  199132. if (png_ptr->filter_weights == NULL)
  199133. {
  199134. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199135. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199136. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199137. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199138. for (i = 0; i < num_weights; i++)
  199139. {
  199140. png_ptr->inv_filter_weights[i] =
  199141. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199142. }
  199143. }
  199144. for (i = 0; i < num_weights; i++)
  199145. {
  199146. if (filter_weights[i] < 0.0)
  199147. {
  199148. png_ptr->inv_filter_weights[i] =
  199149. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199150. }
  199151. else
  199152. {
  199153. png_ptr->inv_filter_weights[i] =
  199154. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199155. png_ptr->filter_weights[i] =
  199156. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199157. }
  199158. }
  199159. }
  199160. /* If, in the future, there are other filter methods, this would
  199161. * need to be based on png_ptr->filter.
  199162. */
  199163. if (png_ptr->filter_costs == NULL)
  199164. {
  199165. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199166. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199167. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199168. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199169. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199170. {
  199171. png_ptr->inv_filter_costs[i] =
  199172. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199173. }
  199174. }
  199175. /* Here is where we set the relative costs of the different filters. We
  199176. * should take the desired compression level into account when setting
  199177. * the costs, so that Paeth, for instance, has a high relative cost at low
  199178. * compression levels, while it has a lower relative cost at higher
  199179. * compression settings. The filter types are in order of increasing
  199180. * relative cost, so it would be possible to do this with an algorithm.
  199181. */
  199182. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199183. {
  199184. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199185. {
  199186. png_ptr->inv_filter_costs[i] =
  199187. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199188. }
  199189. else if (filter_costs[i] >= 1.0)
  199190. {
  199191. png_ptr->inv_filter_costs[i] =
  199192. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199193. png_ptr->filter_costs[i] =
  199194. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199195. }
  199196. }
  199197. }
  199198. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199199. void PNGAPI
  199200. png_set_compression_level(png_structp png_ptr, int level)
  199201. {
  199202. png_debug(1, "in png_set_compression_level\n");
  199203. if (png_ptr == NULL)
  199204. return;
  199205. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199206. png_ptr->zlib_level = level;
  199207. }
  199208. void PNGAPI
  199209. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199210. {
  199211. png_debug(1, "in png_set_compression_mem_level\n");
  199212. if (png_ptr == NULL)
  199213. return;
  199214. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199215. png_ptr->zlib_mem_level = mem_level;
  199216. }
  199217. void PNGAPI
  199218. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199219. {
  199220. png_debug(1, "in png_set_compression_strategy\n");
  199221. if (png_ptr == NULL)
  199222. return;
  199223. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199224. png_ptr->zlib_strategy = strategy;
  199225. }
  199226. void PNGAPI
  199227. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199228. {
  199229. if (png_ptr == NULL)
  199230. return;
  199231. if (window_bits > 15)
  199232. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199233. else if (window_bits < 8)
  199234. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199235. #ifndef WBITS_8_OK
  199236. /* avoid libpng bug with 256-byte windows */
  199237. if (window_bits == 8)
  199238. {
  199239. png_warning(png_ptr, "Compression window is being reset to 512");
  199240. window_bits=9;
  199241. }
  199242. #endif
  199243. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199244. png_ptr->zlib_window_bits = window_bits;
  199245. }
  199246. void PNGAPI
  199247. png_set_compression_method(png_structp png_ptr, int method)
  199248. {
  199249. png_debug(1, "in png_set_compression_method\n");
  199250. if (png_ptr == NULL)
  199251. return;
  199252. if (method != 8)
  199253. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199254. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199255. png_ptr->zlib_method = method;
  199256. }
  199257. void PNGAPI
  199258. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199259. {
  199260. if (png_ptr == NULL)
  199261. return;
  199262. png_ptr->write_row_fn = write_row_fn;
  199263. }
  199264. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199265. void PNGAPI
  199266. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199267. write_user_transform_fn)
  199268. {
  199269. png_debug(1, "in png_set_write_user_transform_fn\n");
  199270. if (png_ptr == NULL)
  199271. return;
  199272. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199273. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199274. }
  199275. #endif
  199276. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199277. void PNGAPI
  199278. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199279. int transforms, voidp params)
  199280. {
  199281. if (png_ptr == NULL || info_ptr == NULL)
  199282. return;
  199283. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199284. /* invert the alpha channel from opacity to transparency */
  199285. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199286. png_set_invert_alpha(png_ptr);
  199287. #endif
  199288. /* Write the file header information. */
  199289. png_write_info(png_ptr, info_ptr);
  199290. /* ------ these transformations don't touch the info structure ------- */
  199291. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199292. /* invert monochrome pixels */
  199293. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199294. png_set_invert_mono(png_ptr);
  199295. #endif
  199296. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199297. /* Shift the pixels up to a legal bit depth and fill in
  199298. * as appropriate to correctly scale the image.
  199299. */
  199300. if ((transforms & PNG_TRANSFORM_SHIFT)
  199301. && (info_ptr->valid & PNG_INFO_sBIT))
  199302. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199303. #endif
  199304. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199305. /* pack pixels into bytes */
  199306. if (transforms & PNG_TRANSFORM_PACKING)
  199307. png_set_packing(png_ptr);
  199308. #endif
  199309. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199310. /* swap location of alpha bytes from ARGB to RGBA */
  199311. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199312. png_set_swap_alpha(png_ptr);
  199313. #endif
  199314. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199315. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199316. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199317. */
  199318. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199319. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199320. #endif
  199321. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199322. /* flip BGR pixels to RGB */
  199323. if (transforms & PNG_TRANSFORM_BGR)
  199324. png_set_bgr(png_ptr);
  199325. #endif
  199326. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199327. /* swap bytes of 16-bit files to most significant byte first */
  199328. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199329. png_set_swap(png_ptr);
  199330. #endif
  199331. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199332. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199333. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199334. png_set_packswap(png_ptr);
  199335. #endif
  199336. /* ----------------------- end of transformations ------------------- */
  199337. /* write the bits */
  199338. if (info_ptr->valid & PNG_INFO_IDAT)
  199339. png_write_image(png_ptr, info_ptr->row_pointers);
  199340. /* It is REQUIRED to call this to finish writing the rest of the file */
  199341. png_write_end(png_ptr, info_ptr);
  199342. transforms = transforms; /* quiet compiler warnings */
  199343. params = params;
  199344. }
  199345. #endif
  199346. #endif /* PNG_WRITE_SUPPORTED */
  199347. /*** End of inlined file: pngwrite.c ***/
  199348. /*** Start of inlined file: pngwtran.c ***/
  199349. /* pngwtran.c - transforms the data in a row for PNG writers
  199350. *
  199351. * Last changed in libpng 1.2.9 April 14, 2006
  199352. * For conditions of distribution and use, see copyright notice in png.h
  199353. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199354. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199355. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199356. */
  199357. #define PNG_INTERNAL
  199358. #ifdef PNG_WRITE_SUPPORTED
  199359. /* Transform the data according to the user's wishes. The order of
  199360. * transformations is significant.
  199361. */
  199362. void /* PRIVATE */
  199363. png_do_write_transformations(png_structp png_ptr)
  199364. {
  199365. png_debug(1, "in png_do_write_transformations\n");
  199366. if (png_ptr == NULL)
  199367. return;
  199368. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199369. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199370. if(png_ptr->write_user_transform_fn != NULL)
  199371. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199372. (png_ptr, /* png_ptr */
  199373. &(png_ptr->row_info), /* row_info: */
  199374. /* png_uint_32 width; width of row */
  199375. /* png_uint_32 rowbytes; number of bytes in row */
  199376. /* png_byte color_type; color type of pixels */
  199377. /* png_byte bit_depth; bit depth of samples */
  199378. /* png_byte channels; number of channels (1-4) */
  199379. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199380. png_ptr->row_buf + 1); /* start of pixel data for row */
  199381. #endif
  199382. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199383. if (png_ptr->transformations & PNG_FILLER)
  199384. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199385. png_ptr->flags);
  199386. #endif
  199387. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199388. if (png_ptr->transformations & PNG_PACKSWAP)
  199389. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199390. #endif
  199391. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199392. if (png_ptr->transformations & PNG_PACK)
  199393. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199394. (png_uint_32)png_ptr->bit_depth);
  199395. #endif
  199396. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199397. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199398. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199399. #endif
  199400. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199401. if (png_ptr->transformations & PNG_SHIFT)
  199402. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199403. &(png_ptr->shift));
  199404. #endif
  199405. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199406. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199407. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199408. #endif
  199409. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199410. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199411. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199412. #endif
  199413. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199414. if (png_ptr->transformations & PNG_BGR)
  199415. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199416. #endif
  199417. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199418. if (png_ptr->transformations & PNG_INVERT_MONO)
  199419. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199420. #endif
  199421. }
  199422. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199423. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199424. * row_info bit depth should be 8 (one pixel per byte). The channels
  199425. * should be 1 (this only happens on grayscale and paletted images).
  199426. */
  199427. void /* PRIVATE */
  199428. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199429. {
  199430. png_debug(1, "in png_do_pack\n");
  199431. if (row_info->bit_depth == 8 &&
  199432. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199433. row != NULL && row_info != NULL &&
  199434. #endif
  199435. row_info->channels == 1)
  199436. {
  199437. switch ((int)bit_depth)
  199438. {
  199439. case 1:
  199440. {
  199441. png_bytep sp, dp;
  199442. int mask, v;
  199443. png_uint_32 i;
  199444. png_uint_32 row_width = row_info->width;
  199445. sp = row;
  199446. dp = row;
  199447. mask = 0x80;
  199448. v = 0;
  199449. for (i = 0; i < row_width; i++)
  199450. {
  199451. if (*sp != 0)
  199452. v |= mask;
  199453. sp++;
  199454. if (mask > 1)
  199455. mask >>= 1;
  199456. else
  199457. {
  199458. mask = 0x80;
  199459. *dp = (png_byte)v;
  199460. dp++;
  199461. v = 0;
  199462. }
  199463. }
  199464. if (mask != 0x80)
  199465. *dp = (png_byte)v;
  199466. break;
  199467. }
  199468. case 2:
  199469. {
  199470. png_bytep sp, dp;
  199471. int shift, v;
  199472. png_uint_32 i;
  199473. png_uint_32 row_width = row_info->width;
  199474. sp = row;
  199475. dp = row;
  199476. shift = 6;
  199477. v = 0;
  199478. for (i = 0; i < row_width; i++)
  199479. {
  199480. png_byte value;
  199481. value = (png_byte)(*sp & 0x03);
  199482. v |= (value << shift);
  199483. if (shift == 0)
  199484. {
  199485. shift = 6;
  199486. *dp = (png_byte)v;
  199487. dp++;
  199488. v = 0;
  199489. }
  199490. else
  199491. shift -= 2;
  199492. sp++;
  199493. }
  199494. if (shift != 6)
  199495. *dp = (png_byte)v;
  199496. break;
  199497. }
  199498. case 4:
  199499. {
  199500. png_bytep sp, dp;
  199501. int shift, v;
  199502. png_uint_32 i;
  199503. png_uint_32 row_width = row_info->width;
  199504. sp = row;
  199505. dp = row;
  199506. shift = 4;
  199507. v = 0;
  199508. for (i = 0; i < row_width; i++)
  199509. {
  199510. png_byte value;
  199511. value = (png_byte)(*sp & 0x0f);
  199512. v |= (value << shift);
  199513. if (shift == 0)
  199514. {
  199515. shift = 4;
  199516. *dp = (png_byte)v;
  199517. dp++;
  199518. v = 0;
  199519. }
  199520. else
  199521. shift -= 4;
  199522. sp++;
  199523. }
  199524. if (shift != 4)
  199525. *dp = (png_byte)v;
  199526. break;
  199527. }
  199528. }
  199529. row_info->bit_depth = (png_byte)bit_depth;
  199530. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199531. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199532. row_info->width);
  199533. }
  199534. }
  199535. #endif
  199536. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199537. /* Shift pixel values to take advantage of whole range. Pass the
  199538. * true number of bits in bit_depth. The row should be packed
  199539. * according to row_info->bit_depth. Thus, if you had a row of
  199540. * bit depth 4, but the pixels only had values from 0 to 7, you
  199541. * would pass 3 as bit_depth, and this routine would translate the
  199542. * data to 0 to 15.
  199543. */
  199544. void /* PRIVATE */
  199545. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199546. {
  199547. png_debug(1, "in png_do_shift\n");
  199548. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199549. if (row != NULL && row_info != NULL &&
  199550. #else
  199551. if (
  199552. #endif
  199553. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199554. {
  199555. int shift_start[4], shift_dec[4];
  199556. int channels = 0;
  199557. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199558. {
  199559. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199560. shift_dec[channels] = bit_depth->red;
  199561. channels++;
  199562. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199563. shift_dec[channels] = bit_depth->green;
  199564. channels++;
  199565. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199566. shift_dec[channels] = bit_depth->blue;
  199567. channels++;
  199568. }
  199569. else
  199570. {
  199571. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199572. shift_dec[channels] = bit_depth->gray;
  199573. channels++;
  199574. }
  199575. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199576. {
  199577. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199578. shift_dec[channels] = bit_depth->alpha;
  199579. channels++;
  199580. }
  199581. /* with low row depths, could only be grayscale, so one channel */
  199582. if (row_info->bit_depth < 8)
  199583. {
  199584. png_bytep bp = row;
  199585. png_uint_32 i;
  199586. png_byte mask;
  199587. png_uint_32 row_bytes = row_info->rowbytes;
  199588. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199589. mask = 0x55;
  199590. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199591. mask = 0x11;
  199592. else
  199593. mask = 0xff;
  199594. for (i = 0; i < row_bytes; i++, bp++)
  199595. {
  199596. png_uint_16 v;
  199597. int j;
  199598. v = *bp;
  199599. *bp = 0;
  199600. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199601. {
  199602. if (j > 0)
  199603. *bp |= (png_byte)((v << j) & 0xff);
  199604. else
  199605. *bp |= (png_byte)((v >> (-j)) & mask);
  199606. }
  199607. }
  199608. }
  199609. else if (row_info->bit_depth == 8)
  199610. {
  199611. png_bytep bp = row;
  199612. png_uint_32 i;
  199613. png_uint_32 istop = channels * row_info->width;
  199614. for (i = 0; i < istop; i++, bp++)
  199615. {
  199616. png_uint_16 v;
  199617. int j;
  199618. int c = (int)(i%channels);
  199619. v = *bp;
  199620. *bp = 0;
  199621. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199622. {
  199623. if (j > 0)
  199624. *bp |= (png_byte)((v << j) & 0xff);
  199625. else
  199626. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199627. }
  199628. }
  199629. }
  199630. else
  199631. {
  199632. png_bytep bp;
  199633. png_uint_32 i;
  199634. png_uint_32 istop = channels * row_info->width;
  199635. for (bp = row, i = 0; i < istop; i++)
  199636. {
  199637. int c = (int)(i%channels);
  199638. png_uint_16 value, v;
  199639. int j;
  199640. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199641. value = 0;
  199642. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199643. {
  199644. if (j > 0)
  199645. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199646. else
  199647. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199648. }
  199649. *bp++ = (png_byte)(value >> 8);
  199650. *bp++ = (png_byte)(value & 0xff);
  199651. }
  199652. }
  199653. }
  199654. }
  199655. #endif
  199656. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199657. void /* PRIVATE */
  199658. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199659. {
  199660. png_debug(1, "in png_do_write_swap_alpha\n");
  199661. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199662. if (row != NULL && row_info != NULL)
  199663. #endif
  199664. {
  199665. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199666. {
  199667. /* This converts from ARGB to RGBA */
  199668. if (row_info->bit_depth == 8)
  199669. {
  199670. png_bytep sp, dp;
  199671. png_uint_32 i;
  199672. png_uint_32 row_width = row_info->width;
  199673. for (i = 0, sp = dp = row; i < row_width; i++)
  199674. {
  199675. png_byte save = *(sp++);
  199676. *(dp++) = *(sp++);
  199677. *(dp++) = *(sp++);
  199678. *(dp++) = *(sp++);
  199679. *(dp++) = save;
  199680. }
  199681. }
  199682. /* This converts from AARRGGBB to RRGGBBAA */
  199683. else
  199684. {
  199685. png_bytep sp, dp;
  199686. png_uint_32 i;
  199687. png_uint_32 row_width = row_info->width;
  199688. for (i = 0, sp = dp = row; i < row_width; i++)
  199689. {
  199690. png_byte save[2];
  199691. save[0] = *(sp++);
  199692. save[1] = *(sp++);
  199693. *(dp++) = *(sp++);
  199694. *(dp++) = *(sp++);
  199695. *(dp++) = *(sp++);
  199696. *(dp++) = *(sp++);
  199697. *(dp++) = *(sp++);
  199698. *(dp++) = *(sp++);
  199699. *(dp++) = save[0];
  199700. *(dp++) = save[1];
  199701. }
  199702. }
  199703. }
  199704. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199705. {
  199706. /* This converts from AG to GA */
  199707. if (row_info->bit_depth == 8)
  199708. {
  199709. png_bytep sp, dp;
  199710. png_uint_32 i;
  199711. png_uint_32 row_width = row_info->width;
  199712. for (i = 0, sp = dp = row; i < row_width; i++)
  199713. {
  199714. png_byte save = *(sp++);
  199715. *(dp++) = *(sp++);
  199716. *(dp++) = save;
  199717. }
  199718. }
  199719. /* This converts from AAGG to GGAA */
  199720. else
  199721. {
  199722. png_bytep sp, dp;
  199723. png_uint_32 i;
  199724. png_uint_32 row_width = row_info->width;
  199725. for (i = 0, sp = dp = row; i < row_width; i++)
  199726. {
  199727. png_byte save[2];
  199728. save[0] = *(sp++);
  199729. save[1] = *(sp++);
  199730. *(dp++) = *(sp++);
  199731. *(dp++) = *(sp++);
  199732. *(dp++) = save[0];
  199733. *(dp++) = save[1];
  199734. }
  199735. }
  199736. }
  199737. }
  199738. }
  199739. #endif
  199740. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199741. void /* PRIVATE */
  199742. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199743. {
  199744. png_debug(1, "in png_do_write_invert_alpha\n");
  199745. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199746. if (row != NULL && row_info != NULL)
  199747. #endif
  199748. {
  199749. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199750. {
  199751. /* This inverts the alpha channel in RGBA */
  199752. if (row_info->bit_depth == 8)
  199753. {
  199754. png_bytep sp, dp;
  199755. png_uint_32 i;
  199756. png_uint_32 row_width = row_info->width;
  199757. for (i = 0, sp = dp = row; i < row_width; i++)
  199758. {
  199759. /* does nothing
  199760. *(dp++) = *(sp++);
  199761. *(dp++) = *(sp++);
  199762. *(dp++) = *(sp++);
  199763. */
  199764. sp+=3; dp = sp;
  199765. *(dp++) = (png_byte)(255 - *(sp++));
  199766. }
  199767. }
  199768. /* This inverts the alpha channel in RRGGBBAA */
  199769. else
  199770. {
  199771. png_bytep sp, dp;
  199772. png_uint_32 i;
  199773. png_uint_32 row_width = row_info->width;
  199774. for (i = 0, sp = dp = row; i < row_width; i++)
  199775. {
  199776. /* does nothing
  199777. *(dp++) = *(sp++);
  199778. *(dp++) = *(sp++);
  199779. *(dp++) = *(sp++);
  199780. *(dp++) = *(sp++);
  199781. *(dp++) = *(sp++);
  199782. *(dp++) = *(sp++);
  199783. */
  199784. sp+=6; dp = sp;
  199785. *(dp++) = (png_byte)(255 - *(sp++));
  199786. *(dp++) = (png_byte)(255 - *(sp++));
  199787. }
  199788. }
  199789. }
  199790. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199791. {
  199792. /* This inverts the alpha channel in GA */
  199793. if (row_info->bit_depth == 8)
  199794. {
  199795. png_bytep sp, dp;
  199796. png_uint_32 i;
  199797. png_uint_32 row_width = row_info->width;
  199798. for (i = 0, sp = dp = row; i < row_width; i++)
  199799. {
  199800. *(dp++) = *(sp++);
  199801. *(dp++) = (png_byte)(255 - *(sp++));
  199802. }
  199803. }
  199804. /* This inverts the alpha channel in GGAA */
  199805. else
  199806. {
  199807. png_bytep sp, dp;
  199808. png_uint_32 i;
  199809. png_uint_32 row_width = row_info->width;
  199810. for (i = 0, sp = dp = row; i < row_width; i++)
  199811. {
  199812. /* does nothing
  199813. *(dp++) = *(sp++);
  199814. *(dp++) = *(sp++);
  199815. */
  199816. sp+=2; dp = sp;
  199817. *(dp++) = (png_byte)(255 - *(sp++));
  199818. *(dp++) = (png_byte)(255 - *(sp++));
  199819. }
  199820. }
  199821. }
  199822. }
  199823. }
  199824. #endif
  199825. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199826. /* undoes intrapixel differencing */
  199827. void /* PRIVATE */
  199828. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  199829. {
  199830. png_debug(1, "in png_do_write_intrapixel\n");
  199831. if (
  199832. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199833. row != NULL && row_info != NULL &&
  199834. #endif
  199835. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  199836. {
  199837. int bytes_per_pixel;
  199838. png_uint_32 row_width = row_info->width;
  199839. if (row_info->bit_depth == 8)
  199840. {
  199841. png_bytep rp;
  199842. png_uint_32 i;
  199843. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199844. bytes_per_pixel = 3;
  199845. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199846. bytes_per_pixel = 4;
  199847. else
  199848. return;
  199849. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199850. {
  199851. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  199852. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  199853. }
  199854. }
  199855. else if (row_info->bit_depth == 16)
  199856. {
  199857. png_bytep rp;
  199858. png_uint_32 i;
  199859. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199860. bytes_per_pixel = 6;
  199861. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199862. bytes_per_pixel = 8;
  199863. else
  199864. return;
  199865. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199866. {
  199867. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  199868. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  199869. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  199870. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  199871. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  199872. *(rp ) = (png_byte)((red >> 8) & 0xff);
  199873. *(rp+1) = (png_byte)(red & 0xff);
  199874. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  199875. *(rp+5) = (png_byte)(blue & 0xff);
  199876. }
  199877. }
  199878. }
  199879. }
  199880. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  199881. #endif /* PNG_WRITE_SUPPORTED */
  199882. /*** End of inlined file: pngwtran.c ***/
  199883. /*** Start of inlined file: pngwutil.c ***/
  199884. /* pngwutil.c - utilities to write a PNG file
  199885. *
  199886. * Last changed in libpng 1.2.20 Septhember 3, 2007
  199887. * For conditions of distribution and use, see copyright notice in png.h
  199888. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199889. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199890. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199891. */
  199892. #define PNG_INTERNAL
  199893. #ifdef PNG_WRITE_SUPPORTED
  199894. /* Place a 32-bit number into a buffer in PNG byte order. We work
  199895. * with unsigned numbers for convenience, although one supported
  199896. * ancillary chunk uses signed (two's complement) numbers.
  199897. */
  199898. void PNGAPI
  199899. png_save_uint_32(png_bytep buf, png_uint_32 i)
  199900. {
  199901. buf[0] = (png_byte)((i >> 24) & 0xff);
  199902. buf[1] = (png_byte)((i >> 16) & 0xff);
  199903. buf[2] = (png_byte)((i >> 8) & 0xff);
  199904. buf[3] = (png_byte)(i & 0xff);
  199905. }
  199906. /* The png_save_int_32 function assumes integers are stored in two's
  199907. * complement format. If this isn't the case, then this routine needs to
  199908. * be modified to write data in two's complement format.
  199909. */
  199910. void PNGAPI
  199911. png_save_int_32(png_bytep buf, png_int_32 i)
  199912. {
  199913. buf[0] = (png_byte)((i >> 24) & 0xff);
  199914. buf[1] = (png_byte)((i >> 16) & 0xff);
  199915. buf[2] = (png_byte)((i >> 8) & 0xff);
  199916. buf[3] = (png_byte)(i & 0xff);
  199917. }
  199918. /* Place a 16-bit number into a buffer in PNG byte order.
  199919. * The parameter is declared unsigned int, not png_uint_16,
  199920. * just to avoid potential problems on pre-ANSI C compilers.
  199921. */
  199922. void PNGAPI
  199923. png_save_uint_16(png_bytep buf, unsigned int i)
  199924. {
  199925. buf[0] = (png_byte)((i >> 8) & 0xff);
  199926. buf[1] = (png_byte)(i & 0xff);
  199927. }
  199928. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  199929. * representing the chunk name. The array must be at least 4 bytes in
  199930. * length, and does not need to be null terminated. To be safe, pass the
  199931. * pre-defined chunk names here, and if you need a new one, define it
  199932. * where the others are defined. The length is the length of the data.
  199933. * All the data must be present. If that is not possible, use the
  199934. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  199935. * functions instead.
  199936. */
  199937. void PNGAPI
  199938. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  199939. png_bytep data, png_size_t length)
  199940. {
  199941. if(png_ptr == NULL) return;
  199942. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  199943. png_write_chunk_data(png_ptr, data, length);
  199944. png_write_chunk_end(png_ptr);
  199945. }
  199946. /* Write the start of a PNG chunk. The type is the chunk type.
  199947. * The total_length is the sum of the lengths of all the data you will be
  199948. * passing in png_write_chunk_data().
  199949. */
  199950. void PNGAPI
  199951. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  199952. png_uint_32 length)
  199953. {
  199954. png_byte buf[4];
  199955. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  199956. if(png_ptr == NULL) return;
  199957. /* write the length */
  199958. png_save_uint_32(buf, length);
  199959. png_write_data(png_ptr, buf, (png_size_t)4);
  199960. /* write the chunk name */
  199961. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  199962. /* reset the crc and run it over the chunk name */
  199963. png_reset_crc(png_ptr);
  199964. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  199965. }
  199966. /* Write the data of a PNG chunk started with png_write_chunk_start().
  199967. * Note that multiple calls to this function are allowed, and that the
  199968. * sum of the lengths from these calls *must* add up to the total_length
  199969. * given to png_write_chunk_start().
  199970. */
  199971. void PNGAPI
  199972. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199973. {
  199974. /* write the data, and run the CRC over it */
  199975. if(png_ptr == NULL) return;
  199976. if (data != NULL && length > 0)
  199977. {
  199978. png_calculate_crc(png_ptr, data, length);
  199979. png_write_data(png_ptr, data, length);
  199980. }
  199981. }
  199982. /* Finish a chunk started with png_write_chunk_start(). */
  199983. void PNGAPI
  199984. png_write_chunk_end(png_structp png_ptr)
  199985. {
  199986. png_byte buf[4];
  199987. if(png_ptr == NULL) return;
  199988. /* write the crc */
  199989. png_save_uint_32(buf, png_ptr->crc);
  199990. png_write_data(png_ptr, buf, (png_size_t)4);
  199991. }
  199992. /* Simple function to write the signature. If we have already written
  199993. * the magic bytes of the signature, or more likely, the PNG stream is
  199994. * being embedded into another stream and doesn't need its own signature,
  199995. * we should call png_set_sig_bytes() to tell libpng how many of the
  199996. * bytes have already been written.
  199997. */
  199998. void /* PRIVATE */
  199999. png_write_sig(png_structp png_ptr)
  200000. {
  200001. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200002. /* write the rest of the 8 byte signature */
  200003. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200004. (png_size_t)8 - png_ptr->sig_bytes);
  200005. if(png_ptr->sig_bytes < 3)
  200006. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200007. }
  200008. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200009. /*
  200010. * This pair of functions encapsulates the operation of (a) compressing a
  200011. * text string, and (b) issuing it later as a series of chunk data writes.
  200012. * The compression_state structure is shared context for these functions
  200013. * set up by the caller in order to make the whole mess thread-safe.
  200014. */
  200015. typedef struct
  200016. {
  200017. char *input; /* the uncompressed input data */
  200018. int input_len; /* its length */
  200019. int num_output_ptr; /* number of output pointers used */
  200020. int max_output_ptr; /* size of output_ptr */
  200021. png_charpp output_ptr; /* array of pointers to output */
  200022. } compression_state;
  200023. /* compress given text into storage in the png_ptr structure */
  200024. static int /* PRIVATE */
  200025. png_text_compress(png_structp png_ptr,
  200026. png_charp text, png_size_t text_len, int compression,
  200027. compression_state *comp)
  200028. {
  200029. int ret;
  200030. comp->num_output_ptr = 0;
  200031. comp->max_output_ptr = 0;
  200032. comp->output_ptr = NULL;
  200033. comp->input = NULL;
  200034. comp->input_len = 0;
  200035. /* we may just want to pass the text right through */
  200036. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200037. {
  200038. comp->input = text;
  200039. comp->input_len = text_len;
  200040. return((int)text_len);
  200041. }
  200042. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200043. {
  200044. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200045. char msg[50];
  200046. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200047. png_warning(png_ptr, msg);
  200048. #else
  200049. png_warning(png_ptr, "Unknown compression type");
  200050. #endif
  200051. }
  200052. /* We can't write the chunk until we find out how much data we have,
  200053. * which means we need to run the compressor first and save the
  200054. * output. This shouldn't be a problem, as the vast majority of
  200055. * comments should be reasonable, but we will set up an array of
  200056. * malloc'd pointers to be sure.
  200057. *
  200058. * If we knew the application was well behaved, we could simplify this
  200059. * greatly by assuming we can always malloc an output buffer large
  200060. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200061. * and malloc this directly. The only time this would be a bad idea is
  200062. * if we can't malloc more than 64K and we have 64K of random input
  200063. * data, or if the input string is incredibly large (although this
  200064. * wouldn't cause a failure, just a slowdown due to swapping).
  200065. */
  200066. /* set up the compression buffers */
  200067. png_ptr->zstream.avail_in = (uInt)text_len;
  200068. png_ptr->zstream.next_in = (Bytef *)text;
  200069. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200070. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200071. /* this is the same compression loop as in png_write_row() */
  200072. do
  200073. {
  200074. /* compress the data */
  200075. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200076. if (ret != Z_OK)
  200077. {
  200078. /* error */
  200079. if (png_ptr->zstream.msg != NULL)
  200080. png_error(png_ptr, png_ptr->zstream.msg);
  200081. else
  200082. png_error(png_ptr, "zlib error");
  200083. }
  200084. /* check to see if we need more room */
  200085. if (!(png_ptr->zstream.avail_out))
  200086. {
  200087. /* make sure the output array has room */
  200088. if (comp->num_output_ptr >= comp->max_output_ptr)
  200089. {
  200090. int old_max;
  200091. old_max = comp->max_output_ptr;
  200092. comp->max_output_ptr = comp->num_output_ptr + 4;
  200093. if (comp->output_ptr != NULL)
  200094. {
  200095. png_charpp old_ptr;
  200096. old_ptr = comp->output_ptr;
  200097. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200098. (png_uint_32)(comp->max_output_ptr *
  200099. png_sizeof (png_charpp)));
  200100. png_memcpy(comp->output_ptr, old_ptr, old_max
  200101. * png_sizeof (png_charp));
  200102. png_free(png_ptr, old_ptr);
  200103. }
  200104. else
  200105. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200106. (png_uint_32)(comp->max_output_ptr *
  200107. png_sizeof (png_charp)));
  200108. }
  200109. /* save the data */
  200110. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200111. (png_uint_32)png_ptr->zbuf_size);
  200112. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200113. png_ptr->zbuf_size);
  200114. comp->num_output_ptr++;
  200115. /* and reset the buffer */
  200116. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200117. png_ptr->zstream.next_out = png_ptr->zbuf;
  200118. }
  200119. /* continue until we don't have any more to compress */
  200120. } while (png_ptr->zstream.avail_in);
  200121. /* finish the compression */
  200122. do
  200123. {
  200124. /* tell zlib we are finished */
  200125. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200126. if (ret == Z_OK)
  200127. {
  200128. /* check to see if we need more room */
  200129. if (!(png_ptr->zstream.avail_out))
  200130. {
  200131. /* check to make sure our output array has room */
  200132. if (comp->num_output_ptr >= comp->max_output_ptr)
  200133. {
  200134. int old_max;
  200135. old_max = comp->max_output_ptr;
  200136. comp->max_output_ptr = comp->num_output_ptr + 4;
  200137. if (comp->output_ptr != NULL)
  200138. {
  200139. png_charpp old_ptr;
  200140. old_ptr = comp->output_ptr;
  200141. /* This could be optimized to realloc() */
  200142. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200143. (png_uint_32)(comp->max_output_ptr *
  200144. png_sizeof (png_charpp)));
  200145. png_memcpy(comp->output_ptr, old_ptr,
  200146. old_max * png_sizeof (png_charp));
  200147. png_free(png_ptr, old_ptr);
  200148. }
  200149. else
  200150. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200151. (png_uint_32)(comp->max_output_ptr *
  200152. png_sizeof (png_charp)));
  200153. }
  200154. /* save off the data */
  200155. comp->output_ptr[comp->num_output_ptr] =
  200156. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200157. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200158. png_ptr->zbuf_size);
  200159. comp->num_output_ptr++;
  200160. /* and reset the buffer pointers */
  200161. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200162. png_ptr->zstream.next_out = png_ptr->zbuf;
  200163. }
  200164. }
  200165. else if (ret != Z_STREAM_END)
  200166. {
  200167. /* we got an error */
  200168. if (png_ptr->zstream.msg != NULL)
  200169. png_error(png_ptr, png_ptr->zstream.msg);
  200170. else
  200171. png_error(png_ptr, "zlib error");
  200172. }
  200173. } while (ret != Z_STREAM_END);
  200174. /* text length is number of buffers plus last buffer */
  200175. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200176. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200177. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200178. return((int)text_len);
  200179. }
  200180. /* ship the compressed text out via chunk writes */
  200181. static void /* PRIVATE */
  200182. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200183. {
  200184. int i;
  200185. /* handle the no-compression case */
  200186. if (comp->input)
  200187. {
  200188. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200189. (png_size_t)comp->input_len);
  200190. return;
  200191. }
  200192. /* write saved output buffers, if any */
  200193. for (i = 0; i < comp->num_output_ptr; i++)
  200194. {
  200195. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200196. png_ptr->zbuf_size);
  200197. png_free(png_ptr, comp->output_ptr[i]);
  200198. comp->output_ptr[i]=NULL;
  200199. }
  200200. if (comp->max_output_ptr != 0)
  200201. png_free(png_ptr, comp->output_ptr);
  200202. comp->output_ptr=NULL;
  200203. /* write anything left in zbuf */
  200204. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200205. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200206. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200207. /* reset zlib for another zTXt/iTXt or image data */
  200208. deflateReset(&png_ptr->zstream);
  200209. png_ptr->zstream.data_type = Z_BINARY;
  200210. }
  200211. #endif
  200212. /* Write the IHDR chunk, and update the png_struct with the necessary
  200213. * information. Note that the rest of this code depends upon this
  200214. * information being correct.
  200215. */
  200216. void /* PRIVATE */
  200217. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200218. int bit_depth, int color_type, int compression_type, int filter_type,
  200219. int interlace_type)
  200220. {
  200221. #ifdef PNG_USE_LOCAL_ARRAYS
  200222. PNG_IHDR;
  200223. #endif
  200224. png_byte buf[13]; /* buffer to store the IHDR info */
  200225. png_debug(1, "in png_write_IHDR\n");
  200226. /* Check that we have valid input data from the application info */
  200227. switch (color_type)
  200228. {
  200229. case PNG_COLOR_TYPE_GRAY:
  200230. switch (bit_depth)
  200231. {
  200232. case 1:
  200233. case 2:
  200234. case 4:
  200235. case 8:
  200236. case 16: png_ptr->channels = 1; break;
  200237. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200238. }
  200239. break;
  200240. case PNG_COLOR_TYPE_RGB:
  200241. if (bit_depth != 8 && bit_depth != 16)
  200242. png_error(png_ptr, "Invalid bit depth for RGB image");
  200243. png_ptr->channels = 3;
  200244. break;
  200245. case PNG_COLOR_TYPE_PALETTE:
  200246. switch (bit_depth)
  200247. {
  200248. case 1:
  200249. case 2:
  200250. case 4:
  200251. case 8: png_ptr->channels = 1; break;
  200252. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200253. }
  200254. break;
  200255. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200256. if (bit_depth != 8 && bit_depth != 16)
  200257. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200258. png_ptr->channels = 2;
  200259. break;
  200260. case PNG_COLOR_TYPE_RGB_ALPHA:
  200261. if (bit_depth != 8 && bit_depth != 16)
  200262. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200263. png_ptr->channels = 4;
  200264. break;
  200265. default:
  200266. png_error(png_ptr, "Invalid image color type specified");
  200267. }
  200268. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200269. {
  200270. png_warning(png_ptr, "Invalid compression type specified");
  200271. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200272. }
  200273. /* Write filter_method 64 (intrapixel differencing) only if
  200274. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200275. * 2. Libpng did not write a PNG signature (this filter_method is only
  200276. * used in PNG datastreams that are embedded in MNG datastreams) and
  200277. * 3. The application called png_permit_mng_features with a mask that
  200278. * included PNG_FLAG_MNG_FILTER_64 and
  200279. * 4. The filter_method is 64 and
  200280. * 5. The color_type is RGB or RGBA
  200281. */
  200282. if (
  200283. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200284. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200285. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200286. (color_type == PNG_COLOR_TYPE_RGB ||
  200287. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200288. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200289. #endif
  200290. filter_type != PNG_FILTER_TYPE_BASE)
  200291. {
  200292. png_warning(png_ptr, "Invalid filter type specified");
  200293. filter_type = PNG_FILTER_TYPE_BASE;
  200294. }
  200295. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200296. if (interlace_type != PNG_INTERLACE_NONE &&
  200297. interlace_type != PNG_INTERLACE_ADAM7)
  200298. {
  200299. png_warning(png_ptr, "Invalid interlace type specified");
  200300. interlace_type = PNG_INTERLACE_ADAM7;
  200301. }
  200302. #else
  200303. interlace_type=PNG_INTERLACE_NONE;
  200304. #endif
  200305. /* save off the relevent information */
  200306. png_ptr->bit_depth = (png_byte)bit_depth;
  200307. png_ptr->color_type = (png_byte)color_type;
  200308. png_ptr->interlaced = (png_byte)interlace_type;
  200309. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200310. png_ptr->filter_type = (png_byte)filter_type;
  200311. #endif
  200312. png_ptr->compression_type = (png_byte)compression_type;
  200313. png_ptr->width = width;
  200314. png_ptr->height = height;
  200315. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200316. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200317. /* set the usr info, so any transformations can modify it */
  200318. png_ptr->usr_width = png_ptr->width;
  200319. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200320. png_ptr->usr_channels = png_ptr->channels;
  200321. /* pack the header information into the buffer */
  200322. png_save_uint_32(buf, width);
  200323. png_save_uint_32(buf + 4, height);
  200324. buf[8] = (png_byte)bit_depth;
  200325. buf[9] = (png_byte)color_type;
  200326. buf[10] = (png_byte)compression_type;
  200327. buf[11] = (png_byte)filter_type;
  200328. buf[12] = (png_byte)interlace_type;
  200329. /* write the chunk */
  200330. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200331. /* initialize zlib with PNG info */
  200332. png_ptr->zstream.zalloc = png_zalloc;
  200333. png_ptr->zstream.zfree = png_zfree;
  200334. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200335. if (!(png_ptr->do_filter))
  200336. {
  200337. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200338. png_ptr->bit_depth < 8)
  200339. png_ptr->do_filter = PNG_FILTER_NONE;
  200340. else
  200341. png_ptr->do_filter = PNG_ALL_FILTERS;
  200342. }
  200343. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200344. {
  200345. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200346. png_ptr->zlib_strategy = Z_FILTERED;
  200347. else
  200348. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200349. }
  200350. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200351. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200352. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200353. png_ptr->zlib_mem_level = 8;
  200354. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200355. png_ptr->zlib_window_bits = 15;
  200356. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200357. png_ptr->zlib_method = 8;
  200358. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200359. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200360. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200361. png_error(png_ptr, "zlib failed to initialize compressor");
  200362. png_ptr->zstream.next_out = png_ptr->zbuf;
  200363. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200364. /* libpng is not interested in zstream.data_type */
  200365. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200366. png_ptr->zstream.data_type = Z_BINARY;
  200367. png_ptr->mode = PNG_HAVE_IHDR;
  200368. }
  200369. /* write the palette. We are careful not to trust png_color to be in the
  200370. * correct order for PNG, so people can redefine it to any convenient
  200371. * structure.
  200372. */
  200373. void /* PRIVATE */
  200374. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200375. {
  200376. #ifdef PNG_USE_LOCAL_ARRAYS
  200377. PNG_PLTE;
  200378. #endif
  200379. png_uint_32 i;
  200380. png_colorp pal_ptr;
  200381. png_byte buf[3];
  200382. png_debug(1, "in png_write_PLTE\n");
  200383. if ((
  200384. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200385. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200386. #endif
  200387. num_pal == 0) || num_pal > 256)
  200388. {
  200389. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200390. {
  200391. png_error(png_ptr, "Invalid number of colors in palette");
  200392. }
  200393. else
  200394. {
  200395. png_warning(png_ptr, "Invalid number of colors in palette");
  200396. return;
  200397. }
  200398. }
  200399. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200400. {
  200401. png_warning(png_ptr,
  200402. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200403. return;
  200404. }
  200405. png_ptr->num_palette = (png_uint_16)num_pal;
  200406. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200407. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200408. #ifndef PNG_NO_POINTER_INDEXING
  200409. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200410. {
  200411. buf[0] = pal_ptr->red;
  200412. buf[1] = pal_ptr->green;
  200413. buf[2] = pal_ptr->blue;
  200414. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200415. }
  200416. #else
  200417. /* This is a little slower but some buggy compilers need to do this instead */
  200418. pal_ptr=palette;
  200419. for (i = 0; i < num_pal; i++)
  200420. {
  200421. buf[0] = pal_ptr[i].red;
  200422. buf[1] = pal_ptr[i].green;
  200423. buf[2] = pal_ptr[i].blue;
  200424. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200425. }
  200426. #endif
  200427. png_write_chunk_end(png_ptr);
  200428. png_ptr->mode |= PNG_HAVE_PLTE;
  200429. }
  200430. /* write an IDAT chunk */
  200431. void /* PRIVATE */
  200432. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200433. {
  200434. #ifdef PNG_USE_LOCAL_ARRAYS
  200435. PNG_IDAT;
  200436. #endif
  200437. png_debug(1, "in png_write_IDAT\n");
  200438. /* Optimize the CMF field in the zlib stream. */
  200439. /* This hack of the zlib stream is compliant to the stream specification. */
  200440. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200441. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200442. {
  200443. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200444. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200445. {
  200446. /* Avoid memory underflows and multiplication overflows. */
  200447. /* The conditions below are practically always satisfied;
  200448. however, they still must be checked. */
  200449. if (length >= 2 &&
  200450. png_ptr->height < 16384 && png_ptr->width < 16384)
  200451. {
  200452. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200453. ((png_ptr->width *
  200454. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200455. unsigned int z_cinfo = z_cmf >> 4;
  200456. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200457. while (uncompressed_idat_size <= half_z_window_size &&
  200458. half_z_window_size >= 256)
  200459. {
  200460. z_cinfo--;
  200461. half_z_window_size >>= 1;
  200462. }
  200463. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200464. if (data[0] != (png_byte)z_cmf)
  200465. {
  200466. data[0] = (png_byte)z_cmf;
  200467. data[1] &= 0xe0;
  200468. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200469. }
  200470. }
  200471. }
  200472. else
  200473. png_error(png_ptr,
  200474. "Invalid zlib compression method or flags in IDAT");
  200475. }
  200476. png_write_chunk(png_ptr, png_IDAT, data, length);
  200477. png_ptr->mode |= PNG_HAVE_IDAT;
  200478. }
  200479. /* write an IEND chunk */
  200480. void /* PRIVATE */
  200481. png_write_IEND(png_structp png_ptr)
  200482. {
  200483. #ifdef PNG_USE_LOCAL_ARRAYS
  200484. PNG_IEND;
  200485. #endif
  200486. png_debug(1, "in png_write_IEND\n");
  200487. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200488. (png_size_t)0);
  200489. png_ptr->mode |= PNG_HAVE_IEND;
  200490. }
  200491. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200492. /* write a gAMA chunk */
  200493. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200494. void /* PRIVATE */
  200495. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200496. {
  200497. #ifdef PNG_USE_LOCAL_ARRAYS
  200498. PNG_gAMA;
  200499. #endif
  200500. png_uint_32 igamma;
  200501. png_byte buf[4];
  200502. png_debug(1, "in png_write_gAMA\n");
  200503. /* file_gamma is saved in 1/100,000ths */
  200504. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200505. png_save_uint_32(buf, igamma);
  200506. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200507. }
  200508. #endif
  200509. #ifdef PNG_FIXED_POINT_SUPPORTED
  200510. void /* PRIVATE */
  200511. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200512. {
  200513. #ifdef PNG_USE_LOCAL_ARRAYS
  200514. PNG_gAMA;
  200515. #endif
  200516. png_byte buf[4];
  200517. png_debug(1, "in png_write_gAMA\n");
  200518. /* file_gamma is saved in 1/100,000ths */
  200519. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200520. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200521. }
  200522. #endif
  200523. #endif
  200524. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200525. /* write a sRGB chunk */
  200526. void /* PRIVATE */
  200527. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200528. {
  200529. #ifdef PNG_USE_LOCAL_ARRAYS
  200530. PNG_sRGB;
  200531. #endif
  200532. png_byte buf[1];
  200533. png_debug(1, "in png_write_sRGB\n");
  200534. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200535. png_warning(png_ptr,
  200536. "Invalid sRGB rendering intent specified");
  200537. buf[0]=(png_byte)srgb_intent;
  200538. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200539. }
  200540. #endif
  200541. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200542. /* write an iCCP chunk */
  200543. void /* PRIVATE */
  200544. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200545. png_charp profile, int profile_len)
  200546. {
  200547. #ifdef PNG_USE_LOCAL_ARRAYS
  200548. PNG_iCCP;
  200549. #endif
  200550. png_size_t name_len;
  200551. png_charp new_name;
  200552. compression_state comp;
  200553. int embedded_profile_len = 0;
  200554. png_debug(1, "in png_write_iCCP\n");
  200555. comp.num_output_ptr = 0;
  200556. comp.max_output_ptr = 0;
  200557. comp.output_ptr = NULL;
  200558. comp.input = NULL;
  200559. comp.input_len = 0;
  200560. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200561. &new_name)) == 0)
  200562. {
  200563. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200564. return;
  200565. }
  200566. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200567. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200568. if (profile == NULL)
  200569. profile_len = 0;
  200570. if (profile_len > 3)
  200571. embedded_profile_len =
  200572. ((*( (png_bytep)profile ))<<24) |
  200573. ((*( (png_bytep)profile+1))<<16) |
  200574. ((*( (png_bytep)profile+2))<< 8) |
  200575. ((*( (png_bytep)profile+3)) );
  200576. if (profile_len < embedded_profile_len)
  200577. {
  200578. png_warning(png_ptr,
  200579. "Embedded profile length too large in iCCP chunk");
  200580. return;
  200581. }
  200582. if (profile_len > embedded_profile_len)
  200583. {
  200584. png_warning(png_ptr,
  200585. "Truncating profile to actual length in iCCP chunk");
  200586. profile_len = embedded_profile_len;
  200587. }
  200588. if (profile_len)
  200589. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200590. PNG_COMPRESSION_TYPE_BASE, &comp);
  200591. /* make sure we include the NULL after the name and the compression type */
  200592. png_write_chunk_start(png_ptr, png_iCCP,
  200593. (png_uint_32)name_len+profile_len+2);
  200594. new_name[name_len+1]=0x00;
  200595. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200596. if (profile_len)
  200597. png_write_compressed_data_out(png_ptr, &comp);
  200598. png_write_chunk_end(png_ptr);
  200599. png_free(png_ptr, new_name);
  200600. }
  200601. #endif
  200602. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200603. /* write a sPLT chunk */
  200604. void /* PRIVATE */
  200605. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200606. {
  200607. #ifdef PNG_USE_LOCAL_ARRAYS
  200608. PNG_sPLT;
  200609. #endif
  200610. png_size_t name_len;
  200611. png_charp new_name;
  200612. png_byte entrybuf[10];
  200613. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200614. int palette_size = entry_size * spalette->nentries;
  200615. png_sPLT_entryp ep;
  200616. #ifdef PNG_NO_POINTER_INDEXING
  200617. int i;
  200618. #endif
  200619. png_debug(1, "in png_write_sPLT\n");
  200620. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200621. spalette->name, &new_name))==0)
  200622. {
  200623. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200624. return;
  200625. }
  200626. /* make sure we include the NULL after the name */
  200627. png_write_chunk_start(png_ptr, png_sPLT,
  200628. (png_uint_32)(name_len + 2 + palette_size));
  200629. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200630. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200631. /* loop through each palette entry, writing appropriately */
  200632. #ifndef PNG_NO_POINTER_INDEXING
  200633. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200634. {
  200635. if (spalette->depth == 8)
  200636. {
  200637. entrybuf[0] = (png_byte)ep->red;
  200638. entrybuf[1] = (png_byte)ep->green;
  200639. entrybuf[2] = (png_byte)ep->blue;
  200640. entrybuf[3] = (png_byte)ep->alpha;
  200641. png_save_uint_16(entrybuf + 4, ep->frequency);
  200642. }
  200643. else
  200644. {
  200645. png_save_uint_16(entrybuf + 0, ep->red);
  200646. png_save_uint_16(entrybuf + 2, ep->green);
  200647. png_save_uint_16(entrybuf + 4, ep->blue);
  200648. png_save_uint_16(entrybuf + 6, ep->alpha);
  200649. png_save_uint_16(entrybuf + 8, ep->frequency);
  200650. }
  200651. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200652. }
  200653. #else
  200654. ep=spalette->entries;
  200655. for (i=0; i>spalette->nentries; i++)
  200656. {
  200657. if (spalette->depth == 8)
  200658. {
  200659. entrybuf[0] = (png_byte)ep[i].red;
  200660. entrybuf[1] = (png_byte)ep[i].green;
  200661. entrybuf[2] = (png_byte)ep[i].blue;
  200662. entrybuf[3] = (png_byte)ep[i].alpha;
  200663. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200664. }
  200665. else
  200666. {
  200667. png_save_uint_16(entrybuf + 0, ep[i].red);
  200668. png_save_uint_16(entrybuf + 2, ep[i].green);
  200669. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200670. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200671. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200672. }
  200673. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200674. }
  200675. #endif
  200676. png_write_chunk_end(png_ptr);
  200677. png_free(png_ptr, new_name);
  200678. }
  200679. #endif
  200680. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200681. /* write the sBIT chunk */
  200682. void /* PRIVATE */
  200683. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200684. {
  200685. #ifdef PNG_USE_LOCAL_ARRAYS
  200686. PNG_sBIT;
  200687. #endif
  200688. png_byte buf[4];
  200689. png_size_t size;
  200690. png_debug(1, "in png_write_sBIT\n");
  200691. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200692. if (color_type & PNG_COLOR_MASK_COLOR)
  200693. {
  200694. png_byte maxbits;
  200695. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200696. png_ptr->usr_bit_depth);
  200697. if (sbit->red == 0 || sbit->red > maxbits ||
  200698. sbit->green == 0 || sbit->green > maxbits ||
  200699. sbit->blue == 0 || sbit->blue > maxbits)
  200700. {
  200701. png_warning(png_ptr, "Invalid sBIT depth specified");
  200702. return;
  200703. }
  200704. buf[0] = sbit->red;
  200705. buf[1] = sbit->green;
  200706. buf[2] = sbit->blue;
  200707. size = 3;
  200708. }
  200709. else
  200710. {
  200711. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200712. {
  200713. png_warning(png_ptr, "Invalid sBIT depth specified");
  200714. return;
  200715. }
  200716. buf[0] = sbit->gray;
  200717. size = 1;
  200718. }
  200719. if (color_type & PNG_COLOR_MASK_ALPHA)
  200720. {
  200721. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200722. {
  200723. png_warning(png_ptr, "Invalid sBIT depth specified");
  200724. return;
  200725. }
  200726. buf[size++] = sbit->alpha;
  200727. }
  200728. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200729. }
  200730. #endif
  200731. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200732. /* write the cHRM chunk */
  200733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200734. void /* PRIVATE */
  200735. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200736. double red_x, double red_y, double green_x, double green_y,
  200737. double blue_x, double blue_y)
  200738. {
  200739. #ifdef PNG_USE_LOCAL_ARRAYS
  200740. PNG_cHRM;
  200741. #endif
  200742. png_byte buf[32];
  200743. png_uint_32 itemp;
  200744. png_debug(1, "in png_write_cHRM\n");
  200745. /* each value is saved in 1/100,000ths */
  200746. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200747. white_x + white_y > 1.0)
  200748. {
  200749. png_warning(png_ptr, "Invalid cHRM white point specified");
  200750. #if !defined(PNG_NO_CONSOLE_IO)
  200751. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200752. #endif
  200753. return;
  200754. }
  200755. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200756. png_save_uint_32(buf, itemp);
  200757. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200758. png_save_uint_32(buf + 4, itemp);
  200759. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200760. {
  200761. png_warning(png_ptr, "Invalid cHRM red point specified");
  200762. return;
  200763. }
  200764. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200765. png_save_uint_32(buf + 8, itemp);
  200766. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200767. png_save_uint_32(buf + 12, itemp);
  200768. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200769. {
  200770. png_warning(png_ptr, "Invalid cHRM green point specified");
  200771. return;
  200772. }
  200773. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200774. png_save_uint_32(buf + 16, itemp);
  200775. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200776. png_save_uint_32(buf + 20, itemp);
  200777. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200778. {
  200779. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200780. return;
  200781. }
  200782. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200783. png_save_uint_32(buf + 24, itemp);
  200784. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200785. png_save_uint_32(buf + 28, itemp);
  200786. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200787. }
  200788. #endif
  200789. #ifdef PNG_FIXED_POINT_SUPPORTED
  200790. void /* PRIVATE */
  200791. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200792. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200793. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200794. png_fixed_point blue_y)
  200795. {
  200796. #ifdef PNG_USE_LOCAL_ARRAYS
  200797. PNG_cHRM;
  200798. #endif
  200799. png_byte buf[32];
  200800. png_debug(1, "in png_write_cHRM\n");
  200801. /* each value is saved in 1/100,000ths */
  200802. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200803. {
  200804. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200805. #if !defined(PNG_NO_CONSOLE_IO)
  200806. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200807. #endif
  200808. return;
  200809. }
  200810. png_save_uint_32(buf, (png_uint_32)white_x);
  200811. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200812. if (red_x + red_y > 100000L)
  200813. {
  200814. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200815. return;
  200816. }
  200817. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200818. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200819. if (green_x + green_y > 100000L)
  200820. {
  200821. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  200822. return;
  200823. }
  200824. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  200825. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  200826. if (blue_x + blue_y > 100000L)
  200827. {
  200828. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  200829. return;
  200830. }
  200831. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  200832. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  200833. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200834. }
  200835. #endif
  200836. #endif
  200837. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  200838. /* write the tRNS chunk */
  200839. void /* PRIVATE */
  200840. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  200841. int num_trans, int color_type)
  200842. {
  200843. #ifdef PNG_USE_LOCAL_ARRAYS
  200844. PNG_tRNS;
  200845. #endif
  200846. png_byte buf[6];
  200847. png_debug(1, "in png_write_tRNS\n");
  200848. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200849. {
  200850. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  200851. {
  200852. png_warning(png_ptr,"Invalid number of transparent colors specified");
  200853. return;
  200854. }
  200855. /* write the chunk out as it is */
  200856. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  200857. }
  200858. else if (color_type == PNG_COLOR_TYPE_GRAY)
  200859. {
  200860. /* one 16 bit value */
  200861. if(tran->gray >= (1 << png_ptr->bit_depth))
  200862. {
  200863. png_warning(png_ptr,
  200864. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  200865. return;
  200866. }
  200867. png_save_uint_16(buf, tran->gray);
  200868. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  200869. }
  200870. else if (color_type == PNG_COLOR_TYPE_RGB)
  200871. {
  200872. /* three 16 bit values */
  200873. png_save_uint_16(buf, tran->red);
  200874. png_save_uint_16(buf + 2, tran->green);
  200875. png_save_uint_16(buf + 4, tran->blue);
  200876. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200877. {
  200878. png_warning(png_ptr,
  200879. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  200880. return;
  200881. }
  200882. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  200883. }
  200884. else
  200885. {
  200886. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  200887. }
  200888. }
  200889. #endif
  200890. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  200891. /* write the background chunk */
  200892. void /* PRIVATE */
  200893. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  200894. {
  200895. #ifdef PNG_USE_LOCAL_ARRAYS
  200896. PNG_bKGD;
  200897. #endif
  200898. png_byte buf[6];
  200899. png_debug(1, "in png_write_bKGD\n");
  200900. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200901. {
  200902. if (
  200903. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200904. (png_ptr->num_palette ||
  200905. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  200906. #endif
  200907. back->index > png_ptr->num_palette)
  200908. {
  200909. png_warning(png_ptr, "Invalid background palette index");
  200910. return;
  200911. }
  200912. buf[0] = back->index;
  200913. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  200914. }
  200915. else if (color_type & PNG_COLOR_MASK_COLOR)
  200916. {
  200917. png_save_uint_16(buf, back->red);
  200918. png_save_uint_16(buf + 2, back->green);
  200919. png_save_uint_16(buf + 4, back->blue);
  200920. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200921. {
  200922. png_warning(png_ptr,
  200923. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  200924. return;
  200925. }
  200926. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  200927. }
  200928. else
  200929. {
  200930. if(back->gray >= (1 << png_ptr->bit_depth))
  200931. {
  200932. png_warning(png_ptr,
  200933. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  200934. return;
  200935. }
  200936. png_save_uint_16(buf, back->gray);
  200937. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  200938. }
  200939. }
  200940. #endif
  200941. #if defined(PNG_WRITE_hIST_SUPPORTED)
  200942. /* write the histogram */
  200943. void /* PRIVATE */
  200944. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  200945. {
  200946. #ifdef PNG_USE_LOCAL_ARRAYS
  200947. PNG_hIST;
  200948. #endif
  200949. int i;
  200950. png_byte buf[3];
  200951. png_debug(1, "in png_write_hIST\n");
  200952. if (num_hist > (int)png_ptr->num_palette)
  200953. {
  200954. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  200955. png_ptr->num_palette);
  200956. png_warning(png_ptr, "Invalid number of histogram entries specified");
  200957. return;
  200958. }
  200959. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  200960. for (i = 0; i < num_hist; i++)
  200961. {
  200962. png_save_uint_16(buf, hist[i]);
  200963. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  200964. }
  200965. png_write_chunk_end(png_ptr);
  200966. }
  200967. #endif
  200968. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  200969. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  200970. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  200971. * and if invalid, correct the keyword rather than discarding the entire
  200972. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  200973. * length, forbids leading or trailing whitespace, multiple internal spaces,
  200974. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  200975. *
  200976. * The new_key is allocated to hold the corrected keyword and must be freed
  200977. * by the calling routine. This avoids problems with trying to write to
  200978. * static keywords without having to have duplicate copies of the strings.
  200979. */
  200980. png_size_t /* PRIVATE */
  200981. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  200982. {
  200983. png_size_t key_len;
  200984. png_charp kp, dp;
  200985. int kflag;
  200986. int kwarn=0;
  200987. png_debug(1, "in png_check_keyword\n");
  200988. *new_key = NULL;
  200989. if (key == NULL || (key_len = png_strlen(key)) == 0)
  200990. {
  200991. png_warning(png_ptr, "zero length keyword");
  200992. return ((png_size_t)0);
  200993. }
  200994. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  200995. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  200996. if (*new_key == NULL)
  200997. {
  200998. png_warning(png_ptr, "Out of memory while procesing keyword");
  200999. return ((png_size_t)0);
  201000. }
  201001. /* Replace non-printing characters with a blank and print a warning */
  201002. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201003. {
  201004. if ((png_byte)*kp < 0x20 ||
  201005. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201006. {
  201007. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201008. char msg[40];
  201009. png_snprintf(msg, 40,
  201010. "invalid keyword character 0x%02X", (png_byte)*kp);
  201011. png_warning(png_ptr, msg);
  201012. #else
  201013. png_warning(png_ptr, "invalid character in keyword");
  201014. #endif
  201015. *dp = ' ';
  201016. }
  201017. else
  201018. {
  201019. *dp = *kp;
  201020. }
  201021. }
  201022. *dp = '\0';
  201023. /* Remove any trailing white space. */
  201024. kp = *new_key + key_len - 1;
  201025. if (*kp == ' ')
  201026. {
  201027. png_warning(png_ptr, "trailing spaces removed from keyword");
  201028. while (*kp == ' ')
  201029. {
  201030. *(kp--) = '\0';
  201031. key_len--;
  201032. }
  201033. }
  201034. /* Remove any leading white space. */
  201035. kp = *new_key;
  201036. if (*kp == ' ')
  201037. {
  201038. png_warning(png_ptr, "leading spaces removed from keyword");
  201039. while (*kp == ' ')
  201040. {
  201041. kp++;
  201042. key_len--;
  201043. }
  201044. }
  201045. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201046. /* Remove multiple internal spaces. */
  201047. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201048. {
  201049. if (*kp == ' ' && kflag == 0)
  201050. {
  201051. *(dp++) = *kp;
  201052. kflag = 1;
  201053. }
  201054. else if (*kp == ' ')
  201055. {
  201056. key_len--;
  201057. kwarn=1;
  201058. }
  201059. else
  201060. {
  201061. *(dp++) = *kp;
  201062. kflag = 0;
  201063. }
  201064. }
  201065. *dp = '\0';
  201066. if(kwarn)
  201067. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201068. if (key_len == 0)
  201069. {
  201070. png_free(png_ptr, *new_key);
  201071. *new_key=NULL;
  201072. png_warning(png_ptr, "Zero length keyword");
  201073. }
  201074. if (key_len > 79)
  201075. {
  201076. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201077. new_key[79] = '\0';
  201078. key_len = 79;
  201079. }
  201080. return (key_len);
  201081. }
  201082. #endif
  201083. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201084. /* write a tEXt chunk */
  201085. void /* PRIVATE */
  201086. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201087. png_size_t text_len)
  201088. {
  201089. #ifdef PNG_USE_LOCAL_ARRAYS
  201090. PNG_tEXt;
  201091. #endif
  201092. png_size_t key_len;
  201093. png_charp new_key;
  201094. png_debug(1, "in png_write_tEXt\n");
  201095. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201096. {
  201097. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201098. return;
  201099. }
  201100. if (text == NULL || *text == '\0')
  201101. text_len = 0;
  201102. else
  201103. text_len = png_strlen(text);
  201104. /* make sure we include the 0 after the key */
  201105. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201106. /*
  201107. * We leave it to the application to meet PNG-1.0 requirements on the
  201108. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201109. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201110. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201111. */
  201112. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201113. if (text_len)
  201114. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201115. png_write_chunk_end(png_ptr);
  201116. png_free(png_ptr, new_key);
  201117. }
  201118. #endif
  201119. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201120. /* write a compressed text chunk */
  201121. void /* PRIVATE */
  201122. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201123. png_size_t text_len, int compression)
  201124. {
  201125. #ifdef PNG_USE_LOCAL_ARRAYS
  201126. PNG_zTXt;
  201127. #endif
  201128. png_size_t key_len;
  201129. char buf[1];
  201130. png_charp new_key;
  201131. compression_state comp;
  201132. png_debug(1, "in png_write_zTXt\n");
  201133. comp.num_output_ptr = 0;
  201134. comp.max_output_ptr = 0;
  201135. comp.output_ptr = NULL;
  201136. comp.input = NULL;
  201137. comp.input_len = 0;
  201138. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201139. {
  201140. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201141. return;
  201142. }
  201143. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201144. {
  201145. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201146. png_free(png_ptr, new_key);
  201147. return;
  201148. }
  201149. text_len = png_strlen(text);
  201150. /* compute the compressed data; do it now for the length */
  201151. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201152. &comp);
  201153. /* write start of chunk */
  201154. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201155. (key_len+text_len+2));
  201156. /* write key */
  201157. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201158. png_free(png_ptr, new_key);
  201159. buf[0] = (png_byte)compression;
  201160. /* write compression */
  201161. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201162. /* write the compressed data */
  201163. png_write_compressed_data_out(png_ptr, &comp);
  201164. /* close the chunk */
  201165. png_write_chunk_end(png_ptr);
  201166. }
  201167. #endif
  201168. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201169. /* write an iTXt chunk */
  201170. void /* PRIVATE */
  201171. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201172. png_charp lang, png_charp lang_key, png_charp text)
  201173. {
  201174. #ifdef PNG_USE_LOCAL_ARRAYS
  201175. PNG_iTXt;
  201176. #endif
  201177. png_size_t lang_len, key_len, lang_key_len, text_len;
  201178. png_charp new_lang, new_key;
  201179. png_byte cbuf[2];
  201180. compression_state comp;
  201181. png_debug(1, "in png_write_iTXt\n");
  201182. comp.num_output_ptr = 0;
  201183. comp.max_output_ptr = 0;
  201184. comp.output_ptr = NULL;
  201185. comp.input = NULL;
  201186. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201187. {
  201188. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201189. return;
  201190. }
  201191. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201192. {
  201193. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201194. new_lang = NULL;
  201195. lang_len = 0;
  201196. }
  201197. if (lang_key == NULL)
  201198. lang_key_len = 0;
  201199. else
  201200. lang_key_len = png_strlen(lang_key);
  201201. if (text == NULL)
  201202. text_len = 0;
  201203. else
  201204. text_len = png_strlen(text);
  201205. /* compute the compressed data; do it now for the length */
  201206. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201207. &comp);
  201208. /* make sure we include the compression flag, the compression byte,
  201209. * and the NULs after the key, lang, and lang_key parts */
  201210. png_write_chunk_start(png_ptr, png_iTXt,
  201211. (png_uint_32)(
  201212. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201213. + key_len
  201214. + lang_len
  201215. + lang_key_len
  201216. + text_len));
  201217. /*
  201218. * We leave it to the application to meet PNG-1.0 requirements on the
  201219. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201220. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201221. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201222. */
  201223. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201224. /* set the compression flag */
  201225. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201226. compression == PNG_TEXT_COMPRESSION_NONE)
  201227. cbuf[0] = 0;
  201228. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201229. cbuf[0] = 1;
  201230. /* set the compression method */
  201231. cbuf[1] = 0;
  201232. png_write_chunk_data(png_ptr, cbuf, 2);
  201233. cbuf[0] = 0;
  201234. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201235. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201236. png_write_compressed_data_out(png_ptr, &comp);
  201237. png_write_chunk_end(png_ptr);
  201238. png_free(png_ptr, new_key);
  201239. if (new_lang)
  201240. png_free(png_ptr, new_lang);
  201241. }
  201242. #endif
  201243. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201244. /* write the oFFs chunk */
  201245. void /* PRIVATE */
  201246. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201247. int unit_type)
  201248. {
  201249. #ifdef PNG_USE_LOCAL_ARRAYS
  201250. PNG_oFFs;
  201251. #endif
  201252. png_byte buf[9];
  201253. png_debug(1, "in png_write_oFFs\n");
  201254. if (unit_type >= PNG_OFFSET_LAST)
  201255. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201256. png_save_int_32(buf, x_offset);
  201257. png_save_int_32(buf + 4, y_offset);
  201258. buf[8] = (png_byte)unit_type;
  201259. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201260. }
  201261. #endif
  201262. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201263. /* write the pCAL chunk (described in the PNG extensions document) */
  201264. void /* PRIVATE */
  201265. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201266. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201267. {
  201268. #ifdef PNG_USE_LOCAL_ARRAYS
  201269. PNG_pCAL;
  201270. #endif
  201271. png_size_t purpose_len, units_len, total_len;
  201272. png_uint_32p params_len;
  201273. png_byte buf[10];
  201274. png_charp new_purpose;
  201275. int i;
  201276. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201277. if (type >= PNG_EQUATION_LAST)
  201278. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201279. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201280. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201281. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201282. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201283. total_len = purpose_len + units_len + 10;
  201284. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201285. *png_sizeof(png_uint_32)));
  201286. /* Find the length of each parameter, making sure we don't count the
  201287. null terminator for the last parameter. */
  201288. for (i = 0; i < nparams; i++)
  201289. {
  201290. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201291. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201292. total_len += (png_size_t)params_len[i];
  201293. }
  201294. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201295. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201296. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201297. png_save_int_32(buf, X0);
  201298. png_save_int_32(buf + 4, X1);
  201299. buf[8] = (png_byte)type;
  201300. buf[9] = (png_byte)nparams;
  201301. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201302. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201303. png_free(png_ptr, new_purpose);
  201304. for (i = 0; i < nparams; i++)
  201305. {
  201306. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201307. (png_size_t)params_len[i]);
  201308. }
  201309. png_free(png_ptr, params_len);
  201310. png_write_chunk_end(png_ptr);
  201311. }
  201312. #endif
  201313. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201314. /* write the sCAL chunk */
  201315. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201316. void /* PRIVATE */
  201317. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201318. {
  201319. #ifdef PNG_USE_LOCAL_ARRAYS
  201320. PNG_sCAL;
  201321. #endif
  201322. char buf[64];
  201323. png_size_t total_len;
  201324. png_debug(1, "in png_write_sCAL\n");
  201325. buf[0] = (char)unit;
  201326. #if defined(_WIN32_WCE)
  201327. /* sprintf() function is not supported on WindowsCE */
  201328. {
  201329. wchar_t wc_buf[32];
  201330. size_t wc_len;
  201331. swprintf(wc_buf, TEXT("%12.12e"), width);
  201332. wc_len = wcslen(wc_buf);
  201333. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201334. total_len = wc_len + 2;
  201335. swprintf(wc_buf, TEXT("%12.12e"), height);
  201336. wc_len = wcslen(wc_buf);
  201337. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201338. NULL, NULL);
  201339. total_len += wc_len;
  201340. }
  201341. #else
  201342. png_snprintf(buf + 1, 63, "%12.12e", width);
  201343. total_len = 1 + png_strlen(buf + 1) + 1;
  201344. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201345. total_len += png_strlen(buf + total_len);
  201346. #endif
  201347. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201348. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201349. }
  201350. #else
  201351. #ifdef PNG_FIXED_POINT_SUPPORTED
  201352. void /* PRIVATE */
  201353. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201354. png_charp height)
  201355. {
  201356. #ifdef PNG_USE_LOCAL_ARRAYS
  201357. PNG_sCAL;
  201358. #endif
  201359. png_byte buf[64];
  201360. png_size_t wlen, hlen, total_len;
  201361. png_debug(1, "in png_write_sCAL_s\n");
  201362. wlen = png_strlen(width);
  201363. hlen = png_strlen(height);
  201364. total_len = wlen + hlen + 2;
  201365. if (total_len > 64)
  201366. {
  201367. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201368. return;
  201369. }
  201370. buf[0] = (png_byte)unit;
  201371. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201372. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201373. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201374. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201375. }
  201376. #endif
  201377. #endif
  201378. #endif
  201379. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201380. /* write the pHYs chunk */
  201381. void /* PRIVATE */
  201382. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201383. png_uint_32 y_pixels_per_unit,
  201384. int unit_type)
  201385. {
  201386. #ifdef PNG_USE_LOCAL_ARRAYS
  201387. PNG_pHYs;
  201388. #endif
  201389. png_byte buf[9];
  201390. png_debug(1, "in png_write_pHYs\n");
  201391. if (unit_type >= PNG_RESOLUTION_LAST)
  201392. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201393. png_save_uint_32(buf, x_pixels_per_unit);
  201394. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201395. buf[8] = (png_byte)unit_type;
  201396. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201397. }
  201398. #endif
  201399. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201400. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201401. * or png_convert_from_time_t(), or fill in the structure yourself.
  201402. */
  201403. void /* PRIVATE */
  201404. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201405. {
  201406. #ifdef PNG_USE_LOCAL_ARRAYS
  201407. PNG_tIME;
  201408. #endif
  201409. png_byte buf[7];
  201410. png_debug(1, "in png_write_tIME\n");
  201411. if (mod_time->month > 12 || mod_time->month < 1 ||
  201412. mod_time->day > 31 || mod_time->day < 1 ||
  201413. mod_time->hour > 23 || mod_time->second > 60)
  201414. {
  201415. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201416. return;
  201417. }
  201418. png_save_uint_16(buf, mod_time->year);
  201419. buf[2] = mod_time->month;
  201420. buf[3] = mod_time->day;
  201421. buf[4] = mod_time->hour;
  201422. buf[5] = mod_time->minute;
  201423. buf[6] = mod_time->second;
  201424. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201425. }
  201426. #endif
  201427. /* initializes the row writing capability of libpng */
  201428. void /* PRIVATE */
  201429. png_write_start_row(png_structp png_ptr)
  201430. {
  201431. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201432. #ifdef PNG_USE_LOCAL_ARRAYS
  201433. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201434. /* start of interlace block */
  201435. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201436. /* offset to next interlace block */
  201437. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201438. /* start of interlace block in the y direction */
  201439. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201440. /* offset to next interlace block in the y direction */
  201441. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201442. #endif
  201443. #endif
  201444. png_size_t buf_size;
  201445. png_debug(1, "in png_write_start_row\n");
  201446. buf_size = (png_size_t)(PNG_ROWBYTES(
  201447. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201448. /* set up row buffer */
  201449. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201450. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201451. #ifndef PNG_NO_WRITE_FILTERING
  201452. /* set up filtering buffer, if using this filter */
  201453. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201454. {
  201455. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201456. (png_ptr->rowbytes + 1));
  201457. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201458. }
  201459. /* We only need to keep the previous row if we are using one of these. */
  201460. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201461. {
  201462. /* set up previous row buffer */
  201463. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201464. png_memset(png_ptr->prev_row, 0, buf_size);
  201465. if (png_ptr->do_filter & PNG_FILTER_UP)
  201466. {
  201467. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201468. (png_ptr->rowbytes + 1));
  201469. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201470. }
  201471. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201472. {
  201473. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201474. (png_ptr->rowbytes + 1));
  201475. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201476. }
  201477. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201478. {
  201479. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201480. (png_ptr->rowbytes + 1));
  201481. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201482. }
  201483. #endif /* PNG_NO_WRITE_FILTERING */
  201484. }
  201485. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201486. /* if interlaced, we need to set up width and height of pass */
  201487. if (png_ptr->interlaced)
  201488. {
  201489. if (!(png_ptr->transformations & PNG_INTERLACE))
  201490. {
  201491. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201492. png_pass_ystart[0]) / png_pass_yinc[0];
  201493. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201494. png_pass_start[0]) / png_pass_inc[0];
  201495. }
  201496. else
  201497. {
  201498. png_ptr->num_rows = png_ptr->height;
  201499. png_ptr->usr_width = png_ptr->width;
  201500. }
  201501. }
  201502. else
  201503. #endif
  201504. {
  201505. png_ptr->num_rows = png_ptr->height;
  201506. png_ptr->usr_width = png_ptr->width;
  201507. }
  201508. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201509. png_ptr->zstream.next_out = png_ptr->zbuf;
  201510. }
  201511. /* Internal use only. Called when finished processing a row of data. */
  201512. void /* PRIVATE */
  201513. png_write_finish_row(png_structp png_ptr)
  201514. {
  201515. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201516. #ifdef PNG_USE_LOCAL_ARRAYS
  201517. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201518. /* start of interlace block */
  201519. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201520. /* offset to next interlace block */
  201521. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201522. /* start of interlace block in the y direction */
  201523. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201524. /* offset to next interlace block in the y direction */
  201525. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201526. #endif
  201527. #endif
  201528. int ret;
  201529. png_debug(1, "in png_write_finish_row\n");
  201530. /* next row */
  201531. png_ptr->row_number++;
  201532. /* see if we are done */
  201533. if (png_ptr->row_number < png_ptr->num_rows)
  201534. return;
  201535. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201536. /* if interlaced, go to next pass */
  201537. if (png_ptr->interlaced)
  201538. {
  201539. png_ptr->row_number = 0;
  201540. if (png_ptr->transformations & PNG_INTERLACE)
  201541. {
  201542. png_ptr->pass++;
  201543. }
  201544. else
  201545. {
  201546. /* loop until we find a non-zero width or height pass */
  201547. do
  201548. {
  201549. png_ptr->pass++;
  201550. if (png_ptr->pass >= 7)
  201551. break;
  201552. png_ptr->usr_width = (png_ptr->width +
  201553. png_pass_inc[png_ptr->pass] - 1 -
  201554. png_pass_start[png_ptr->pass]) /
  201555. png_pass_inc[png_ptr->pass];
  201556. png_ptr->num_rows = (png_ptr->height +
  201557. png_pass_yinc[png_ptr->pass] - 1 -
  201558. png_pass_ystart[png_ptr->pass]) /
  201559. png_pass_yinc[png_ptr->pass];
  201560. if (png_ptr->transformations & PNG_INTERLACE)
  201561. break;
  201562. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201563. }
  201564. /* reset the row above the image for the next pass */
  201565. if (png_ptr->pass < 7)
  201566. {
  201567. if (png_ptr->prev_row != NULL)
  201568. png_memset(png_ptr->prev_row, 0,
  201569. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201570. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201571. return;
  201572. }
  201573. }
  201574. #endif
  201575. /* if we get here, we've just written the last row, so we need
  201576. to flush the compressor */
  201577. do
  201578. {
  201579. /* tell the compressor we are done */
  201580. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201581. /* check for an error */
  201582. if (ret == Z_OK)
  201583. {
  201584. /* check to see if we need more room */
  201585. if (!(png_ptr->zstream.avail_out))
  201586. {
  201587. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201588. png_ptr->zstream.next_out = png_ptr->zbuf;
  201589. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201590. }
  201591. }
  201592. else if (ret != Z_STREAM_END)
  201593. {
  201594. if (png_ptr->zstream.msg != NULL)
  201595. png_error(png_ptr, png_ptr->zstream.msg);
  201596. else
  201597. png_error(png_ptr, "zlib error");
  201598. }
  201599. } while (ret != Z_STREAM_END);
  201600. /* write any extra space */
  201601. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201602. {
  201603. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201604. png_ptr->zstream.avail_out);
  201605. }
  201606. deflateReset(&png_ptr->zstream);
  201607. png_ptr->zstream.data_type = Z_BINARY;
  201608. }
  201609. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201610. /* Pick out the correct pixels for the interlace pass.
  201611. * The basic idea here is to go through the row with a source
  201612. * pointer and a destination pointer (sp and dp), and copy the
  201613. * correct pixels for the pass. As the row gets compacted,
  201614. * sp will always be >= dp, so we should never overwrite anything.
  201615. * See the default: case for the easiest code to understand.
  201616. */
  201617. void /* PRIVATE */
  201618. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201619. {
  201620. #ifdef PNG_USE_LOCAL_ARRAYS
  201621. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201622. /* start of interlace block */
  201623. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201624. /* offset to next interlace block */
  201625. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201626. #endif
  201627. png_debug(1, "in png_do_write_interlace\n");
  201628. /* we don't have to do anything on the last pass (6) */
  201629. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201630. if (row != NULL && row_info != NULL && pass < 6)
  201631. #else
  201632. if (pass < 6)
  201633. #endif
  201634. {
  201635. /* each pixel depth is handled separately */
  201636. switch (row_info->pixel_depth)
  201637. {
  201638. case 1:
  201639. {
  201640. png_bytep sp;
  201641. png_bytep dp;
  201642. int shift;
  201643. int d;
  201644. int value;
  201645. png_uint_32 i;
  201646. png_uint_32 row_width = row_info->width;
  201647. dp = row;
  201648. d = 0;
  201649. shift = 7;
  201650. for (i = png_pass_start[pass]; i < row_width;
  201651. i += png_pass_inc[pass])
  201652. {
  201653. sp = row + (png_size_t)(i >> 3);
  201654. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201655. d |= (value << shift);
  201656. if (shift == 0)
  201657. {
  201658. shift = 7;
  201659. *dp++ = (png_byte)d;
  201660. d = 0;
  201661. }
  201662. else
  201663. shift--;
  201664. }
  201665. if (shift != 7)
  201666. *dp = (png_byte)d;
  201667. break;
  201668. }
  201669. case 2:
  201670. {
  201671. png_bytep sp;
  201672. png_bytep dp;
  201673. int shift;
  201674. int d;
  201675. int value;
  201676. png_uint_32 i;
  201677. png_uint_32 row_width = row_info->width;
  201678. dp = row;
  201679. shift = 6;
  201680. d = 0;
  201681. for (i = png_pass_start[pass]; i < row_width;
  201682. i += png_pass_inc[pass])
  201683. {
  201684. sp = row + (png_size_t)(i >> 2);
  201685. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201686. d |= (value << shift);
  201687. if (shift == 0)
  201688. {
  201689. shift = 6;
  201690. *dp++ = (png_byte)d;
  201691. d = 0;
  201692. }
  201693. else
  201694. shift -= 2;
  201695. }
  201696. if (shift != 6)
  201697. *dp = (png_byte)d;
  201698. break;
  201699. }
  201700. case 4:
  201701. {
  201702. png_bytep sp;
  201703. png_bytep dp;
  201704. int shift;
  201705. int d;
  201706. int value;
  201707. png_uint_32 i;
  201708. png_uint_32 row_width = row_info->width;
  201709. dp = row;
  201710. shift = 4;
  201711. d = 0;
  201712. for (i = png_pass_start[pass]; i < row_width;
  201713. i += png_pass_inc[pass])
  201714. {
  201715. sp = row + (png_size_t)(i >> 1);
  201716. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201717. d |= (value << shift);
  201718. if (shift == 0)
  201719. {
  201720. shift = 4;
  201721. *dp++ = (png_byte)d;
  201722. d = 0;
  201723. }
  201724. else
  201725. shift -= 4;
  201726. }
  201727. if (shift != 4)
  201728. *dp = (png_byte)d;
  201729. break;
  201730. }
  201731. default:
  201732. {
  201733. png_bytep sp;
  201734. png_bytep dp;
  201735. png_uint_32 i;
  201736. png_uint_32 row_width = row_info->width;
  201737. png_size_t pixel_bytes;
  201738. /* start at the beginning */
  201739. dp = row;
  201740. /* find out how many bytes each pixel takes up */
  201741. pixel_bytes = (row_info->pixel_depth >> 3);
  201742. /* loop through the row, only looking at the pixels that
  201743. matter */
  201744. for (i = png_pass_start[pass]; i < row_width;
  201745. i += png_pass_inc[pass])
  201746. {
  201747. /* find out where the original pixel is */
  201748. sp = row + (png_size_t)i * pixel_bytes;
  201749. /* move the pixel */
  201750. if (dp != sp)
  201751. png_memcpy(dp, sp, pixel_bytes);
  201752. /* next pixel */
  201753. dp += pixel_bytes;
  201754. }
  201755. break;
  201756. }
  201757. }
  201758. /* set new row width */
  201759. row_info->width = (row_info->width +
  201760. png_pass_inc[pass] - 1 -
  201761. png_pass_start[pass]) /
  201762. png_pass_inc[pass];
  201763. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201764. row_info->width);
  201765. }
  201766. }
  201767. #endif
  201768. /* This filters the row, chooses which filter to use, if it has not already
  201769. * been specified by the application, and then writes the row out with the
  201770. * chosen filter.
  201771. */
  201772. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201773. #define PNG_HISHIFT 10
  201774. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201775. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201776. void /* PRIVATE */
  201777. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201778. {
  201779. png_bytep best_row;
  201780. #ifndef PNG_NO_WRITE_FILTER
  201781. png_bytep prev_row, row_buf;
  201782. png_uint_32 mins, bpp;
  201783. png_byte filter_to_do = png_ptr->do_filter;
  201784. png_uint_32 row_bytes = row_info->rowbytes;
  201785. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201786. int num_p_filters = (int)png_ptr->num_prev_filters;
  201787. #endif
  201788. png_debug(1, "in png_write_find_filter\n");
  201789. /* find out how many bytes offset each pixel is */
  201790. bpp = (row_info->pixel_depth + 7) >> 3;
  201791. prev_row = png_ptr->prev_row;
  201792. #endif
  201793. best_row = png_ptr->row_buf;
  201794. #ifndef PNG_NO_WRITE_FILTER
  201795. row_buf = best_row;
  201796. mins = PNG_MAXSUM;
  201797. /* The prediction method we use is to find which method provides the
  201798. * smallest value when summing the absolute values of the distances
  201799. * from zero, using anything >= 128 as negative numbers. This is known
  201800. * as the "minimum sum of absolute differences" heuristic. Other
  201801. * heuristics are the "weighted minimum sum of absolute differences"
  201802. * (experimental and can in theory improve compression), and the "zlib
  201803. * predictive" method (not implemented yet), which does test compressions
  201804. * of lines using different filter methods, and then chooses the
  201805. * (series of) filter(s) that give minimum compressed data size (VERY
  201806. * computationally expensive).
  201807. *
  201808. * GRR 980525: consider also
  201809. * (1) minimum sum of absolute differences from running average (i.e.,
  201810. * keep running sum of non-absolute differences & count of bytes)
  201811. * [track dispersion, too? restart average if dispersion too large?]
  201812. * (1b) minimum sum of absolute differences from sliding average, probably
  201813. * with window size <= deflate window (usually 32K)
  201814. * (2) minimum sum of squared differences from zero or running average
  201815. * (i.e., ~ root-mean-square approach)
  201816. */
  201817. /* We don't need to test the 'no filter' case if this is the only filter
  201818. * that has been chosen, as it doesn't actually do anything to the data.
  201819. */
  201820. if ((filter_to_do & PNG_FILTER_NONE) &&
  201821. filter_to_do != PNG_FILTER_NONE)
  201822. {
  201823. png_bytep rp;
  201824. png_uint_32 sum = 0;
  201825. png_uint_32 i;
  201826. int v;
  201827. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  201828. {
  201829. v = *rp;
  201830. sum += (v < 128) ? v : 256 - v;
  201831. }
  201832. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201833. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201834. {
  201835. png_uint_32 sumhi, sumlo;
  201836. int j;
  201837. sumlo = sum & PNG_LOMASK;
  201838. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  201839. /* Reduce the sum if we match any of the previous rows */
  201840. for (j = 0; j < num_p_filters; j++)
  201841. {
  201842. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201843. {
  201844. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201845. PNG_WEIGHT_SHIFT;
  201846. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201847. PNG_WEIGHT_SHIFT;
  201848. }
  201849. }
  201850. /* Factor in the cost of this filter (this is here for completeness,
  201851. * but it makes no sense to have a "cost" for the NONE filter, as
  201852. * it has the minimum possible computational cost - none).
  201853. */
  201854. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201855. PNG_COST_SHIFT;
  201856. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201857. PNG_COST_SHIFT;
  201858. if (sumhi > PNG_HIMASK)
  201859. sum = PNG_MAXSUM;
  201860. else
  201861. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201862. }
  201863. #endif
  201864. mins = sum;
  201865. }
  201866. /* sub filter */
  201867. if (filter_to_do == PNG_FILTER_SUB)
  201868. /* it's the only filter so no testing is needed */
  201869. {
  201870. png_bytep rp, lp, dp;
  201871. png_uint_32 i;
  201872. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201873. i++, rp++, dp++)
  201874. {
  201875. *dp = *rp;
  201876. }
  201877. for (lp = row_buf + 1; i < row_bytes;
  201878. i++, rp++, lp++, dp++)
  201879. {
  201880. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201881. }
  201882. best_row = png_ptr->sub_row;
  201883. }
  201884. else if (filter_to_do & PNG_FILTER_SUB)
  201885. {
  201886. png_bytep rp, dp, lp;
  201887. png_uint_32 sum = 0, lmins = mins;
  201888. png_uint_32 i;
  201889. int v;
  201890. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201891. /* We temporarily increase the "minimum sum" by the factor we
  201892. * would reduce the sum of this filter, so that we can do the
  201893. * early exit comparison without scaling the sum each time.
  201894. */
  201895. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201896. {
  201897. int j;
  201898. png_uint_32 lmhi, lmlo;
  201899. lmlo = lmins & PNG_LOMASK;
  201900. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201901. for (j = 0; j < num_p_filters; j++)
  201902. {
  201903. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201904. {
  201905. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201906. PNG_WEIGHT_SHIFT;
  201907. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201908. PNG_WEIGHT_SHIFT;
  201909. }
  201910. }
  201911. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201912. PNG_COST_SHIFT;
  201913. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201914. PNG_COST_SHIFT;
  201915. if (lmhi > PNG_HIMASK)
  201916. lmins = PNG_MAXSUM;
  201917. else
  201918. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201919. }
  201920. #endif
  201921. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201922. i++, rp++, dp++)
  201923. {
  201924. v = *dp = *rp;
  201925. sum += (v < 128) ? v : 256 - v;
  201926. }
  201927. for (lp = row_buf + 1; i < row_bytes;
  201928. i++, rp++, lp++, dp++)
  201929. {
  201930. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201931. sum += (v < 128) ? v : 256 - v;
  201932. if (sum > lmins) /* We are already worse, don't continue. */
  201933. break;
  201934. }
  201935. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201936. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201937. {
  201938. int j;
  201939. png_uint_32 sumhi, sumlo;
  201940. sumlo = sum & PNG_LOMASK;
  201941. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201942. for (j = 0; j < num_p_filters; j++)
  201943. {
  201944. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201945. {
  201946. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  201947. PNG_WEIGHT_SHIFT;
  201948. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  201949. PNG_WEIGHT_SHIFT;
  201950. }
  201951. }
  201952. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201953. PNG_COST_SHIFT;
  201954. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201955. PNG_COST_SHIFT;
  201956. if (sumhi > PNG_HIMASK)
  201957. sum = PNG_MAXSUM;
  201958. else
  201959. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201960. }
  201961. #endif
  201962. if (sum < mins)
  201963. {
  201964. mins = sum;
  201965. best_row = png_ptr->sub_row;
  201966. }
  201967. }
  201968. /* up filter */
  201969. if (filter_to_do == PNG_FILTER_UP)
  201970. {
  201971. png_bytep rp, dp, pp;
  201972. png_uint_32 i;
  201973. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201974. pp = prev_row + 1; i < row_bytes;
  201975. i++, rp++, pp++, dp++)
  201976. {
  201977. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  201978. }
  201979. best_row = png_ptr->up_row;
  201980. }
  201981. else if (filter_to_do & PNG_FILTER_UP)
  201982. {
  201983. png_bytep rp, dp, pp;
  201984. png_uint_32 sum = 0, lmins = mins;
  201985. png_uint_32 i;
  201986. int v;
  201987. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201988. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201989. {
  201990. int j;
  201991. png_uint_32 lmhi, lmlo;
  201992. lmlo = lmins & PNG_LOMASK;
  201993. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201994. for (j = 0; j < num_p_filters; j++)
  201995. {
  201996. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201997. {
  201998. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201999. PNG_WEIGHT_SHIFT;
  202000. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202001. PNG_WEIGHT_SHIFT;
  202002. }
  202003. }
  202004. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202005. PNG_COST_SHIFT;
  202006. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202007. PNG_COST_SHIFT;
  202008. if (lmhi > PNG_HIMASK)
  202009. lmins = PNG_MAXSUM;
  202010. else
  202011. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202012. }
  202013. #endif
  202014. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202015. pp = prev_row + 1; i < row_bytes; i++)
  202016. {
  202017. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202018. sum += (v < 128) ? v : 256 - v;
  202019. if (sum > lmins) /* We are already worse, don't continue. */
  202020. break;
  202021. }
  202022. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202023. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202024. {
  202025. int j;
  202026. png_uint_32 sumhi, sumlo;
  202027. sumlo = sum & PNG_LOMASK;
  202028. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202029. for (j = 0; j < num_p_filters; j++)
  202030. {
  202031. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202032. {
  202033. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202034. PNG_WEIGHT_SHIFT;
  202035. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202036. PNG_WEIGHT_SHIFT;
  202037. }
  202038. }
  202039. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202040. PNG_COST_SHIFT;
  202041. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202042. PNG_COST_SHIFT;
  202043. if (sumhi > PNG_HIMASK)
  202044. sum = PNG_MAXSUM;
  202045. else
  202046. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202047. }
  202048. #endif
  202049. if (sum < mins)
  202050. {
  202051. mins = sum;
  202052. best_row = png_ptr->up_row;
  202053. }
  202054. }
  202055. /* avg filter */
  202056. if (filter_to_do == PNG_FILTER_AVG)
  202057. {
  202058. png_bytep rp, dp, pp, lp;
  202059. png_uint_32 i;
  202060. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202061. pp = prev_row + 1; i < bpp; i++)
  202062. {
  202063. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202064. }
  202065. for (lp = row_buf + 1; i < row_bytes; i++)
  202066. {
  202067. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202068. & 0xff);
  202069. }
  202070. best_row = png_ptr->avg_row;
  202071. }
  202072. else if (filter_to_do & PNG_FILTER_AVG)
  202073. {
  202074. png_bytep rp, dp, pp, lp;
  202075. png_uint_32 sum = 0, lmins = mins;
  202076. png_uint_32 i;
  202077. int v;
  202078. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202079. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202080. {
  202081. int j;
  202082. png_uint_32 lmhi, lmlo;
  202083. lmlo = lmins & PNG_LOMASK;
  202084. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202085. for (j = 0; j < num_p_filters; j++)
  202086. {
  202087. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202088. {
  202089. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202090. PNG_WEIGHT_SHIFT;
  202091. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202092. PNG_WEIGHT_SHIFT;
  202093. }
  202094. }
  202095. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202096. PNG_COST_SHIFT;
  202097. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202098. PNG_COST_SHIFT;
  202099. if (lmhi > PNG_HIMASK)
  202100. lmins = PNG_MAXSUM;
  202101. else
  202102. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202103. }
  202104. #endif
  202105. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202106. pp = prev_row + 1; i < bpp; i++)
  202107. {
  202108. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202109. sum += (v < 128) ? v : 256 - v;
  202110. }
  202111. for (lp = row_buf + 1; i < row_bytes; i++)
  202112. {
  202113. v = *dp++ =
  202114. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202115. sum += (v < 128) ? v : 256 - v;
  202116. if (sum > lmins) /* We are already worse, don't continue. */
  202117. break;
  202118. }
  202119. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202120. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202121. {
  202122. int j;
  202123. png_uint_32 sumhi, sumlo;
  202124. sumlo = sum & PNG_LOMASK;
  202125. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202126. for (j = 0; j < num_p_filters; j++)
  202127. {
  202128. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202129. {
  202130. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202131. PNG_WEIGHT_SHIFT;
  202132. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202133. PNG_WEIGHT_SHIFT;
  202134. }
  202135. }
  202136. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202137. PNG_COST_SHIFT;
  202138. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202139. PNG_COST_SHIFT;
  202140. if (sumhi > PNG_HIMASK)
  202141. sum = PNG_MAXSUM;
  202142. else
  202143. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202144. }
  202145. #endif
  202146. if (sum < mins)
  202147. {
  202148. mins = sum;
  202149. best_row = png_ptr->avg_row;
  202150. }
  202151. }
  202152. /* Paeth filter */
  202153. if (filter_to_do == PNG_FILTER_PAETH)
  202154. {
  202155. png_bytep rp, dp, pp, cp, lp;
  202156. png_uint_32 i;
  202157. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202158. pp = prev_row + 1; i < bpp; i++)
  202159. {
  202160. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202161. }
  202162. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202163. {
  202164. int a, b, c, pa, pb, pc, p;
  202165. b = *pp++;
  202166. c = *cp++;
  202167. a = *lp++;
  202168. p = b - c;
  202169. pc = a - c;
  202170. #ifdef PNG_USE_ABS
  202171. pa = abs(p);
  202172. pb = abs(pc);
  202173. pc = abs(p + pc);
  202174. #else
  202175. pa = p < 0 ? -p : p;
  202176. pb = pc < 0 ? -pc : pc;
  202177. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202178. #endif
  202179. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202180. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202181. }
  202182. best_row = png_ptr->paeth_row;
  202183. }
  202184. else if (filter_to_do & PNG_FILTER_PAETH)
  202185. {
  202186. png_bytep rp, dp, pp, cp, lp;
  202187. png_uint_32 sum = 0, lmins = mins;
  202188. png_uint_32 i;
  202189. int v;
  202190. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202191. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202192. {
  202193. int j;
  202194. png_uint_32 lmhi, lmlo;
  202195. lmlo = lmins & PNG_LOMASK;
  202196. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202197. for (j = 0; j < num_p_filters; j++)
  202198. {
  202199. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202200. {
  202201. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202202. PNG_WEIGHT_SHIFT;
  202203. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202204. PNG_WEIGHT_SHIFT;
  202205. }
  202206. }
  202207. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202208. PNG_COST_SHIFT;
  202209. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202210. PNG_COST_SHIFT;
  202211. if (lmhi > PNG_HIMASK)
  202212. lmins = PNG_MAXSUM;
  202213. else
  202214. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202215. }
  202216. #endif
  202217. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202218. pp = prev_row + 1; i < bpp; i++)
  202219. {
  202220. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202221. sum += (v < 128) ? v : 256 - v;
  202222. }
  202223. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202224. {
  202225. int a, b, c, pa, pb, pc, p;
  202226. b = *pp++;
  202227. c = *cp++;
  202228. a = *lp++;
  202229. #ifndef PNG_SLOW_PAETH
  202230. p = b - c;
  202231. pc = a - c;
  202232. #ifdef PNG_USE_ABS
  202233. pa = abs(p);
  202234. pb = abs(pc);
  202235. pc = abs(p + pc);
  202236. #else
  202237. pa = p < 0 ? -p : p;
  202238. pb = pc < 0 ? -pc : pc;
  202239. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202240. #endif
  202241. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202242. #else /* PNG_SLOW_PAETH */
  202243. p = a + b - c;
  202244. pa = abs(p - a);
  202245. pb = abs(p - b);
  202246. pc = abs(p - c);
  202247. if (pa <= pb && pa <= pc)
  202248. p = a;
  202249. else if (pb <= pc)
  202250. p = b;
  202251. else
  202252. p = c;
  202253. #endif /* PNG_SLOW_PAETH */
  202254. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202255. sum += (v < 128) ? v : 256 - v;
  202256. if (sum > lmins) /* We are already worse, don't continue. */
  202257. break;
  202258. }
  202259. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202260. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202261. {
  202262. int j;
  202263. png_uint_32 sumhi, sumlo;
  202264. sumlo = sum & PNG_LOMASK;
  202265. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202266. for (j = 0; j < num_p_filters; j++)
  202267. {
  202268. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202269. {
  202270. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202271. PNG_WEIGHT_SHIFT;
  202272. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202273. PNG_WEIGHT_SHIFT;
  202274. }
  202275. }
  202276. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202277. PNG_COST_SHIFT;
  202278. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202279. PNG_COST_SHIFT;
  202280. if (sumhi > PNG_HIMASK)
  202281. sum = PNG_MAXSUM;
  202282. else
  202283. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202284. }
  202285. #endif
  202286. if (sum < mins)
  202287. {
  202288. best_row = png_ptr->paeth_row;
  202289. }
  202290. }
  202291. #endif /* PNG_NO_WRITE_FILTER */
  202292. /* Do the actual writing of the filtered row data from the chosen filter. */
  202293. png_write_filtered_row(png_ptr, best_row);
  202294. #ifndef PNG_NO_WRITE_FILTER
  202295. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202296. /* Save the type of filter we picked this time for future calculations */
  202297. if (png_ptr->num_prev_filters > 0)
  202298. {
  202299. int j;
  202300. for (j = 1; j < num_p_filters; j++)
  202301. {
  202302. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202303. }
  202304. png_ptr->prev_filters[j] = best_row[0];
  202305. }
  202306. #endif
  202307. #endif /* PNG_NO_WRITE_FILTER */
  202308. }
  202309. /* Do the actual writing of a previously filtered row. */
  202310. void /* PRIVATE */
  202311. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202312. {
  202313. png_debug(1, "in png_write_filtered_row\n");
  202314. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202315. /* set up the zlib input buffer */
  202316. png_ptr->zstream.next_in = filtered_row;
  202317. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202318. /* repeat until we have compressed all the data */
  202319. do
  202320. {
  202321. int ret; /* return of zlib */
  202322. /* compress the data */
  202323. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202324. /* check for compression errors */
  202325. if (ret != Z_OK)
  202326. {
  202327. if (png_ptr->zstream.msg != NULL)
  202328. png_error(png_ptr, png_ptr->zstream.msg);
  202329. else
  202330. png_error(png_ptr, "zlib error");
  202331. }
  202332. /* see if it is time to write another IDAT */
  202333. if (!(png_ptr->zstream.avail_out))
  202334. {
  202335. /* write the IDAT and reset the zlib output buffer */
  202336. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202337. png_ptr->zstream.next_out = png_ptr->zbuf;
  202338. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202339. }
  202340. /* repeat until all data has been compressed */
  202341. } while (png_ptr->zstream.avail_in);
  202342. /* swap the current and previous rows */
  202343. if (png_ptr->prev_row != NULL)
  202344. {
  202345. png_bytep tptr;
  202346. tptr = png_ptr->prev_row;
  202347. png_ptr->prev_row = png_ptr->row_buf;
  202348. png_ptr->row_buf = tptr;
  202349. }
  202350. /* finish row - updates counters and flushes zlib if last row */
  202351. png_write_finish_row(png_ptr);
  202352. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202353. png_ptr->flush_rows++;
  202354. if (png_ptr->flush_dist > 0 &&
  202355. png_ptr->flush_rows >= png_ptr->flush_dist)
  202356. {
  202357. png_write_flush(png_ptr);
  202358. }
  202359. #endif
  202360. }
  202361. #endif /* PNG_WRITE_SUPPORTED */
  202362. /*** End of inlined file: pngwutil.c ***/
  202363. }
  202364. #else
  202365. extern "C"
  202366. {
  202367. #include <png.h>
  202368. #include <pngconf.h>
  202369. }
  202370. #endif
  202371. }
  202372. #undef max
  202373. #undef min
  202374. #if JUCE_MSVC
  202375. #pragma warning (pop)
  202376. #endif
  202377. BEGIN_JUCE_NAMESPACE
  202378. using ::calloc;
  202379. using ::malloc;
  202380. using ::free;
  202381. namespace PNGHelpers
  202382. {
  202383. using namespace pnglibNamespace;
  202384. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202385. {
  202386. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202387. }
  202388. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202389. {
  202390. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202391. }
  202392. struct PNGErrorStruct {};
  202393. static void errorCallback (png_structp, png_const_charp)
  202394. {
  202395. throw PNGErrorStruct();
  202396. }
  202397. }
  202398. PNGImageFormat::PNGImageFormat() {}
  202399. PNGImageFormat::~PNGImageFormat() {}
  202400. const String PNGImageFormat::getFormatName()
  202401. {
  202402. return "PNG";
  202403. }
  202404. bool PNGImageFormat::canUnderstand (InputStream& in)
  202405. {
  202406. const int bytesNeeded = 4;
  202407. char header [bytesNeeded];
  202408. return in.read (header, bytesNeeded) == bytesNeeded
  202409. && header[1] == 'P'
  202410. && header[2] == 'N'
  202411. && header[3] == 'G';
  202412. }
  202413. const Image PNGImageFormat::decodeImage (InputStream& in)
  202414. {
  202415. using namespace pnglibNamespace;
  202416. Image image;
  202417. png_structp pngReadStruct;
  202418. png_infop pngInfoStruct;
  202419. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202420. if (pngReadStruct != 0)
  202421. {
  202422. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202423. if (pngInfoStruct == 0)
  202424. {
  202425. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202426. return Image();
  202427. }
  202428. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202429. // read the header..
  202430. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202431. png_uint_32 width, height;
  202432. int bitDepth, colorType, interlaceType;
  202433. png_read_info (pngReadStruct, pngInfoStruct);
  202434. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202435. &width, &height,
  202436. &bitDepth, &colorType,
  202437. &interlaceType, 0, 0);
  202438. if (bitDepth == 16)
  202439. png_set_strip_16 (pngReadStruct);
  202440. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202441. png_set_expand (pngReadStruct);
  202442. if (bitDepth < 8)
  202443. png_set_expand (pngReadStruct);
  202444. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202445. png_set_expand (pngReadStruct);
  202446. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202447. png_set_gray_to_rgb (pngReadStruct);
  202448. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202449. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202450. || pngInfoStruct->num_trans > 0;
  202451. // Load the image into a temp buffer in the pnglib format..
  202452. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202453. {
  202454. HeapBlock <png_bytep> rows (height);
  202455. for (int y = (int) height; --y >= 0;)
  202456. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202457. png_read_image (pngReadStruct, rows);
  202458. png_read_end (pngReadStruct, pngInfoStruct);
  202459. }
  202460. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202461. // now convert the data to a juce image format..
  202462. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202463. (int) width, (int) height, hasAlphaChan);
  202464. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202465. const Image::BitmapData destData (image, 0, 0, (int) width, (int) height, true);
  202466. uint8* srcRow = tempBuffer;
  202467. uint8* destRow = destData.data;
  202468. for (int y = 0; y < (int) height; ++y)
  202469. {
  202470. const uint8* src = srcRow;
  202471. srcRow += (width << 2);
  202472. uint8* dest = destRow;
  202473. destRow += destData.lineStride;
  202474. if (hasAlphaChan)
  202475. {
  202476. for (int i = (int) width; --i >= 0;)
  202477. {
  202478. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202479. ((PixelARGB*) dest)->premultiply();
  202480. dest += destData.pixelStride;
  202481. src += 4;
  202482. }
  202483. }
  202484. else
  202485. {
  202486. for (int i = (int) width; --i >= 0;)
  202487. {
  202488. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202489. dest += destData.pixelStride;
  202490. src += 4;
  202491. }
  202492. }
  202493. }
  202494. }
  202495. return image;
  202496. }
  202497. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202498. {
  202499. using namespace pnglibNamespace;
  202500. const int width = image.getWidth();
  202501. const int height = image.getHeight();
  202502. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202503. if (pngWriteStruct == 0)
  202504. return false;
  202505. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202506. if (pngInfoStruct == 0)
  202507. {
  202508. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202509. return false;
  202510. }
  202511. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202512. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202513. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202514. : PNG_COLOR_TYPE_RGB,
  202515. PNG_INTERLACE_NONE,
  202516. PNG_COMPRESSION_TYPE_BASE,
  202517. PNG_FILTER_TYPE_BASE);
  202518. HeapBlock <uint8> rowData (width * 4);
  202519. png_color_8 sig_bit;
  202520. sig_bit.red = 8;
  202521. sig_bit.green = 8;
  202522. sig_bit.blue = 8;
  202523. sig_bit.alpha = 8;
  202524. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202525. png_write_info (pngWriteStruct, pngInfoStruct);
  202526. png_set_shift (pngWriteStruct, &sig_bit);
  202527. png_set_packing (pngWriteStruct);
  202528. const Image::BitmapData srcData (image, 0, 0, width, height);
  202529. for (int y = 0; y < height; ++y)
  202530. {
  202531. uint8* dst = rowData;
  202532. const uint8* src = srcData.getLinePointer (y);
  202533. if (image.hasAlphaChannel())
  202534. {
  202535. for (int i = width; --i >= 0;)
  202536. {
  202537. PixelARGB p (*(const PixelARGB*) src);
  202538. p.unpremultiply();
  202539. *dst++ = p.getRed();
  202540. *dst++ = p.getGreen();
  202541. *dst++ = p.getBlue();
  202542. *dst++ = p.getAlpha();
  202543. src += srcData.pixelStride;
  202544. }
  202545. }
  202546. else
  202547. {
  202548. for (int i = width; --i >= 0;)
  202549. {
  202550. *dst++ = ((const PixelRGB*) src)->getRed();
  202551. *dst++ = ((const PixelRGB*) src)->getGreen();
  202552. *dst++ = ((const PixelRGB*) src)->getBlue();
  202553. src += srcData.pixelStride;
  202554. }
  202555. }
  202556. png_write_rows (pngWriteStruct, &rowData, 1);
  202557. }
  202558. png_write_end (pngWriteStruct, pngInfoStruct);
  202559. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202560. out.flush();
  202561. return true;
  202562. }
  202563. END_JUCE_NAMESPACE
  202564. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202565. #endif
  202566. //==============================================================================
  202567. #if JUCE_BUILD_NATIVE
  202568. #if JUCE_WINDOWS
  202569. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202570. /*
  202571. This file wraps together all the win32-specific code, so that
  202572. we can include all the native headers just once, and compile all our
  202573. platform-specific stuff in one big lump, keeping it out of the way of
  202574. the rest of the codebase.
  202575. */
  202576. #if JUCE_WINDOWS
  202577. BEGIN_JUCE_NAMESPACE
  202578. #define JUCE_INCLUDED_FILE 1
  202579. // Now include the actual code files..
  202580. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202581. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202582. // compiled on its own).
  202583. #if JUCE_INCLUDED_FILE
  202584. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202585. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202586. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202587. #ifndef DOXYGEN
  202588. // use with DynamicLibraryLoader to simplify importing functions
  202589. //
  202590. // functionName: function to import
  202591. // localFunctionName: name you want to use to actually call it (must be different)
  202592. // returnType: the return type
  202593. // object: the DynamicLibraryLoader to use
  202594. // params: list of params (bracketed)
  202595. //
  202596. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202597. typedef returnType (WINAPI *type##localFunctionName) params; \
  202598. type##localFunctionName localFunctionName \
  202599. = (type##localFunctionName)object.findProcAddress (#functionName);
  202600. // loads and unloads a DLL automatically
  202601. class JUCE_API DynamicLibraryLoader
  202602. {
  202603. public:
  202604. DynamicLibraryLoader (const String& name);
  202605. ~DynamicLibraryLoader();
  202606. void* findProcAddress (const String& functionName);
  202607. private:
  202608. void* libHandle;
  202609. };
  202610. #endif
  202611. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202612. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202613. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202614. {
  202615. libHandle = LoadLibrary (name);
  202616. }
  202617. DynamicLibraryLoader::~DynamicLibraryLoader()
  202618. {
  202619. FreeLibrary ((HMODULE) libHandle);
  202620. }
  202621. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202622. {
  202623. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202624. }
  202625. #endif
  202626. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202627. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202628. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202629. // compiled on its own).
  202630. #if JUCE_INCLUDED_FILE
  202631. extern void juce_initialiseThreadEvents();
  202632. void Logger::outputDebugString (const String& text)
  202633. {
  202634. OutputDebugString (text + "\n");
  202635. }
  202636. static int64 hiResTicksPerSecond;
  202637. static double hiResTicksScaleFactor;
  202638. #if JUCE_USE_INTRINSICS
  202639. // CPU info functions using intrinsics...
  202640. #pragma intrinsic (__cpuid)
  202641. #pragma intrinsic (__rdtsc)
  202642. const String SystemStats::getCpuVendor()
  202643. {
  202644. int info [4];
  202645. __cpuid (info, 0);
  202646. char v [12];
  202647. memcpy (v, info + 1, 4);
  202648. memcpy (v + 4, info + 3, 4);
  202649. memcpy (v + 8, info + 2, 4);
  202650. return String (v, 12);
  202651. }
  202652. #else
  202653. // CPU info functions using old fashioned inline asm...
  202654. static void juce_getCpuVendor (char* const v)
  202655. {
  202656. int vendor[4];
  202657. zeromem (vendor, 16);
  202658. #ifdef JUCE_64BIT
  202659. #else
  202660. #ifndef __MINGW32__
  202661. __try
  202662. #endif
  202663. {
  202664. #if JUCE_GCC
  202665. unsigned int dummy = 0;
  202666. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202667. #else
  202668. __asm
  202669. {
  202670. mov eax, 0
  202671. cpuid
  202672. mov [vendor], ebx
  202673. mov [vendor + 4], edx
  202674. mov [vendor + 8], ecx
  202675. }
  202676. #endif
  202677. }
  202678. #ifndef __MINGW32__
  202679. __except (EXCEPTION_EXECUTE_HANDLER)
  202680. {
  202681. *v = 0;
  202682. }
  202683. #endif
  202684. #endif
  202685. memcpy (v, vendor, 16);
  202686. }
  202687. const String SystemStats::getCpuVendor()
  202688. {
  202689. char v [16];
  202690. juce_getCpuVendor (v);
  202691. return String (v, 16);
  202692. }
  202693. #endif
  202694. void SystemStats::initialiseStats()
  202695. {
  202696. juce_initialiseThreadEvents();
  202697. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202698. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202699. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202700. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202701. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202702. #else
  202703. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202704. #endif
  202705. {
  202706. SYSTEM_INFO systemInfo;
  202707. GetSystemInfo (&systemInfo);
  202708. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  202709. }
  202710. LARGE_INTEGER f;
  202711. QueryPerformanceFrequency (&f);
  202712. hiResTicksPerSecond = f.QuadPart;
  202713. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202714. String s (SystemStats::getJUCEVersion());
  202715. const MMRESULT res = timeBeginPeriod (1);
  202716. (void) res;
  202717. jassert (res == TIMERR_NOERROR);
  202718. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202719. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202720. #endif
  202721. }
  202722. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202723. {
  202724. OSVERSIONINFO info;
  202725. info.dwOSVersionInfoSize = sizeof (info);
  202726. GetVersionEx (&info);
  202727. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202728. {
  202729. switch (info.dwMajorVersion)
  202730. {
  202731. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202732. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202733. default: jassertfalse; break; // !! not a supported OS!
  202734. }
  202735. }
  202736. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202737. {
  202738. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202739. return Win98;
  202740. }
  202741. return UnknownOS;
  202742. }
  202743. const String SystemStats::getOperatingSystemName()
  202744. {
  202745. const char* name = "Unknown OS";
  202746. switch (getOperatingSystemType())
  202747. {
  202748. case Windows7: name = "Windows 7"; break;
  202749. case WinVista: name = "Windows Vista"; break;
  202750. case WinXP: name = "Windows XP"; break;
  202751. case Win2000: name = "Windows 2000"; break;
  202752. case Win98: name = "Windows 98"; break;
  202753. default: jassertfalse; break; // !! new type of OS?
  202754. }
  202755. return name;
  202756. }
  202757. bool SystemStats::isOperatingSystem64Bit()
  202758. {
  202759. #ifdef _WIN64
  202760. return true;
  202761. #else
  202762. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202763. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202764. BOOL isWow64 = FALSE;
  202765. return (fnIsWow64Process != 0)
  202766. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202767. && (isWow64 != FALSE);
  202768. #endif
  202769. }
  202770. int SystemStats::getMemorySizeInMegabytes()
  202771. {
  202772. MEMORYSTATUSEX mem;
  202773. mem.dwLength = sizeof (mem);
  202774. GlobalMemoryStatusEx (&mem);
  202775. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202776. }
  202777. uint32 juce_millisecondsSinceStartup() throw()
  202778. {
  202779. return (uint32) GetTickCount();
  202780. }
  202781. int64 Time::getHighResolutionTicks() throw()
  202782. {
  202783. LARGE_INTEGER ticks;
  202784. QueryPerformanceCounter (&ticks);
  202785. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202786. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202787. // fix for a very obscure PCI hardware bug that can make the counter
  202788. // sometimes jump forwards by a few seconds..
  202789. static int64 hiResTicksOffset = 0;
  202790. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202791. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202792. hiResTicksOffset = newOffset;
  202793. return ticks.QuadPart + hiResTicksOffset;
  202794. }
  202795. double Time::getMillisecondCounterHiRes() throw()
  202796. {
  202797. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202798. }
  202799. int64 Time::getHighResolutionTicksPerSecond() throw()
  202800. {
  202801. return hiResTicksPerSecond;
  202802. }
  202803. static int64 juce_getClockCycleCounter() throw()
  202804. {
  202805. #if JUCE_USE_INTRINSICS
  202806. // MS intrinsics version...
  202807. return __rdtsc();
  202808. #elif JUCE_GCC
  202809. // GNU inline asm version...
  202810. unsigned int hi = 0, lo = 0;
  202811. __asm__ __volatile__ (
  202812. "xor %%eax, %%eax \n\
  202813. xor %%edx, %%edx \n\
  202814. rdtsc \n\
  202815. movl %%eax, %[lo] \n\
  202816. movl %%edx, %[hi]"
  202817. :
  202818. : [hi] "m" (hi),
  202819. [lo] "m" (lo)
  202820. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  202821. return (int64) ((((uint64) hi) << 32) | lo);
  202822. #else
  202823. // MSVC inline asm version...
  202824. unsigned int hi = 0, lo = 0;
  202825. __asm
  202826. {
  202827. xor eax, eax
  202828. xor edx, edx
  202829. rdtsc
  202830. mov lo, eax
  202831. mov hi, edx
  202832. }
  202833. return (int64) ((((uint64) hi) << 32) | lo);
  202834. #endif
  202835. }
  202836. int SystemStats::getCpuSpeedInMegaherz()
  202837. {
  202838. const int64 cycles = juce_getClockCycleCounter();
  202839. const uint32 millis = Time::getMillisecondCounter();
  202840. int lastResult = 0;
  202841. for (;;)
  202842. {
  202843. int n = 1000000;
  202844. while (--n > 0) {}
  202845. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  202846. const int64 cyclesNow = juce_getClockCycleCounter();
  202847. if (millisElapsed > 80)
  202848. {
  202849. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  202850. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  202851. return newResult;
  202852. lastResult = newResult;
  202853. }
  202854. }
  202855. }
  202856. bool Time::setSystemTimeToThisTime() const
  202857. {
  202858. SYSTEMTIME st;
  202859. st.wDayOfWeek = 0;
  202860. st.wYear = (WORD) getYear();
  202861. st.wMonth = (WORD) (getMonth() + 1);
  202862. st.wDay = (WORD) getDayOfMonth();
  202863. st.wHour = (WORD) getHours();
  202864. st.wMinute = (WORD) getMinutes();
  202865. st.wSecond = (WORD) getSeconds();
  202866. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  202867. // do this twice because of daylight saving conversion problems - the
  202868. // first one sets it up, the second one kicks it in.
  202869. return SetLocalTime (&st) != 0
  202870. && SetLocalTime (&st) != 0;
  202871. }
  202872. int SystemStats::getPageSize()
  202873. {
  202874. SYSTEM_INFO systemInfo;
  202875. GetSystemInfo (&systemInfo);
  202876. return systemInfo.dwPageSize;
  202877. }
  202878. const String SystemStats::getLogonName()
  202879. {
  202880. TCHAR text [256];
  202881. DWORD len = numElementsInArray (text) - 2;
  202882. zerostruct (text);
  202883. GetUserName (text, &len);
  202884. return String (text, len);
  202885. }
  202886. const String SystemStats::getFullUserName()
  202887. {
  202888. return getLogonName();
  202889. }
  202890. #endif
  202891. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  202892. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  202893. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202894. // compiled on its own).
  202895. #if JUCE_INCLUDED_FILE
  202896. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202897. extern HWND juce_messageWindowHandle;
  202898. #endif
  202899. #if ! JUCE_USE_INTRINSICS
  202900. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  202901. // older ones we have to actually call the ops as win32 functions..
  202902. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  202903. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  202904. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  202905. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  202906. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  202907. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  202908. {
  202909. jassertfalse; // This operation isn't available in old MS compiler versions!
  202910. __int64 oldValue = *value;
  202911. if (oldValue == valueToCompare)
  202912. *value = newValue;
  202913. return oldValue;
  202914. }
  202915. #endif
  202916. CriticalSection::CriticalSection() throw()
  202917. {
  202918. // (just to check the MS haven't changed this structure and broken things...)
  202919. #if _MSC_VER >= 1400
  202920. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  202921. #else
  202922. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  202923. #endif
  202924. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  202925. }
  202926. CriticalSection::~CriticalSection() throw()
  202927. {
  202928. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  202929. }
  202930. void CriticalSection::enter() const throw()
  202931. {
  202932. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  202933. }
  202934. bool CriticalSection::tryEnter() const throw()
  202935. {
  202936. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  202937. }
  202938. void CriticalSection::exit() const throw()
  202939. {
  202940. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  202941. }
  202942. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  202943. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  202944. {
  202945. }
  202946. WaitableEvent::~WaitableEvent() throw()
  202947. {
  202948. CloseHandle (internal);
  202949. }
  202950. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  202951. {
  202952. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  202953. }
  202954. void WaitableEvent::signal() const throw()
  202955. {
  202956. SetEvent (internal);
  202957. }
  202958. void WaitableEvent::reset() const throw()
  202959. {
  202960. ResetEvent (internal);
  202961. }
  202962. void JUCE_API juce_threadEntryPoint (void*);
  202963. static unsigned int __stdcall threadEntryProc (void* userData)
  202964. {
  202965. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202966. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  202967. GetCurrentThreadId(), TRUE);
  202968. #endif
  202969. juce_threadEntryPoint (userData);
  202970. _endthreadex (0);
  202971. return 0;
  202972. }
  202973. void juce_CloseThreadHandle (void* handle)
  202974. {
  202975. CloseHandle ((HANDLE) handle);
  202976. }
  202977. void* juce_createThread (void* userData)
  202978. {
  202979. unsigned int threadId;
  202980. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  202981. }
  202982. void juce_killThread (void* handle)
  202983. {
  202984. if (handle != 0)
  202985. {
  202986. #if JUCE_DEBUG
  202987. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  202988. #endif
  202989. TerminateThread (handle, 0);
  202990. }
  202991. }
  202992. void juce_setCurrentThreadName (const String& name)
  202993. {
  202994. #if JUCE_DEBUG && JUCE_MSVC
  202995. struct
  202996. {
  202997. DWORD dwType;
  202998. LPCSTR szName;
  202999. DWORD dwThreadID;
  203000. DWORD dwFlags;
  203001. } info;
  203002. info.dwType = 0x1000;
  203003. info.szName = name.toCString();
  203004. info.dwThreadID = GetCurrentThreadId();
  203005. info.dwFlags = 0;
  203006. __try
  203007. {
  203008. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203009. }
  203010. __except (EXCEPTION_CONTINUE_EXECUTION)
  203011. {}
  203012. #else
  203013. (void) name;
  203014. #endif
  203015. }
  203016. Thread::ThreadID Thread::getCurrentThreadId()
  203017. {
  203018. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203019. }
  203020. // priority 1 to 10 where 5=normal, 1=low
  203021. bool juce_setThreadPriority (void* threadHandle, int priority)
  203022. {
  203023. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203024. if (priority < 1)
  203025. pri = THREAD_PRIORITY_IDLE;
  203026. else if (priority < 2)
  203027. pri = THREAD_PRIORITY_LOWEST;
  203028. else if (priority < 5)
  203029. pri = THREAD_PRIORITY_BELOW_NORMAL;
  203030. else if (priority < 7)
  203031. pri = THREAD_PRIORITY_NORMAL;
  203032. else if (priority < 9)
  203033. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203034. else if (priority < 10)
  203035. pri = THREAD_PRIORITY_HIGHEST;
  203036. if (threadHandle == 0)
  203037. threadHandle = GetCurrentThread();
  203038. return SetThreadPriority (threadHandle, pri) != FALSE;
  203039. }
  203040. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203041. {
  203042. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203043. }
  203044. static HANDLE sleepEvent = 0;
  203045. void juce_initialiseThreadEvents()
  203046. {
  203047. if (sleepEvent == 0)
  203048. #if JUCE_DEBUG
  203049. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203050. #else
  203051. sleepEvent = CreateEvent (0, 0, 0, 0);
  203052. #endif
  203053. }
  203054. void Thread::yield()
  203055. {
  203056. Sleep (0);
  203057. }
  203058. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203059. {
  203060. if (millisecs >= 10)
  203061. {
  203062. Sleep (millisecs);
  203063. }
  203064. else
  203065. {
  203066. jassert (sleepEvent != 0);
  203067. // unlike Sleep() this is guaranteed to return to the current thread after
  203068. // the time expires, so we'll use this for short waits, which are more likely
  203069. // to need to be accurate
  203070. WaitForSingleObject (sleepEvent, millisecs);
  203071. }
  203072. }
  203073. static int lastProcessPriority = -1;
  203074. // called by WindowDriver because Windows does wierd things to process priority
  203075. // when you swap apps, and this forces an update when the app is brought to the front.
  203076. void juce_repeatLastProcessPriority()
  203077. {
  203078. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203079. {
  203080. DWORD p;
  203081. switch (lastProcessPriority)
  203082. {
  203083. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203084. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203085. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203086. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203087. default: jassertfalse; return; // bad priority value
  203088. }
  203089. SetPriorityClass (GetCurrentProcess(), p);
  203090. }
  203091. }
  203092. void Process::setPriority (ProcessPriority prior)
  203093. {
  203094. if (lastProcessPriority != (int) prior)
  203095. {
  203096. lastProcessPriority = (int) prior;
  203097. juce_repeatLastProcessPriority();
  203098. }
  203099. }
  203100. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203101. {
  203102. return IsDebuggerPresent() != FALSE;
  203103. }
  203104. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203105. {
  203106. return juce_isRunningUnderDebugger();
  203107. }
  203108. void Process::raisePrivilege()
  203109. {
  203110. jassertfalse; // xxx not implemented
  203111. }
  203112. void Process::lowerPrivilege()
  203113. {
  203114. jassertfalse; // xxx not implemented
  203115. }
  203116. void Process::terminate()
  203117. {
  203118. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203119. _CrtDumpMemoryLeaks();
  203120. #endif
  203121. // bullet in the head in case there's a problem shutting down..
  203122. ExitProcess (0);
  203123. }
  203124. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203125. {
  203126. void* result = 0;
  203127. JUCE_TRY
  203128. {
  203129. result = LoadLibrary (name);
  203130. }
  203131. JUCE_CATCH_ALL
  203132. return result;
  203133. }
  203134. void PlatformUtilities::freeDynamicLibrary (void* h)
  203135. {
  203136. JUCE_TRY
  203137. {
  203138. if (h != 0)
  203139. FreeLibrary ((HMODULE) h);
  203140. }
  203141. JUCE_CATCH_ALL
  203142. }
  203143. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203144. {
  203145. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203146. }
  203147. class InterProcessLock::Pimpl
  203148. {
  203149. public:
  203150. Pimpl (const String& name, const int timeOutMillisecs)
  203151. : handle (0), refCount (1)
  203152. {
  203153. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203154. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203155. {
  203156. if (timeOutMillisecs == 0)
  203157. {
  203158. close();
  203159. return;
  203160. }
  203161. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203162. {
  203163. case WAIT_OBJECT_0:
  203164. case WAIT_ABANDONED:
  203165. break;
  203166. case WAIT_TIMEOUT:
  203167. default:
  203168. close();
  203169. break;
  203170. }
  203171. }
  203172. }
  203173. ~Pimpl()
  203174. {
  203175. close();
  203176. }
  203177. void close()
  203178. {
  203179. if (handle != 0)
  203180. {
  203181. ReleaseMutex (handle);
  203182. CloseHandle (handle);
  203183. handle = 0;
  203184. }
  203185. }
  203186. HANDLE handle;
  203187. int refCount;
  203188. };
  203189. InterProcessLock::InterProcessLock (const String& name_)
  203190. : name (name_)
  203191. {
  203192. }
  203193. InterProcessLock::~InterProcessLock()
  203194. {
  203195. }
  203196. bool InterProcessLock::enter (const int timeOutMillisecs)
  203197. {
  203198. const ScopedLock sl (lock);
  203199. if (pimpl == 0)
  203200. {
  203201. pimpl = new Pimpl (name, timeOutMillisecs);
  203202. if (pimpl->handle == 0)
  203203. pimpl = 0;
  203204. }
  203205. else
  203206. {
  203207. pimpl->refCount++;
  203208. }
  203209. return pimpl != 0;
  203210. }
  203211. void InterProcessLock::exit()
  203212. {
  203213. const ScopedLock sl (lock);
  203214. // Trying to release the lock too many times!
  203215. jassert (pimpl != 0);
  203216. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203217. pimpl = 0;
  203218. }
  203219. #endif
  203220. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203221. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203222. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203223. // compiled on its own).
  203224. #if JUCE_INCLUDED_FILE
  203225. #ifndef CSIDL_MYMUSIC
  203226. #define CSIDL_MYMUSIC 0x000d
  203227. #endif
  203228. #ifndef CSIDL_MYVIDEO
  203229. #define CSIDL_MYVIDEO 0x000e
  203230. #endif
  203231. #ifndef INVALID_FILE_ATTRIBUTES
  203232. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203233. #endif
  203234. const juce_wchar File::separator = '\\';
  203235. const String File::separatorString ("\\");
  203236. bool File::exists() const
  203237. {
  203238. return fullPath.isNotEmpty()
  203239. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203240. }
  203241. bool File::existsAsFile() const
  203242. {
  203243. return fullPath.isNotEmpty()
  203244. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203245. }
  203246. bool File::isDirectory() const
  203247. {
  203248. const DWORD attr = GetFileAttributes (fullPath);
  203249. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203250. }
  203251. bool File::hasWriteAccess() const
  203252. {
  203253. if (exists())
  203254. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203255. // on windows, it seems that even read-only directories can still be written into,
  203256. // so checking the parent directory's permissions would return the wrong result..
  203257. return true;
  203258. }
  203259. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203260. {
  203261. DWORD attr = GetFileAttributes (fullPath);
  203262. if (attr == INVALID_FILE_ATTRIBUTES)
  203263. return false;
  203264. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203265. return true;
  203266. if (shouldBeReadOnly)
  203267. attr |= FILE_ATTRIBUTE_READONLY;
  203268. else
  203269. attr &= ~FILE_ATTRIBUTE_READONLY;
  203270. return SetFileAttributes (fullPath, attr) != FALSE;
  203271. }
  203272. bool File::isHidden() const
  203273. {
  203274. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203275. }
  203276. bool File::deleteFile() const
  203277. {
  203278. if (! exists())
  203279. return true;
  203280. else if (isDirectory())
  203281. return RemoveDirectory (fullPath) != 0;
  203282. else
  203283. return DeleteFile (fullPath) != 0;
  203284. }
  203285. bool File::moveToTrash() const
  203286. {
  203287. if (! exists())
  203288. return true;
  203289. SHFILEOPSTRUCT fos;
  203290. zerostruct (fos);
  203291. // The string we pass in must be double null terminated..
  203292. String doubleNullTermPath (getFullPathName() + " ");
  203293. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203294. p [getFullPathName().length()] = 0;
  203295. fos.wFunc = FO_DELETE;
  203296. fos.pFrom = p;
  203297. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203298. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203299. return SHFileOperation (&fos) == 0;
  203300. }
  203301. bool File::copyInternal (const File& dest) const
  203302. {
  203303. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203304. }
  203305. bool File::moveInternal (const File& dest) const
  203306. {
  203307. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203308. }
  203309. void File::createDirectoryInternal (const String& fileName) const
  203310. {
  203311. CreateDirectory (fileName, 0);
  203312. }
  203313. // return 0 if not possible
  203314. void* juce_fileOpen (const File& file, bool forWriting)
  203315. {
  203316. HANDLE h;
  203317. if (forWriting)
  203318. {
  203319. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203320. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203321. if (h != INVALID_HANDLE_VALUE)
  203322. SetFilePointer (h, 0, 0, FILE_END);
  203323. else
  203324. h = 0;
  203325. }
  203326. else
  203327. {
  203328. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203329. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203330. if (h == INVALID_HANDLE_VALUE)
  203331. h = 0;
  203332. }
  203333. return h;
  203334. }
  203335. void juce_fileClose (void* handle)
  203336. {
  203337. CloseHandle (handle);
  203338. }
  203339. int juce_fileRead (void* handle, void* buffer, int size)
  203340. {
  203341. DWORD num = 0;
  203342. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203343. return (int) num;
  203344. }
  203345. int juce_fileWrite (void* handle, const void* buffer, int size)
  203346. {
  203347. DWORD num;
  203348. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203349. return (int) num;
  203350. }
  203351. int64 juce_fileSetPosition (void* handle, int64 pos)
  203352. {
  203353. LARGE_INTEGER li;
  203354. li.QuadPart = pos;
  203355. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203356. return li.QuadPart;
  203357. }
  203358. int64 FileOutputStream::getPositionInternal() const
  203359. {
  203360. if (fileHandle == 0)
  203361. return -1;
  203362. LARGE_INTEGER li;
  203363. li.QuadPart = 0;
  203364. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203365. return jmax ((int64) 0, li.QuadPart);
  203366. }
  203367. void FileOutputStream::flushInternal()
  203368. {
  203369. if (fileHandle != 0)
  203370. FlushFileBuffers ((HANDLE) fileHandle);
  203371. }
  203372. int64 File::getSize() const
  203373. {
  203374. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203375. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203376. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203377. return 0;
  203378. }
  203379. static int64 fileTimeToTime (const FILETIME* const ft)
  203380. {
  203381. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203382. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203383. }
  203384. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203385. {
  203386. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203387. }
  203388. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203389. {
  203390. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203391. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203392. {
  203393. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203394. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203395. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203396. }
  203397. else
  203398. {
  203399. creationTime = accessTime = modificationTime = 0;
  203400. }
  203401. }
  203402. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203403. {
  203404. void* const h = juce_fileOpen (fullPath, true);
  203405. bool ok = false;
  203406. if (h != 0)
  203407. {
  203408. FILETIME m, a, c;
  203409. timeToFileTime (modificationTime, &m);
  203410. timeToFileTime (accessTime, &a);
  203411. timeToFileTime (creationTime, &c);
  203412. ok = SetFileTime ((HANDLE) h,
  203413. creationTime > 0 ? &c : 0,
  203414. accessTime > 0 ? &a : 0,
  203415. modificationTime > 0 ? &m : 0) != 0;
  203416. juce_fileClose (h);
  203417. }
  203418. return ok;
  203419. }
  203420. void File::findFileSystemRoots (Array<File>& destArray)
  203421. {
  203422. TCHAR buffer [2048];
  203423. buffer[0] = 0;
  203424. buffer[1] = 0;
  203425. GetLogicalDriveStrings (2048, buffer);
  203426. const TCHAR* n = buffer;
  203427. StringArray roots;
  203428. while (*n != 0)
  203429. {
  203430. roots.add (String (n));
  203431. while (*n++ != 0)
  203432. {}
  203433. }
  203434. roots.sort (true);
  203435. for (int i = 0; i < roots.size(); ++i)
  203436. destArray.add (roots [i]);
  203437. }
  203438. static const String getDriveFromPath (const String& path)
  203439. {
  203440. if (path.isNotEmpty() && path[1] == ':')
  203441. return path.substring (0, 2) + '\\';
  203442. return path;
  203443. }
  203444. const String File::getVolumeLabel() const
  203445. {
  203446. TCHAR dest[64];
  203447. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203448. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203449. dest[0] = 0;
  203450. return dest;
  203451. }
  203452. int File::getVolumeSerialNumber() const
  203453. {
  203454. TCHAR dest[64];
  203455. DWORD serialNum;
  203456. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203457. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203458. return 0;
  203459. return (int) serialNum;
  203460. }
  203461. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203462. {
  203463. ULARGE_INTEGER spc, tot, totFree;
  203464. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203465. return total ? (int64) tot.QuadPart
  203466. : (int64) spc.QuadPart;
  203467. return 0;
  203468. }
  203469. int64 File::getBytesFreeOnVolume() const
  203470. {
  203471. return getDiskSpaceInfo (getFullPathName(), false);
  203472. }
  203473. int64 File::getVolumeTotalSize() const
  203474. {
  203475. return getDiskSpaceInfo (getFullPathName(), true);
  203476. }
  203477. static unsigned int getWindowsDriveType (const String& path)
  203478. {
  203479. return GetDriveType (getDriveFromPath (path));
  203480. }
  203481. bool File::isOnCDRomDrive() const
  203482. {
  203483. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203484. }
  203485. bool File::isOnHardDisk() const
  203486. {
  203487. if (fullPath.isEmpty())
  203488. return false;
  203489. const unsigned int n = getWindowsDriveType (getFullPathName());
  203490. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203491. return n != DRIVE_REMOVABLE;
  203492. else
  203493. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203494. }
  203495. bool File::isOnRemovableDrive() const
  203496. {
  203497. if (fullPath.isEmpty())
  203498. return false;
  203499. const unsigned int n = getWindowsDriveType (getFullPathName());
  203500. return n == DRIVE_CDROM
  203501. || n == DRIVE_REMOTE
  203502. || n == DRIVE_REMOVABLE
  203503. || n == DRIVE_RAMDISK;
  203504. }
  203505. static const File juce_getSpecialFolderPath (int type)
  203506. {
  203507. WCHAR path [MAX_PATH + 256];
  203508. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203509. return File (String (path));
  203510. return File::nonexistent;
  203511. }
  203512. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203513. {
  203514. int csidlType = 0;
  203515. switch (type)
  203516. {
  203517. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203518. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203519. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203520. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203521. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203522. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203523. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203524. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203525. case tempDirectory:
  203526. {
  203527. WCHAR dest [2048];
  203528. dest[0] = 0;
  203529. GetTempPath (numElementsInArray (dest), dest);
  203530. return File (String (dest));
  203531. }
  203532. case invokedExecutableFile:
  203533. case currentExecutableFile:
  203534. case currentApplicationFile:
  203535. {
  203536. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203537. WCHAR dest [MAX_PATH + 256];
  203538. dest[0] = 0;
  203539. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203540. return File (String (dest));
  203541. }
  203542. break;
  203543. default:
  203544. jassertfalse; // unknown type?
  203545. return File::nonexistent;
  203546. }
  203547. return juce_getSpecialFolderPath (csidlType);
  203548. }
  203549. const File File::getCurrentWorkingDirectory()
  203550. {
  203551. WCHAR dest [MAX_PATH + 256];
  203552. dest[0] = 0;
  203553. GetCurrentDirectory (numElementsInArray (dest), dest);
  203554. return File (String (dest));
  203555. }
  203556. bool File::setAsCurrentWorkingDirectory() const
  203557. {
  203558. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203559. }
  203560. const String File::getVersion() const
  203561. {
  203562. String result;
  203563. DWORD handle = 0;
  203564. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203565. HeapBlock<char> buffer;
  203566. buffer.calloc (bufferSize);
  203567. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203568. {
  203569. VS_FIXEDFILEINFO* vffi;
  203570. UINT len = 0;
  203571. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203572. {
  203573. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203574. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203575. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203576. << (int) LOWORD (vffi->dwFileVersionLS);
  203577. }
  203578. }
  203579. return result;
  203580. }
  203581. const File File::getLinkedTarget() const
  203582. {
  203583. File result (*this);
  203584. String p (getFullPathName());
  203585. if (! exists())
  203586. p += ".lnk";
  203587. else if (getFileExtension() != ".lnk")
  203588. return result;
  203589. ComSmartPtr <IShellLink> shellLink;
  203590. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203591. {
  203592. ComSmartPtr <IPersistFile> persistFile;
  203593. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203594. {
  203595. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203596. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203597. {
  203598. WIN32_FIND_DATA winFindData;
  203599. WCHAR resolvedPath [MAX_PATH];
  203600. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203601. result = File (resolvedPath);
  203602. }
  203603. }
  203604. }
  203605. return result;
  203606. }
  203607. class DirectoryIterator::NativeIterator::Pimpl
  203608. {
  203609. public:
  203610. Pimpl (const File& directory, const String& wildCard)
  203611. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203612. handle (INVALID_HANDLE_VALUE)
  203613. {
  203614. }
  203615. ~Pimpl()
  203616. {
  203617. if (handle != INVALID_HANDLE_VALUE)
  203618. FindClose (handle);
  203619. }
  203620. bool next (String& filenameFound,
  203621. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203622. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203623. {
  203624. WIN32_FIND_DATA findData;
  203625. if (handle == INVALID_HANDLE_VALUE)
  203626. {
  203627. handle = FindFirstFile (directoryWithWildCard, &findData);
  203628. if (handle == INVALID_HANDLE_VALUE)
  203629. return false;
  203630. }
  203631. else
  203632. {
  203633. if (FindNextFile (handle, &findData) == 0)
  203634. return false;
  203635. }
  203636. filenameFound = findData.cFileName;
  203637. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203638. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203639. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203640. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203641. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203642. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203643. return true;
  203644. }
  203645. juce_UseDebuggingNewOperator
  203646. private:
  203647. const String directoryWithWildCard;
  203648. HANDLE handle;
  203649. Pimpl (const Pimpl&);
  203650. Pimpl& operator= (const Pimpl&);
  203651. };
  203652. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203653. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203654. {
  203655. }
  203656. DirectoryIterator::NativeIterator::~NativeIterator()
  203657. {
  203658. }
  203659. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203660. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203661. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203662. {
  203663. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203664. }
  203665. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203666. {
  203667. HINSTANCE hInstance = 0;
  203668. JUCE_TRY
  203669. {
  203670. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203671. }
  203672. JUCE_CATCH_ALL
  203673. return hInstance > (HINSTANCE) 32;
  203674. }
  203675. void File::revealToUser() const
  203676. {
  203677. if (isDirectory())
  203678. startAsProcess();
  203679. else if (getParentDirectory().exists())
  203680. getParentDirectory().startAsProcess();
  203681. }
  203682. class NamedPipeInternal
  203683. {
  203684. public:
  203685. NamedPipeInternal (const String& file, const bool isPipe_)
  203686. : pipeH (0),
  203687. cancelEvent (0),
  203688. connected (false),
  203689. isPipe (isPipe_)
  203690. {
  203691. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203692. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203693. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203694. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203695. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203696. }
  203697. ~NamedPipeInternal()
  203698. {
  203699. disconnectPipe();
  203700. if (pipeH != 0)
  203701. CloseHandle (pipeH);
  203702. CloseHandle (cancelEvent);
  203703. }
  203704. bool connect (const int timeOutMs)
  203705. {
  203706. if (! isPipe)
  203707. return true;
  203708. if (! connected)
  203709. {
  203710. OVERLAPPED over;
  203711. zerostruct (over);
  203712. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203713. if (ConnectNamedPipe (pipeH, &over))
  203714. {
  203715. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203716. }
  203717. else
  203718. {
  203719. const int err = GetLastError();
  203720. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203721. {
  203722. HANDLE handles[] = { over.hEvent, cancelEvent };
  203723. if (WaitForMultipleObjects (2, handles, FALSE,
  203724. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203725. connected = true;
  203726. }
  203727. else if (err == ERROR_PIPE_CONNECTED)
  203728. {
  203729. connected = true;
  203730. }
  203731. }
  203732. CloseHandle (over.hEvent);
  203733. }
  203734. return connected;
  203735. }
  203736. void disconnectPipe()
  203737. {
  203738. if (connected)
  203739. {
  203740. DisconnectNamedPipe (pipeH);
  203741. connected = false;
  203742. }
  203743. }
  203744. HANDLE pipeH;
  203745. HANDLE cancelEvent;
  203746. bool connected, isPipe;
  203747. };
  203748. void NamedPipe::close()
  203749. {
  203750. cancelPendingReads();
  203751. const ScopedLock sl (lock);
  203752. delete static_cast<NamedPipeInternal*> (internal);
  203753. internal = 0;
  203754. }
  203755. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203756. {
  203757. close();
  203758. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203759. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203760. {
  203761. internal = intern.release();
  203762. return true;
  203763. }
  203764. return false;
  203765. }
  203766. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203767. {
  203768. const ScopedLock sl (lock);
  203769. int bytesRead = -1;
  203770. bool waitAgain = true;
  203771. while (waitAgain && internal != 0)
  203772. {
  203773. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203774. waitAgain = false;
  203775. if (! intern->connect (timeOutMilliseconds))
  203776. break;
  203777. if (maxBytesToRead <= 0)
  203778. return 0;
  203779. OVERLAPPED over;
  203780. zerostruct (over);
  203781. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203782. unsigned long numRead;
  203783. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203784. {
  203785. bytesRead = (int) numRead;
  203786. }
  203787. else if (GetLastError() == ERROR_IO_PENDING)
  203788. {
  203789. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203790. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203791. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203792. : INFINITE);
  203793. if (waitResult != WAIT_OBJECT_0)
  203794. {
  203795. // if the operation timed out, let's cancel it...
  203796. CancelIo (intern->pipeH);
  203797. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203798. }
  203799. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203800. {
  203801. bytesRead = (int) numRead;
  203802. }
  203803. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203804. {
  203805. intern->disconnectPipe();
  203806. waitAgain = true;
  203807. }
  203808. }
  203809. else
  203810. {
  203811. waitAgain = internal != 0;
  203812. Sleep (5);
  203813. }
  203814. CloseHandle (over.hEvent);
  203815. }
  203816. return bytesRead;
  203817. }
  203818. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203819. {
  203820. int bytesWritten = -1;
  203821. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203822. if (intern != 0 && intern->connect (timeOutMilliseconds))
  203823. {
  203824. if (numBytesToWrite <= 0)
  203825. return 0;
  203826. OVERLAPPED over;
  203827. zerostruct (over);
  203828. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203829. unsigned long numWritten;
  203830. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  203831. {
  203832. bytesWritten = (int) numWritten;
  203833. }
  203834. else if (GetLastError() == ERROR_IO_PENDING)
  203835. {
  203836. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203837. DWORD waitResult;
  203838. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203839. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203840. : INFINITE);
  203841. if (waitResult != WAIT_OBJECT_0)
  203842. {
  203843. CancelIo (intern->pipeH);
  203844. WaitForSingleObject (over.hEvent, INFINITE);
  203845. }
  203846. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  203847. {
  203848. bytesWritten = (int) numWritten;
  203849. }
  203850. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203851. {
  203852. intern->disconnectPipe();
  203853. }
  203854. }
  203855. CloseHandle (over.hEvent);
  203856. }
  203857. return bytesWritten;
  203858. }
  203859. void NamedPipe::cancelPendingReads()
  203860. {
  203861. if (internal != 0)
  203862. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  203863. }
  203864. #endif
  203865. /*** End of inlined file: juce_win32_Files.cpp ***/
  203866. /*** Start of inlined file: juce_win32_Network.cpp ***/
  203867. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203868. // compiled on its own).
  203869. #if JUCE_INCLUDED_FILE
  203870. #ifndef INTERNET_FLAG_NEED_FILE
  203871. #define INTERNET_FLAG_NEED_FILE 0x00000010
  203872. #endif
  203873. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  203874. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  203875. #endif
  203876. struct ConnectionAndRequestStruct
  203877. {
  203878. HINTERNET connection, request;
  203879. };
  203880. static HINTERNET sessionHandle = 0;
  203881. #ifndef WORKAROUND_TIMEOUT_BUG
  203882. //#define WORKAROUND_TIMEOUT_BUG 1
  203883. #endif
  203884. #if WORKAROUND_TIMEOUT_BUG
  203885. // Required because of a Microsoft bug in setting a timeout
  203886. class InternetConnectThread : public Thread
  203887. {
  203888. public:
  203889. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  203890. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  203891. {
  203892. startThread();
  203893. }
  203894. ~InternetConnectThread()
  203895. {
  203896. stopThread (60000);
  203897. }
  203898. void run()
  203899. {
  203900. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  203901. uc.nPort, _T(""), _T(""),
  203902. isFtp ? INTERNET_SERVICE_FTP
  203903. : INTERNET_SERVICE_HTTP,
  203904. 0, 0);
  203905. notify();
  203906. }
  203907. juce_UseDebuggingNewOperator
  203908. private:
  203909. URL_COMPONENTS& uc;
  203910. HINTERNET& connection;
  203911. const bool isFtp;
  203912. InternetConnectThread (const InternetConnectThread&);
  203913. InternetConnectThread& operator= (const InternetConnectThread&);
  203914. };
  203915. #endif
  203916. void* juce_openInternetFile (const String& url,
  203917. const String& headers,
  203918. const MemoryBlock& postData,
  203919. const bool isPost,
  203920. URL::OpenStreamProgressCallback* callback,
  203921. void* callbackContext,
  203922. int timeOutMs)
  203923. {
  203924. if (sessionHandle == 0)
  203925. sessionHandle = InternetOpen (_T("juce"),
  203926. INTERNET_OPEN_TYPE_PRECONFIG,
  203927. 0, 0, 0);
  203928. if (sessionHandle != 0)
  203929. {
  203930. // break up the url..
  203931. TCHAR file[1024], server[1024];
  203932. URL_COMPONENTS uc;
  203933. zerostruct (uc);
  203934. uc.dwStructSize = sizeof (uc);
  203935. uc.dwUrlPathLength = sizeof (file);
  203936. uc.dwHostNameLength = sizeof (server);
  203937. uc.lpszUrlPath = file;
  203938. uc.lpszHostName = server;
  203939. if (InternetCrackUrl (url, 0, 0, &uc))
  203940. {
  203941. int disable = 1;
  203942. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  203943. if (timeOutMs == 0)
  203944. timeOutMs = 30000;
  203945. else if (timeOutMs < 0)
  203946. timeOutMs = -1;
  203947. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  203948. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  203949. #if WORKAROUND_TIMEOUT_BUG
  203950. HINTERNET connection = 0;
  203951. {
  203952. InternetConnectThread connectThread (uc, connection, isFtp);
  203953. connectThread.wait (timeOutMs);
  203954. if (connection == 0)
  203955. {
  203956. InternetCloseHandle (sessionHandle);
  203957. sessionHandle = 0;
  203958. }
  203959. }
  203960. #else
  203961. HINTERNET connection = InternetConnect (sessionHandle,
  203962. uc.lpszHostName,
  203963. uc.nPort,
  203964. _T(""), _T(""),
  203965. isFtp ? INTERNET_SERVICE_FTP
  203966. : INTERNET_SERVICE_HTTP,
  203967. 0, 0);
  203968. #endif
  203969. if (connection != 0)
  203970. {
  203971. if (isFtp)
  203972. {
  203973. HINTERNET request = FtpOpenFile (connection,
  203974. uc.lpszUrlPath,
  203975. GENERIC_READ,
  203976. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  203977. 0);
  203978. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  203979. result->connection = connection;
  203980. result->request = request;
  203981. return result;
  203982. }
  203983. else
  203984. {
  203985. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  203986. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  203987. if (url.startsWithIgnoreCase ("https:"))
  203988. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  203989. // IE7 seems to automatically work out when it's https)
  203990. HINTERNET request = HttpOpenRequest (connection,
  203991. isPost ? _T("POST")
  203992. : _T("GET"),
  203993. uc.lpszUrlPath,
  203994. 0, 0, mimeTypes, flags, 0);
  203995. if (request != 0)
  203996. {
  203997. INTERNET_BUFFERS buffers;
  203998. zerostruct (buffers);
  203999. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204000. buffers.lpcszHeader = (LPCTSTR) headers;
  204001. buffers.dwHeadersLength = headers.length();
  204002. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204003. ConnectionAndRequestStruct* result = 0;
  204004. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204005. {
  204006. int bytesSent = 0;
  204007. for (;;)
  204008. {
  204009. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204010. DWORD bytesDone = 0;
  204011. if (bytesToDo > 0
  204012. && ! InternetWriteFile (request,
  204013. static_cast <const char*> (postData.getData()) + bytesSent,
  204014. bytesToDo, &bytesDone))
  204015. {
  204016. break;
  204017. }
  204018. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204019. {
  204020. result = new ConnectionAndRequestStruct();
  204021. result->connection = connection;
  204022. result->request = request;
  204023. if (! HttpEndRequest (request, 0, 0, 0))
  204024. break;
  204025. return result;
  204026. }
  204027. bytesSent += bytesDone;
  204028. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204029. break;
  204030. }
  204031. }
  204032. InternetCloseHandle (request);
  204033. }
  204034. InternetCloseHandle (connection);
  204035. }
  204036. }
  204037. }
  204038. }
  204039. return 0;
  204040. }
  204041. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204042. {
  204043. DWORD bytesRead = 0;
  204044. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204045. if (crs != 0)
  204046. InternetReadFile (crs->request,
  204047. buffer, bytesToRead,
  204048. &bytesRead);
  204049. return bytesRead;
  204050. }
  204051. int juce_seekInInternetFile (void* handle, int newPosition)
  204052. {
  204053. if (handle != 0)
  204054. {
  204055. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204056. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204057. }
  204058. return -1;
  204059. }
  204060. int64 juce_getInternetFileContentLength (void* handle)
  204061. {
  204062. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204063. if (crs != 0)
  204064. {
  204065. DWORD index = 0, result = 0, size = sizeof (result);
  204066. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204067. return (int64) result;
  204068. }
  204069. return -1;
  204070. }
  204071. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204072. {
  204073. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204074. if (crs != 0)
  204075. {
  204076. DWORD bufferSizeBytes = 4096;
  204077. for (;;)
  204078. {
  204079. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204080. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204081. {
  204082. StringArray headersArray;
  204083. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204084. for (int i = 0; i < headersArray.size(); ++i)
  204085. {
  204086. const String& header = headersArray[i];
  204087. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204088. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204089. const String previousValue (headers [key]);
  204090. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204091. }
  204092. break;
  204093. }
  204094. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204095. break;
  204096. }
  204097. }
  204098. }
  204099. void juce_closeInternetFile (void* handle)
  204100. {
  204101. if (handle != 0)
  204102. {
  204103. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204104. InternetCloseHandle (crs->request);
  204105. InternetCloseHandle (crs->connection);
  204106. }
  204107. }
  204108. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204109. {
  204110. int numFound = 0;
  204111. DynamicLibraryLoader dll ("iphlpapi.dll");
  204112. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204113. if (getAdaptersInfo != 0)
  204114. {
  204115. ULONG len = sizeof (IP_ADAPTER_INFO);
  204116. MemoryBlock mb;
  204117. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204118. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204119. {
  204120. mb.setSize (len);
  204121. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204122. }
  204123. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204124. {
  204125. PIP_ADAPTER_INFO adapter = adapterInfo;
  204126. while (adapter != 0)
  204127. {
  204128. int64 mac = 0;
  204129. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204130. mac = (mac << 8) | adapter->Address[i];
  204131. if (littleEndian)
  204132. mac = (int64) ByteOrder::swap ((uint64) mac);
  204133. if (numFound < maxNum && mac != 0)
  204134. addresses [numFound++] = mac;
  204135. adapter = adapter->Next;
  204136. }
  204137. }
  204138. }
  204139. return numFound;
  204140. }
  204141. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204142. {
  204143. int numFound = 0;
  204144. DynamicLibraryLoader dll ("netapi32.dll");
  204145. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204146. if (NetbiosCall != 0)
  204147. {
  204148. NCB ncb;
  204149. zerostruct (ncb);
  204150. struct ASTAT
  204151. {
  204152. ADAPTER_STATUS adapt;
  204153. NAME_BUFFER NameBuff [30];
  204154. };
  204155. ASTAT astat;
  204156. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204157. LANA_ENUM enums;
  204158. zerostruct (enums);
  204159. ncb.ncb_command = NCBENUM;
  204160. ncb.ncb_buffer = (unsigned char*) &enums;
  204161. ncb.ncb_length = sizeof (LANA_ENUM);
  204162. NetbiosCall (&ncb);
  204163. for (int i = 0; i < enums.length; ++i)
  204164. {
  204165. zerostruct (ncb);
  204166. ncb.ncb_command = NCBRESET;
  204167. ncb.ncb_lana_num = enums.lana[i];
  204168. if (NetbiosCall (&ncb) == 0)
  204169. {
  204170. zerostruct (ncb);
  204171. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204172. ncb.ncb_command = NCBASTAT;
  204173. ncb.ncb_lana_num = enums.lana[i];
  204174. ncb.ncb_buffer = (unsigned char*) &astat;
  204175. ncb.ncb_length = sizeof (ASTAT);
  204176. if (NetbiosCall (&ncb) == 0)
  204177. {
  204178. if (astat.adapt.adapter_type == 0xfe)
  204179. {
  204180. uint64 mac = 0;
  204181. for (int i = 6; --i >= 0;)
  204182. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204183. if (numFound < maxNum && mac != 0)
  204184. addresses [numFound++] = mac;
  204185. }
  204186. }
  204187. }
  204188. }
  204189. }
  204190. return numFound;
  204191. }
  204192. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204193. {
  204194. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204195. if (numFound == 0)
  204196. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204197. return numFound;
  204198. }
  204199. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204200. const String& emailSubject,
  204201. const String& bodyText,
  204202. const StringArray& filesToAttach)
  204203. {
  204204. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204205. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204206. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204207. bool ok = false;
  204208. if (mapiSendMail != 0)
  204209. {
  204210. MapiMessage message;
  204211. zerostruct (message);
  204212. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204213. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204214. MapiRecipDesc recip;
  204215. zerostruct (recip);
  204216. recip.ulRecipClass = MAPI_TO;
  204217. String targetEmailAddress_ (targetEmailAddress);
  204218. if (targetEmailAddress_.isEmpty())
  204219. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204220. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204221. message.nRecipCount = 1;
  204222. message.lpRecips = &recip;
  204223. HeapBlock <MapiFileDesc> files;
  204224. files.calloc (filesToAttach.size());
  204225. message.nFileCount = filesToAttach.size();
  204226. message.lpFiles = files;
  204227. for (int i = 0; i < filesToAttach.size(); ++i)
  204228. {
  204229. files[i].nPosition = (ULONG) -1;
  204230. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204231. }
  204232. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204233. }
  204234. FreeLibrary (h);
  204235. return ok;
  204236. }
  204237. #endif
  204238. /*** End of inlined file: juce_win32_Network.cpp ***/
  204239. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204240. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204241. // compiled on its own).
  204242. #if JUCE_INCLUDED_FILE
  204243. static HKEY findKeyForPath (String name,
  204244. const bool createForWriting,
  204245. String& valueName)
  204246. {
  204247. HKEY rootKey = 0;
  204248. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204249. rootKey = HKEY_CURRENT_USER;
  204250. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204251. rootKey = HKEY_LOCAL_MACHINE;
  204252. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204253. rootKey = HKEY_CLASSES_ROOT;
  204254. if (rootKey != 0)
  204255. {
  204256. name = name.substring (name.indexOfChar ('\\') + 1);
  204257. const int lastSlash = name.lastIndexOfChar ('\\');
  204258. valueName = name.substring (lastSlash + 1);
  204259. name = name.substring (0, lastSlash);
  204260. HKEY key;
  204261. DWORD result;
  204262. if (createForWriting)
  204263. {
  204264. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204265. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204266. return key;
  204267. }
  204268. else
  204269. {
  204270. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204271. return key;
  204272. }
  204273. }
  204274. return 0;
  204275. }
  204276. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204277. const String& defaultValue)
  204278. {
  204279. String valueName, result (defaultValue);
  204280. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204281. if (k != 0)
  204282. {
  204283. WCHAR buffer [2048];
  204284. unsigned long bufferSize = sizeof (buffer);
  204285. DWORD type = REG_SZ;
  204286. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204287. {
  204288. if (type == REG_SZ)
  204289. result = buffer;
  204290. else if (type == REG_DWORD)
  204291. result = String ((int) *(DWORD*) buffer);
  204292. }
  204293. RegCloseKey (k);
  204294. }
  204295. return result;
  204296. }
  204297. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204298. const String& value)
  204299. {
  204300. String valueName;
  204301. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204302. if (k != 0)
  204303. {
  204304. RegSetValueEx (k, valueName, 0, REG_SZ,
  204305. (const BYTE*) (const WCHAR*) value,
  204306. sizeof (WCHAR) * (value.length() + 1));
  204307. RegCloseKey (k);
  204308. }
  204309. }
  204310. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204311. {
  204312. bool exists = false;
  204313. String valueName;
  204314. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204315. if (k != 0)
  204316. {
  204317. unsigned char buffer [2048];
  204318. unsigned long bufferSize = sizeof (buffer);
  204319. DWORD type = 0;
  204320. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204321. exists = true;
  204322. RegCloseKey (k);
  204323. }
  204324. return exists;
  204325. }
  204326. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204327. {
  204328. String valueName;
  204329. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204330. if (k != 0)
  204331. {
  204332. RegDeleteValue (k, valueName);
  204333. RegCloseKey (k);
  204334. }
  204335. }
  204336. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204337. {
  204338. String valueName;
  204339. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204340. if (k != 0)
  204341. {
  204342. RegDeleteKey (k, valueName);
  204343. RegCloseKey (k);
  204344. }
  204345. }
  204346. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204347. const String& symbolicDescription,
  204348. const String& fullDescription,
  204349. const File& targetExecutable,
  204350. int iconResourceNumber)
  204351. {
  204352. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204353. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204354. if (iconResourceNumber != 0)
  204355. setRegistryValue (key + "\\DefaultIcon\\",
  204356. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204357. setRegistryValue (key + "\\", fullDescription);
  204358. setRegistryValue (key + "\\shell\\open\\command\\",
  204359. targetExecutable.getFullPathName() + " %1");
  204360. }
  204361. bool juce_IsRunningInWine()
  204362. {
  204363. HKEY key;
  204364. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204365. {
  204366. RegCloseKey (key);
  204367. return true;
  204368. }
  204369. return false;
  204370. }
  204371. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204372. {
  204373. String s (::GetCommandLineW());
  204374. StringArray tokens;
  204375. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204376. return tokens.joinIntoString (" ", 1);
  204377. }
  204378. static void* currentModuleHandle = 0;
  204379. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204380. {
  204381. if (currentModuleHandle == 0)
  204382. currentModuleHandle = GetModuleHandle (0);
  204383. return currentModuleHandle;
  204384. }
  204385. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204386. {
  204387. currentModuleHandle = newHandle;
  204388. }
  204389. void PlatformUtilities::fpuReset()
  204390. {
  204391. #if JUCE_MSVC
  204392. _clearfp();
  204393. #endif
  204394. }
  204395. void PlatformUtilities::beep()
  204396. {
  204397. MessageBeep (MB_OK);
  204398. }
  204399. #endif
  204400. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204401. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204402. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204403. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204404. // compiled on its own).
  204405. #if JUCE_INCLUDED_FILE
  204406. static const unsigned int specialId = WM_APP + 0x4400;
  204407. static const unsigned int broadcastId = WM_APP + 0x4403;
  204408. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204409. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204410. HWND juce_messageWindowHandle = 0;
  204411. extern long improbableWindowNumber; // defined in windowing.cpp
  204412. #ifndef WM_APPCOMMAND
  204413. #define WM_APPCOMMAND 0x0319
  204414. #endif
  204415. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204416. const UINT message,
  204417. const WPARAM wParam,
  204418. const LPARAM lParam) throw()
  204419. {
  204420. JUCE_TRY
  204421. {
  204422. if (h == juce_messageWindowHandle)
  204423. {
  204424. if (message == specialCallbackId)
  204425. {
  204426. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204427. return (LRESULT) (*func) ((void*) lParam);
  204428. }
  204429. else if (message == specialId)
  204430. {
  204431. // these are trapped early in the dispatch call, but must also be checked
  204432. // here in case there are windows modal dialog boxes doing their own
  204433. // dispatch loop and not calling our version
  204434. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  204435. return 0;
  204436. }
  204437. else if (message == broadcastId)
  204438. {
  204439. const ScopedPointer <String> messageString ((String*) lParam);
  204440. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204441. return 0;
  204442. }
  204443. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204444. {
  204445. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204446. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204447. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204448. return 0;
  204449. }
  204450. }
  204451. }
  204452. JUCE_CATCH_EXCEPTION
  204453. return DefWindowProc (h, message, wParam, lParam);
  204454. }
  204455. static bool isEventBlockedByModalComps (MSG& m)
  204456. {
  204457. if (Component::getNumCurrentlyModalComponents() == 0
  204458. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204459. return false;
  204460. switch (m.message)
  204461. {
  204462. case WM_MOUSEMOVE:
  204463. case WM_NCMOUSEMOVE:
  204464. case 0x020A: /* WM_MOUSEWHEEL */
  204465. case 0x020E: /* WM_MOUSEHWHEEL */
  204466. case WM_KEYUP:
  204467. case WM_SYSKEYUP:
  204468. case WM_CHAR:
  204469. case WM_APPCOMMAND:
  204470. case WM_LBUTTONUP:
  204471. case WM_MBUTTONUP:
  204472. case WM_RBUTTONUP:
  204473. case WM_MOUSEACTIVATE:
  204474. case WM_NCMOUSEHOVER:
  204475. case WM_MOUSEHOVER:
  204476. return true;
  204477. case WM_NCLBUTTONDOWN:
  204478. case WM_NCLBUTTONDBLCLK:
  204479. case WM_NCRBUTTONDOWN:
  204480. case WM_NCRBUTTONDBLCLK:
  204481. case WM_NCMBUTTONDOWN:
  204482. case WM_NCMBUTTONDBLCLK:
  204483. case WM_LBUTTONDOWN:
  204484. case WM_LBUTTONDBLCLK:
  204485. case WM_MBUTTONDOWN:
  204486. case WM_MBUTTONDBLCLK:
  204487. case WM_RBUTTONDOWN:
  204488. case WM_RBUTTONDBLCLK:
  204489. case WM_KEYDOWN:
  204490. case WM_SYSKEYDOWN:
  204491. {
  204492. Component* const modal = Component::getCurrentlyModalComponent (0);
  204493. if (modal != 0)
  204494. modal->inputAttemptWhenModal();
  204495. return true;
  204496. }
  204497. default:
  204498. break;
  204499. }
  204500. return false;
  204501. }
  204502. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204503. {
  204504. MSG m;
  204505. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204506. return false;
  204507. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204508. {
  204509. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204510. {
  204511. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  204512. }
  204513. else if (m.message == WM_QUIT)
  204514. {
  204515. if (JUCEApplication::getInstance())
  204516. JUCEApplication::getInstance()->systemRequestedQuit();
  204517. }
  204518. else if (! isEventBlockedByModalComps (m))
  204519. {
  204520. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204521. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204522. {
  204523. // if it's someone else's window being clicked on, and the focus is
  204524. // currently on a juce window, pass the kb focus over..
  204525. HWND currentFocus = GetFocus();
  204526. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204527. SetFocus (m.hwnd);
  204528. }
  204529. TranslateMessage (&m);
  204530. DispatchMessage (&m);
  204531. }
  204532. }
  204533. return true;
  204534. }
  204535. bool juce_postMessageToSystemQueue (Message* message)
  204536. {
  204537. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204538. }
  204539. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204540. void* userData)
  204541. {
  204542. if (MessageManager::getInstance()->isThisTheMessageThread())
  204543. {
  204544. return (*callback) (userData);
  204545. }
  204546. else
  204547. {
  204548. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204549. // deadlock because the message manager is blocked from running, and can't
  204550. // call your function..
  204551. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204552. return (void*) SendMessage (juce_messageWindowHandle,
  204553. specialCallbackId,
  204554. (WPARAM) callback,
  204555. (LPARAM) userData);
  204556. }
  204557. }
  204558. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204559. {
  204560. if (hwnd != juce_messageWindowHandle)
  204561. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204562. return TRUE;
  204563. }
  204564. void MessageManager::broadcastMessage (const String& value) throw()
  204565. {
  204566. Array<void*> windows;
  204567. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204568. const String localCopy (value);
  204569. COPYDATASTRUCT data;
  204570. data.dwData = broadcastId;
  204571. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204572. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204573. for (int i = windows.size(); --i >= 0;)
  204574. {
  204575. HWND hwnd = (HWND) windows.getUnchecked(i);
  204576. TCHAR windowName [64]; // no need to read longer strings than this
  204577. GetWindowText (hwnd, windowName, 64);
  204578. windowName [63] = 0;
  204579. if (String (windowName) == messageWindowName)
  204580. {
  204581. DWORD_PTR result;
  204582. SendMessageTimeout (hwnd, WM_COPYDATA,
  204583. (WPARAM) juce_messageWindowHandle,
  204584. (LPARAM) &data,
  204585. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204586. 8000,
  204587. &result);
  204588. }
  204589. }
  204590. }
  204591. static const String getMessageWindowClassName()
  204592. {
  204593. // this name has to be different for each app/dll instance because otherwise
  204594. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204595. // window class).
  204596. static int number = 0;
  204597. if (number == 0)
  204598. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204599. return "JUCEcs_" + String (number);
  204600. }
  204601. void MessageManager::doPlatformSpecificInitialisation()
  204602. {
  204603. OleInitialize (0);
  204604. const String className (getMessageWindowClassName());
  204605. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204606. WNDCLASSEX wc;
  204607. zerostruct (wc);
  204608. wc.cbSize = sizeof (wc);
  204609. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204610. wc.cbWndExtra = 4;
  204611. wc.hInstance = hmod;
  204612. wc.lpszClassName = className;
  204613. RegisterClassEx (&wc);
  204614. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204615. messageWindowName,
  204616. 0, 0, 0, 0, 0, 0, 0,
  204617. hmod, 0);
  204618. }
  204619. void MessageManager::doPlatformSpecificShutdown()
  204620. {
  204621. DestroyWindow (juce_messageWindowHandle);
  204622. UnregisterClass (getMessageWindowClassName(), 0);
  204623. OleUninitialize();
  204624. }
  204625. #endif
  204626. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204627. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204628. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204629. // compiled on its own).
  204630. #if JUCE_INCLUDED_FILE
  204631. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204632. // these are in the windows SDK, but need to be repeated here for GCC..
  204633. #ifndef GET_APPCOMMAND_LPARAM
  204634. #define FAPPCOMMAND_MASK 0xF000
  204635. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204636. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204637. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204638. #define APPCOMMAND_MEDIA_STOP 13
  204639. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204640. #define WM_APPCOMMAND 0x0319
  204641. #endif
  204642. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204643. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204644. extern bool juce_IsRunningInWine();
  204645. #ifndef ULW_ALPHA
  204646. #define ULW_ALPHA 0x00000002
  204647. #endif
  204648. #ifndef AC_SRC_ALPHA
  204649. #define AC_SRC_ALPHA 0x01
  204650. #endif
  204651. static HPALETTE palette = 0;
  204652. static bool createPaletteIfNeeded = true;
  204653. static bool shouldDeactivateTitleBar = true;
  204654. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204655. #define WM_TRAYNOTIFY WM_USER + 100
  204656. using ::abs;
  204657. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204658. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204659. bool Desktop::canUseSemiTransparentWindows() throw()
  204660. {
  204661. if (updateLayeredWindow == 0)
  204662. {
  204663. if (! juce_IsRunningInWine())
  204664. {
  204665. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204666. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204667. }
  204668. }
  204669. return updateLayeredWindow != 0;
  204670. }
  204671. const int extendedKeyModifier = 0x10000;
  204672. const int KeyPress::spaceKey = VK_SPACE;
  204673. const int KeyPress::returnKey = VK_RETURN;
  204674. const int KeyPress::escapeKey = VK_ESCAPE;
  204675. const int KeyPress::backspaceKey = VK_BACK;
  204676. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204677. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204678. const int KeyPress::tabKey = VK_TAB;
  204679. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204680. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204681. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204682. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204683. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204684. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204685. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204686. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204687. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204688. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204689. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204690. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204691. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204692. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204693. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204694. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204695. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204696. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204697. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204698. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204699. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204700. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204701. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204702. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204703. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204704. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204705. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204706. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204707. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204708. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204709. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204710. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204711. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204712. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204713. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204714. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204715. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204716. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204717. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204718. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204719. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204720. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204721. const int KeyPress::playKey = 0x30000;
  204722. const int KeyPress::stopKey = 0x30001;
  204723. const int KeyPress::fastForwardKey = 0x30002;
  204724. const int KeyPress::rewindKey = 0x30003;
  204725. class WindowsBitmapImage : public Image::SharedImage
  204726. {
  204727. public:
  204728. HBITMAP hBitmap;
  204729. BITMAPV4HEADER bitmapInfo;
  204730. HDC hdc;
  204731. unsigned char* bitmapData;
  204732. WindowsBitmapImage (const Image::PixelFormat format_,
  204733. const int w, const int h, const bool clearImage)
  204734. : Image::SharedImage (format_, w, h)
  204735. {
  204736. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204737. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204738. zerostruct (bitmapInfo);
  204739. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204740. bitmapInfo.bV4Width = w;
  204741. bitmapInfo.bV4Height = h;
  204742. bitmapInfo.bV4Planes = 1;
  204743. bitmapInfo.bV4CSType = 1;
  204744. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204745. if (format_ == Image::ARGB)
  204746. {
  204747. bitmapInfo.bV4AlphaMask = 0xff000000;
  204748. bitmapInfo.bV4RedMask = 0xff0000;
  204749. bitmapInfo.bV4GreenMask = 0xff00;
  204750. bitmapInfo.bV4BlueMask = 0xff;
  204751. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204752. }
  204753. else
  204754. {
  204755. bitmapInfo.bV4V4Compression = BI_RGB;
  204756. }
  204757. lineStride = -((w * pixelStride + 3) & ~3);
  204758. HDC dc = GetDC (0);
  204759. hdc = CreateCompatibleDC (dc);
  204760. ReleaseDC (0, dc);
  204761. SetMapMode (hdc, MM_TEXT);
  204762. hBitmap = CreateDIBSection (hdc,
  204763. (BITMAPINFO*) &(bitmapInfo),
  204764. DIB_RGB_COLORS,
  204765. (void**) &bitmapData,
  204766. 0, 0);
  204767. SelectObject (hdc, hBitmap);
  204768. if (format_ == Image::ARGB && clearImage)
  204769. zeromem (bitmapData, abs (h * lineStride));
  204770. imageData = bitmapData - (lineStride * (h - 1));
  204771. }
  204772. ~WindowsBitmapImage()
  204773. {
  204774. DeleteDC (hdc);
  204775. DeleteObject (hBitmap);
  204776. }
  204777. Image::ImageType getType() const { return Image::NativeImage; }
  204778. LowLevelGraphicsContext* createLowLevelContext()
  204779. {
  204780. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204781. }
  204782. SharedImage* clone()
  204783. {
  204784. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204785. for (int i = 0; i < height; ++i)
  204786. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204787. return im;
  204788. }
  204789. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204790. const int x, const int y,
  204791. const RectangleList& maskedRegion) throw()
  204792. {
  204793. static HDRAWDIB hdd = 0;
  204794. static bool needToCreateDrawDib = true;
  204795. if (needToCreateDrawDib)
  204796. {
  204797. needToCreateDrawDib = false;
  204798. HDC dc = GetDC (0);
  204799. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204800. ReleaseDC (0, dc);
  204801. // only open if we're not palettised
  204802. if (n > 8)
  204803. hdd = DrawDibOpen();
  204804. }
  204805. if (createPaletteIfNeeded)
  204806. {
  204807. HDC dc = GetDC (0);
  204808. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204809. ReleaseDC (0, dc);
  204810. if (n <= 8)
  204811. palette = CreateHalftonePalette (dc);
  204812. createPaletteIfNeeded = false;
  204813. }
  204814. if (palette != 0)
  204815. {
  204816. SelectPalette (dc, palette, FALSE);
  204817. RealizePalette (dc);
  204818. SetStretchBltMode (dc, HALFTONE);
  204819. }
  204820. SetMapMode (dc, MM_TEXT);
  204821. if (transparent)
  204822. {
  204823. POINT p, pos;
  204824. SIZE size;
  204825. RECT windowBounds;
  204826. GetWindowRect (hwnd, &windowBounds);
  204827. p.x = -x;
  204828. p.y = -y;
  204829. pos.x = windowBounds.left;
  204830. pos.y = windowBounds.top;
  204831. size.cx = windowBounds.right - windowBounds.left;
  204832. size.cy = windowBounds.bottom - windowBounds.top;
  204833. BLENDFUNCTION bf;
  204834. bf.AlphaFormat = AC_SRC_ALPHA;
  204835. bf.BlendFlags = 0;
  204836. bf.BlendOp = AC_SRC_OVER;
  204837. bf.SourceConstantAlpha = 0xff;
  204838. if (! maskedRegion.isEmpty())
  204839. {
  204840. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204841. {
  204842. const Rectangle<int>& r = *i.getRectangle();
  204843. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204844. }
  204845. }
  204846. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  204847. }
  204848. else
  204849. {
  204850. int savedDC = 0;
  204851. if (! maskedRegion.isEmpty())
  204852. {
  204853. savedDC = SaveDC (dc);
  204854. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204855. {
  204856. const Rectangle<int>& r = *i.getRectangle();
  204857. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204858. }
  204859. }
  204860. if (hdd == 0)
  204861. {
  204862. StretchDIBits (dc,
  204863. x, y, width, height,
  204864. 0, 0, width, height,
  204865. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  204866. DIB_RGB_COLORS, SRCCOPY);
  204867. }
  204868. else
  204869. {
  204870. DrawDibDraw (hdd, dc, x, y, -1, -1,
  204871. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  204872. 0, 0, width, height, 0);
  204873. }
  204874. if (! maskedRegion.isEmpty())
  204875. RestoreDC (dc, savedDC);
  204876. }
  204877. }
  204878. juce_UseDebuggingNewOperator
  204879. private:
  204880. WindowsBitmapImage (const WindowsBitmapImage&);
  204881. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  204882. };
  204883. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  204884. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  204885. {
  204886. SHORT k = (SHORT) keyCode;
  204887. if ((keyCode & extendedKeyModifier) == 0
  204888. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  204889. k += (SHORT) 'A' - (SHORT) 'a';
  204890. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  204891. (SHORT) '+', VK_OEM_PLUS,
  204892. (SHORT) '-', VK_OEM_MINUS,
  204893. (SHORT) '.', VK_OEM_PERIOD,
  204894. (SHORT) ';', VK_OEM_1,
  204895. (SHORT) ':', VK_OEM_1,
  204896. (SHORT) '/', VK_OEM_2,
  204897. (SHORT) '?', VK_OEM_2,
  204898. (SHORT) '[', VK_OEM_4,
  204899. (SHORT) ']', VK_OEM_6 };
  204900. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  204901. if (k == translatedValues [i])
  204902. k = translatedValues [i + 1];
  204903. return (GetKeyState (k) & 0x8000) != 0;
  204904. }
  204905. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  204906. {
  204907. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  204908. return callback (userData);
  204909. else
  204910. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  204911. }
  204912. class Win32ComponentPeer : public ComponentPeer
  204913. {
  204914. public:
  204915. Win32ComponentPeer (Component* const component,
  204916. const int windowStyleFlags)
  204917. : ComponentPeer (component, windowStyleFlags),
  204918. dontRepaint (false),
  204919. fullScreen (false),
  204920. isDragging (false),
  204921. isMouseOver (false),
  204922. hasCreatedCaret (false),
  204923. currentWindowIcon (0),
  204924. taskBarIcon (0),
  204925. dropTarget (0)
  204926. {
  204927. callFunctionIfNotLocked (&createWindowCallback, this);
  204928. setTitle (component->getName());
  204929. if ((windowStyleFlags & windowHasDropShadow) != 0
  204930. && Desktop::canUseSemiTransparentWindows())
  204931. {
  204932. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  204933. if (shadower != 0)
  204934. shadower->setOwner (component);
  204935. }
  204936. else
  204937. {
  204938. shadower = 0;
  204939. }
  204940. }
  204941. ~Win32ComponentPeer()
  204942. {
  204943. setTaskBarIcon (Image());
  204944. deleteAndZero (shadower);
  204945. // do this before the next bit to avoid messages arriving for this window
  204946. // before it's destroyed
  204947. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  204948. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  204949. if (currentWindowIcon != 0)
  204950. DestroyIcon (currentWindowIcon);
  204951. if (dropTarget != 0)
  204952. {
  204953. dropTarget->Release();
  204954. dropTarget = 0;
  204955. }
  204956. }
  204957. void* getNativeHandle() const
  204958. {
  204959. return hwnd;
  204960. }
  204961. void setVisible (bool shouldBeVisible)
  204962. {
  204963. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204964. if (shouldBeVisible)
  204965. InvalidateRect (hwnd, 0, 0);
  204966. else
  204967. lastPaintTime = 0;
  204968. }
  204969. void setTitle (const String& title)
  204970. {
  204971. SetWindowText (hwnd, title);
  204972. }
  204973. void setPosition (int x, int y)
  204974. {
  204975. offsetWithinParent (x, y);
  204976. SetWindowPos (hwnd, 0,
  204977. x - windowBorder.getLeft(),
  204978. y - windowBorder.getTop(),
  204979. 0, 0,
  204980. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204981. }
  204982. void repaintNowIfTransparent()
  204983. {
  204984. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  204985. handlePaintMessage();
  204986. }
  204987. void updateBorderSize()
  204988. {
  204989. WINDOWINFO info;
  204990. info.cbSize = sizeof (info);
  204991. if (GetWindowInfo (hwnd, &info))
  204992. {
  204993. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  204994. info.rcClient.left - info.rcWindow.left,
  204995. info.rcWindow.bottom - info.rcClient.bottom,
  204996. info.rcWindow.right - info.rcClient.right);
  204997. }
  204998. }
  204999. void setSize (int w, int h)
  205000. {
  205001. SetWindowPos (hwnd, 0, 0, 0,
  205002. w + windowBorder.getLeftAndRight(),
  205003. h + windowBorder.getTopAndBottom(),
  205004. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205005. updateBorderSize();
  205006. repaintNowIfTransparent();
  205007. }
  205008. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  205009. {
  205010. fullScreen = isNowFullScreen;
  205011. offsetWithinParent (x, y);
  205012. SetWindowPos (hwnd, 0,
  205013. x - windowBorder.getLeft(),
  205014. y - windowBorder.getTop(),
  205015. w + windowBorder.getLeftAndRight(),
  205016. h + windowBorder.getTopAndBottom(),
  205017. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205018. updateBorderSize();
  205019. repaintNowIfTransparent();
  205020. }
  205021. const Rectangle<int> getBounds() const
  205022. {
  205023. RECT r;
  205024. GetWindowRect (hwnd, &r);
  205025. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  205026. HWND parentH = GetParent (hwnd);
  205027. if (parentH != 0)
  205028. {
  205029. GetWindowRect (parentH, &r);
  205030. bounds.translate (-r.left, -r.top);
  205031. }
  205032. return windowBorder.subtractedFrom (bounds);
  205033. }
  205034. const Point<int> getScreenPosition() const
  205035. {
  205036. RECT r;
  205037. GetWindowRect (hwnd, &r);
  205038. return Point<int> (r.left + windowBorder.getLeft(),
  205039. r.top + windowBorder.getTop());
  205040. }
  205041. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  205042. {
  205043. return relativePosition + getScreenPosition();
  205044. }
  205045. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  205046. {
  205047. return screenPosition - getScreenPosition();
  205048. }
  205049. void setMinimised (bool shouldBeMinimised)
  205050. {
  205051. if (shouldBeMinimised != isMinimised())
  205052. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205053. }
  205054. bool isMinimised() const
  205055. {
  205056. WINDOWPLACEMENT wp;
  205057. wp.length = sizeof (WINDOWPLACEMENT);
  205058. GetWindowPlacement (hwnd, &wp);
  205059. return wp.showCmd == SW_SHOWMINIMIZED;
  205060. }
  205061. void setFullScreen (bool shouldBeFullScreen)
  205062. {
  205063. setMinimised (false);
  205064. if (fullScreen != shouldBeFullScreen)
  205065. {
  205066. fullScreen = shouldBeFullScreen;
  205067. const Component::SafePointer<Component> deletionChecker (component);
  205068. if (! fullScreen)
  205069. {
  205070. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  205071. if (hasTitleBar())
  205072. ShowWindow (hwnd, SW_SHOWNORMAL);
  205073. if (! boundsCopy.isEmpty())
  205074. {
  205075. setBounds (boundsCopy.getX(),
  205076. boundsCopy.getY(),
  205077. boundsCopy.getWidth(),
  205078. boundsCopy.getHeight(),
  205079. false);
  205080. }
  205081. }
  205082. else
  205083. {
  205084. if (hasTitleBar())
  205085. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  205086. else
  205087. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  205088. }
  205089. if (deletionChecker != 0)
  205090. handleMovedOrResized();
  205091. }
  205092. }
  205093. bool isFullScreen() const
  205094. {
  205095. if (! hasTitleBar())
  205096. return fullScreen;
  205097. WINDOWPLACEMENT wp;
  205098. wp.length = sizeof (wp);
  205099. GetWindowPlacement (hwnd, &wp);
  205100. return wp.showCmd == SW_SHOWMAXIMIZED;
  205101. }
  205102. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  205103. {
  205104. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  205105. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  205106. return false;
  205107. RECT r;
  205108. GetWindowRect (hwnd, &r);
  205109. POINT p;
  205110. p.x = position.getX() + r.left + windowBorder.getLeft();
  205111. p.y = position.getY() + r.top + windowBorder.getTop();
  205112. HWND w = WindowFromPoint (p);
  205113. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  205114. }
  205115. const BorderSize getFrameSize() const
  205116. {
  205117. return windowBorder;
  205118. }
  205119. bool setAlwaysOnTop (bool alwaysOnTop)
  205120. {
  205121. const bool oldDeactivate = shouldDeactivateTitleBar;
  205122. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205123. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  205124. 0, 0, 0, 0,
  205125. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205126. shouldDeactivateTitleBar = oldDeactivate;
  205127. if (shadower != 0)
  205128. shadower->componentBroughtToFront (*component);
  205129. return true;
  205130. }
  205131. void toFront (bool makeActive)
  205132. {
  205133. setMinimised (false);
  205134. const bool oldDeactivate = shouldDeactivateTitleBar;
  205135. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205136. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  205137. shouldDeactivateTitleBar = oldDeactivate;
  205138. if (! makeActive)
  205139. {
  205140. // in this case a broughttofront call won't have occured, so do it now..
  205141. handleBroughtToFront();
  205142. }
  205143. }
  205144. void toBehind (ComponentPeer* other)
  205145. {
  205146. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205147. jassert (otherPeer != 0); // wrong type of window?
  205148. if (otherPeer != 0)
  205149. {
  205150. setMinimised (false);
  205151. // must be careful not to try to put a topmost window behind a normal one, or win32
  205152. // promotes the normal one to be topmost!
  205153. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  205154. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205155. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205156. else if (otherPeer->getComponent()->isAlwaysOnTop())
  205157. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  205158. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205159. }
  205160. }
  205161. bool isFocused() const
  205162. {
  205163. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  205164. }
  205165. void grabFocus()
  205166. {
  205167. const bool oldDeactivate = shouldDeactivateTitleBar;
  205168. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205169. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  205170. shouldDeactivateTitleBar = oldDeactivate;
  205171. }
  205172. void textInputRequired (const Point<int>&)
  205173. {
  205174. if (! hasCreatedCaret)
  205175. {
  205176. hasCreatedCaret = true;
  205177. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  205178. }
  205179. ShowCaret (hwnd);
  205180. SetCaretPos (0, 0);
  205181. }
  205182. void repaint (const Rectangle<int>& area)
  205183. {
  205184. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  205185. InvalidateRect (hwnd, &r, FALSE);
  205186. }
  205187. void performAnyPendingRepaintsNow()
  205188. {
  205189. MSG m;
  205190. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205191. DispatchMessage (&m);
  205192. }
  205193. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205194. {
  205195. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205196. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  205197. return 0;
  205198. }
  205199. void setTaskBarIcon (const Image& image)
  205200. {
  205201. if (image.isValid())
  205202. {
  205203. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  205204. if (taskBarIcon == 0)
  205205. {
  205206. taskBarIcon = new NOTIFYICONDATA();
  205207. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205208. taskBarIcon->hWnd = (HWND) hwnd;
  205209. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205210. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205211. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205212. taskBarIcon->hIcon = hicon;
  205213. taskBarIcon->szTip[0] = 0;
  205214. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205215. }
  205216. else
  205217. {
  205218. HICON oldIcon = taskBarIcon->hIcon;
  205219. taskBarIcon->hIcon = hicon;
  205220. taskBarIcon->uFlags = NIF_ICON;
  205221. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205222. DestroyIcon (oldIcon);
  205223. }
  205224. DestroyIcon (hicon);
  205225. }
  205226. else if (taskBarIcon != 0)
  205227. {
  205228. taskBarIcon->uFlags = 0;
  205229. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205230. DestroyIcon (taskBarIcon->hIcon);
  205231. deleteAndZero (taskBarIcon);
  205232. }
  205233. }
  205234. void setTaskBarIconToolTip (const String& toolTip) const
  205235. {
  205236. if (taskBarIcon != 0)
  205237. {
  205238. taskBarIcon->uFlags = NIF_TIP;
  205239. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205240. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205241. }
  205242. }
  205243. bool isInside (HWND h) const
  205244. {
  205245. return GetAncestor (hwnd, GA_ROOT) == h;
  205246. }
  205247. static void updateKeyModifiers() throw()
  205248. {
  205249. int keyMods = 0;
  205250. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  205251. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  205252. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  205253. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205254. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205255. }
  205256. static void updateModifiersFromWParam (const WPARAM wParam)
  205257. {
  205258. int mouseMods = 0;
  205259. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  205260. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  205261. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  205262. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  205263. updateKeyModifiers();
  205264. }
  205265. static int64 getMouseEventTime()
  205266. {
  205267. static int64 eventTimeOffset = 0;
  205268. static DWORD lastMessageTime = 0;
  205269. const DWORD thisMessageTime = GetMessageTime();
  205270. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205271. {
  205272. lastMessageTime = thisMessageTime;
  205273. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205274. }
  205275. return eventTimeOffset + thisMessageTime;
  205276. }
  205277. juce_UseDebuggingNewOperator
  205278. bool dontRepaint;
  205279. static ModifierKeys currentModifiers;
  205280. static ModifierKeys modifiersAtLastCallback;
  205281. private:
  205282. HWND hwnd;
  205283. DropShadower* shadower;
  205284. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205285. BorderSize windowBorder;
  205286. HICON currentWindowIcon;
  205287. NOTIFYICONDATA* taskBarIcon;
  205288. IDropTarget* dropTarget;
  205289. class TemporaryImage : public Timer
  205290. {
  205291. public:
  205292. TemporaryImage() {}
  205293. ~TemporaryImage() {}
  205294. const Image& getImage (const bool transparent, const int w, const int h)
  205295. {
  205296. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205297. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205298. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205299. startTimer (3000);
  205300. return image;
  205301. }
  205302. void timerCallback()
  205303. {
  205304. stopTimer();
  205305. image = Image();
  205306. }
  205307. private:
  205308. Image image;
  205309. TemporaryImage (const TemporaryImage&);
  205310. TemporaryImage& operator= (const TemporaryImage&);
  205311. };
  205312. TemporaryImage offscreenImageGenerator;
  205313. class WindowClassHolder : public DeletedAtShutdown
  205314. {
  205315. public:
  205316. WindowClassHolder()
  205317. : windowClassName ("JUCE_")
  205318. {
  205319. // this name has to be different for each app/dll instance because otherwise
  205320. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205321. // window class).
  205322. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205323. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205324. TCHAR moduleFile [1024];
  205325. moduleFile[0] = 0;
  205326. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205327. WORD iconNum = 0;
  205328. WNDCLASSEX wcex;
  205329. wcex.cbSize = sizeof (wcex);
  205330. wcex.style = CS_OWNDC;
  205331. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205332. wcex.lpszClassName = windowClassName;
  205333. wcex.cbClsExtra = 0;
  205334. wcex.cbWndExtra = 32;
  205335. wcex.hInstance = moduleHandle;
  205336. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205337. iconNum = 1;
  205338. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205339. wcex.hCursor = 0;
  205340. wcex.hbrBackground = 0;
  205341. wcex.lpszMenuName = 0;
  205342. RegisterClassEx (&wcex);
  205343. }
  205344. ~WindowClassHolder()
  205345. {
  205346. if (ComponentPeer::getNumPeers() == 0)
  205347. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205348. clearSingletonInstance();
  205349. }
  205350. String windowClassName;
  205351. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205352. };
  205353. static void* createWindowCallback (void* userData)
  205354. {
  205355. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205356. return 0;
  205357. }
  205358. void createWindow()
  205359. {
  205360. DWORD exstyle = WS_EX_ACCEPTFILES;
  205361. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205362. if (hasTitleBar())
  205363. {
  205364. type |= WS_OVERLAPPED;
  205365. if ((styleFlags & windowHasCloseButton) != 0)
  205366. {
  205367. type |= WS_SYSMENU;
  205368. }
  205369. else
  205370. {
  205371. // annoyingly, windows won't let you have a min/max button without a close button
  205372. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205373. }
  205374. if ((styleFlags & windowIsResizable) != 0)
  205375. type |= WS_THICKFRAME;
  205376. }
  205377. else
  205378. {
  205379. type |= WS_POPUP | WS_SYSMENU;
  205380. }
  205381. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205382. exstyle |= WS_EX_TOOLWINDOW;
  205383. else
  205384. exstyle |= WS_EX_APPWINDOW;
  205385. if ((styleFlags & windowHasMinimiseButton) != 0)
  205386. type |= WS_MINIMIZEBOX;
  205387. if ((styleFlags & windowHasMaximiseButton) != 0)
  205388. type |= WS_MAXIMIZEBOX;
  205389. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205390. exstyle |= WS_EX_TRANSPARENT;
  205391. if ((styleFlags & windowIsSemiTransparent) != 0
  205392. && Desktop::canUseSemiTransparentWindows())
  205393. exstyle |= WS_EX_LAYERED;
  205394. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205395. if (hwnd != 0)
  205396. {
  205397. SetWindowLongPtr (hwnd, 0, 0);
  205398. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205399. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205400. if (dropTarget == 0)
  205401. dropTarget = new JuceDropTarget (this);
  205402. RegisterDragDrop (hwnd, dropTarget);
  205403. updateBorderSize();
  205404. // Calling this function here is (for some reason) necessary to make Windows
  205405. // correctly enable the menu items that we specify in the wm_initmenu message.
  205406. GetSystemMenu (hwnd, false);
  205407. }
  205408. else
  205409. {
  205410. jassertfalse;
  205411. }
  205412. }
  205413. static void* destroyWindowCallback (void* handle)
  205414. {
  205415. RevokeDragDrop ((HWND) handle);
  205416. DestroyWindow ((HWND) handle);
  205417. return 0;
  205418. }
  205419. static void* toFrontCallback1 (void* h)
  205420. {
  205421. SetForegroundWindow ((HWND) h);
  205422. return 0;
  205423. }
  205424. static void* toFrontCallback2 (void* h)
  205425. {
  205426. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205427. return 0;
  205428. }
  205429. static void* setFocusCallback (void* h)
  205430. {
  205431. SetFocus ((HWND) h);
  205432. return 0;
  205433. }
  205434. static void* getFocusCallback (void*)
  205435. {
  205436. return GetFocus();
  205437. }
  205438. void offsetWithinParent (int& x, int& y) const
  205439. {
  205440. if (isTransparent())
  205441. {
  205442. HWND parentHwnd = GetParent (hwnd);
  205443. if (parentHwnd != 0)
  205444. {
  205445. RECT parentRect;
  205446. GetWindowRect (parentHwnd, &parentRect);
  205447. x += parentRect.left;
  205448. y += parentRect.top;
  205449. }
  205450. }
  205451. }
  205452. bool isTransparent() const
  205453. {
  205454. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205455. }
  205456. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205457. void setIcon (const Image& newIcon)
  205458. {
  205459. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205460. if (hicon != 0)
  205461. {
  205462. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205463. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205464. if (currentWindowIcon != 0)
  205465. DestroyIcon (currentWindowIcon);
  205466. currentWindowIcon = hicon;
  205467. }
  205468. }
  205469. void handlePaintMessage()
  205470. {
  205471. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205472. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205473. PAINTSTRUCT paintStruct;
  205474. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205475. // message and become re-entrant, but that's OK
  205476. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205477. // corrupt the image it's using to paint into, so do a check here.
  205478. static bool reentrant = false;
  205479. if (reentrant)
  205480. {
  205481. DeleteObject (rgn);
  205482. EndPaint (hwnd, &paintStruct);
  205483. return;
  205484. }
  205485. reentrant = true;
  205486. // this is the rectangle to update..
  205487. int x = paintStruct.rcPaint.left;
  205488. int y = paintStruct.rcPaint.top;
  205489. int w = paintStruct.rcPaint.right - x;
  205490. int h = paintStruct.rcPaint.bottom - y;
  205491. const bool transparent = isTransparent();
  205492. if (transparent)
  205493. {
  205494. // it's not possible to have a transparent window with a title bar at the moment!
  205495. jassert (! hasTitleBar());
  205496. RECT r;
  205497. GetWindowRect (hwnd, &r);
  205498. x = y = 0;
  205499. w = r.right - r.left;
  205500. h = r.bottom - r.top;
  205501. }
  205502. if (w > 0 && h > 0)
  205503. {
  205504. clearMaskedRegion();
  205505. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205506. RectangleList contextClip;
  205507. const Rectangle<int> clipBounds (0, 0, w, h);
  205508. bool needToPaintAll = true;
  205509. if (regionType == COMPLEXREGION && ! transparent)
  205510. {
  205511. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205512. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205513. DeleteObject (clipRgn);
  205514. char rgnData [8192];
  205515. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205516. if (res > 0 && res <= sizeof (rgnData))
  205517. {
  205518. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205519. if (hdr->iType == RDH_RECTANGLES
  205520. && hdr->rcBound.right - hdr->rcBound.left >= w
  205521. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205522. {
  205523. needToPaintAll = false;
  205524. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205525. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205526. while (--num >= 0)
  205527. {
  205528. if (rects->right <= x + w && rects->bottom <= y + h)
  205529. {
  205530. // (need to move this one pixel to the left because of a win32 bug)
  205531. const int cx = jmax (x, (int) rects->left - 1);
  205532. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205533. .getIntersection (clipBounds));
  205534. }
  205535. else
  205536. {
  205537. needToPaintAll = true;
  205538. break;
  205539. }
  205540. ++rects;
  205541. }
  205542. }
  205543. }
  205544. }
  205545. if (needToPaintAll)
  205546. {
  205547. contextClip.clear();
  205548. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  205549. }
  205550. if (transparent)
  205551. {
  205552. RectangleList::Iterator i (contextClip);
  205553. while (i.next())
  205554. offscreenImage.clear (*i.getRectangle());
  205555. }
  205556. // if the component's not opaque, this won't draw properly unless the platform can support this
  205557. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205558. updateCurrentModifiers();
  205559. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205560. handlePaint (context);
  205561. if (! dontRepaint)
  205562. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205563. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205564. }
  205565. DeleteObject (rgn);
  205566. EndPaint (hwnd, &paintStruct);
  205567. reentrant = false;
  205568. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205569. _fpreset(); // because some graphics cards can unmask FP exceptions
  205570. #endif
  205571. lastPaintTime = Time::getMillisecondCounter();
  205572. }
  205573. void doMouseEvent (const Point<int>& position)
  205574. {
  205575. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205576. }
  205577. void doMouseMove (const Point<int>& position)
  205578. {
  205579. if (! isMouseOver)
  205580. {
  205581. isMouseOver = true;
  205582. updateKeyModifiers();
  205583. TRACKMOUSEEVENT tme;
  205584. tme.cbSize = sizeof (tme);
  205585. tme.dwFlags = TME_LEAVE;
  205586. tme.hwndTrack = hwnd;
  205587. tme.dwHoverTime = 0;
  205588. if (! TrackMouseEvent (&tme))
  205589. jassertfalse;
  205590. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205591. }
  205592. else if (! isDragging)
  205593. {
  205594. if (! contains (position, false))
  205595. return;
  205596. }
  205597. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205598. static uint32 lastMouseTime = 0;
  205599. const uint32 now = Time::getMillisecondCounter();
  205600. const int maxMouseMovesPerSecond = 60;
  205601. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205602. {
  205603. lastMouseTime = now;
  205604. doMouseEvent (position);
  205605. }
  205606. }
  205607. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205608. {
  205609. if (GetCapture() != hwnd)
  205610. SetCapture (hwnd);
  205611. doMouseMove (position);
  205612. updateModifiersFromWParam (wParam);
  205613. isDragging = true;
  205614. doMouseEvent (position);
  205615. }
  205616. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205617. {
  205618. updateModifiersFromWParam (wParam);
  205619. isDragging = false;
  205620. // release the mouse capture if the user has released all buttons
  205621. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205622. ReleaseCapture();
  205623. doMouseEvent (position);
  205624. }
  205625. void doCaptureChanged()
  205626. {
  205627. if (isDragging)
  205628. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205629. }
  205630. void doMouseExit()
  205631. {
  205632. isMouseOver = false;
  205633. doMouseEvent (getCurrentMousePos());
  205634. }
  205635. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205636. {
  205637. updateKeyModifiers();
  205638. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205639. handleMouseWheel (0, position, getMouseEventTime(),
  205640. isVertical ? 0.0f : amount,
  205641. isVertical ? amount : 0.0f);
  205642. }
  205643. void sendModifierKeyChangeIfNeeded()
  205644. {
  205645. if (modifiersAtLastCallback != currentModifiers)
  205646. {
  205647. modifiersAtLastCallback = currentModifiers;
  205648. handleModifierKeysChange();
  205649. }
  205650. }
  205651. bool doKeyUp (const WPARAM key)
  205652. {
  205653. updateKeyModifiers();
  205654. switch (key)
  205655. {
  205656. case VK_SHIFT:
  205657. case VK_CONTROL:
  205658. case VK_MENU:
  205659. case VK_CAPITAL:
  205660. case VK_LWIN:
  205661. case VK_RWIN:
  205662. case VK_APPS:
  205663. case VK_NUMLOCK:
  205664. case VK_SCROLL:
  205665. case VK_LSHIFT:
  205666. case VK_RSHIFT:
  205667. case VK_LCONTROL:
  205668. case VK_LMENU:
  205669. case VK_RCONTROL:
  205670. case VK_RMENU:
  205671. sendModifierKeyChangeIfNeeded();
  205672. }
  205673. return handleKeyUpOrDown (false)
  205674. || Component::getCurrentlyModalComponent() != 0;
  205675. }
  205676. bool doKeyDown (const WPARAM key)
  205677. {
  205678. updateKeyModifiers();
  205679. bool used = false;
  205680. switch (key)
  205681. {
  205682. case VK_SHIFT:
  205683. case VK_LSHIFT:
  205684. case VK_RSHIFT:
  205685. case VK_CONTROL:
  205686. case VK_LCONTROL:
  205687. case VK_RCONTROL:
  205688. case VK_MENU:
  205689. case VK_LMENU:
  205690. case VK_RMENU:
  205691. case VK_LWIN:
  205692. case VK_RWIN:
  205693. case VK_CAPITAL:
  205694. case VK_NUMLOCK:
  205695. case VK_SCROLL:
  205696. case VK_APPS:
  205697. sendModifierKeyChangeIfNeeded();
  205698. break;
  205699. case VK_LEFT:
  205700. case VK_RIGHT:
  205701. case VK_UP:
  205702. case VK_DOWN:
  205703. case VK_PRIOR:
  205704. case VK_NEXT:
  205705. case VK_HOME:
  205706. case VK_END:
  205707. case VK_DELETE:
  205708. case VK_INSERT:
  205709. case VK_F1:
  205710. case VK_F2:
  205711. case VK_F3:
  205712. case VK_F4:
  205713. case VK_F5:
  205714. case VK_F6:
  205715. case VK_F7:
  205716. case VK_F8:
  205717. case VK_F9:
  205718. case VK_F10:
  205719. case VK_F11:
  205720. case VK_F12:
  205721. case VK_F13:
  205722. case VK_F14:
  205723. case VK_F15:
  205724. case VK_F16:
  205725. used = handleKeyUpOrDown (true);
  205726. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205727. break;
  205728. case VK_ADD:
  205729. case VK_SUBTRACT:
  205730. case VK_MULTIPLY:
  205731. case VK_DIVIDE:
  205732. case VK_SEPARATOR:
  205733. case VK_DECIMAL:
  205734. used = handleKeyUpOrDown (true);
  205735. break;
  205736. default:
  205737. used = handleKeyUpOrDown (true);
  205738. {
  205739. MSG msg;
  205740. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205741. {
  205742. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205743. // manually generate the key-press event that matches this key-down.
  205744. const UINT keyChar = MapVirtualKey (key, 2);
  205745. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205746. }
  205747. }
  205748. break;
  205749. }
  205750. if (Component::getCurrentlyModalComponent() != 0)
  205751. used = true;
  205752. return used;
  205753. }
  205754. bool doKeyChar (int key, const LPARAM flags)
  205755. {
  205756. updateKeyModifiers();
  205757. juce_wchar textChar = (juce_wchar) key;
  205758. const int virtualScanCode = (flags >> 16) & 0xff;
  205759. if (key >= '0' && key <= '9')
  205760. {
  205761. switch (virtualScanCode) // check for a numeric keypad scan-code
  205762. {
  205763. case 0x52:
  205764. case 0x4f:
  205765. case 0x50:
  205766. case 0x51:
  205767. case 0x4b:
  205768. case 0x4c:
  205769. case 0x4d:
  205770. case 0x47:
  205771. case 0x48:
  205772. case 0x49:
  205773. key = (key - '0') + KeyPress::numberPad0;
  205774. break;
  205775. default:
  205776. break;
  205777. }
  205778. }
  205779. else
  205780. {
  205781. // convert the scan code to an unmodified character code..
  205782. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205783. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205784. keyChar = LOWORD (keyChar);
  205785. if (keyChar != 0)
  205786. key = (int) keyChar;
  205787. // avoid sending junk text characters for some control-key combinations
  205788. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205789. textChar = 0;
  205790. }
  205791. return handleKeyPress (key, textChar);
  205792. }
  205793. bool doAppCommand (const LPARAM lParam)
  205794. {
  205795. int key = 0;
  205796. switch (GET_APPCOMMAND_LPARAM (lParam))
  205797. {
  205798. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205799. key = KeyPress::playKey;
  205800. break;
  205801. case APPCOMMAND_MEDIA_STOP:
  205802. key = KeyPress::stopKey;
  205803. break;
  205804. case APPCOMMAND_MEDIA_NEXTTRACK:
  205805. key = KeyPress::fastForwardKey;
  205806. break;
  205807. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205808. key = KeyPress::rewindKey;
  205809. break;
  205810. }
  205811. if (key != 0)
  205812. {
  205813. updateKeyModifiers();
  205814. if (hwnd == GetActiveWindow())
  205815. {
  205816. handleKeyPress (key, 0);
  205817. return true;
  205818. }
  205819. }
  205820. return false;
  205821. }
  205822. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  205823. {
  205824. public:
  205825. JuceDropTarget (Win32ComponentPeer* const owner_)
  205826. : owner (owner_)
  205827. {
  205828. }
  205829. ~JuceDropTarget() {}
  205830. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205831. {
  205832. updateFileList (pDataObject);
  205833. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205834. *pdwEffect = DROPEFFECT_COPY;
  205835. return S_OK;
  205836. }
  205837. HRESULT __stdcall DragLeave()
  205838. {
  205839. owner->handleFileDragExit (files);
  205840. return S_OK;
  205841. }
  205842. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205843. {
  205844. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205845. *pdwEffect = DROPEFFECT_COPY;
  205846. return S_OK;
  205847. }
  205848. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205849. {
  205850. updateFileList (pDataObject);
  205851. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205852. *pdwEffect = DROPEFFECT_COPY;
  205853. return S_OK;
  205854. }
  205855. private:
  205856. Win32ComponentPeer* const owner;
  205857. StringArray files;
  205858. void updateFileList (IDataObject* const pDataObject)
  205859. {
  205860. files.clear();
  205861. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  205862. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  205863. if (pDataObject->GetData (&format, &medium) == S_OK)
  205864. {
  205865. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  205866. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  205867. unsigned int i = 0;
  205868. if (pDropFiles->fWide)
  205869. {
  205870. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  205871. for (;;)
  205872. {
  205873. unsigned int len = 0;
  205874. while (i + len < totalLen && fname [i + len] != 0)
  205875. ++len;
  205876. if (len == 0)
  205877. break;
  205878. files.add (String (fname + i, len));
  205879. i += len + 1;
  205880. }
  205881. }
  205882. else
  205883. {
  205884. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  205885. for (;;)
  205886. {
  205887. unsigned int len = 0;
  205888. while (i + len < totalLen && fname [i + len] != 0)
  205889. ++len;
  205890. if (len == 0)
  205891. break;
  205892. files.add (String (fname + i, len));
  205893. i += len + 1;
  205894. }
  205895. }
  205896. GlobalUnlock (medium.hGlobal);
  205897. }
  205898. }
  205899. JuceDropTarget (const JuceDropTarget&);
  205900. JuceDropTarget& operator= (const JuceDropTarget&);
  205901. };
  205902. void doSettingChange()
  205903. {
  205904. Desktop::getInstance().refreshMonitorSizes();
  205905. if (fullScreen && ! isMinimised())
  205906. {
  205907. const Rectangle<int> r (component->getParentMonitorArea());
  205908. SetWindowPos (hwnd, 0,
  205909. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  205910. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  205911. }
  205912. }
  205913. public:
  205914. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205915. {
  205916. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  205917. if (peer != 0)
  205918. return peer->peerWindowProc (h, message, wParam, lParam);
  205919. return DefWindowProcW (h, message, wParam, lParam);
  205920. }
  205921. private:
  205922. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  205923. {
  205924. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  205925. }
  205926. const Point<int> getCurrentMousePos() throw()
  205927. {
  205928. RECT wr;
  205929. GetWindowRect (hwnd, &wr);
  205930. const DWORD mp = GetMessagePos();
  205931. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205932. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  205933. }
  205934. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205935. {
  205936. if (isValidPeer (this))
  205937. {
  205938. switch (message)
  205939. {
  205940. case WM_NCHITTEST:
  205941. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205942. return HTTRANSPARENT;
  205943. if (hasTitleBar())
  205944. break;
  205945. return HTCLIENT;
  205946. case WM_PAINT:
  205947. handlePaintMessage();
  205948. return 0;
  205949. case WM_NCPAINT:
  205950. if (wParam != 1)
  205951. handlePaintMessage();
  205952. if (hasTitleBar())
  205953. break;
  205954. return 0;
  205955. case WM_ERASEBKGND:
  205956. case WM_NCCALCSIZE:
  205957. if (hasTitleBar())
  205958. break;
  205959. return 1;
  205960. case WM_MOUSEMOVE:
  205961. doMouseMove (getPointFromLParam (lParam));
  205962. return 0;
  205963. case WM_MOUSELEAVE:
  205964. doMouseExit();
  205965. return 0;
  205966. case WM_LBUTTONDOWN:
  205967. case WM_MBUTTONDOWN:
  205968. case WM_RBUTTONDOWN:
  205969. doMouseDown (getPointFromLParam (lParam), wParam);
  205970. return 0;
  205971. case WM_LBUTTONUP:
  205972. case WM_MBUTTONUP:
  205973. case WM_RBUTTONUP:
  205974. doMouseUp (getPointFromLParam (lParam), wParam);
  205975. return 0;
  205976. case WM_CAPTURECHANGED:
  205977. doCaptureChanged();
  205978. return 0;
  205979. case WM_NCMOUSEMOVE:
  205980. if (hasTitleBar())
  205981. break;
  205982. return 0;
  205983. case 0x020A: /* WM_MOUSEWHEEL */
  205984. doMouseWheel (getCurrentMousePos(), wParam, true);
  205985. return 0;
  205986. case 0x020E: /* WM_MOUSEHWHEEL */
  205987. doMouseWheel (getCurrentMousePos(), wParam, false);
  205988. return 0;
  205989. case WM_WINDOWPOSCHANGING:
  205990. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  205991. {
  205992. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  205993. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  205994. {
  205995. if (constrainer != 0)
  205996. {
  205997. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  205998. component->getY() - windowBorder.getTop(),
  205999. component->getWidth() + windowBorder.getLeftAndRight(),
  206000. component->getHeight() + windowBorder.getTopAndBottom());
  206001. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  206002. constrainer->checkBounds (pos, current,
  206003. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206004. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  206005. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  206006. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  206007. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  206008. wp->x = pos.getX();
  206009. wp->y = pos.getY();
  206010. wp->cx = pos.getWidth();
  206011. wp->cy = pos.getHeight();
  206012. }
  206013. }
  206014. }
  206015. return 0;
  206016. case WM_WINDOWPOSCHANGED:
  206017. handleMovedOrResized();
  206018. if (dontRepaint)
  206019. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  206020. return 0;
  206021. case WM_KEYDOWN:
  206022. case WM_SYSKEYDOWN:
  206023. if (doKeyDown (wParam))
  206024. return 0;
  206025. break;
  206026. case WM_KEYUP:
  206027. case WM_SYSKEYUP:
  206028. if (doKeyUp (wParam))
  206029. return 0;
  206030. break;
  206031. case WM_CHAR:
  206032. if (doKeyChar ((int) wParam, lParam))
  206033. return 0;
  206034. break;
  206035. case WM_APPCOMMAND:
  206036. if (doAppCommand (lParam))
  206037. return TRUE;
  206038. break;
  206039. case WM_SETFOCUS:
  206040. updateKeyModifiers();
  206041. handleFocusGain();
  206042. break;
  206043. case WM_KILLFOCUS:
  206044. if (hasCreatedCaret)
  206045. {
  206046. hasCreatedCaret = false;
  206047. DestroyCaret();
  206048. }
  206049. handleFocusLoss();
  206050. break;
  206051. case WM_ACTIVATEAPP:
  206052. // Windows does weird things to process priority when you swap apps,
  206053. // so this forces an update when the app is brought to the front
  206054. if (wParam != FALSE)
  206055. juce_repeatLastProcessPriority();
  206056. else
  206057. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  206058. juce_CheckCurrentlyFocusedTopLevelWindow();
  206059. modifiersAtLastCallback = -1;
  206060. return 0;
  206061. case WM_ACTIVATE:
  206062. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  206063. {
  206064. modifiersAtLastCallback = -1;
  206065. updateKeyModifiers();
  206066. if (isMinimised())
  206067. {
  206068. component->repaint();
  206069. handleMovedOrResized();
  206070. if (! ComponentPeer::isValidPeer (this))
  206071. return 0;
  206072. }
  206073. if (LOWORD (wParam) == WA_CLICKACTIVE
  206074. && component->isCurrentlyBlockedByAnotherModalComponent())
  206075. {
  206076. const Point<int> mousePos (component->getMouseXYRelative());
  206077. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  206078. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  206079. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  206080. return 0;
  206081. }
  206082. handleBroughtToFront();
  206083. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206084. Component::getCurrentlyModalComponent()->toFront (true);
  206085. return 0;
  206086. }
  206087. break;
  206088. case WM_NCACTIVATE:
  206089. // while a temporary window is being shown, prevent Windows from deactivating the
  206090. // title bars of our main windows.
  206091. if (wParam == 0 && ! shouldDeactivateTitleBar)
  206092. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  206093. break;
  206094. case WM_MOUSEACTIVATE:
  206095. if (! component->getMouseClickGrabsKeyboardFocus())
  206096. return MA_NOACTIVATE;
  206097. break;
  206098. case WM_SHOWWINDOW:
  206099. if (wParam != 0)
  206100. handleBroughtToFront();
  206101. break;
  206102. case WM_CLOSE:
  206103. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  206104. handleUserClosingWindow();
  206105. return 0;
  206106. case WM_QUERYENDSESSION:
  206107. if (JUCEApplication::getInstance() != 0)
  206108. {
  206109. JUCEApplication::getInstance()->systemRequestedQuit();
  206110. return MessageManager::getInstance()->hasStopMessageBeenSent();
  206111. }
  206112. return TRUE;
  206113. case WM_TRAYNOTIFY:
  206114. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206115. {
  206116. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206117. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206118. {
  206119. Component* const current = Component::getCurrentlyModalComponent();
  206120. if (current != 0)
  206121. current->inputAttemptWhenModal();
  206122. }
  206123. }
  206124. else
  206125. {
  206126. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206127. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206128. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206129. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206130. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206131. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206132. eventMods = eventMods.withoutMouseButtons();
  206133. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206134. Point<int>(), eventMods, component, component, getMouseEventTime(),
  206135. Point<int>(), getMouseEventTime(), 1, false);
  206136. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206137. {
  206138. SetFocus (hwnd);
  206139. SetForegroundWindow (hwnd);
  206140. component->mouseDown (e);
  206141. }
  206142. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206143. {
  206144. component->mouseUp (e);
  206145. }
  206146. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206147. {
  206148. component->mouseDoubleClick (e);
  206149. }
  206150. else if (lParam == WM_MOUSEMOVE)
  206151. {
  206152. component->mouseMove (e);
  206153. }
  206154. }
  206155. break;
  206156. case WM_SYNCPAINT:
  206157. return 0;
  206158. case WM_PALETTECHANGED:
  206159. InvalidateRect (h, 0, 0);
  206160. break;
  206161. case WM_DISPLAYCHANGE:
  206162. InvalidateRect (h, 0, 0);
  206163. createPaletteIfNeeded = true;
  206164. // intentional fall-through...
  206165. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206166. doSettingChange();
  206167. break;
  206168. case WM_INITMENU:
  206169. if (! hasTitleBar())
  206170. {
  206171. if (isFullScreen())
  206172. {
  206173. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206174. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206175. }
  206176. else if (! isMinimised())
  206177. {
  206178. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206179. }
  206180. }
  206181. break;
  206182. case WM_SYSCOMMAND:
  206183. switch (wParam & 0xfff0)
  206184. {
  206185. case SC_CLOSE:
  206186. if (sendInputAttemptWhenModalMessage())
  206187. return 0;
  206188. if (hasTitleBar())
  206189. {
  206190. PostMessage (h, WM_CLOSE, 0, 0);
  206191. return 0;
  206192. }
  206193. break;
  206194. case SC_KEYMENU:
  206195. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  206196. // obscure situations that can arise if a modal loop is started from an alt-key
  206197. // keypress).
  206198. if (hasTitleBar() && h == GetCapture())
  206199. ReleaseCapture();
  206200. break;
  206201. case SC_MAXIMIZE:
  206202. if (sendInputAttemptWhenModalMessage())
  206203. return 0;
  206204. setFullScreen (true);
  206205. return 0;
  206206. case SC_MINIMIZE:
  206207. if (sendInputAttemptWhenModalMessage())
  206208. return 0;
  206209. if (! hasTitleBar())
  206210. {
  206211. setMinimised (true);
  206212. return 0;
  206213. }
  206214. break;
  206215. case SC_RESTORE:
  206216. if (sendInputAttemptWhenModalMessage())
  206217. return 0;
  206218. if (hasTitleBar())
  206219. {
  206220. if (isFullScreen())
  206221. {
  206222. setFullScreen (false);
  206223. return 0;
  206224. }
  206225. }
  206226. else
  206227. {
  206228. if (isMinimised())
  206229. setMinimised (false);
  206230. else if (isFullScreen())
  206231. setFullScreen (false);
  206232. return 0;
  206233. }
  206234. break;
  206235. }
  206236. break;
  206237. case WM_NCLBUTTONDOWN:
  206238. case WM_NCRBUTTONDOWN:
  206239. case WM_NCMBUTTONDOWN:
  206240. sendInputAttemptWhenModalMessage();
  206241. break;
  206242. //case WM_IME_STARTCOMPOSITION;
  206243. // return 0;
  206244. case WM_GETDLGCODE:
  206245. return DLGC_WANTALLKEYS;
  206246. default:
  206247. break;
  206248. }
  206249. }
  206250. return DefWindowProcW (h, message, wParam, lParam);
  206251. }
  206252. bool sendInputAttemptWhenModalMessage()
  206253. {
  206254. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206255. {
  206256. Component* const current = Component::getCurrentlyModalComponent();
  206257. if (current != 0)
  206258. current->inputAttemptWhenModal();
  206259. return true;
  206260. }
  206261. return false;
  206262. }
  206263. Win32ComponentPeer (const Win32ComponentPeer&);
  206264. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206265. };
  206266. ModifierKeys Win32ComponentPeer::currentModifiers;
  206267. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206268. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206269. {
  206270. return new Win32ComponentPeer (this, styleFlags);
  206271. }
  206272. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206273. void ModifierKeys::updateCurrentModifiers() throw()
  206274. {
  206275. currentModifiers = Win32ComponentPeer::currentModifiers;
  206276. }
  206277. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206278. {
  206279. Win32ComponentPeer::updateKeyModifiers();
  206280. int keyMods = 0;
  206281. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206282. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206283. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206284. Win32ComponentPeer::currentModifiers
  206285. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206286. return Win32ComponentPeer::currentModifiers;
  206287. }
  206288. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206289. {
  206290. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206291. if (wp != 0)
  206292. wp->setTaskBarIcon (newImage);
  206293. }
  206294. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206295. {
  206296. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206297. if (wp != 0)
  206298. wp->setTaskBarIconToolTip (tooltip);
  206299. }
  206300. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206301. {
  206302. DWORD val = GetWindowLong (h, styleType);
  206303. if (bitIsSet)
  206304. val |= feature;
  206305. else
  206306. val &= ~feature;
  206307. SetWindowLongPtr (h, styleType, val);
  206308. SetWindowPos (h, 0, 0, 0, 0, 0,
  206309. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206310. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206311. }
  206312. bool Process::isForegroundProcess()
  206313. {
  206314. HWND fg = GetForegroundWindow();
  206315. if (fg == 0)
  206316. return true;
  206317. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206318. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206319. // have to see if any of our windows are children of the foreground window
  206320. fg = GetAncestor (fg, GA_ROOT);
  206321. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206322. {
  206323. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206324. if (wp != 0 && wp->isInside (fg))
  206325. return true;
  206326. }
  206327. return false;
  206328. }
  206329. bool AlertWindow::showNativeDialogBox (const String& title,
  206330. const String& bodyText,
  206331. bool isOkCancel)
  206332. {
  206333. return MessageBox (0, bodyText, title,
  206334. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206335. : MB_OK)) == IDOK;
  206336. }
  206337. void Desktop::createMouseInputSources()
  206338. {
  206339. mouseSources.add (new MouseInputSource (0, true));
  206340. }
  206341. const Point<int> Desktop::getMousePosition()
  206342. {
  206343. POINT mousePos;
  206344. GetCursorPos (&mousePos);
  206345. return Point<int> (mousePos.x, mousePos.y);
  206346. }
  206347. void Desktop::setMousePosition (const Point<int>& newPosition)
  206348. {
  206349. SetCursorPos (newPosition.getX(), newPosition.getY());
  206350. }
  206351. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206352. {
  206353. return createSoftwareImage (format, width, height, clearImage);
  206354. }
  206355. class ScreenSaverDefeater : public Timer,
  206356. public DeletedAtShutdown
  206357. {
  206358. public:
  206359. ScreenSaverDefeater()
  206360. {
  206361. startTimer (10000);
  206362. timerCallback();
  206363. }
  206364. ~ScreenSaverDefeater() {}
  206365. void timerCallback()
  206366. {
  206367. if (Process::isForegroundProcess())
  206368. {
  206369. // simulate a shift key getting pressed..
  206370. INPUT input[2];
  206371. input[0].type = INPUT_KEYBOARD;
  206372. input[0].ki.wVk = VK_SHIFT;
  206373. input[0].ki.dwFlags = 0;
  206374. input[0].ki.dwExtraInfo = 0;
  206375. input[1].type = INPUT_KEYBOARD;
  206376. input[1].ki.wVk = VK_SHIFT;
  206377. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206378. input[1].ki.dwExtraInfo = 0;
  206379. SendInput (2, input, sizeof (INPUT));
  206380. }
  206381. }
  206382. };
  206383. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206384. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206385. {
  206386. if (isEnabled)
  206387. deleteAndZero (screenSaverDefeater);
  206388. else if (screenSaverDefeater == 0)
  206389. screenSaverDefeater = new ScreenSaverDefeater();
  206390. }
  206391. bool Desktop::isScreenSaverEnabled()
  206392. {
  206393. return screenSaverDefeater == 0;
  206394. }
  206395. /* (The code below is the "correct" way to disable the screen saver, but it
  206396. completely fails on winXP when the saver is password-protected...)
  206397. static bool juce_screenSaverEnabled = true;
  206398. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206399. {
  206400. juce_screenSaverEnabled = isEnabled;
  206401. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206402. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206403. }
  206404. bool Desktop::isScreenSaverEnabled() throw()
  206405. {
  206406. return juce_screenSaverEnabled;
  206407. }
  206408. */
  206409. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206410. {
  206411. if (enableOrDisable)
  206412. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206413. }
  206414. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206415. {
  206416. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206417. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206418. return TRUE;
  206419. }
  206420. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206421. {
  206422. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206423. // make sure the first in the list is the main monitor
  206424. for (int i = 1; i < monitorCoords.size(); ++i)
  206425. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206426. monitorCoords.swap (i, 0);
  206427. if (monitorCoords.size() == 0)
  206428. {
  206429. RECT r;
  206430. GetWindowRect (GetDesktopWindow(), &r);
  206431. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206432. }
  206433. if (clipToWorkArea)
  206434. {
  206435. // clip the main monitor to the active non-taskbar area
  206436. RECT r;
  206437. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206438. Rectangle<int>& screen = monitorCoords.getReference (0);
  206439. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206440. jmax (screen.getY(), (int) r.top));
  206441. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206442. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206443. }
  206444. }
  206445. static const Image createImageFromHBITMAP (HBITMAP bitmap) throw()
  206446. {
  206447. Image im;
  206448. if (bitmap != 0)
  206449. {
  206450. BITMAP bm;
  206451. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206452. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206453. {
  206454. HDC tempDC = GetDC (0);
  206455. HDC dc = CreateCompatibleDC (tempDC);
  206456. ReleaseDC (0, tempDC);
  206457. SelectObject (dc, bitmap);
  206458. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206459. Image::BitmapData imageData (im, 0, 0, bm.bmWidth, bm.bmHeight, true);
  206460. for (int y = bm.bmHeight; --y >= 0;)
  206461. {
  206462. for (int x = bm.bmWidth; --x >= 0;)
  206463. {
  206464. COLORREF col = GetPixel (dc, x, y);
  206465. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206466. (uint8) GetGValue (col),
  206467. (uint8) GetBValue (col)));
  206468. }
  206469. }
  206470. DeleteDC (dc);
  206471. }
  206472. }
  206473. return im;
  206474. }
  206475. static const Image createImageFromHICON (HICON icon) throw()
  206476. {
  206477. ICONINFO info;
  206478. if (GetIconInfo (icon, &info))
  206479. {
  206480. Image mask (createImageFromHBITMAP (info.hbmMask));
  206481. Image image (createImageFromHBITMAP (info.hbmColor));
  206482. if (mask.isValid() && image.isValid())
  206483. {
  206484. for (int y = image.getHeight(); --y >= 0;)
  206485. {
  206486. for (int x = image.getWidth(); --x >= 0;)
  206487. {
  206488. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206489. if (brightness > 0.0f)
  206490. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206491. }
  206492. }
  206493. return image;
  206494. }
  206495. }
  206496. return Image();
  206497. }
  206498. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206499. {
  206500. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206501. Image bitmap (nativeBitmap);
  206502. {
  206503. Graphics g (bitmap);
  206504. g.drawImageAt (image, 0, 0);
  206505. }
  206506. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206507. ICONINFO info;
  206508. info.fIcon = isIcon;
  206509. info.xHotspot = hotspotX;
  206510. info.yHotspot = hotspotY;
  206511. info.hbmMask = mask;
  206512. info.hbmColor = nativeBitmap->hBitmap;
  206513. HICON hi = CreateIconIndirect (&info);
  206514. DeleteObject (mask);
  206515. return hi;
  206516. }
  206517. const Image juce_createIconForFile (const File& file)
  206518. {
  206519. Image image;
  206520. WCHAR filename [1024];
  206521. file.getFullPathName().copyToUnicode (filename, 1023);
  206522. WORD iconNum = 0;
  206523. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206524. filename, &iconNum);
  206525. if (icon != 0)
  206526. {
  206527. image = createImageFromHICON (icon);
  206528. DestroyIcon (icon);
  206529. }
  206530. return image;
  206531. }
  206532. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206533. {
  206534. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206535. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206536. Image im (image);
  206537. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206538. {
  206539. im = im.rescaled (maxW, maxH);
  206540. hotspotX = (hotspotX * maxW) / image.getWidth();
  206541. hotspotY = (hotspotY * maxH) / image.getHeight();
  206542. }
  206543. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206544. }
  206545. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206546. {
  206547. if (cursorHandle != 0 && ! isStandard)
  206548. DestroyCursor ((HCURSOR) cursorHandle);
  206549. }
  206550. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206551. {
  206552. LPCTSTR cursorName = IDC_ARROW;
  206553. switch (type)
  206554. {
  206555. case NormalCursor: break;
  206556. case NoCursor: return 0;
  206557. case WaitCursor: cursorName = IDC_WAIT; break;
  206558. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206559. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206560. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206561. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206562. case LeftRightResizeCursor:
  206563. case LeftEdgeResizeCursor:
  206564. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206565. case UpDownResizeCursor:
  206566. case TopEdgeResizeCursor:
  206567. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206568. case TopLeftCornerResizeCursor:
  206569. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206570. case TopRightCornerResizeCursor:
  206571. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206572. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206573. case DraggingHandCursor:
  206574. {
  206575. static void* dragHandCursor = 0;
  206576. if (dragHandCursor == 0)
  206577. {
  206578. static const unsigned char dragHandData[] =
  206579. { 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,
  206580. 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,
  206581. 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 };
  206582. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206583. }
  206584. return dragHandCursor;
  206585. }
  206586. default:
  206587. jassertfalse; break;
  206588. }
  206589. HCURSOR cursorH = LoadCursor (0, cursorName);
  206590. if (cursorH == 0)
  206591. cursorH = LoadCursor (0, IDC_ARROW);
  206592. return cursorH;
  206593. }
  206594. void MouseCursor::showInWindow (ComponentPeer*) const
  206595. {
  206596. SetCursor ((HCURSOR) getHandle());
  206597. }
  206598. void MouseCursor::showInAllWindows() const
  206599. {
  206600. showInWindow (0);
  206601. }
  206602. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206603. {
  206604. public:
  206605. JuceDropSource() {}
  206606. ~JuceDropSource() {}
  206607. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206608. {
  206609. if (escapePressed)
  206610. return DRAGDROP_S_CANCEL;
  206611. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206612. return DRAGDROP_S_DROP;
  206613. return S_OK;
  206614. }
  206615. HRESULT __stdcall GiveFeedback (DWORD)
  206616. {
  206617. return DRAGDROP_S_USEDEFAULTCURSORS;
  206618. }
  206619. };
  206620. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206621. {
  206622. public:
  206623. JuceEnumFormatEtc (const FORMATETC* const format_)
  206624. : format (format_),
  206625. index (0)
  206626. {
  206627. }
  206628. ~JuceEnumFormatEtc() {}
  206629. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206630. {
  206631. if (result == 0)
  206632. return E_POINTER;
  206633. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206634. newOne->index = index;
  206635. *result = newOne;
  206636. return S_OK;
  206637. }
  206638. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206639. {
  206640. if (pceltFetched != 0)
  206641. *pceltFetched = 0;
  206642. else if (celt != 1)
  206643. return S_FALSE;
  206644. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206645. {
  206646. copyFormatEtc (lpFormatEtc [0], *format);
  206647. ++index;
  206648. if (pceltFetched != 0)
  206649. *pceltFetched = 1;
  206650. return S_OK;
  206651. }
  206652. return S_FALSE;
  206653. }
  206654. HRESULT __stdcall Skip (ULONG celt)
  206655. {
  206656. if (index + (int) celt >= 1)
  206657. return S_FALSE;
  206658. index += celt;
  206659. return S_OK;
  206660. }
  206661. HRESULT __stdcall Reset()
  206662. {
  206663. index = 0;
  206664. return S_OK;
  206665. }
  206666. private:
  206667. const FORMATETC* const format;
  206668. int index;
  206669. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206670. {
  206671. dest = source;
  206672. if (source.ptd != 0)
  206673. {
  206674. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206675. *(dest.ptd) = *(source.ptd);
  206676. }
  206677. }
  206678. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206679. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206680. };
  206681. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206682. {
  206683. public:
  206684. JuceDataObject (JuceDropSource* const dropSource_,
  206685. const FORMATETC* const format_,
  206686. const STGMEDIUM* const medium_)
  206687. : dropSource (dropSource_),
  206688. format (format_),
  206689. medium (medium_)
  206690. {
  206691. }
  206692. virtual ~JuceDataObject()
  206693. {
  206694. jassert (refCount == 0);
  206695. }
  206696. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206697. {
  206698. if ((pFormatEtc->tymed & format->tymed) != 0
  206699. && pFormatEtc->cfFormat == format->cfFormat
  206700. && pFormatEtc->dwAspect == format->dwAspect)
  206701. {
  206702. pMedium->tymed = format->tymed;
  206703. pMedium->pUnkForRelease = 0;
  206704. if (format->tymed == TYMED_HGLOBAL)
  206705. {
  206706. const SIZE_T len = GlobalSize (medium->hGlobal);
  206707. void* const src = GlobalLock (medium->hGlobal);
  206708. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206709. memcpy (dst, src, len);
  206710. GlobalUnlock (medium->hGlobal);
  206711. pMedium->hGlobal = dst;
  206712. return S_OK;
  206713. }
  206714. }
  206715. return DV_E_FORMATETC;
  206716. }
  206717. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206718. {
  206719. if (f == 0)
  206720. return E_INVALIDARG;
  206721. if (f->tymed == format->tymed
  206722. && f->cfFormat == format->cfFormat
  206723. && f->dwAspect == format->dwAspect)
  206724. return S_OK;
  206725. return DV_E_FORMATETC;
  206726. }
  206727. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206728. {
  206729. pFormatEtcOut->ptd = 0;
  206730. return E_NOTIMPL;
  206731. }
  206732. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206733. {
  206734. if (result == 0)
  206735. return E_POINTER;
  206736. if (direction == DATADIR_GET)
  206737. {
  206738. *result = new JuceEnumFormatEtc (format);
  206739. return S_OK;
  206740. }
  206741. *result = 0;
  206742. return E_NOTIMPL;
  206743. }
  206744. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206745. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206746. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206747. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206748. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206749. private:
  206750. JuceDropSource* const dropSource;
  206751. const FORMATETC* const format;
  206752. const STGMEDIUM* const medium;
  206753. JuceDataObject (const JuceDataObject&);
  206754. JuceDataObject& operator= (const JuceDataObject&);
  206755. };
  206756. static HDROP createHDrop (const StringArray& fileNames) throw()
  206757. {
  206758. int totalChars = 0;
  206759. for (int i = fileNames.size(); --i >= 0;)
  206760. totalChars += fileNames[i].length() + 1;
  206761. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206762. sizeof (DROPFILES)
  206763. + sizeof (WCHAR) * (totalChars + 2));
  206764. if (hDrop != 0)
  206765. {
  206766. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206767. pDropFiles->pFiles = sizeof (DROPFILES);
  206768. pDropFiles->fWide = true;
  206769. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206770. for (int i = 0; i < fileNames.size(); ++i)
  206771. {
  206772. fileNames[i].copyToUnicode (fname, 2048);
  206773. fname += fileNames[i].length() + 1;
  206774. }
  206775. *fname = 0;
  206776. GlobalUnlock (hDrop);
  206777. }
  206778. return hDrop;
  206779. }
  206780. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  206781. {
  206782. JuceDropSource* const source = new JuceDropSource();
  206783. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206784. DWORD effect;
  206785. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206786. data->Release();
  206787. source->Release();
  206788. return res == DRAGDROP_S_DROP;
  206789. }
  206790. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206791. {
  206792. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206793. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206794. medium.hGlobal = createHDrop (files);
  206795. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206796. : DROPEFFECT_COPY);
  206797. }
  206798. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206799. {
  206800. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206801. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206802. const int numChars = text.length();
  206803. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206804. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206805. text.copyToUnicode (data, numChars + 1);
  206806. format.cfFormat = CF_UNICODETEXT;
  206807. GlobalUnlock (medium.hGlobal);
  206808. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206809. }
  206810. #endif
  206811. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206812. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206813. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206814. // compiled on its own).
  206815. #if JUCE_INCLUDED_FILE
  206816. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206817. NEWTEXTMETRICEXW*,
  206818. int type,
  206819. LPARAM lParam)
  206820. {
  206821. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206822. {
  206823. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206824. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  206825. }
  206826. return 1;
  206827. }
  206828. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  206829. NEWTEXTMETRICEXW*,
  206830. int type,
  206831. LPARAM lParam)
  206832. {
  206833. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206834. {
  206835. LOGFONTW lf;
  206836. zerostruct (lf);
  206837. lf.lfWeight = FW_DONTCARE;
  206838. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206839. lf.lfQuality = DEFAULT_QUALITY;
  206840. lf.lfCharSet = DEFAULT_CHARSET;
  206841. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206842. lf.lfPitchAndFamily = FF_DONTCARE;
  206843. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206844. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  206845. HDC dc = CreateCompatibleDC (0);
  206846. EnumFontFamiliesEx (dc, &lf,
  206847. (FONTENUMPROCW) &wfontEnum2,
  206848. lParam, 0);
  206849. DeleteDC (dc);
  206850. }
  206851. return 1;
  206852. }
  206853. const StringArray Font::findAllTypefaceNames()
  206854. {
  206855. StringArray results;
  206856. HDC dc = CreateCompatibleDC (0);
  206857. {
  206858. LOGFONTW lf;
  206859. zerostruct (lf);
  206860. lf.lfWeight = FW_DONTCARE;
  206861. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206862. lf.lfQuality = DEFAULT_QUALITY;
  206863. lf.lfCharSet = DEFAULT_CHARSET;
  206864. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206865. lf.lfPitchAndFamily = FF_DONTCARE;
  206866. lf.lfFaceName[0] = 0;
  206867. EnumFontFamiliesEx (dc, &lf,
  206868. (FONTENUMPROCW) &wfontEnum1,
  206869. (LPARAM) &results, 0);
  206870. }
  206871. DeleteDC (dc);
  206872. results.sort (true);
  206873. return results;
  206874. }
  206875. extern bool juce_IsRunningInWine();
  206876. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  206877. {
  206878. if (juce_IsRunningInWine())
  206879. {
  206880. // If we're running in Wine, then use fonts that might be available on Linux..
  206881. defaultSans = "Bitstream Vera Sans";
  206882. defaultSerif = "Bitstream Vera Serif";
  206883. defaultFixed = "Bitstream Vera Sans Mono";
  206884. }
  206885. else
  206886. {
  206887. defaultSans = "Verdana";
  206888. defaultSerif = "Times";
  206889. defaultFixed = "Lucida Console";
  206890. }
  206891. }
  206892. class FontDCHolder : private DeletedAtShutdown
  206893. {
  206894. public:
  206895. FontDCHolder()
  206896. : dc (0), numKPs (0), size (0),
  206897. bold (false), italic (false)
  206898. {
  206899. }
  206900. ~FontDCHolder()
  206901. {
  206902. if (dc != 0)
  206903. {
  206904. DeleteDC (dc);
  206905. DeleteObject (fontH);
  206906. }
  206907. clearSingletonInstance();
  206908. }
  206909. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  206910. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  206911. {
  206912. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  206913. {
  206914. fontName = fontName_;
  206915. bold = bold_;
  206916. italic = italic_;
  206917. size = size_;
  206918. if (dc != 0)
  206919. {
  206920. DeleteDC (dc);
  206921. DeleteObject (fontH);
  206922. kps.free();
  206923. }
  206924. fontH = 0;
  206925. dc = CreateCompatibleDC (0);
  206926. SetMapperFlags (dc, 0);
  206927. SetMapMode (dc, MM_TEXT);
  206928. LOGFONTW lfw;
  206929. zerostruct (lfw);
  206930. lfw.lfCharSet = DEFAULT_CHARSET;
  206931. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206932. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206933. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  206934. lfw.lfQuality = PROOF_QUALITY;
  206935. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  206936. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  206937. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  206938. lfw.lfHeight = size > 0 ? size : -256;
  206939. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  206940. if (standardSizedFont != 0)
  206941. {
  206942. if (SelectObject (dc, standardSizedFont) != 0)
  206943. {
  206944. fontH = standardSizedFont;
  206945. if (size == 0)
  206946. {
  206947. OUTLINETEXTMETRIC otm;
  206948. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  206949. {
  206950. lfw.lfHeight = -(int) otm.otmEMSquare;
  206951. fontH = CreateFontIndirect (&lfw);
  206952. SelectObject (dc, fontH);
  206953. DeleteObject (standardSizedFont);
  206954. }
  206955. }
  206956. }
  206957. else
  206958. {
  206959. jassertfalse;
  206960. }
  206961. }
  206962. else
  206963. {
  206964. jassertfalse;
  206965. }
  206966. }
  206967. return dc;
  206968. }
  206969. KERNINGPAIR* getKerningPairs (int& numKPs_)
  206970. {
  206971. if (kps == 0)
  206972. {
  206973. numKPs = GetKerningPairs (dc, 0, 0);
  206974. kps.calloc (numKPs);
  206975. GetKerningPairs (dc, numKPs, kps);
  206976. }
  206977. numKPs_ = numKPs;
  206978. return kps;
  206979. }
  206980. private:
  206981. HFONT fontH;
  206982. HDC dc;
  206983. String fontName;
  206984. HeapBlock <KERNINGPAIR> kps;
  206985. int numKPs, size;
  206986. bool bold, italic;
  206987. FontDCHolder (const FontDCHolder&);
  206988. FontDCHolder& operator= (const FontDCHolder&);
  206989. };
  206990. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  206991. class WindowsTypeface : public CustomTypeface
  206992. {
  206993. public:
  206994. WindowsTypeface (const Font& font)
  206995. {
  206996. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  206997. font.isBold(), font.isItalic(), 0);
  206998. TEXTMETRIC tm;
  206999. tm.tmAscent = tm.tmHeight = 1;
  207000. tm.tmDefaultChar = 0;
  207001. GetTextMetrics (dc, &tm);
  207002. setCharacteristics (font.getTypefaceName(),
  207003. tm.tmAscent / (float) tm.tmHeight,
  207004. font.isBold(), font.isItalic(),
  207005. tm.tmDefaultChar);
  207006. }
  207007. bool loadGlyphIfPossible (juce_wchar character)
  207008. {
  207009. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  207010. GLYPHMETRICS gm;
  207011. {
  207012. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  207013. WORD index = 0;
  207014. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  207015. && index == 0xffff)
  207016. {
  207017. return false;
  207018. }
  207019. }
  207020. Path glyphPath;
  207021. TEXTMETRIC tm;
  207022. if (! GetTextMetrics (dc, &tm))
  207023. {
  207024. addGlyph (character, glyphPath, 0);
  207025. return true;
  207026. }
  207027. const float height = (float) tm.tmHeight;
  207028. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  207029. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  207030. &gm, 0, 0, &identityMatrix);
  207031. if (bufSize > 0)
  207032. {
  207033. HeapBlock<char> data (bufSize);
  207034. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  207035. bufSize, data, &identityMatrix);
  207036. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  207037. const float scaleX = 1.0f / height;
  207038. const float scaleY = -1.0f / height;
  207039. while ((char*) pheader < data + bufSize)
  207040. {
  207041. float x = scaleX * pheader->pfxStart.x.value;
  207042. float y = scaleY * pheader->pfxStart.y.value;
  207043. glyphPath.startNewSubPath (x, y);
  207044. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  207045. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  207046. while ((const char*) curve < curveEnd)
  207047. {
  207048. if (curve->wType == TT_PRIM_LINE)
  207049. {
  207050. for (int i = 0; i < curve->cpfx; ++i)
  207051. {
  207052. x = scaleX * curve->apfx[i].x.value;
  207053. y = scaleY * curve->apfx[i].y.value;
  207054. glyphPath.lineTo (x, y);
  207055. }
  207056. }
  207057. else if (curve->wType == TT_PRIM_QSPLINE)
  207058. {
  207059. for (int i = 0; i < curve->cpfx - 1; ++i)
  207060. {
  207061. const float x2 = scaleX * curve->apfx[i].x.value;
  207062. const float y2 = scaleY * curve->apfx[i].y.value;
  207063. float x3, y3;
  207064. if (i < curve->cpfx - 2)
  207065. {
  207066. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  207067. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  207068. }
  207069. else
  207070. {
  207071. x3 = scaleX * curve->apfx[i + 1].x.value;
  207072. y3 = scaleY * curve->apfx[i + 1].y.value;
  207073. }
  207074. glyphPath.quadraticTo (x2, y2, x3, y3);
  207075. x = x3;
  207076. y = y3;
  207077. }
  207078. }
  207079. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  207080. }
  207081. pheader = (const TTPOLYGONHEADER*) curve;
  207082. glyphPath.closeSubPath();
  207083. }
  207084. }
  207085. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  207086. int numKPs;
  207087. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  207088. for (int i = 0; i < numKPs; ++i)
  207089. {
  207090. if (kps[i].wFirst == character)
  207091. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  207092. kps[i].iKernAmount / height);
  207093. }
  207094. return true;
  207095. }
  207096. juce_UseDebuggingNewOperator
  207097. };
  207098. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  207099. {
  207100. return new WindowsTypeface (font);
  207101. }
  207102. #endif
  207103. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  207104. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  207105. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207106. // compiled on its own).
  207107. #if JUCE_INCLUDED_FILE
  207108. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  207109. namespace FileChooserHelpers
  207110. {
  207111. static const void* defaultDirPath = 0;
  207112. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  207113. static Component* currentExtraFileWin = 0;
  207114. static bool areThereAnyAlwaysOnTopWindows()
  207115. {
  207116. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  207117. {
  207118. Component* c = Desktop::getInstance().getComponent (i);
  207119. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  207120. return true;
  207121. }
  207122. return false;
  207123. }
  207124. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  207125. {
  207126. if (msg == BFFM_INITIALIZED)
  207127. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  207128. else if (msg == BFFM_VALIDATEFAILEDW)
  207129. returnedString = (LPCWSTR) lParam;
  207130. else if (msg == BFFM_VALIDATEFAILEDA)
  207131. returnedString = (const char*) lParam;
  207132. return 0;
  207133. }
  207134. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  207135. {
  207136. if (currentExtraFileWin != 0)
  207137. {
  207138. if (uiMsg == WM_INITDIALOG)
  207139. {
  207140. HWND dialogH = GetParent (hdlg);
  207141. jassert (dialogH != 0);
  207142. if (dialogH == 0)
  207143. dialogH = hdlg;
  207144. RECT r, cr;
  207145. GetWindowRect (dialogH, &r);
  207146. GetClientRect (dialogH, &cr);
  207147. SetWindowPos (dialogH, 0,
  207148. r.left, r.top,
  207149. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  207150. jmax (150, (int) (r.bottom - r.top)),
  207151. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  207152. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  207153. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  207154. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  207155. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  207156. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  207157. }
  207158. else if (uiMsg == WM_NOTIFY)
  207159. {
  207160. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  207161. if (ofn->hdr.code == CDN_SELCHANGE)
  207162. {
  207163. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  207164. if (comp != 0)
  207165. {
  207166. TCHAR path [MAX_PATH * 2];
  207167. path[0] = 0;
  207168. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  207169. const String fn ((const WCHAR*) path);
  207170. comp->selectedFileChanged (File (fn));
  207171. }
  207172. }
  207173. }
  207174. }
  207175. return 0;
  207176. }
  207177. class FPComponentHolder : public Component
  207178. {
  207179. public:
  207180. FPComponentHolder()
  207181. {
  207182. setVisible (true);
  207183. setOpaque (true);
  207184. }
  207185. ~FPComponentHolder()
  207186. {
  207187. }
  207188. void paint (Graphics& g)
  207189. {
  207190. g.fillAll (Colours::lightgrey);
  207191. }
  207192. private:
  207193. FPComponentHolder (const FPComponentHolder&);
  207194. FPComponentHolder& operator= (const FPComponentHolder&);
  207195. };
  207196. }
  207197. void FileChooser::showPlatformDialog (Array<File>& results,
  207198. const String& title,
  207199. const File& currentFileOrDirectory,
  207200. const String& filter,
  207201. bool selectsDirectory,
  207202. bool /*selectsFiles*/,
  207203. bool isSaveDialogue,
  207204. bool warnAboutOverwritingExistingFiles,
  207205. bool selectMultipleFiles,
  207206. FilePreviewComponent* extraInfoComponent)
  207207. {
  207208. using namespace FileChooserHelpers;
  207209. const int numCharsAvailable = 32768;
  207210. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  207211. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  207212. int fnameIdx = 0;
  207213. JUCE_TRY
  207214. {
  207215. // use a modal window as the parent for this dialog box
  207216. // to block input from other app windows
  207217. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  207218. Component w (String::empty);
  207219. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  207220. mainMon.getY() + mainMon.getHeight() / 4,
  207221. 0, 0);
  207222. w.setOpaque (true);
  207223. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  207224. w.addToDesktop (0);
  207225. if (extraInfoComponent == 0)
  207226. w.enterModalState();
  207227. String initialDir;
  207228. if (currentFileOrDirectory.isDirectory())
  207229. {
  207230. initialDir = currentFileOrDirectory.getFullPathName();
  207231. }
  207232. else
  207233. {
  207234. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  207235. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  207236. }
  207237. if (currentExtraFileWin->isValidComponent())
  207238. {
  207239. jassertfalse;
  207240. return;
  207241. }
  207242. if (selectsDirectory)
  207243. {
  207244. LPITEMIDLIST list = 0;
  207245. filenameSpace.fillWith (0);
  207246. {
  207247. BROWSEINFO bi;
  207248. zerostruct (bi);
  207249. bi.hwndOwner = (HWND) w.getWindowHandle();
  207250. bi.pszDisplayName = fname;
  207251. bi.lpszTitle = title;
  207252. bi.lpfn = browseCallbackProc;
  207253. #ifdef BIF_USENEWUI
  207254. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  207255. #else
  207256. bi.ulFlags = 0x50;
  207257. #endif
  207258. defaultDirPath = (const WCHAR*) initialDir;
  207259. list = SHBrowseForFolder (&bi);
  207260. if (! SHGetPathFromIDListW (list, fname))
  207261. {
  207262. fname[0] = 0;
  207263. returnedString = String::empty;
  207264. }
  207265. }
  207266. LPMALLOC al;
  207267. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207268. al->Free (list);
  207269. defaultDirPath = 0;
  207270. if (returnedString.isNotEmpty())
  207271. {
  207272. const String stringFName (fname);
  207273. results.add (File (stringFName).getSiblingFile (returnedString));
  207274. returnedString = String::empty;
  207275. return;
  207276. }
  207277. }
  207278. else
  207279. {
  207280. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207281. if (warnAboutOverwritingExistingFiles)
  207282. flags |= OFN_OVERWRITEPROMPT;
  207283. if (selectMultipleFiles)
  207284. flags |= OFN_ALLOWMULTISELECT;
  207285. if (extraInfoComponent != 0)
  207286. {
  207287. flags |= OFN_ENABLEHOOK;
  207288. currentExtraFileWin = new FPComponentHolder();
  207289. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207290. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207291. extraInfoComponent->getHeight());
  207292. currentExtraFileWin->addToDesktop (0);
  207293. currentExtraFileWin->enterModalState();
  207294. }
  207295. {
  207296. WCHAR filters [1024];
  207297. zeromem (filters, sizeof (filters));
  207298. filter.copyToUnicode (filters, 1024);
  207299. filter.copyToUnicode (filters + filter.length() + 1,
  207300. 1022 - filter.length());
  207301. OPENFILENAMEW of;
  207302. zerostruct (of);
  207303. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207304. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207305. #else
  207306. of.lStructSize = sizeof (of);
  207307. #endif
  207308. of.hwndOwner = (HWND) w.getWindowHandle();
  207309. of.lpstrFilter = filters;
  207310. of.nFilterIndex = 1;
  207311. of.lpstrFile = fname;
  207312. of.nMaxFile = numCharsAvailable;
  207313. of.lpstrInitialDir = initialDir;
  207314. of.lpstrTitle = title;
  207315. of.Flags = flags;
  207316. if (extraInfoComponent != 0)
  207317. of.lpfnHook = &openCallback;
  207318. if (isSaveDialogue)
  207319. {
  207320. if (! GetSaveFileName (&of))
  207321. fname[0] = 0;
  207322. else
  207323. fnameIdx = of.nFileOffset;
  207324. }
  207325. else
  207326. {
  207327. if (! GetOpenFileName (&of))
  207328. fname[0] = 0;
  207329. else
  207330. fnameIdx = of.nFileOffset;
  207331. }
  207332. }
  207333. }
  207334. }
  207335. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207336. catch (...)
  207337. {
  207338. fname[0] = 0;
  207339. }
  207340. #endif
  207341. deleteAndZero (currentExtraFileWin);
  207342. const WCHAR* const files = fname;
  207343. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207344. {
  207345. const WCHAR* filename = files + fnameIdx;
  207346. while (*filename != 0)
  207347. {
  207348. const String filepath (String (files) + "\\" + String (filename));
  207349. results.add (File (filepath));
  207350. filename += CharacterFunctions::length (filename) + 1;
  207351. }
  207352. }
  207353. else if (files[0] != 0)
  207354. {
  207355. results.add (File (files));
  207356. }
  207357. }
  207358. #endif
  207359. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207360. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207361. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207362. // compiled on its own).
  207363. #if JUCE_INCLUDED_FILE
  207364. void SystemClipboard::copyTextToClipboard (const String& text)
  207365. {
  207366. if (OpenClipboard (0) != 0)
  207367. {
  207368. if (EmptyClipboard() != 0)
  207369. {
  207370. const int len = text.length();
  207371. if (len > 0)
  207372. {
  207373. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207374. (len + 1) * sizeof (wchar_t));
  207375. if (bufH != 0)
  207376. {
  207377. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207378. text.copyToUnicode (data, len);
  207379. GlobalUnlock (bufH);
  207380. SetClipboardData (CF_UNICODETEXT, bufH);
  207381. }
  207382. }
  207383. }
  207384. CloseClipboard();
  207385. }
  207386. }
  207387. const String SystemClipboard::getTextFromClipboard()
  207388. {
  207389. String result;
  207390. if (OpenClipboard (0) != 0)
  207391. {
  207392. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207393. if (bufH != 0)
  207394. {
  207395. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207396. if (data != 0)
  207397. {
  207398. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207399. GlobalUnlock (bufH);
  207400. }
  207401. }
  207402. CloseClipboard();
  207403. }
  207404. return result;
  207405. }
  207406. #endif
  207407. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207408. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207409. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207410. // compiled on its own).
  207411. #if JUCE_INCLUDED_FILE
  207412. namespace ActiveXHelpers
  207413. {
  207414. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207415. {
  207416. public:
  207417. JuceIStorage() {}
  207418. ~JuceIStorage() {}
  207419. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207420. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207421. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207422. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207423. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207424. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207425. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207426. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207427. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207428. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207429. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207430. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207431. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207432. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207433. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207434. juce_UseDebuggingNewOperator
  207435. };
  207436. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207437. {
  207438. HWND window;
  207439. public:
  207440. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207441. ~JuceOleInPlaceFrame() {}
  207442. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207443. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207444. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207445. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207446. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207447. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207448. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207449. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207450. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207451. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207452. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207453. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207454. juce_UseDebuggingNewOperator
  207455. };
  207456. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207457. {
  207458. HWND window;
  207459. JuceOleInPlaceFrame* frame;
  207460. public:
  207461. JuceIOleInPlaceSite (HWND window_)
  207462. : window (window_),
  207463. frame (new JuceOleInPlaceFrame (window))
  207464. {}
  207465. ~JuceIOleInPlaceSite()
  207466. {
  207467. frame->Release();
  207468. }
  207469. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207470. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207471. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207472. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207473. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207474. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207475. {
  207476. *lplpFrame = frame;
  207477. *lplpDoc = 0;
  207478. lpFrameInfo->fMDIApp = FALSE;
  207479. lpFrameInfo->hwndFrame = window;
  207480. lpFrameInfo->haccel = 0;
  207481. lpFrameInfo->cAccelEntries = 0;
  207482. return S_OK;
  207483. }
  207484. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207485. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207486. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207487. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207488. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207489. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207490. juce_UseDebuggingNewOperator
  207491. };
  207492. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207493. {
  207494. JuceIOleInPlaceSite* inplaceSite;
  207495. public:
  207496. JuceIOleClientSite (HWND window)
  207497. : inplaceSite (new JuceIOleInPlaceSite (window))
  207498. {}
  207499. ~JuceIOleClientSite()
  207500. {
  207501. inplaceSite->Release();
  207502. }
  207503. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207504. {
  207505. if (type == IID_IOleInPlaceSite)
  207506. {
  207507. inplaceSite->AddRef();
  207508. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207509. return S_OK;
  207510. }
  207511. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207512. }
  207513. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207514. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207515. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207516. HRESULT __stdcall ShowObject() { return S_OK; }
  207517. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207518. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207519. juce_UseDebuggingNewOperator
  207520. };
  207521. static Array<ActiveXControlComponent*> activeXComps;
  207522. static HWND getHWND (const ActiveXControlComponent* const component)
  207523. {
  207524. HWND hwnd = 0;
  207525. const IID iid = IID_IOleWindow;
  207526. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207527. if (window != 0)
  207528. {
  207529. window->GetWindow (&hwnd);
  207530. window->Release();
  207531. }
  207532. return hwnd;
  207533. }
  207534. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207535. {
  207536. RECT activeXRect, peerRect;
  207537. GetWindowRect (hwnd, &activeXRect);
  207538. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207539. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207540. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207541. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207542. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207543. switch (message)
  207544. {
  207545. case WM_MOUSEMOVE:
  207546. case WM_LBUTTONDOWN:
  207547. case WM_MBUTTONDOWN:
  207548. case WM_RBUTTONDOWN:
  207549. case WM_LBUTTONUP:
  207550. case WM_MBUTTONUP:
  207551. case WM_RBUTTONUP:
  207552. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207553. break;
  207554. default:
  207555. break;
  207556. }
  207557. }
  207558. }
  207559. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207560. {
  207561. ActiveXControlComponent* const owner;
  207562. bool wasShowing;
  207563. public:
  207564. HWND controlHWND;
  207565. IStorage* storage;
  207566. IOleClientSite* clientSite;
  207567. IOleObject* control;
  207568. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207569. : ComponentMovementWatcher (owner_),
  207570. owner (owner_),
  207571. wasShowing (owner_ != 0 && owner_->isShowing()),
  207572. controlHWND (0),
  207573. storage (new ActiveXHelpers::JuceIStorage()),
  207574. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207575. control (0)
  207576. {
  207577. }
  207578. ~Pimpl()
  207579. {
  207580. if (control != 0)
  207581. {
  207582. control->Close (OLECLOSE_NOSAVE);
  207583. control->Release();
  207584. }
  207585. clientSite->Release();
  207586. storage->Release();
  207587. }
  207588. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207589. {
  207590. Component* const topComp = owner->getTopLevelComponent();
  207591. if (topComp->getPeer() != 0)
  207592. {
  207593. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207594. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207595. }
  207596. }
  207597. void componentPeerChanged()
  207598. {
  207599. const bool isShowingNow = owner->isShowing();
  207600. if (wasShowing != isShowingNow)
  207601. {
  207602. wasShowing = isShowingNow;
  207603. owner->setControlVisible (isShowingNow);
  207604. }
  207605. componentMovedOrResized (true, true);
  207606. }
  207607. void componentVisibilityChanged (Component&)
  207608. {
  207609. componentPeerChanged();
  207610. }
  207611. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207612. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207613. {
  207614. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207615. {
  207616. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207617. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207618. {
  207619. switch (message)
  207620. {
  207621. case WM_MOUSEMOVE:
  207622. case WM_LBUTTONDOWN:
  207623. case WM_MBUTTONDOWN:
  207624. case WM_RBUTTONDOWN:
  207625. case WM_LBUTTONUP:
  207626. case WM_MBUTTONUP:
  207627. case WM_RBUTTONUP:
  207628. case WM_LBUTTONDBLCLK:
  207629. case WM_MBUTTONDBLCLK:
  207630. case WM_RBUTTONDBLCLK:
  207631. if (ax->isShowing())
  207632. {
  207633. ComponentPeer* const peer = ax->getPeer();
  207634. if (peer != 0)
  207635. {
  207636. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207637. if (! ax->areMouseEventsAllowed())
  207638. return 0;
  207639. }
  207640. }
  207641. break;
  207642. default:
  207643. break;
  207644. }
  207645. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207646. }
  207647. }
  207648. return DefWindowProc (hwnd, message, wParam, lParam);
  207649. }
  207650. };
  207651. ActiveXControlComponent::ActiveXControlComponent()
  207652. : originalWndProc (0),
  207653. mouseEventsAllowed (true)
  207654. {
  207655. ActiveXHelpers::activeXComps.add (this);
  207656. }
  207657. ActiveXControlComponent::~ActiveXControlComponent()
  207658. {
  207659. deleteControl();
  207660. ActiveXHelpers::activeXComps.removeValue (this);
  207661. }
  207662. void ActiveXControlComponent::paint (Graphics& g)
  207663. {
  207664. if (control == 0)
  207665. g.fillAll (Colours::lightgrey);
  207666. }
  207667. bool ActiveXControlComponent::createControl (const void* controlIID)
  207668. {
  207669. deleteControl();
  207670. ComponentPeer* const peer = getPeer();
  207671. // the component must have already been added to a real window when you call this!
  207672. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207673. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207674. {
  207675. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207676. HWND hwnd = (HWND) peer->getNativeHandle();
  207677. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207678. HRESULT hr;
  207679. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207680. newControl->clientSite, newControl->storage,
  207681. (void**) &(newControl->control))) == S_OK)
  207682. {
  207683. newControl->control->SetHostNames (L"Juce", 0);
  207684. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207685. {
  207686. RECT rect;
  207687. rect.left = pos.getX();
  207688. rect.top = pos.getY();
  207689. rect.right = pos.getX() + getWidth();
  207690. rect.bottom = pos.getY() + getHeight();
  207691. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207692. {
  207693. control = newControl;
  207694. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207695. control->controlHWND = ActiveXHelpers::getHWND (this);
  207696. if (control->controlHWND != 0)
  207697. {
  207698. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207699. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207700. }
  207701. return true;
  207702. }
  207703. }
  207704. }
  207705. }
  207706. return false;
  207707. }
  207708. void ActiveXControlComponent::deleteControl()
  207709. {
  207710. control = 0;
  207711. originalWndProc = 0;
  207712. }
  207713. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207714. {
  207715. void* result = 0;
  207716. if (control != 0 && control->control != 0
  207717. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207718. return result;
  207719. return 0;
  207720. }
  207721. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207722. {
  207723. if (control->controlHWND != 0)
  207724. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207725. }
  207726. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207727. {
  207728. if (control->controlHWND != 0)
  207729. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207730. }
  207731. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207732. {
  207733. mouseEventsAllowed = eventsCanReachControl;
  207734. }
  207735. #endif
  207736. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207737. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207738. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207739. // compiled on its own).
  207740. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207741. using namespace QTOLibrary;
  207742. using namespace QTOControlLib;
  207743. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207744. static bool isQTAvailable = false;
  207745. class QuickTimeMovieComponent::Pimpl
  207746. {
  207747. public:
  207748. Pimpl() : dataHandle (0)
  207749. {
  207750. }
  207751. ~Pimpl()
  207752. {
  207753. clearHandle();
  207754. }
  207755. void clearHandle()
  207756. {
  207757. if (dataHandle != 0)
  207758. {
  207759. DisposeHandle (dataHandle);
  207760. dataHandle = 0;
  207761. }
  207762. }
  207763. IQTControlPtr qtControl;
  207764. IQTMoviePtr qtMovie;
  207765. Handle dataHandle;
  207766. };
  207767. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207768. : movieLoaded (false),
  207769. controllerVisible (true)
  207770. {
  207771. pimpl = new Pimpl();
  207772. setMouseEventsAllowed (false);
  207773. }
  207774. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207775. {
  207776. closeMovie();
  207777. pimpl->qtControl = 0;
  207778. deleteControl();
  207779. pimpl = 0;
  207780. }
  207781. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207782. {
  207783. if (! isQTAvailable)
  207784. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207785. return isQTAvailable;
  207786. }
  207787. void QuickTimeMovieComponent::createControlIfNeeded()
  207788. {
  207789. if (isShowing() && ! isControlCreated())
  207790. {
  207791. const IID qtIID = __uuidof (QTControl);
  207792. if (createControl (&qtIID))
  207793. {
  207794. const IID qtInterfaceIID = __uuidof (IQTControl);
  207795. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207796. if (pimpl->qtControl != 0)
  207797. {
  207798. pimpl->qtControl->Release(); // it has one ref too many at this point
  207799. pimpl->qtControl->QuickTimeInitialize();
  207800. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207801. if (movieFile != File::nonexistent)
  207802. loadMovie (movieFile, controllerVisible);
  207803. }
  207804. }
  207805. }
  207806. }
  207807. bool QuickTimeMovieComponent::isControlCreated() const
  207808. {
  207809. return isControlOpen();
  207810. }
  207811. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207812. const bool isControllerVisible)
  207813. {
  207814. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207815. movieFile = File::nonexistent;
  207816. movieLoaded = false;
  207817. pimpl->qtMovie = 0;
  207818. controllerVisible = isControllerVisible;
  207819. createControlIfNeeded();
  207820. if (isControlCreated())
  207821. {
  207822. if (pimpl->qtControl != 0)
  207823. {
  207824. pimpl->qtControl->Put_MovieHandle (0);
  207825. pimpl->clearHandle();
  207826. Movie movie;
  207827. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  207828. {
  207829. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  207830. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  207831. if (pimpl->qtMovie != 0)
  207832. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  207833. : qtMovieControllerTypeNone);
  207834. }
  207835. if (movie == 0)
  207836. pimpl->clearHandle();
  207837. }
  207838. movieLoaded = (pimpl->qtMovie != 0);
  207839. }
  207840. else
  207841. {
  207842. // You're trying to open a movie when the control hasn't yet been created, probably because
  207843. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  207844. jassertfalse;
  207845. }
  207846. return movieLoaded;
  207847. }
  207848. void QuickTimeMovieComponent::closeMovie()
  207849. {
  207850. stop();
  207851. movieFile = File::nonexistent;
  207852. movieLoaded = false;
  207853. pimpl->qtMovie = 0;
  207854. if (pimpl->qtControl != 0)
  207855. pimpl->qtControl->Put_MovieHandle (0);
  207856. pimpl->clearHandle();
  207857. }
  207858. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  207859. {
  207860. return movieFile;
  207861. }
  207862. bool QuickTimeMovieComponent::isMovieOpen() const
  207863. {
  207864. return movieLoaded;
  207865. }
  207866. double QuickTimeMovieComponent::getMovieDuration() const
  207867. {
  207868. if (pimpl->qtMovie != 0)
  207869. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  207870. return 0.0;
  207871. }
  207872. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  207873. {
  207874. if (pimpl->qtMovie != 0)
  207875. {
  207876. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  207877. width = r.right - r.left;
  207878. height = r.bottom - r.top;
  207879. }
  207880. else
  207881. {
  207882. width = height = 0;
  207883. }
  207884. }
  207885. void QuickTimeMovieComponent::play()
  207886. {
  207887. if (pimpl->qtMovie != 0)
  207888. pimpl->qtMovie->Play();
  207889. }
  207890. void QuickTimeMovieComponent::stop()
  207891. {
  207892. if (pimpl->qtMovie != 0)
  207893. pimpl->qtMovie->Stop();
  207894. }
  207895. bool QuickTimeMovieComponent::isPlaying() const
  207896. {
  207897. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  207898. }
  207899. void QuickTimeMovieComponent::setPosition (const double seconds)
  207900. {
  207901. if (pimpl->qtMovie != 0)
  207902. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  207903. }
  207904. double QuickTimeMovieComponent::getPosition() const
  207905. {
  207906. if (pimpl->qtMovie != 0)
  207907. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  207908. return 0.0;
  207909. }
  207910. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  207911. {
  207912. if (pimpl->qtMovie != 0)
  207913. pimpl->qtMovie->PutRate (newSpeed);
  207914. }
  207915. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  207916. {
  207917. if (pimpl->qtMovie != 0)
  207918. {
  207919. pimpl->qtMovie->PutAudioVolume (newVolume);
  207920. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  207921. }
  207922. }
  207923. float QuickTimeMovieComponent::getMovieVolume() const
  207924. {
  207925. if (pimpl->qtMovie != 0)
  207926. return pimpl->qtMovie->GetAudioVolume();
  207927. return 0.0f;
  207928. }
  207929. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  207930. {
  207931. if (pimpl->qtMovie != 0)
  207932. pimpl->qtMovie->PutLoop (shouldLoop);
  207933. }
  207934. bool QuickTimeMovieComponent::isLooping() const
  207935. {
  207936. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  207937. }
  207938. bool QuickTimeMovieComponent::isControllerVisible() const
  207939. {
  207940. return controllerVisible;
  207941. }
  207942. void QuickTimeMovieComponent::parentHierarchyChanged()
  207943. {
  207944. createControlIfNeeded();
  207945. QTCompBaseClass::parentHierarchyChanged();
  207946. }
  207947. void QuickTimeMovieComponent::visibilityChanged()
  207948. {
  207949. createControlIfNeeded();
  207950. QTCompBaseClass::visibilityChanged();
  207951. }
  207952. void QuickTimeMovieComponent::paint (Graphics& g)
  207953. {
  207954. if (! isControlCreated())
  207955. g.fillAll (Colours::black);
  207956. }
  207957. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  207958. {
  207959. Handle dataRef = 0;
  207960. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  207961. if (err == noErr)
  207962. {
  207963. Str255 suffix;
  207964. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  207965. StringPtr name = suffix;
  207966. err = PtrAndHand (name, dataRef, name[0] + 1);
  207967. if (err == noErr)
  207968. {
  207969. long atoms[3];
  207970. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  207971. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  207972. atoms[2] = EndianU32_NtoB (MovieFileType);
  207973. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  207974. if (err == noErr)
  207975. return dataRef;
  207976. }
  207977. DisposeHandle (dataRef);
  207978. }
  207979. return 0;
  207980. }
  207981. static CFStringRef juceStringToCFString (const String& s)
  207982. {
  207983. const int len = s.length();
  207984. const juce_wchar* const t = s;
  207985. HeapBlock <UniChar> temp (len + 2);
  207986. for (int i = 0; i <= len; ++i)
  207987. temp[i] = t[i];
  207988. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  207989. }
  207990. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  207991. {
  207992. Boolean trueBool = true;
  207993. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207994. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  207995. props[prop].propValueSize = sizeof (trueBool);
  207996. props[prop].propValueAddress = &trueBool;
  207997. ++prop;
  207998. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207999. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  208000. props[prop].propValueSize = sizeof (trueBool);
  208001. props[prop].propValueAddress = &trueBool;
  208002. ++prop;
  208003. Boolean isActive = true;
  208004. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  208005. props[prop].propID = kQTNewMoviePropertyID_Active;
  208006. props[prop].propValueSize = sizeof (isActive);
  208007. props[prop].propValueAddress = &isActive;
  208008. ++prop;
  208009. MacSetPort (0);
  208010. jassert (prop <= 5);
  208011. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  208012. return err == noErr;
  208013. }
  208014. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  208015. {
  208016. if (input == 0)
  208017. return false;
  208018. dataHandle = 0;
  208019. bool ok = false;
  208020. QTNewMoviePropertyElement props[5];
  208021. zeromem (props, sizeof (props));
  208022. int prop = 0;
  208023. DataReferenceRecord dr;
  208024. props[prop].propClass = kQTPropertyClass_DataLocation;
  208025. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  208026. props[prop].propValueSize = sizeof (dr);
  208027. props[prop].propValueAddress = &dr;
  208028. ++prop;
  208029. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  208030. if (fin != 0)
  208031. {
  208032. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  208033. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  208034. &dr.dataRef, &dr.dataRefType);
  208035. ok = openMovie (props, prop, movie);
  208036. DisposeHandle (dr.dataRef);
  208037. CFRelease (filePath);
  208038. }
  208039. else
  208040. {
  208041. // sanity-check because this currently needs to load the whole stream into memory..
  208042. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  208043. dataHandle = NewHandle ((Size) input->getTotalLength());
  208044. HLock (dataHandle);
  208045. // read the entire stream into memory - this is a pain, but can't get it to work
  208046. // properly using a custom callback to supply the data.
  208047. input->read (*dataHandle, (int) input->getTotalLength());
  208048. HUnlock (dataHandle);
  208049. // different types to get QT to try. (We should really be a bit smarter here by
  208050. // working out in advance which one the stream contains, rather than just trying
  208051. // each one)
  208052. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  208053. "\04.avi", "\04.m4a" };
  208054. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  208055. {
  208056. /* // this fails for some bizarre reason - it can be bodged to work with
  208057. // movies, but can't seem to do it for other file types..
  208058. QTNewMovieUserProcRecord procInfo;
  208059. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  208060. procInfo.getMovieUserProcRefcon = this;
  208061. procInfo.defaultDataRef.dataRef = dataRef;
  208062. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  208063. props[prop].propClass = kQTPropertyClass_DataLocation;
  208064. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  208065. props[prop].propValueSize = sizeof (procInfo);
  208066. props[prop].propValueAddress = (void*) &procInfo;
  208067. ++prop; */
  208068. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  208069. dr.dataRefType = HandleDataHandlerSubType;
  208070. ok = openMovie (props, prop, movie);
  208071. DisposeHandle (dr.dataRef);
  208072. }
  208073. }
  208074. return ok;
  208075. }
  208076. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  208077. const bool isControllerVisible)
  208078. {
  208079. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  208080. movieFile = movieFile_;
  208081. return ok;
  208082. }
  208083. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  208084. const bool isControllerVisible)
  208085. {
  208086. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  208087. }
  208088. void QuickTimeMovieComponent::goToStart()
  208089. {
  208090. setPosition (0.0);
  208091. }
  208092. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  208093. const RectanglePlacement& placement)
  208094. {
  208095. int normalWidth, normalHeight;
  208096. getMovieNormalSize (normalWidth, normalHeight);
  208097. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  208098. {
  208099. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  208100. placement.applyTo (x, y, w, h,
  208101. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  208102. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  208103. if (w > 0 && h > 0)
  208104. {
  208105. setBounds (roundToInt (x), roundToInt (y),
  208106. roundToInt (w), roundToInt (h));
  208107. }
  208108. }
  208109. else
  208110. {
  208111. setBounds (spaceToFitWithin);
  208112. }
  208113. }
  208114. #endif
  208115. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  208116. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208117. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208118. // compiled on its own).
  208119. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  208120. class WebBrowserComponentInternal : public ActiveXControlComponent
  208121. {
  208122. public:
  208123. WebBrowserComponentInternal()
  208124. : browser (0),
  208125. connectionPoint (0),
  208126. adviseCookie (0)
  208127. {
  208128. }
  208129. ~WebBrowserComponentInternal()
  208130. {
  208131. if (connectionPoint != 0)
  208132. connectionPoint->Unadvise (adviseCookie);
  208133. if (browser != 0)
  208134. browser->Release();
  208135. }
  208136. void createBrowser()
  208137. {
  208138. createControl (&CLSID_WebBrowser);
  208139. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  208140. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  208141. if (connectionPointContainer != 0)
  208142. {
  208143. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  208144. &connectionPoint);
  208145. if (connectionPoint != 0)
  208146. {
  208147. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  208148. jassert (owner != 0);
  208149. EventHandler* handler = new EventHandler (owner);
  208150. connectionPoint->Advise (handler, &adviseCookie);
  208151. handler->Release();
  208152. }
  208153. }
  208154. }
  208155. void goToURL (const String& url,
  208156. const StringArray* headers,
  208157. const MemoryBlock* postData)
  208158. {
  208159. if (browser != 0)
  208160. {
  208161. LPSAFEARRAY sa = 0;
  208162. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  208163. VariantInit (&flags);
  208164. VariantInit (&frame);
  208165. VariantInit (&postDataVar);
  208166. VariantInit (&headersVar);
  208167. if (headers != 0)
  208168. {
  208169. V_VT (&headersVar) = VT_BSTR;
  208170. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  208171. }
  208172. if (postData != 0 && postData->getSize() > 0)
  208173. {
  208174. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  208175. if (sa != 0)
  208176. {
  208177. void* data = 0;
  208178. SafeArrayAccessData (sa, &data);
  208179. jassert (data != 0);
  208180. if (data != 0)
  208181. {
  208182. postData->copyTo (data, 0, postData->getSize());
  208183. SafeArrayUnaccessData (sa);
  208184. VARIANT postDataVar2;
  208185. VariantInit (&postDataVar2);
  208186. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  208187. V_ARRAY (&postDataVar2) = sa;
  208188. postDataVar = postDataVar2;
  208189. }
  208190. }
  208191. }
  208192. browser->Navigate ((BSTR) (const OLECHAR*) url,
  208193. &flags, &frame,
  208194. &postDataVar, &headersVar);
  208195. if (sa != 0)
  208196. SafeArrayDestroy (sa);
  208197. VariantClear (&flags);
  208198. VariantClear (&frame);
  208199. VariantClear (&postDataVar);
  208200. VariantClear (&headersVar);
  208201. }
  208202. }
  208203. IWebBrowser2* browser;
  208204. juce_UseDebuggingNewOperator
  208205. private:
  208206. IConnectionPoint* connectionPoint;
  208207. DWORD adviseCookie;
  208208. class EventHandler : public ComBaseClassHelper <IDispatch>,
  208209. public ComponentMovementWatcher
  208210. {
  208211. public:
  208212. EventHandler (WebBrowserComponent* owner_)
  208213. : ComponentMovementWatcher (owner_),
  208214. owner (owner_)
  208215. {
  208216. }
  208217. ~EventHandler()
  208218. {
  208219. }
  208220. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  208221. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  208222. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  208223. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  208224. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  208225. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  208226. UINT __RPC_FAR* /*puArgErr*/)
  208227. {
  208228. switch (dispIdMember)
  208229. {
  208230. case DISPID_BEFORENAVIGATE2:
  208231. {
  208232. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  208233. String url;
  208234. if ((vurl->vt & VT_BYREF) != 0)
  208235. url = *vurl->pbstrVal;
  208236. else
  208237. url = vurl->bstrVal;
  208238. *pDispParams->rgvarg->pboolVal
  208239. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  208240. : VARIANT_TRUE;
  208241. return S_OK;
  208242. }
  208243. default:
  208244. break;
  208245. }
  208246. return E_NOTIMPL;
  208247. }
  208248. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  208249. void componentPeerChanged() {}
  208250. void componentVisibilityChanged (Component&)
  208251. {
  208252. owner->visibilityChanged();
  208253. }
  208254. juce_UseDebuggingNewOperator
  208255. private:
  208256. WebBrowserComponent* const owner;
  208257. EventHandler (const EventHandler&);
  208258. EventHandler& operator= (const EventHandler&);
  208259. };
  208260. };
  208261. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  208262. : browser (0),
  208263. blankPageShown (false),
  208264. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  208265. {
  208266. setOpaque (true);
  208267. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208268. }
  208269. WebBrowserComponent::~WebBrowserComponent()
  208270. {
  208271. delete browser;
  208272. }
  208273. void WebBrowserComponent::goToURL (const String& url,
  208274. const StringArray* headers,
  208275. const MemoryBlock* postData)
  208276. {
  208277. lastURL = url;
  208278. lastHeaders.clear();
  208279. if (headers != 0)
  208280. lastHeaders = *headers;
  208281. lastPostData.setSize (0);
  208282. if (postData != 0)
  208283. lastPostData = *postData;
  208284. blankPageShown = false;
  208285. browser->goToURL (url, headers, postData);
  208286. }
  208287. void WebBrowserComponent::stop()
  208288. {
  208289. if (browser->browser != 0)
  208290. browser->browser->Stop();
  208291. }
  208292. void WebBrowserComponent::goBack()
  208293. {
  208294. lastURL = String::empty;
  208295. blankPageShown = false;
  208296. if (browser->browser != 0)
  208297. browser->browser->GoBack();
  208298. }
  208299. void WebBrowserComponent::goForward()
  208300. {
  208301. lastURL = String::empty;
  208302. if (browser->browser != 0)
  208303. browser->browser->GoForward();
  208304. }
  208305. void WebBrowserComponent::refresh()
  208306. {
  208307. if (browser->browser != 0)
  208308. browser->browser->Refresh();
  208309. }
  208310. void WebBrowserComponent::paint (Graphics& g)
  208311. {
  208312. if (browser->browser == 0)
  208313. g.fillAll (Colours::white);
  208314. }
  208315. void WebBrowserComponent::checkWindowAssociation()
  208316. {
  208317. if (isShowing())
  208318. {
  208319. if (browser->browser == 0 && getPeer() != 0)
  208320. {
  208321. browser->createBrowser();
  208322. reloadLastURL();
  208323. }
  208324. else
  208325. {
  208326. if (blankPageShown)
  208327. goBack();
  208328. }
  208329. }
  208330. else
  208331. {
  208332. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208333. {
  208334. // when the component becomes invisible, some stuff like flash
  208335. // carries on playing audio, so we need to force it onto a blank
  208336. // page to avoid this..
  208337. blankPageShown = true;
  208338. browser->goToURL ("about:blank", 0, 0);
  208339. }
  208340. }
  208341. }
  208342. void WebBrowserComponent::reloadLastURL()
  208343. {
  208344. if (lastURL.isNotEmpty())
  208345. {
  208346. goToURL (lastURL, &lastHeaders, &lastPostData);
  208347. lastURL = String::empty;
  208348. }
  208349. }
  208350. void WebBrowserComponent::parentHierarchyChanged()
  208351. {
  208352. checkWindowAssociation();
  208353. }
  208354. void WebBrowserComponent::resized()
  208355. {
  208356. browser->setSize (getWidth(), getHeight());
  208357. }
  208358. void WebBrowserComponent::visibilityChanged()
  208359. {
  208360. checkWindowAssociation();
  208361. }
  208362. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208363. {
  208364. return true;
  208365. }
  208366. #endif
  208367. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208368. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208369. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208370. // compiled on its own).
  208371. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208372. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208373. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208374. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208375. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208376. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208377. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208378. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208379. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208380. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208381. #define WGL_ACCELERATION_ARB 0x2003
  208382. #define WGL_SWAP_METHOD_ARB 0x2007
  208383. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208384. #define WGL_PIXEL_TYPE_ARB 0x2013
  208385. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208386. #define WGL_COLOR_BITS_ARB 0x2014
  208387. #define WGL_RED_BITS_ARB 0x2015
  208388. #define WGL_GREEN_BITS_ARB 0x2017
  208389. #define WGL_BLUE_BITS_ARB 0x2019
  208390. #define WGL_ALPHA_BITS_ARB 0x201B
  208391. #define WGL_DEPTH_BITS_ARB 0x2022
  208392. #define WGL_STENCIL_BITS_ARB 0x2023
  208393. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208394. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208395. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208396. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208397. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208398. #define WGL_STEREO_ARB 0x2012
  208399. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208400. #define WGL_SAMPLES_ARB 0x2042
  208401. #define WGL_TYPE_RGBA_ARB 0x202B
  208402. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208403. {
  208404. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208405. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208406. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208407. else
  208408. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208409. }
  208410. class WindowedGLContext : public OpenGLContext
  208411. {
  208412. public:
  208413. WindowedGLContext (Component* const component_,
  208414. HGLRC contextToShareWith,
  208415. const OpenGLPixelFormat& pixelFormat)
  208416. : renderContext (0),
  208417. nativeWindow (0),
  208418. dc (0),
  208419. component (component_)
  208420. {
  208421. jassert (component != 0);
  208422. createNativeWindow();
  208423. // Use a default pixel format that should be supported everywhere
  208424. PIXELFORMATDESCRIPTOR pfd;
  208425. zerostruct (pfd);
  208426. pfd.nSize = sizeof (pfd);
  208427. pfd.nVersion = 1;
  208428. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208429. pfd.iPixelType = PFD_TYPE_RGBA;
  208430. pfd.cColorBits = 24;
  208431. pfd.cDepthBits = 16;
  208432. const int format = ChoosePixelFormat (dc, &pfd);
  208433. if (format != 0)
  208434. SetPixelFormat (dc, format, &pfd);
  208435. renderContext = wglCreateContext (dc);
  208436. makeActive();
  208437. setPixelFormat (pixelFormat);
  208438. if (contextToShareWith != 0 && renderContext != 0)
  208439. wglShareLists (contextToShareWith, renderContext);
  208440. }
  208441. ~WindowedGLContext()
  208442. {
  208443. makeInactive();
  208444. wglDeleteContext (renderContext);
  208445. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208446. delete nativeWindow;
  208447. }
  208448. bool makeActive() const throw()
  208449. {
  208450. jassert (renderContext != 0);
  208451. return wglMakeCurrent (dc, renderContext) != 0;
  208452. }
  208453. bool makeInactive() const throw()
  208454. {
  208455. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208456. }
  208457. bool isActive() const throw()
  208458. {
  208459. return wglGetCurrentContext() == renderContext;
  208460. }
  208461. const OpenGLPixelFormat getPixelFormat() const
  208462. {
  208463. OpenGLPixelFormat pf;
  208464. makeActive();
  208465. StringArray availableExtensions;
  208466. getWglExtensions (dc, availableExtensions);
  208467. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208468. return pf;
  208469. }
  208470. void* getRawContext() const throw()
  208471. {
  208472. return renderContext;
  208473. }
  208474. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208475. {
  208476. makeActive();
  208477. PIXELFORMATDESCRIPTOR pfd;
  208478. zerostruct (pfd);
  208479. pfd.nSize = sizeof (pfd);
  208480. pfd.nVersion = 1;
  208481. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208482. pfd.iPixelType = PFD_TYPE_RGBA;
  208483. pfd.iLayerType = PFD_MAIN_PLANE;
  208484. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208485. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208486. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208487. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208488. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208489. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208490. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208491. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208492. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208493. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208494. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208495. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208496. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208497. int format = 0;
  208498. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208499. StringArray availableExtensions;
  208500. getWglExtensions (dc, availableExtensions);
  208501. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208502. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208503. {
  208504. int attributes[64];
  208505. int n = 0;
  208506. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208507. attributes[n++] = GL_TRUE;
  208508. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208509. attributes[n++] = GL_TRUE;
  208510. attributes[n++] = WGL_ACCELERATION_ARB;
  208511. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208512. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208513. attributes[n++] = GL_TRUE;
  208514. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208515. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208516. attributes[n++] = WGL_COLOR_BITS_ARB;
  208517. attributes[n++] = pfd.cColorBits;
  208518. attributes[n++] = WGL_RED_BITS_ARB;
  208519. attributes[n++] = pixelFormat.redBits;
  208520. attributes[n++] = WGL_GREEN_BITS_ARB;
  208521. attributes[n++] = pixelFormat.greenBits;
  208522. attributes[n++] = WGL_BLUE_BITS_ARB;
  208523. attributes[n++] = pixelFormat.blueBits;
  208524. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208525. attributes[n++] = pixelFormat.alphaBits;
  208526. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208527. attributes[n++] = pixelFormat.depthBufferBits;
  208528. if (pixelFormat.stencilBufferBits > 0)
  208529. {
  208530. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208531. attributes[n++] = pixelFormat.stencilBufferBits;
  208532. }
  208533. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208534. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208535. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208536. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208537. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208538. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208539. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208540. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208541. if (availableExtensions.contains ("WGL_ARB_multisample")
  208542. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208543. {
  208544. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208545. attributes[n++] = 1;
  208546. attributes[n++] = WGL_SAMPLES_ARB;
  208547. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208548. }
  208549. attributes[n++] = 0;
  208550. UINT formatsCount;
  208551. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208552. (void) ok;
  208553. jassert (ok);
  208554. }
  208555. else
  208556. {
  208557. format = ChoosePixelFormat (dc, &pfd);
  208558. }
  208559. if (format != 0)
  208560. {
  208561. makeInactive();
  208562. // win32 can't change the pixel format of a window, so need to delete the
  208563. // old one and create a new one..
  208564. jassert (nativeWindow != 0);
  208565. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208566. delete nativeWindow;
  208567. createNativeWindow();
  208568. if (SetPixelFormat (dc, format, &pfd))
  208569. {
  208570. wglDeleteContext (renderContext);
  208571. renderContext = wglCreateContext (dc);
  208572. jassert (renderContext != 0);
  208573. return renderContext != 0;
  208574. }
  208575. }
  208576. return false;
  208577. }
  208578. void updateWindowPosition (int x, int y, int w, int h, int)
  208579. {
  208580. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208581. x, y, w, h,
  208582. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208583. }
  208584. void repaint()
  208585. {
  208586. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208587. }
  208588. void swapBuffers()
  208589. {
  208590. SwapBuffers (dc);
  208591. }
  208592. bool setSwapInterval (int numFramesPerSwap)
  208593. {
  208594. makeActive();
  208595. StringArray availableExtensions;
  208596. getWglExtensions (dc, availableExtensions);
  208597. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208598. return availableExtensions.contains ("WGL_EXT_swap_control")
  208599. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208600. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208601. }
  208602. int getSwapInterval() const
  208603. {
  208604. makeActive();
  208605. StringArray availableExtensions;
  208606. getWglExtensions (dc, availableExtensions);
  208607. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208608. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208609. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208610. return wglGetSwapIntervalEXT();
  208611. return 0;
  208612. }
  208613. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208614. {
  208615. jassert (isActive());
  208616. StringArray availableExtensions;
  208617. getWglExtensions (dc, availableExtensions);
  208618. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208619. int numTypes = 0;
  208620. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208621. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208622. {
  208623. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208624. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208625. jassertfalse;
  208626. }
  208627. else
  208628. {
  208629. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208630. }
  208631. OpenGLPixelFormat pf;
  208632. for (int i = 0; i < numTypes; ++i)
  208633. {
  208634. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208635. {
  208636. bool alreadyListed = false;
  208637. for (int j = results.size(); --j >= 0;)
  208638. if (pf == *results.getUnchecked(j))
  208639. alreadyListed = true;
  208640. if (! alreadyListed)
  208641. results.add (new OpenGLPixelFormat (pf));
  208642. }
  208643. }
  208644. }
  208645. void* getNativeWindowHandle() const
  208646. {
  208647. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208648. }
  208649. juce_UseDebuggingNewOperator
  208650. HGLRC renderContext;
  208651. private:
  208652. Win32ComponentPeer* nativeWindow;
  208653. Component* const component;
  208654. HDC dc;
  208655. void createNativeWindow()
  208656. {
  208657. nativeWindow = new Win32ComponentPeer (component, 0);
  208658. nativeWindow->dontRepaint = true;
  208659. nativeWindow->setVisible (true);
  208660. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208661. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208662. if (peer != 0)
  208663. {
  208664. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208665. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208666. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208667. }
  208668. dc = GetDC (hwnd);
  208669. }
  208670. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208671. OpenGLPixelFormat& result,
  208672. const StringArray& availableExtensions) const throw()
  208673. {
  208674. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208675. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208676. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208677. {
  208678. int attributes[32];
  208679. int numAttributes = 0;
  208680. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208681. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208682. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208683. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208684. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208685. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208686. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208687. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208688. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208689. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208690. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208691. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208692. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208693. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208694. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208695. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208696. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208697. int values[32];
  208698. zeromem (values, sizeof (values));
  208699. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208700. {
  208701. int n = 0;
  208702. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208703. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208704. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208705. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208706. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208707. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208708. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208709. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208710. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208711. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208712. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208713. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208714. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208715. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208716. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208717. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208718. return isValidFormat;
  208719. }
  208720. else
  208721. {
  208722. jassertfalse;
  208723. }
  208724. }
  208725. else
  208726. {
  208727. PIXELFORMATDESCRIPTOR pfd;
  208728. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208729. {
  208730. result.redBits = pfd.cRedBits;
  208731. result.greenBits = pfd.cGreenBits;
  208732. result.blueBits = pfd.cBlueBits;
  208733. result.alphaBits = pfd.cAlphaBits;
  208734. result.depthBufferBits = pfd.cDepthBits;
  208735. result.stencilBufferBits = pfd.cStencilBits;
  208736. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208737. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208738. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208739. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208740. result.fullSceneAntiAliasingNumSamples = 0;
  208741. return true;
  208742. }
  208743. else
  208744. {
  208745. jassertfalse;
  208746. }
  208747. }
  208748. return false;
  208749. }
  208750. WindowedGLContext (const WindowedGLContext&);
  208751. WindowedGLContext& operator= (const WindowedGLContext&);
  208752. };
  208753. OpenGLContext* OpenGLComponent::createContext()
  208754. {
  208755. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208756. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208757. preferredPixelFormat));
  208758. return (c->renderContext != 0) ? c.release() : 0;
  208759. }
  208760. void* OpenGLComponent::getNativeWindowHandle() const
  208761. {
  208762. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208763. }
  208764. void juce_glViewport (const int w, const int h)
  208765. {
  208766. glViewport (0, 0, w, h);
  208767. }
  208768. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208769. OwnedArray <OpenGLPixelFormat>& results)
  208770. {
  208771. Component tempComp;
  208772. {
  208773. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208774. wc.makeActive();
  208775. wc.findAlternativeOpenGLPixelFormats (results);
  208776. }
  208777. }
  208778. #endif
  208779. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208780. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208781. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208782. // compiled on its own).
  208783. #if JUCE_INCLUDED_FILE
  208784. #if JUCE_USE_CDREADER
  208785. namespace CDReaderHelpers
  208786. {
  208787. //***************************************************************************
  208788. // %%% TARGET STATUS VALUES %%%
  208789. //***************************************************************************
  208790. #define STATUS_GOOD 0x00 // Status Good
  208791. #define STATUS_CHKCOND 0x02 // Check Condition
  208792. #define STATUS_CONDMET 0x04 // Condition Met
  208793. #define STATUS_BUSY 0x08 // Busy
  208794. #define STATUS_INTERM 0x10 // Intermediate
  208795. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208796. #define STATUS_RESCONF 0x18 // Reservation conflict
  208797. #define STATUS_COMTERM 0x22 // Command Terminated
  208798. #define STATUS_QFULL 0x28 // Queue full
  208799. //***************************************************************************
  208800. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208801. //***************************************************************************
  208802. #define MAXLUN 7 // Maximum Logical Unit Id
  208803. #define MAXTARG 7 // Maximum Target Id
  208804. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208805. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208806. //***************************************************************************
  208807. // %%% Commands for all Device Types %%%
  208808. //***************************************************************************
  208809. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208810. #define SCSI_COMPARE 0x39 // Compare (O)
  208811. #define SCSI_COPY 0x18 // Copy (O)
  208812. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  208813. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  208814. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  208815. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  208816. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  208817. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  208818. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  208819. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  208820. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  208821. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  208822. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  208823. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  208824. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  208825. //***************************************************************************
  208826. // %%% Commands Unique to Direct Access Devices %%%
  208827. //***************************************************************************
  208828. #define SCSI_COMPARE 0x39 // Compare (O)
  208829. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  208830. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  208831. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  208832. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  208833. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  208834. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  208835. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  208836. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  208837. #define SCSI_READ_LONG 0x3E // Read Long (O)
  208838. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  208839. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  208840. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  208841. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  208842. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  208843. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  208844. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  208845. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  208846. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  208847. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  208848. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  208849. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  208850. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  208851. #define SCSI_VERIFY 0x2F // Verify (O)
  208852. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  208853. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  208854. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  208855. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  208856. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  208857. //***************************************************************************
  208858. // %%% Commands Unique to Sequential Access Devices %%%
  208859. //***************************************************************************
  208860. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  208861. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  208862. #define SCSI_LOCATE 0x2B // Locate (O)
  208863. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  208864. #define SCSI_READ_POS 0x34 // Read Position (O)
  208865. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  208866. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  208867. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  208868. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  208869. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  208870. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  208871. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  208872. //***************************************************************************
  208873. // %%% Commands Unique to Printer Devices %%%
  208874. //***************************************************************************
  208875. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  208876. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  208877. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  208878. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  208879. //***************************************************************************
  208880. // %%% Commands Unique to Processor Devices %%%
  208881. //***************************************************************************
  208882. #define SCSI_RECEIVE 0x08 // Receive (O)
  208883. #define SCSI_SEND 0x0A // Send (O)
  208884. //***************************************************************************
  208885. // %%% Commands Unique to Write-Once Devices %%%
  208886. //***************************************************************************
  208887. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  208888. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  208889. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  208890. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  208891. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  208892. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  208893. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  208894. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  208895. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  208896. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  208897. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  208898. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  208899. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  208900. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  208901. //***************************************************************************
  208902. // %%% Commands Unique to CD-ROM Devices %%%
  208903. //***************************************************************************
  208904. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  208905. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  208906. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  208907. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  208908. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  208909. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  208910. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  208911. #define SCSI_READHEADER 0x44 // Read Header (O)
  208912. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  208913. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  208914. //***************************************************************************
  208915. // %%% Commands Unique to Scanner Devices %%%
  208916. //***************************************************************************
  208917. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  208918. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  208919. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  208920. #define SCSI_SCAN 0x1B // Scan (O)
  208921. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  208922. //***************************************************************************
  208923. // %%% Commands Unique to Optical Memory Devices %%%
  208924. //***************************************************************************
  208925. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  208926. //***************************************************************************
  208927. // %%% Commands Unique to Medium Changer Devices %%%
  208928. //***************************************************************************
  208929. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  208930. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  208931. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  208932. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  208933. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  208934. //***************************************************************************
  208935. // %%% Commands Unique to Communication Devices %%%
  208936. //***************************************************************************
  208937. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  208938. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  208939. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  208940. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  208941. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  208942. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  208943. //***************************************************************************
  208944. // %%% Request Sense Data Format %%%
  208945. //***************************************************************************
  208946. typedef struct {
  208947. BYTE ErrorCode; // Error Code (70H or 71H)
  208948. BYTE SegmentNum; // Number of current segment descriptor
  208949. BYTE SenseKey; // Sense Key(See bit definitions too)
  208950. BYTE InfoByte0; // Information MSB
  208951. BYTE InfoByte1; // Information MID
  208952. BYTE InfoByte2; // Information MID
  208953. BYTE InfoByte3; // Information LSB
  208954. BYTE AddSenLen; // Additional Sense Length
  208955. BYTE ComSpecInf0; // Command Specific Information MSB
  208956. BYTE ComSpecInf1; // Command Specific Information MID
  208957. BYTE ComSpecInf2; // Command Specific Information MID
  208958. BYTE ComSpecInf3; // Command Specific Information LSB
  208959. BYTE AddSenseCode; // Additional Sense Code
  208960. BYTE AddSenQual; // Additional Sense Code Qualifier
  208961. BYTE FieldRepUCode; // Field Replaceable Unit Code
  208962. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  208963. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  208964. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  208965. BYTE AddSenseBytes; // Additional Sense Bytes
  208966. } SENSE_DATA_FMT;
  208967. //***************************************************************************
  208968. // %%% REQUEST SENSE ERROR CODE %%%
  208969. //***************************************************************************
  208970. #define SERROR_CURRENT 0x70 // Current Errors
  208971. #define SERROR_DEFERED 0x71 // Deferred Errors
  208972. //***************************************************************************
  208973. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  208974. //***************************************************************************
  208975. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  208976. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  208977. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  208978. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  208979. //***************************************************************************
  208980. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  208981. //***************************************************************************
  208982. #define KEY_NOSENSE 0x00 // No Sense
  208983. #define KEY_RECERROR 0x01 // Recovered Error
  208984. #define KEY_NOTREADY 0x02 // Not Ready
  208985. #define KEY_MEDIUMERR 0x03 // Medium Error
  208986. #define KEY_HARDERROR 0x04 // Hardware Error
  208987. #define KEY_ILLGLREQ 0x05 // Illegal Request
  208988. #define KEY_UNITATT 0x06 // Unit Attention
  208989. #define KEY_DATAPROT 0x07 // Data Protect
  208990. #define KEY_BLANKCHK 0x08 // Blank Check
  208991. #define KEY_VENDSPEC 0x09 // Vendor Specific
  208992. #define KEY_COPYABORT 0x0A // Copy Abort
  208993. #define KEY_EQUAL 0x0C // Equal (Search)
  208994. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  208995. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  208996. #define KEY_RESERVED 0x0F // Reserved
  208997. //***************************************************************************
  208998. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  208999. //***************************************************************************
  209000. #define DTYPE_DASD 0x00 // Disk Device
  209001. #define DTYPE_SEQD 0x01 // Tape Device
  209002. #define DTYPE_PRNT 0x02 // Printer
  209003. #define DTYPE_PROC 0x03 // Processor
  209004. #define DTYPE_WORM 0x04 // Write-once read-multiple
  209005. #define DTYPE_CROM 0x05 // CD-ROM device
  209006. #define DTYPE_SCAN 0x06 // Scanner device
  209007. #define DTYPE_OPTI 0x07 // Optical memory device
  209008. #define DTYPE_JUKE 0x08 // Medium Changer device
  209009. #define DTYPE_COMM 0x09 // Communications device
  209010. #define DTYPE_RESL 0x0A // Reserved (low)
  209011. #define DTYPE_RESH 0x1E // Reserved (high)
  209012. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  209013. //***************************************************************************
  209014. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  209015. //***************************************************************************
  209016. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  209017. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  209018. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  209019. #define ANSI_RESLO 0x3 // Reserved (low)
  209020. #define ANSI_RESHI 0x7 // Reserved (high)
  209021. typedef struct
  209022. {
  209023. USHORT Length;
  209024. UCHAR ScsiStatus;
  209025. UCHAR PathId;
  209026. UCHAR TargetId;
  209027. UCHAR Lun;
  209028. UCHAR CdbLength;
  209029. UCHAR SenseInfoLength;
  209030. UCHAR DataIn;
  209031. ULONG DataTransferLength;
  209032. ULONG TimeOutValue;
  209033. ULONG DataBufferOffset;
  209034. ULONG SenseInfoOffset;
  209035. UCHAR Cdb[16];
  209036. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  209037. typedef struct
  209038. {
  209039. USHORT Length;
  209040. UCHAR ScsiStatus;
  209041. UCHAR PathId;
  209042. UCHAR TargetId;
  209043. UCHAR Lun;
  209044. UCHAR CdbLength;
  209045. UCHAR SenseInfoLength;
  209046. UCHAR DataIn;
  209047. ULONG DataTransferLength;
  209048. ULONG TimeOutValue;
  209049. PVOID DataBuffer;
  209050. ULONG SenseInfoOffset;
  209051. UCHAR Cdb[16];
  209052. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  209053. typedef struct
  209054. {
  209055. SCSI_PASS_THROUGH_DIRECT spt;
  209056. ULONG Filler;
  209057. UCHAR ucSenseBuf[32];
  209058. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  209059. typedef struct
  209060. {
  209061. ULONG Length;
  209062. UCHAR PortNumber;
  209063. UCHAR PathId;
  209064. UCHAR TargetId;
  209065. UCHAR Lun;
  209066. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  209067. #define METHOD_BUFFERED 0
  209068. #define METHOD_IN_DIRECT 1
  209069. #define METHOD_OUT_DIRECT 2
  209070. #define METHOD_NEITHER 3
  209071. #define FILE_ANY_ACCESS 0
  209072. #ifndef FILE_READ_ACCESS
  209073. #define FILE_READ_ACCESS (0x0001)
  209074. #endif
  209075. #ifndef FILE_WRITE_ACCESS
  209076. #define FILE_WRITE_ACCESS (0x0002)
  209077. #endif
  209078. #define IOCTL_SCSI_BASE 0x00000004
  209079. #define SCSI_IOCTL_DATA_OUT 0
  209080. #define SCSI_IOCTL_DATA_IN 1
  209081. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  209082. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  209083. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  209084. )
  209085. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209086. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  209087. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209088. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  209089. #define SENSE_LEN 14
  209090. #define SRB_DIR_SCSI 0x00
  209091. #define SRB_POSTING 0x01
  209092. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  209093. #define SRB_DIR_IN 0x08
  209094. #define SRB_DIR_OUT 0x10
  209095. #define SRB_EVENT_NOTIFY 0x40
  209096. #define RESIDUAL_COUNT_SUPPORTED 0x02
  209097. #define MAX_SRB_TIMEOUT 1080001u
  209098. #define DEFAULT_SRB_TIMEOUT 1080001u
  209099. #define SC_HA_INQUIRY 0x00
  209100. #define SC_GET_DEV_TYPE 0x01
  209101. #define SC_EXEC_SCSI_CMD 0x02
  209102. #define SC_ABORT_SRB 0x03
  209103. #define SC_RESET_DEV 0x04
  209104. #define SC_SET_HA_PARMS 0x05
  209105. #define SC_GET_DISK_INFO 0x06
  209106. #define SC_RESCAN_SCSI_BUS 0x07
  209107. #define SC_GETSET_TIMEOUTS 0x08
  209108. #define SS_PENDING 0x00
  209109. #define SS_COMP 0x01
  209110. #define SS_ABORTED 0x02
  209111. #define SS_ABORT_FAIL 0x03
  209112. #define SS_ERR 0x04
  209113. #define SS_INVALID_CMD 0x80
  209114. #define SS_INVALID_HA 0x81
  209115. #define SS_NO_DEVICE 0x82
  209116. #define SS_INVALID_SRB 0xE0
  209117. #define SS_OLD_MANAGER 0xE1
  209118. #define SS_BUFFER_ALIGN 0xE1
  209119. #define SS_ILLEGAL_MODE 0xE2
  209120. #define SS_NO_ASPI 0xE3
  209121. #define SS_FAILED_INIT 0xE4
  209122. #define SS_ASPI_IS_BUSY 0xE5
  209123. #define SS_BUFFER_TO_BIG 0xE6
  209124. #define SS_BUFFER_TOO_BIG 0xE6
  209125. #define SS_MISMATCHED_COMPONENTS 0xE7
  209126. #define SS_NO_ADAPTERS 0xE8
  209127. #define SS_INSUFFICIENT_RESOURCES 0xE9
  209128. #define SS_ASPI_IS_SHUTDOWN 0xEA
  209129. #define SS_BAD_INSTALL 0xEB
  209130. #define HASTAT_OK 0x00
  209131. #define HASTAT_SEL_TO 0x11
  209132. #define HASTAT_DO_DU 0x12
  209133. #define HASTAT_BUS_FREE 0x13
  209134. #define HASTAT_PHASE_ERR 0x14
  209135. #define HASTAT_TIMEOUT 0x09
  209136. #define HASTAT_COMMAND_TIMEOUT 0x0B
  209137. #define HASTAT_MESSAGE_REJECT 0x0D
  209138. #define HASTAT_BUS_RESET 0x0E
  209139. #define HASTAT_PARITY_ERROR 0x0F
  209140. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  209141. #define PACKED
  209142. #pragma pack(1)
  209143. typedef struct
  209144. {
  209145. BYTE SRB_Cmd;
  209146. BYTE SRB_Status;
  209147. BYTE SRB_HaID;
  209148. BYTE SRB_Flags;
  209149. DWORD SRB_Hdr_Rsvd;
  209150. BYTE HA_Count;
  209151. BYTE HA_SCSI_ID;
  209152. BYTE HA_ManagerId[16];
  209153. BYTE HA_Identifier[16];
  209154. BYTE HA_Unique[16];
  209155. WORD HA_Rsvd1;
  209156. BYTE pad[20];
  209157. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  209158. typedef struct
  209159. {
  209160. BYTE SRB_Cmd;
  209161. BYTE SRB_Status;
  209162. BYTE SRB_HaID;
  209163. BYTE SRB_Flags;
  209164. DWORD SRB_Hdr_Rsvd;
  209165. BYTE SRB_Target;
  209166. BYTE SRB_Lun;
  209167. BYTE SRB_DeviceType;
  209168. BYTE SRB_Rsvd1;
  209169. BYTE pad[68];
  209170. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  209171. typedef struct
  209172. {
  209173. BYTE SRB_Cmd;
  209174. BYTE SRB_Status;
  209175. BYTE SRB_HaID;
  209176. BYTE SRB_Flags;
  209177. DWORD SRB_Hdr_Rsvd;
  209178. BYTE SRB_Target;
  209179. BYTE SRB_Lun;
  209180. WORD SRB_Rsvd1;
  209181. DWORD SRB_BufLen;
  209182. BYTE FAR *SRB_BufPointer;
  209183. BYTE SRB_SenseLen;
  209184. BYTE SRB_CDBLen;
  209185. BYTE SRB_HaStat;
  209186. BYTE SRB_TargStat;
  209187. VOID FAR *SRB_PostProc;
  209188. BYTE SRB_Rsvd2[20];
  209189. BYTE CDBByte[16];
  209190. BYTE SenseArea[SENSE_LEN+2];
  209191. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  209192. typedef struct
  209193. {
  209194. BYTE SRB_Cmd;
  209195. BYTE SRB_Status;
  209196. BYTE SRB_HaId;
  209197. BYTE SRB_Flags;
  209198. DWORD SRB_Hdr_Rsvd;
  209199. } PACKED SRB, *PSRB, FAR *LPSRB;
  209200. #pragma pack()
  209201. struct CDDeviceInfo
  209202. {
  209203. char vendor[9];
  209204. char productId[17];
  209205. char rev[5];
  209206. char vendorSpec[21];
  209207. BYTE ha;
  209208. BYTE tgt;
  209209. BYTE lun;
  209210. char scsiDriveLetter; // will be 0 if not using scsi
  209211. };
  209212. class CDReadBuffer
  209213. {
  209214. public:
  209215. int startFrame;
  209216. int numFrames;
  209217. int dataStartOffset;
  209218. int dataLength;
  209219. int bufferSize;
  209220. HeapBlock<BYTE> buffer;
  209221. int index;
  209222. bool wantsIndex;
  209223. CDReadBuffer (const int numberOfFrames)
  209224. : startFrame (0),
  209225. numFrames (0),
  209226. dataStartOffset (0),
  209227. dataLength (0),
  209228. bufferSize (2352 * numberOfFrames),
  209229. buffer (bufferSize),
  209230. index (0),
  209231. wantsIndex (false)
  209232. {
  209233. }
  209234. bool isZero() const throw()
  209235. {
  209236. BYTE* p = buffer + dataStartOffset;
  209237. for (int i = dataLength; --i >= 0;)
  209238. if (*p++ != 0)
  209239. return false;
  209240. return true;
  209241. }
  209242. };
  209243. class CDDeviceHandle;
  209244. class CDController
  209245. {
  209246. public:
  209247. CDController();
  209248. virtual ~CDController();
  209249. virtual bool read (CDReadBuffer* t) = 0;
  209250. virtual void shutDown();
  209251. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  209252. int getLastIndex();
  209253. public:
  209254. bool initialised;
  209255. CDDeviceHandle* deviceInfo;
  209256. int framesToCheck, framesOverlap;
  209257. void prepare (SRB_ExecSCSICmd& s);
  209258. void perform (SRB_ExecSCSICmd& s);
  209259. void setPaused (bool paused);
  209260. };
  209261. #pragma pack(1)
  209262. struct TOCTRACK
  209263. {
  209264. BYTE rsvd;
  209265. BYTE ADR;
  209266. BYTE trackNumber;
  209267. BYTE rsvd2;
  209268. BYTE addr[4];
  209269. };
  209270. struct TOC
  209271. {
  209272. WORD tocLen;
  209273. BYTE firstTrack;
  209274. BYTE lastTrack;
  209275. TOCTRACK tracks[100];
  209276. };
  209277. #pragma pack()
  209278. enum
  209279. {
  209280. READTYPE_ANY = 0,
  209281. READTYPE_ATAPI1 = 1,
  209282. READTYPE_ATAPI2 = 2,
  209283. READTYPE_READ6 = 3,
  209284. READTYPE_READ10 = 4,
  209285. READTYPE_READ_D8 = 5,
  209286. READTYPE_READ_D4 = 6,
  209287. READTYPE_READ_D4_1 = 7,
  209288. READTYPE_READ10_2 = 8
  209289. };
  209290. class CDDeviceHandle
  209291. {
  209292. public:
  209293. CDDeviceHandle (const CDDeviceInfo* const device)
  209294. : scsiHandle (0),
  209295. readType (READTYPE_ANY),
  209296. controller (0)
  209297. {
  209298. memcpy (&info, device, sizeof (info));
  209299. }
  209300. ~CDDeviceHandle()
  209301. {
  209302. if (controller != 0)
  209303. {
  209304. controller->shutDown();
  209305. controller = 0;
  209306. }
  209307. if (scsiHandle != 0)
  209308. CloseHandle (scsiHandle);
  209309. }
  209310. bool readTOC (TOC* lpToc, bool useMSF);
  209311. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209312. void openDrawer (bool shouldBeOpen);
  209313. CDDeviceInfo info;
  209314. HANDLE scsiHandle;
  209315. BYTE readType;
  209316. private:
  209317. ScopedPointer<CDController> controller;
  209318. bool testController (const int readType,
  209319. CDController* const newController,
  209320. CDReadBuffer* const bufferToUse);
  209321. };
  209322. DWORD (*fGetASPI32SupportInfo)(void);
  209323. DWORD (*fSendASPI32Command)(LPSRB);
  209324. static HINSTANCE winAspiLib = 0;
  209325. static bool usingScsi = false;
  209326. static bool initialised = false;
  209327. static bool InitialiseCDRipper()
  209328. {
  209329. if (! initialised)
  209330. {
  209331. initialised = true;
  209332. OSVERSIONINFO info;
  209333. info.dwOSVersionInfoSize = sizeof (info);
  209334. GetVersionEx (&info);
  209335. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209336. if (! usingScsi)
  209337. {
  209338. fGetASPI32SupportInfo = 0;
  209339. fSendASPI32Command = 0;
  209340. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209341. if (winAspiLib != 0)
  209342. {
  209343. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209344. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209345. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209346. return false;
  209347. }
  209348. else
  209349. {
  209350. usingScsi = true;
  209351. }
  209352. }
  209353. }
  209354. return true;
  209355. }
  209356. static void DeinitialiseCDRipper()
  209357. {
  209358. if (winAspiLib != 0)
  209359. {
  209360. fGetASPI32SupportInfo = 0;
  209361. fSendASPI32Command = 0;
  209362. FreeLibrary (winAspiLib);
  209363. winAspiLib = 0;
  209364. }
  209365. initialised = false;
  209366. }
  209367. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209368. {
  209369. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209370. OSVERSIONINFO info;
  209371. info.dwOSVersionInfoSize = sizeof (info);
  209372. GetVersionEx (&info);
  209373. DWORD flags = GENERIC_READ;
  209374. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209375. flags = GENERIC_READ | GENERIC_WRITE;
  209376. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209377. if (h == INVALID_HANDLE_VALUE)
  209378. {
  209379. flags ^= GENERIC_WRITE;
  209380. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209381. }
  209382. return h;
  209383. }
  209384. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209385. const char driveLetter,
  209386. HANDLE& deviceHandle,
  209387. const bool retryOnFailure = true)
  209388. {
  209389. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209390. zerostruct (s);
  209391. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209392. s.spt.CdbLength = srb->SRB_CDBLen;
  209393. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209394. ? SCSI_IOCTL_DATA_IN
  209395. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209396. ? SCSI_IOCTL_DATA_OUT
  209397. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209398. s.spt.DataTransferLength = srb->SRB_BufLen;
  209399. s.spt.TimeOutValue = 5;
  209400. s.spt.DataBuffer = srb->SRB_BufPointer;
  209401. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209402. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209403. srb->SRB_Status = SS_ERR;
  209404. srb->SRB_TargStat = 0x0004;
  209405. DWORD bytesReturned = 0;
  209406. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209407. &s, sizeof (s),
  209408. &s, sizeof (s),
  209409. &bytesReturned, 0) != 0)
  209410. {
  209411. srb->SRB_Status = SS_COMP;
  209412. }
  209413. else if (retryOnFailure)
  209414. {
  209415. const DWORD error = GetLastError();
  209416. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209417. {
  209418. if (error != ERROR_INVALID_HANDLE)
  209419. CloseHandle (deviceHandle);
  209420. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209421. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209422. }
  209423. }
  209424. return srb->SRB_Status;
  209425. }
  209426. // Controller types..
  209427. class ControllerType1 : public CDController
  209428. {
  209429. public:
  209430. ControllerType1() {}
  209431. ~ControllerType1() {}
  209432. bool read (CDReadBuffer* rb)
  209433. {
  209434. if (rb->numFrames * 2352 > rb->bufferSize)
  209435. return false;
  209436. SRB_ExecSCSICmd s;
  209437. prepare (s);
  209438. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209439. s.SRB_BufLen = rb->bufferSize;
  209440. s.SRB_BufPointer = rb->buffer;
  209441. s.SRB_CDBLen = 12;
  209442. s.CDBByte[0] = 0xBE;
  209443. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209444. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209445. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209446. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209447. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209448. perform (s);
  209449. if (s.SRB_Status != SS_COMP)
  209450. return false;
  209451. rb->dataLength = rb->numFrames * 2352;
  209452. rb->dataStartOffset = 0;
  209453. return true;
  209454. }
  209455. };
  209456. class ControllerType2 : public CDController
  209457. {
  209458. public:
  209459. ControllerType2() {}
  209460. ~ControllerType2() {}
  209461. void shutDown()
  209462. {
  209463. if (initialised)
  209464. {
  209465. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209466. SRB_ExecSCSICmd s;
  209467. prepare (s);
  209468. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209469. s.SRB_BufLen = 0x0C;
  209470. s.SRB_BufPointer = bufPointer;
  209471. s.SRB_CDBLen = 6;
  209472. s.CDBByte[0] = 0x15;
  209473. s.CDBByte[4] = 0x0C;
  209474. perform (s);
  209475. }
  209476. }
  209477. bool init()
  209478. {
  209479. SRB_ExecSCSICmd s;
  209480. s.SRB_Status = SS_ERR;
  209481. if (deviceInfo->readType == READTYPE_READ10_2)
  209482. {
  209483. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209484. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209485. for (int i = 0; i < 2; ++i)
  209486. {
  209487. prepare (s);
  209488. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209489. s.SRB_BufLen = 0x14;
  209490. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209491. s.SRB_CDBLen = 6;
  209492. s.CDBByte[0] = 0x15;
  209493. s.CDBByte[1] = 0x10;
  209494. s.CDBByte[4] = 0x14;
  209495. perform (s);
  209496. if (s.SRB_Status != SS_COMP)
  209497. return false;
  209498. }
  209499. }
  209500. else
  209501. {
  209502. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209503. prepare (s);
  209504. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209505. s.SRB_BufLen = 0x0C;
  209506. s.SRB_BufPointer = bufPointer;
  209507. s.SRB_CDBLen = 6;
  209508. s.CDBByte[0] = 0x15;
  209509. s.CDBByte[4] = 0x0C;
  209510. perform (s);
  209511. }
  209512. return s.SRB_Status == SS_COMP;
  209513. }
  209514. bool read (CDReadBuffer* rb)
  209515. {
  209516. if (rb->numFrames * 2352 > rb->bufferSize)
  209517. return false;
  209518. if (!initialised)
  209519. {
  209520. initialised = init();
  209521. if (!initialised)
  209522. return false;
  209523. }
  209524. SRB_ExecSCSICmd s;
  209525. prepare (s);
  209526. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209527. s.SRB_BufLen = rb->bufferSize;
  209528. s.SRB_BufPointer = rb->buffer;
  209529. s.SRB_CDBLen = 10;
  209530. s.CDBByte[0] = 0x28;
  209531. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209532. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209533. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209534. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209535. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209536. perform (s);
  209537. if (s.SRB_Status != SS_COMP)
  209538. return false;
  209539. rb->dataLength = rb->numFrames * 2352;
  209540. rb->dataStartOffset = 0;
  209541. return true;
  209542. }
  209543. };
  209544. class ControllerType3 : public CDController
  209545. {
  209546. public:
  209547. ControllerType3() {}
  209548. ~ControllerType3() {}
  209549. bool read (CDReadBuffer* rb)
  209550. {
  209551. if (rb->numFrames * 2352 > rb->bufferSize)
  209552. return false;
  209553. if (!initialised)
  209554. {
  209555. setPaused (false);
  209556. initialised = true;
  209557. }
  209558. SRB_ExecSCSICmd s;
  209559. prepare (s);
  209560. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209561. s.SRB_BufLen = rb->numFrames * 2352;
  209562. s.SRB_BufPointer = rb->buffer;
  209563. s.SRB_CDBLen = 12;
  209564. s.CDBByte[0] = 0xD8;
  209565. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209566. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209567. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209568. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209569. perform (s);
  209570. if (s.SRB_Status != SS_COMP)
  209571. return false;
  209572. rb->dataLength = rb->numFrames * 2352;
  209573. rb->dataStartOffset = 0;
  209574. return true;
  209575. }
  209576. };
  209577. class ControllerType4 : public CDController
  209578. {
  209579. public:
  209580. ControllerType4() {}
  209581. ~ControllerType4() {}
  209582. bool selectD4Mode()
  209583. {
  209584. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209585. SRB_ExecSCSICmd s;
  209586. prepare (s);
  209587. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209588. s.SRB_CDBLen = 6;
  209589. s.SRB_BufLen = 12;
  209590. s.SRB_BufPointer = bufPointer;
  209591. s.CDBByte[0] = 0x15;
  209592. s.CDBByte[1] = 0x10;
  209593. s.CDBByte[4] = 0x08;
  209594. perform (s);
  209595. return s.SRB_Status == SS_COMP;
  209596. }
  209597. bool read (CDReadBuffer* rb)
  209598. {
  209599. if (rb->numFrames * 2352 > rb->bufferSize)
  209600. return false;
  209601. if (!initialised)
  209602. {
  209603. setPaused (true);
  209604. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209605. selectD4Mode();
  209606. initialised = true;
  209607. }
  209608. SRB_ExecSCSICmd s;
  209609. prepare (s);
  209610. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209611. s.SRB_BufLen = rb->bufferSize;
  209612. s.SRB_BufPointer = rb->buffer;
  209613. s.SRB_CDBLen = 10;
  209614. s.CDBByte[0] = 0xD4;
  209615. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209616. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209617. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209618. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209619. perform (s);
  209620. if (s.SRB_Status != SS_COMP)
  209621. return false;
  209622. rb->dataLength = rb->numFrames * 2352;
  209623. rb->dataStartOffset = 0;
  209624. return true;
  209625. }
  209626. };
  209627. CDController::CDController() : initialised (false)
  209628. {
  209629. }
  209630. CDController::~CDController()
  209631. {
  209632. }
  209633. void CDController::prepare (SRB_ExecSCSICmd& s)
  209634. {
  209635. zerostruct (s);
  209636. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209637. s.SRB_HaID = deviceInfo->info.ha;
  209638. s.SRB_Target = deviceInfo->info.tgt;
  209639. s.SRB_Lun = deviceInfo->info.lun;
  209640. s.SRB_SenseLen = SENSE_LEN;
  209641. }
  209642. void CDController::perform (SRB_ExecSCSICmd& s)
  209643. {
  209644. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209645. s.SRB_PostProc = event;
  209646. ResetEvent (event);
  209647. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209648. deviceInfo->info.scsiDriveLetter,
  209649. deviceInfo->scsiHandle)
  209650. : fSendASPI32Command ((LPSRB)&s);
  209651. if (status == SS_PENDING)
  209652. WaitForSingleObject (event, 4000);
  209653. CloseHandle (event);
  209654. }
  209655. void CDController::setPaused (bool paused)
  209656. {
  209657. SRB_ExecSCSICmd s;
  209658. prepare (s);
  209659. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209660. s.SRB_CDBLen = 10;
  209661. s.CDBByte[0] = 0x4B;
  209662. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209663. perform (s);
  209664. }
  209665. void CDController::shutDown()
  209666. {
  209667. }
  209668. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209669. {
  209670. if (overlapBuffer != 0)
  209671. {
  209672. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209673. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209674. if (doJitter
  209675. && overlapBuffer->startFrame > 0
  209676. && overlapBuffer->numFrames > 0
  209677. && overlapBuffer->dataLength > 0)
  209678. {
  209679. const int numFrames = rb->numFrames;
  209680. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209681. {
  209682. rb->startFrame -= framesOverlap;
  209683. if (framesToCheck < framesOverlap
  209684. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209685. rb->numFrames += framesOverlap;
  209686. }
  209687. else
  209688. {
  209689. overlapBuffer->dataLength = 0;
  209690. overlapBuffer->startFrame = 0;
  209691. overlapBuffer->numFrames = 0;
  209692. }
  209693. }
  209694. if (! read (rb))
  209695. return false;
  209696. if (doJitter)
  209697. {
  209698. const int checkLen = framesToCheck * 2352;
  209699. const int maxToCheck = rb->dataLength - checkLen;
  209700. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209701. return true;
  209702. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209703. bool found = false;
  209704. for (int i = 0; i < maxToCheck; ++i)
  209705. {
  209706. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209707. {
  209708. i += checkLen;
  209709. rb->dataStartOffset = i;
  209710. rb->dataLength -= i;
  209711. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209712. found = true;
  209713. break;
  209714. }
  209715. }
  209716. rb->numFrames = rb->dataLength / 2352;
  209717. rb->dataLength = 2352 * rb->numFrames;
  209718. if (!found)
  209719. return false;
  209720. }
  209721. if (canDoJitter)
  209722. {
  209723. memcpy (overlapBuffer->buffer,
  209724. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209725. 2352 * framesToCheck);
  209726. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209727. overlapBuffer->numFrames = framesToCheck;
  209728. overlapBuffer->dataLength = 2352 * framesToCheck;
  209729. overlapBuffer->dataStartOffset = 0;
  209730. }
  209731. else
  209732. {
  209733. overlapBuffer->startFrame = 0;
  209734. overlapBuffer->numFrames = 0;
  209735. overlapBuffer->dataLength = 0;
  209736. }
  209737. return true;
  209738. }
  209739. else
  209740. {
  209741. return read (rb);
  209742. }
  209743. }
  209744. int CDController::getLastIndex()
  209745. {
  209746. char qdata[100];
  209747. SRB_ExecSCSICmd s;
  209748. prepare (s);
  209749. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209750. s.SRB_BufLen = sizeof (qdata);
  209751. s.SRB_BufPointer = (BYTE*)qdata;
  209752. s.SRB_CDBLen = 12;
  209753. s.CDBByte[0] = 0x42;
  209754. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209755. s.CDBByte[2] = 64;
  209756. s.CDBByte[3] = 1; // get current position
  209757. s.CDBByte[7] = 0;
  209758. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209759. perform (s);
  209760. if (s.SRB_Status == SS_COMP)
  209761. return qdata[7];
  209762. return 0;
  209763. }
  209764. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209765. {
  209766. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209767. SRB_ExecSCSICmd s;
  209768. zerostruct (s);
  209769. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209770. s.SRB_HaID = info.ha;
  209771. s.SRB_Target = info.tgt;
  209772. s.SRB_Lun = info.lun;
  209773. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209774. s.SRB_BufLen = 0x324;
  209775. s.SRB_BufPointer = (BYTE*)lpToc;
  209776. s.SRB_SenseLen = 0x0E;
  209777. s.SRB_CDBLen = 0x0A;
  209778. s.SRB_PostProc = event;
  209779. s.CDBByte[0] = 0x43;
  209780. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209781. s.CDBByte[7] = 0x03;
  209782. s.CDBByte[8] = 0x24;
  209783. ResetEvent (event);
  209784. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209785. : fSendASPI32Command ((LPSRB)&s);
  209786. if (status == SS_PENDING)
  209787. WaitForSingleObject (event, 4000);
  209788. CloseHandle (event);
  209789. return (s.SRB_Status == SS_COMP);
  209790. }
  209791. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209792. CDReadBuffer* const overlapBuffer)
  209793. {
  209794. if (controller == 0)
  209795. {
  209796. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209797. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209798. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209799. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209800. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209801. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209802. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209803. }
  209804. buffer->index = 0;
  209805. if ((controller != 0)
  209806. && controller->readAudio (buffer, overlapBuffer))
  209807. {
  209808. if (buffer->wantsIndex)
  209809. buffer->index = controller->getLastIndex();
  209810. return true;
  209811. }
  209812. return false;
  209813. }
  209814. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  209815. {
  209816. if (shouldBeOpen)
  209817. {
  209818. if (controller != 0)
  209819. {
  209820. controller->shutDown();
  209821. controller = 0;
  209822. }
  209823. if (scsiHandle != 0)
  209824. {
  209825. CloseHandle (scsiHandle);
  209826. scsiHandle = 0;
  209827. }
  209828. }
  209829. SRB_ExecSCSICmd s;
  209830. zerostruct (s);
  209831. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209832. s.SRB_HaID = info.ha;
  209833. s.SRB_Target = info.tgt;
  209834. s.SRB_Lun = info.lun;
  209835. s.SRB_SenseLen = SENSE_LEN;
  209836. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209837. s.SRB_BufLen = 0;
  209838. s.SRB_BufPointer = 0;
  209839. s.SRB_CDBLen = 12;
  209840. s.CDBByte[0] = 0x1b;
  209841. s.CDBByte[1] = (BYTE)(info.lun << 5);
  209842. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  209843. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209844. s.SRB_PostProc = event;
  209845. ResetEvent (event);
  209846. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209847. : fSendASPI32Command ((LPSRB)&s);
  209848. if (status == SS_PENDING)
  209849. WaitForSingleObject (event, 4000);
  209850. CloseHandle (event);
  209851. }
  209852. bool CDDeviceHandle::testController (const int type,
  209853. CDController* const newController,
  209854. CDReadBuffer* const rb)
  209855. {
  209856. controller = newController;
  209857. readType = (BYTE)type;
  209858. controller->deviceInfo = this;
  209859. controller->framesToCheck = 1;
  209860. controller->framesOverlap = 3;
  209861. bool passed = false;
  209862. memset (rb->buffer, 0xcd, rb->bufferSize);
  209863. if (controller->read (rb))
  209864. {
  209865. passed = true;
  209866. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  209867. int wrong = 0;
  209868. for (int i = rb->dataLength / 4; --i >= 0;)
  209869. {
  209870. if (*p++ == (int) 0xcdcdcdcd)
  209871. {
  209872. if (++wrong == 4)
  209873. {
  209874. passed = false;
  209875. break;
  209876. }
  209877. }
  209878. else
  209879. {
  209880. wrong = 0;
  209881. }
  209882. }
  209883. }
  209884. if (! passed)
  209885. {
  209886. controller->shutDown();
  209887. controller = 0;
  209888. }
  209889. return passed;
  209890. }
  209891. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  209892. {
  209893. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209894. const int bufSize = 128;
  209895. BYTE buffer[bufSize];
  209896. zeromem (buffer, bufSize);
  209897. SRB_ExecSCSICmd s;
  209898. zerostruct (s);
  209899. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209900. s.SRB_HaID = ha;
  209901. s.SRB_Target = tgt;
  209902. s.SRB_Lun = lun;
  209903. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209904. s.SRB_BufLen = bufSize;
  209905. s.SRB_BufPointer = buffer;
  209906. s.SRB_SenseLen = SENSE_LEN;
  209907. s.SRB_CDBLen = 6;
  209908. s.SRB_PostProc = event;
  209909. s.CDBByte[0] = SCSI_INQUIRY;
  209910. s.CDBByte[4] = 100;
  209911. ResetEvent (event);
  209912. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  209913. WaitForSingleObject (event, 4000);
  209914. CloseHandle (event);
  209915. if (s.SRB_Status == SS_COMP)
  209916. {
  209917. memcpy (dev->vendor, &buffer[8], 8);
  209918. memcpy (dev->productId, &buffer[16], 16);
  209919. memcpy (dev->rev, &buffer[32], 4);
  209920. memcpy (dev->vendorSpec, &buffer[36], 20);
  209921. }
  209922. }
  209923. static int FindCDDevices (CDDeviceInfo* const list,
  209924. int maxItems)
  209925. {
  209926. int count = 0;
  209927. if (usingScsi)
  209928. {
  209929. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  209930. {
  209931. TCHAR drivePath[8];
  209932. drivePath[0] = driveLetter;
  209933. drivePath[1] = ':';
  209934. drivePath[2] = '\\';
  209935. drivePath[3] = 0;
  209936. if (GetDriveType (drivePath) == DRIVE_CDROM)
  209937. {
  209938. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  209939. if (h != INVALID_HANDLE_VALUE)
  209940. {
  209941. BYTE buffer[100], passThroughStruct[1024];
  209942. zeromem (buffer, sizeof (buffer));
  209943. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209944. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  209945. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  209946. p->spt.CdbLength = 6;
  209947. p->spt.SenseInfoLength = 24;
  209948. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  209949. p->spt.DataTransferLength = 100;
  209950. p->spt.TimeOutValue = 2;
  209951. p->spt.DataBuffer = buffer;
  209952. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209953. p->spt.Cdb[0] = 0x12;
  209954. p->spt.Cdb[4] = 100;
  209955. DWORD bytesReturned = 0;
  209956. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209957. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209958. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209959. &bytesReturned, 0) != 0)
  209960. {
  209961. zeromem (&list[count], sizeof (CDDeviceInfo));
  209962. list[count].scsiDriveLetter = driveLetter;
  209963. memcpy (list[count].vendor, &buffer[8], 8);
  209964. memcpy (list[count].productId, &buffer[16], 16);
  209965. memcpy (list[count].rev, &buffer[32], 4);
  209966. memcpy (list[count].vendorSpec, &buffer[36], 20);
  209967. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209968. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  209969. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  209970. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  209971. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  209972. &bytesReturned, 0) != 0)
  209973. {
  209974. list[count].ha = scsiAddr->PortNumber;
  209975. list[count].tgt = scsiAddr->TargetId;
  209976. list[count].lun = scsiAddr->Lun;
  209977. ++count;
  209978. }
  209979. }
  209980. CloseHandle (h);
  209981. }
  209982. }
  209983. }
  209984. }
  209985. else
  209986. {
  209987. const DWORD d = fGetASPI32SupportInfo();
  209988. BYTE status = HIBYTE (LOWORD (d));
  209989. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  209990. return 0;
  209991. const int numAdapters = LOBYTE (LOWORD (d));
  209992. for (BYTE ha = 0; ha < numAdapters; ++ha)
  209993. {
  209994. SRB_HAInquiry s;
  209995. zerostruct (s);
  209996. s.SRB_Cmd = SC_HA_INQUIRY;
  209997. s.SRB_HaID = ha;
  209998. fSendASPI32Command ((LPSRB)&s);
  209999. if (s.SRB_Status == SS_COMP)
  210000. {
  210001. maxItems = (int)s.HA_Unique[3];
  210002. if (maxItems == 0)
  210003. maxItems = 8;
  210004. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  210005. {
  210006. for (BYTE lun = 0; lun < 8; ++lun)
  210007. {
  210008. SRB_GDEVBlock sb;
  210009. zerostruct (sb);
  210010. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  210011. sb.SRB_HaID = ha;
  210012. sb.SRB_Target = tgt;
  210013. sb.SRB_Lun = lun;
  210014. fSendASPI32Command ((LPSRB) &sb);
  210015. if (sb.SRB_Status == SS_COMP
  210016. && sb.SRB_DeviceType == DTYPE_CROM)
  210017. {
  210018. zeromem (&list[count], sizeof (CDDeviceInfo));
  210019. list[count].ha = ha;
  210020. list[count].tgt = tgt;
  210021. list[count].lun = lun;
  210022. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  210023. ++count;
  210024. }
  210025. }
  210026. }
  210027. }
  210028. }
  210029. }
  210030. return count;
  210031. }
  210032. static int ripperUsers = 0;
  210033. static bool initialisedOk = false;
  210034. class DeinitialiseTimer : private Timer,
  210035. private DeletedAtShutdown
  210036. {
  210037. DeinitialiseTimer (const DeinitialiseTimer&);
  210038. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  210039. public:
  210040. DeinitialiseTimer()
  210041. {
  210042. startTimer (4000);
  210043. }
  210044. ~DeinitialiseTimer()
  210045. {
  210046. if (--ripperUsers == 0)
  210047. DeinitialiseCDRipper();
  210048. }
  210049. void timerCallback()
  210050. {
  210051. delete this;
  210052. }
  210053. juce_UseDebuggingNewOperator
  210054. };
  210055. static void incUserCount()
  210056. {
  210057. if (ripperUsers++ == 0)
  210058. initialisedOk = InitialiseCDRipper();
  210059. }
  210060. static void decUserCount()
  210061. {
  210062. new DeinitialiseTimer();
  210063. }
  210064. struct CDDeviceWrapper
  210065. {
  210066. ScopedPointer<CDDeviceHandle> cdH;
  210067. ScopedPointer<CDReadBuffer> overlapBuffer;
  210068. bool jitter;
  210069. };
  210070. static int getAddressOf (const TOCTRACK* const t)
  210071. {
  210072. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  210073. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  210074. }
  210075. static int getMSFAddressOf (const TOCTRACK* const t)
  210076. {
  210077. return 60 * t->addr[1] + t->addr[2];
  210078. }
  210079. static const int samplesPerFrame = 44100 / 75;
  210080. static const int bytesPerFrame = samplesPerFrame * 4;
  210081. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  210082. {
  210083. SRB_GDEVBlock s;
  210084. zerostruct (s);
  210085. s.SRB_Cmd = SC_GET_DEV_TYPE;
  210086. s.SRB_HaID = device->ha;
  210087. s.SRB_Target = device->tgt;
  210088. s.SRB_Lun = device->lun;
  210089. if (usingScsi)
  210090. {
  210091. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  210092. if (h != INVALID_HANDLE_VALUE)
  210093. {
  210094. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  210095. cdh->scsiHandle = h;
  210096. return cdh;
  210097. }
  210098. }
  210099. else
  210100. {
  210101. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  210102. && s.SRB_DeviceType == DTYPE_CROM)
  210103. {
  210104. return new CDDeviceHandle (device);
  210105. }
  210106. }
  210107. return 0;
  210108. }
  210109. }
  210110. const StringArray AudioCDReader::getAvailableCDNames()
  210111. {
  210112. using namespace CDReaderHelpers;
  210113. StringArray results;
  210114. incUserCount();
  210115. if (initialisedOk)
  210116. {
  210117. CDDeviceInfo list[8];
  210118. const int num = FindCDDevices (list, 8);
  210119. decUserCount();
  210120. for (int i = 0; i < num; ++i)
  210121. {
  210122. String s;
  210123. if (list[i].scsiDriveLetter > 0)
  210124. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210125. s << String (list[i].vendor).trim()
  210126. << ' ' << String (list[i].productId).trim()
  210127. << ' ' << String (list[i].rev).trim();
  210128. results.add (s);
  210129. }
  210130. }
  210131. return results;
  210132. }
  210133. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210134. {
  210135. using namespace CDReaderHelpers;
  210136. incUserCount();
  210137. if (initialisedOk)
  210138. {
  210139. CDDeviceInfo list[8];
  210140. const int num = FindCDDevices (list, 8);
  210141. if (((unsigned int) deviceIndex) < (unsigned int) num)
  210142. {
  210143. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  210144. if (handle != 0)
  210145. {
  210146. CDDeviceWrapper* const d = new CDDeviceWrapper();
  210147. d->cdH = handle;
  210148. d->overlapBuffer = new CDReadBuffer(3);
  210149. return new AudioCDReader (d);
  210150. }
  210151. }
  210152. }
  210153. decUserCount();
  210154. return 0;
  210155. }
  210156. AudioCDReader::AudioCDReader (void* handle_)
  210157. : AudioFormatReader (0, "CD Audio"),
  210158. handle (handle_),
  210159. indexingEnabled (false),
  210160. lastIndex (0),
  210161. firstFrameInBuffer (0),
  210162. samplesInBuffer (0)
  210163. {
  210164. using namespace CDReaderHelpers;
  210165. jassert (handle_ != 0);
  210166. refreshTrackLengths();
  210167. sampleRate = 44100.0;
  210168. bitsPerSample = 16;
  210169. lengthInSamples = getPositionOfTrackStart (numTracks);
  210170. numChannels = 2;
  210171. usesFloatingPointData = false;
  210172. buffer.setSize (4 * bytesPerFrame, true);
  210173. }
  210174. AudioCDReader::~AudioCDReader()
  210175. {
  210176. using namespace CDReaderHelpers;
  210177. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210178. delete device;
  210179. decUserCount();
  210180. }
  210181. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210182. int64 startSampleInFile, int numSamples)
  210183. {
  210184. using namespace CDReaderHelpers;
  210185. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210186. bool ok = true;
  210187. while (numSamples > 0)
  210188. {
  210189. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210190. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210191. if (startSampleInFile >= bufferStartSample
  210192. && startSampleInFile < bufferEndSample)
  210193. {
  210194. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210195. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210196. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210197. const short* src = (const short*) buffer.getData();
  210198. src += 2 * (startSampleInFile - bufferStartSample);
  210199. for (int i = 0; i < toDo; ++i)
  210200. {
  210201. l[i] = src [i << 1] << 16;
  210202. if (r != 0)
  210203. r[i] = src [(i << 1) + 1] << 16;
  210204. }
  210205. startOffsetInDestBuffer += toDo;
  210206. startSampleInFile += toDo;
  210207. numSamples -= toDo;
  210208. }
  210209. else
  210210. {
  210211. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210212. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210213. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210214. {
  210215. device->overlapBuffer->dataLength = 0;
  210216. device->overlapBuffer->startFrame = 0;
  210217. device->overlapBuffer->numFrames = 0;
  210218. device->jitter = false;
  210219. }
  210220. firstFrameInBuffer = frameNeeded;
  210221. lastIndex = 0;
  210222. CDReadBuffer readBuffer (framesInBuffer + 4);
  210223. readBuffer.wantsIndex = indexingEnabled;
  210224. int i;
  210225. for (i = 5; --i >= 0;)
  210226. {
  210227. readBuffer.startFrame = frameNeeded;
  210228. readBuffer.numFrames = framesInBuffer;
  210229. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  210230. break;
  210231. else
  210232. device->overlapBuffer->dataLength = 0;
  210233. }
  210234. if (i >= 0)
  210235. {
  210236. memcpy ((char*) buffer.getData(),
  210237. readBuffer.buffer + readBuffer.dataStartOffset,
  210238. readBuffer.dataLength);
  210239. samplesInBuffer = readBuffer.dataLength >> 2;
  210240. lastIndex = readBuffer.index;
  210241. }
  210242. else
  210243. {
  210244. int* l = destSamples[0] + startOffsetInDestBuffer;
  210245. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210246. while (--numSamples >= 0)
  210247. {
  210248. *l++ = 0;
  210249. if (r != 0)
  210250. *r++ = 0;
  210251. }
  210252. // sometimes the read fails for just the very last couple of blocks, so
  210253. // we'll ignore and errors in the last half-second of the disk..
  210254. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  210255. break;
  210256. }
  210257. }
  210258. }
  210259. return ok;
  210260. }
  210261. bool AudioCDReader::isCDStillPresent() const
  210262. {
  210263. using namespace CDReaderHelpers;
  210264. TOC toc;
  210265. zerostruct (toc);
  210266. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  210267. }
  210268. int AudioCDReader::getNumTracks() const
  210269. {
  210270. return numTracks;
  210271. }
  210272. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210273. {
  210274. using namespace CDReaderHelpers;
  210275. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  210276. : 0;
  210277. }
  210278. void AudioCDReader::refreshTrackLengths()
  210279. {
  210280. using namespace CDReaderHelpers;
  210281. zeromem (trackStarts, sizeof (trackStarts));
  210282. zeromem (audioTracks, sizeof (audioTracks));
  210283. TOC toc;
  210284. zerostruct (toc);
  210285. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  210286. {
  210287. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210288. for (int i = 0; i <= numTracks; ++i)
  210289. {
  210290. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  210291. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  210292. }
  210293. }
  210294. else
  210295. {
  210296. numTracks = 0;
  210297. }
  210298. }
  210299. bool AudioCDReader::isTrackAudio (int trackNum) const
  210300. {
  210301. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  210302. : false;
  210303. }
  210304. void AudioCDReader::enableIndexScanning (bool b)
  210305. {
  210306. indexingEnabled = b;
  210307. }
  210308. int AudioCDReader::getLastIndex() const
  210309. {
  210310. return lastIndex;
  210311. }
  210312. const int framesPerIndexRead = 4;
  210313. int AudioCDReader::getIndexAt (int samplePos)
  210314. {
  210315. using namespace CDReaderHelpers;
  210316. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210317. const int frameNeeded = samplePos / samplesPerFrame;
  210318. device->overlapBuffer->dataLength = 0;
  210319. device->overlapBuffer->startFrame = 0;
  210320. device->overlapBuffer->numFrames = 0;
  210321. device->jitter = false;
  210322. firstFrameInBuffer = 0;
  210323. lastIndex = 0;
  210324. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210325. readBuffer.wantsIndex = true;
  210326. int i;
  210327. for (i = 5; --i >= 0;)
  210328. {
  210329. readBuffer.startFrame = frameNeeded;
  210330. readBuffer.numFrames = framesPerIndexRead;
  210331. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210332. break;
  210333. }
  210334. if (i >= 0)
  210335. return readBuffer.index;
  210336. return -1;
  210337. }
  210338. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210339. {
  210340. using namespace CDReaderHelpers;
  210341. Array <int> indexes;
  210342. const int trackStart = getPositionOfTrackStart (trackNumber);
  210343. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210344. bool needToScan = true;
  210345. if (trackEnd - trackStart > 20 * 44100)
  210346. {
  210347. // check the end of the track for indexes before scanning the whole thing
  210348. needToScan = false;
  210349. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210350. bool seenAnIndex = false;
  210351. while (pos <= trackEnd - samplesPerFrame)
  210352. {
  210353. const int index = getIndexAt (pos);
  210354. if (index == 0)
  210355. {
  210356. // lead-out, so skip back a bit if we've not found any indexes yet..
  210357. if (seenAnIndex)
  210358. break;
  210359. pos -= 44100 * 5;
  210360. if (pos < trackStart)
  210361. break;
  210362. }
  210363. else
  210364. {
  210365. if (index > 0)
  210366. seenAnIndex = true;
  210367. if (index > 1)
  210368. {
  210369. needToScan = true;
  210370. break;
  210371. }
  210372. pos += samplesPerFrame * framesPerIndexRead;
  210373. }
  210374. }
  210375. }
  210376. if (needToScan)
  210377. {
  210378. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210379. int pos = trackStart;
  210380. int last = -1;
  210381. while (pos < trackEnd - samplesPerFrame * 10)
  210382. {
  210383. const int frameNeeded = pos / samplesPerFrame;
  210384. device->overlapBuffer->dataLength = 0;
  210385. device->overlapBuffer->startFrame = 0;
  210386. device->overlapBuffer->numFrames = 0;
  210387. device->jitter = false;
  210388. firstFrameInBuffer = 0;
  210389. CDReadBuffer readBuffer (4);
  210390. readBuffer.wantsIndex = true;
  210391. int i;
  210392. for (i = 5; --i >= 0;)
  210393. {
  210394. readBuffer.startFrame = frameNeeded;
  210395. readBuffer.numFrames = framesPerIndexRead;
  210396. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210397. break;
  210398. }
  210399. if (i < 0)
  210400. break;
  210401. if (readBuffer.index > last && readBuffer.index > 1)
  210402. {
  210403. last = readBuffer.index;
  210404. indexes.add (pos);
  210405. }
  210406. pos += samplesPerFrame * framesPerIndexRead;
  210407. }
  210408. indexes.removeValue (trackStart);
  210409. }
  210410. return indexes;
  210411. }
  210412. int AudioCDReader::getCDDBId()
  210413. {
  210414. using namespace CDReaderHelpers;
  210415. refreshTrackLengths();
  210416. if (numTracks > 0)
  210417. {
  210418. TOC toc;
  210419. zerostruct (toc);
  210420. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210421. {
  210422. int n = 0;
  210423. for (int i = numTracks; --i >= 0;)
  210424. {
  210425. int j = getMSFAddressOf (&toc.tracks[i]);
  210426. while (j > 0)
  210427. {
  210428. n += (j % 10);
  210429. j /= 10;
  210430. }
  210431. }
  210432. if (n != 0)
  210433. {
  210434. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210435. - getMSFAddressOf (&toc.tracks[0]);
  210436. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210437. }
  210438. }
  210439. }
  210440. return 0;
  210441. }
  210442. void AudioCDReader::ejectDisk()
  210443. {
  210444. using namespace CDReaderHelpers;
  210445. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210446. }
  210447. #endif
  210448. #if JUCE_USE_CDBURNER
  210449. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210450. {
  210451. CoInitialize (0);
  210452. IDiscMaster* dm;
  210453. IDiscRecorder* result = 0;
  210454. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210455. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210456. IID_IDiscMaster,
  210457. (void**) &dm)))
  210458. {
  210459. if (SUCCEEDED (dm->Open()))
  210460. {
  210461. IEnumDiscRecorders* drEnum = 0;
  210462. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210463. {
  210464. IDiscRecorder* dr = 0;
  210465. DWORD dummy;
  210466. int index = 0;
  210467. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210468. {
  210469. if (indexToOpen == index)
  210470. {
  210471. result = dr;
  210472. break;
  210473. }
  210474. else if (list != 0)
  210475. {
  210476. BSTR path;
  210477. if (SUCCEEDED (dr->GetPath (&path)))
  210478. list->add ((const WCHAR*) path);
  210479. }
  210480. ++index;
  210481. dr->Release();
  210482. }
  210483. drEnum->Release();
  210484. }
  210485. if (master == 0)
  210486. dm->Close();
  210487. }
  210488. if (master != 0)
  210489. *master = dm;
  210490. else
  210491. dm->Release();
  210492. }
  210493. return result;
  210494. }
  210495. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210496. public Timer
  210497. {
  210498. public:
  210499. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210500. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210501. listener (0), progress (0), shouldCancel (false)
  210502. {
  210503. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210504. jassert (SUCCEEDED (hr));
  210505. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210506. //jassert (SUCCEEDED (hr));
  210507. lastState = getDiskState();
  210508. startTimer (2000);
  210509. }
  210510. ~Pimpl() {}
  210511. void releaseObjects()
  210512. {
  210513. discRecorder->Close();
  210514. if (redbook != 0)
  210515. redbook->Release();
  210516. discRecorder->Release();
  210517. discMaster->Release();
  210518. Release();
  210519. }
  210520. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210521. {
  210522. if (listener != 0 && ! shouldCancel)
  210523. shouldCancel = listener->audioCDBurnProgress (progress);
  210524. *pbCancel = shouldCancel;
  210525. return S_OK;
  210526. }
  210527. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210528. {
  210529. progress = nCompleted / (float) nTotal;
  210530. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210531. return E_NOTIMPL;
  210532. }
  210533. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210534. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210535. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210536. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210537. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210538. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210539. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210540. class ScopedDiscOpener
  210541. {
  210542. public:
  210543. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210544. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210545. private:
  210546. Pimpl& pimpl;
  210547. ScopedDiscOpener (const ScopedDiscOpener&);
  210548. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210549. };
  210550. DiskState getDiskState()
  210551. {
  210552. const ScopedDiscOpener opener (*this);
  210553. long type, flags;
  210554. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210555. if (FAILED (hr))
  210556. return unknown;
  210557. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210558. return writableDiskPresent;
  210559. if (type == 0)
  210560. return noDisc;
  210561. else
  210562. return readOnlyDiskPresent;
  210563. }
  210564. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210565. {
  210566. ComSmartPtr<IPropertyStorage> prop;
  210567. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210568. return defaultReturn;
  210569. PROPSPEC iPropSpec;
  210570. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210571. iPropSpec.lpwstr = name;
  210572. PROPVARIANT iPropVariant;
  210573. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210574. ? defaultReturn : (int) iPropVariant.lVal;
  210575. }
  210576. bool setIntProperty (const LPOLESTR name, const int value) const
  210577. {
  210578. ComSmartPtr<IPropertyStorage> prop;
  210579. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210580. return false;
  210581. PROPSPEC iPropSpec;
  210582. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210583. iPropSpec.lpwstr = name;
  210584. PROPVARIANT iPropVariant;
  210585. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210586. return false;
  210587. iPropVariant.lVal = (long) value;
  210588. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210589. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210590. }
  210591. void timerCallback()
  210592. {
  210593. const DiskState state = getDiskState();
  210594. if (state != lastState)
  210595. {
  210596. lastState = state;
  210597. owner.sendChangeMessage (&owner);
  210598. }
  210599. }
  210600. AudioCDBurner& owner;
  210601. DiskState lastState;
  210602. IDiscMaster* discMaster;
  210603. IDiscRecorder* discRecorder;
  210604. IRedbookDiscMaster* redbook;
  210605. AudioCDBurner::BurnProgressListener* listener;
  210606. float progress;
  210607. bool shouldCancel;
  210608. };
  210609. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210610. {
  210611. IDiscMaster* discMaster = 0;
  210612. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210613. if (discRecorder != 0)
  210614. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210615. }
  210616. AudioCDBurner::~AudioCDBurner()
  210617. {
  210618. if (pimpl != 0)
  210619. pimpl.release()->releaseObjects();
  210620. }
  210621. const StringArray AudioCDBurner::findAvailableDevices()
  210622. {
  210623. StringArray devs;
  210624. enumCDBurners (&devs, -1, 0);
  210625. return devs;
  210626. }
  210627. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210628. {
  210629. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210630. if (b->pimpl == 0)
  210631. b = 0;
  210632. return b.release();
  210633. }
  210634. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210635. {
  210636. return pimpl->getDiskState();
  210637. }
  210638. bool AudioCDBurner::isDiskPresent() const
  210639. {
  210640. return getDiskState() == writableDiskPresent;
  210641. }
  210642. bool AudioCDBurner::openTray()
  210643. {
  210644. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210645. return SUCCEEDED (pimpl->discRecorder->Eject());
  210646. }
  210647. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210648. {
  210649. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210650. DiskState oldState = getDiskState();
  210651. DiskState newState = oldState;
  210652. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210653. {
  210654. newState = getDiskState();
  210655. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210656. }
  210657. return newState;
  210658. }
  210659. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210660. {
  210661. Array<int> results;
  210662. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210663. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210664. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210665. if (speeds[i] <= maxSpeed)
  210666. results.add (speeds[i]);
  210667. results.addIfNotAlreadyThere (maxSpeed);
  210668. return results;
  210669. }
  210670. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210671. {
  210672. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210673. return false;
  210674. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210675. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210676. }
  210677. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210678. {
  210679. long blocksFree = 0;
  210680. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210681. return blocksFree;
  210682. }
  210683. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210684. bool performFakeBurnForTesting, int writeSpeed)
  210685. {
  210686. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210687. pimpl->listener = listener;
  210688. pimpl->progress = 0;
  210689. pimpl->shouldCancel = false;
  210690. UINT_PTR cookie;
  210691. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210692. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210693. ejectDiscAfterwards);
  210694. String error;
  210695. if (hr != S_OK)
  210696. {
  210697. const char* e = "Couldn't open or write to the CD device";
  210698. if (hr == IMAPI_E_USERABORT)
  210699. e = "User cancelled the write operation";
  210700. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210701. e = "No Disk present";
  210702. error = e;
  210703. }
  210704. pimpl->discMaster->ProgressUnadvise (cookie);
  210705. pimpl->listener = 0;
  210706. return error;
  210707. }
  210708. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210709. {
  210710. if (audioSource == 0)
  210711. return false;
  210712. ScopedPointer<AudioSource> source (audioSource);
  210713. long bytesPerBlock;
  210714. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210715. const int samplesPerBlock = bytesPerBlock / 4;
  210716. bool ok = true;
  210717. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210718. HeapBlock <byte> buffer (bytesPerBlock);
  210719. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210720. int samplesDone = 0;
  210721. source->prepareToPlay (samplesPerBlock, 44100.0);
  210722. while (ok)
  210723. {
  210724. {
  210725. AudioSourceChannelInfo info;
  210726. info.buffer = &sourceBuffer;
  210727. info.numSamples = samplesPerBlock;
  210728. info.startSample = 0;
  210729. sourceBuffer.clear();
  210730. source->getNextAudioBlock (info);
  210731. }
  210732. zeromem (buffer, bytesPerBlock);
  210733. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210734. buffer, samplesPerBlock, 4);
  210735. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210736. buffer + 2, samplesPerBlock, 4);
  210737. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210738. if (FAILED (hr))
  210739. ok = false;
  210740. samplesDone += samplesPerBlock;
  210741. if (samplesDone >= numSamples)
  210742. break;
  210743. }
  210744. hr = pimpl->redbook->CloseAudioTrack();
  210745. return ok && hr == S_OK;
  210746. }
  210747. #endif
  210748. #endif
  210749. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210750. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210751. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210752. // compiled on its own).
  210753. #if JUCE_INCLUDED_FILE
  210754. using ::free;
  210755. namespace MidiConstants
  210756. {
  210757. static const int midiBufferSize = 1024 * 10;
  210758. static const int numInHeaders = 32;
  210759. static const int inBufferSize = 256;
  210760. }
  210761. class MidiInThread : public Thread
  210762. {
  210763. public:
  210764. MidiInThread (MidiInput* const input_,
  210765. MidiInputCallback* const callback_)
  210766. : Thread ("Juce Midi"),
  210767. hIn (0),
  210768. input (input_),
  210769. callback (callback_),
  210770. isStarted (false),
  210771. startTime (0),
  210772. pendingLength(0)
  210773. {
  210774. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210775. {
  210776. zeromem (&hdr[i], sizeof (MIDIHDR));
  210777. hdr[i].lpData = inData[i];
  210778. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210779. }
  210780. };
  210781. ~MidiInThread()
  210782. {
  210783. stop();
  210784. if (hIn != 0)
  210785. {
  210786. int count = 5;
  210787. while (--count >= 0)
  210788. {
  210789. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210790. break;
  210791. Sleep (20);
  210792. }
  210793. }
  210794. }
  210795. void handle (const uint32 message, const uint32 timeStamp)
  210796. {
  210797. const int byte = message & 0xff;
  210798. if (byte < 0x80)
  210799. return;
  210800. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210801. const double time = timeStampToTime (timeStamp);
  210802. {
  210803. const ScopedLock sl (lock);
  210804. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210805. {
  210806. char* const p = pending + pendingLength;
  210807. *(double*) p = time;
  210808. *(uint32*) (p + 8) = numBytes;
  210809. *(uint32*) (p + 12) = message;
  210810. pendingLength += 12 + numBytes;
  210811. }
  210812. else
  210813. {
  210814. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210815. }
  210816. }
  210817. notify();
  210818. }
  210819. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  210820. {
  210821. const int num = hdr->dwBytesRecorded;
  210822. if (num > 0)
  210823. {
  210824. const double time = timeStampToTime (timeStamp);
  210825. {
  210826. const ScopedLock sl (lock);
  210827. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  210828. {
  210829. char* const p = pending + pendingLength;
  210830. *(double*) p = time;
  210831. *(uint32*) (p + 8) = num;
  210832. memcpy (p + 12, hdr->lpData, num);
  210833. pendingLength += 12 + num;
  210834. }
  210835. else
  210836. {
  210837. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210838. }
  210839. }
  210840. notify();
  210841. }
  210842. }
  210843. void writeBlock (const int i)
  210844. {
  210845. hdr[i].dwBytesRecorded = 0;
  210846. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210847. jassert (res == MMSYSERR_NOERROR);
  210848. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  210849. jassert (res == MMSYSERR_NOERROR);
  210850. }
  210851. void run()
  210852. {
  210853. MemoryBlock pendingCopy (64);
  210854. while (! threadShouldExit())
  210855. {
  210856. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  210857. {
  210858. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210859. {
  210860. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210861. (void) res;
  210862. jassert (res == MMSYSERR_NOERROR);
  210863. writeBlock (i);
  210864. }
  210865. }
  210866. int len;
  210867. {
  210868. const ScopedLock sl (lock);
  210869. len = pendingLength;
  210870. if (len > 0)
  210871. {
  210872. pendingCopy.ensureSize (len);
  210873. pendingCopy.copyFrom (pending, 0, len);
  210874. pendingLength = 0;
  210875. }
  210876. }
  210877. //xxx needs to figure out if blocks are broken up or not
  210878. if (len == 0)
  210879. {
  210880. wait (500);
  210881. }
  210882. else
  210883. {
  210884. const char* p = (const char*) pendingCopy.getData();
  210885. while (len > 0)
  210886. {
  210887. const double time = *(const double*) p;
  210888. const int messageLen = *(const int*) (p + 8);
  210889. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  210890. callback->handleIncomingMidiMessage (input, message);
  210891. p += 12 + messageLen;
  210892. len -= 12 + messageLen;
  210893. }
  210894. }
  210895. }
  210896. }
  210897. void start()
  210898. {
  210899. jassert (hIn != 0);
  210900. if (hIn != 0 && ! isStarted)
  210901. {
  210902. stop();
  210903. activeMidiThreads.addIfNotAlreadyThere (this);
  210904. int i;
  210905. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  210906. writeBlock (i);
  210907. startTime = Time::getMillisecondCounter();
  210908. MMRESULT res = midiInStart (hIn);
  210909. jassert (res == MMSYSERR_NOERROR);
  210910. if (res == MMSYSERR_NOERROR)
  210911. {
  210912. isStarted = true;
  210913. pendingLength = 0;
  210914. startThread (6);
  210915. }
  210916. }
  210917. }
  210918. void stop()
  210919. {
  210920. if (isStarted)
  210921. {
  210922. stopThread (5000);
  210923. midiInReset (hIn);
  210924. midiInStop (hIn);
  210925. activeMidiThreads.removeValue (this);
  210926. { const ScopedLock sl (lock); }
  210927. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210928. {
  210929. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210930. {
  210931. int c = 10;
  210932. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  210933. Sleep (20);
  210934. jassert (c >= 0);
  210935. }
  210936. }
  210937. isStarted = false;
  210938. pendingLength = 0;
  210939. }
  210940. }
  210941. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  210942. {
  210943. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  210944. if (thread != 0 && activeMidiThreads.contains (thread))
  210945. {
  210946. if (uMsg == MIM_DATA)
  210947. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  210948. else if (uMsg == MIM_LONGDATA)
  210949. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  210950. }
  210951. }
  210952. juce_UseDebuggingNewOperator
  210953. HMIDIIN hIn;
  210954. private:
  210955. static Array <void*, CriticalSection> activeMidiThreads;
  210956. MidiInput* input;
  210957. MidiInputCallback* callback;
  210958. bool isStarted;
  210959. uint32 startTime;
  210960. CriticalSection lock;
  210961. MIDIHDR hdr [MidiConstants::numInHeaders];
  210962. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  210963. int pendingLength;
  210964. char pending [MidiConstants::midiBufferSize];
  210965. double timeStampToTime (uint32 timeStamp)
  210966. {
  210967. timeStamp += startTime;
  210968. const uint32 now = Time::getMillisecondCounter();
  210969. if (timeStamp > now)
  210970. {
  210971. if (timeStamp > now + 2)
  210972. --startTime;
  210973. timeStamp = now;
  210974. }
  210975. return 0.001 * timeStamp;
  210976. }
  210977. MidiInThread (const MidiInThread&);
  210978. MidiInThread& operator= (const MidiInThread&);
  210979. };
  210980. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  210981. const StringArray MidiInput::getDevices()
  210982. {
  210983. StringArray s;
  210984. const int num = midiInGetNumDevs();
  210985. for (int i = 0; i < num; ++i)
  210986. {
  210987. MIDIINCAPS mc;
  210988. zerostruct (mc);
  210989. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210990. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210991. }
  210992. return s;
  210993. }
  210994. int MidiInput::getDefaultDeviceIndex()
  210995. {
  210996. return 0;
  210997. }
  210998. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  210999. {
  211000. if (callback == 0)
  211001. return 0;
  211002. UINT deviceId = MIDI_MAPPER;
  211003. int n = 0;
  211004. String name;
  211005. const int num = midiInGetNumDevs();
  211006. for (int i = 0; i < num; ++i)
  211007. {
  211008. MIDIINCAPS mc;
  211009. zerostruct (mc);
  211010. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211011. {
  211012. if (index == n)
  211013. {
  211014. deviceId = i;
  211015. name = String (mc.szPname, sizeof (mc.szPname));
  211016. break;
  211017. }
  211018. ++n;
  211019. }
  211020. }
  211021. ScopedPointer <MidiInput> in (new MidiInput (name));
  211022. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  211023. HMIDIIN h;
  211024. HRESULT err = midiInOpen (&h, deviceId,
  211025. (DWORD_PTR) &MidiInThread::midiInCallback,
  211026. (DWORD_PTR) (MidiInThread*) thread,
  211027. CALLBACK_FUNCTION);
  211028. if (err == MMSYSERR_NOERROR)
  211029. {
  211030. thread->hIn = h;
  211031. in->internal = thread.release();
  211032. return in.release();
  211033. }
  211034. return 0;
  211035. }
  211036. MidiInput::MidiInput (const String& name_)
  211037. : name (name_),
  211038. internal (0)
  211039. {
  211040. }
  211041. MidiInput::~MidiInput()
  211042. {
  211043. delete static_cast <MidiInThread*> (internal);
  211044. }
  211045. void MidiInput::start()
  211046. {
  211047. static_cast <MidiInThread*> (internal)->start();
  211048. }
  211049. void MidiInput::stop()
  211050. {
  211051. static_cast <MidiInThread*> (internal)->stop();
  211052. }
  211053. struct MidiOutHandle
  211054. {
  211055. int refCount;
  211056. UINT deviceId;
  211057. HMIDIOUT handle;
  211058. static Array<MidiOutHandle*> activeHandles;
  211059. juce_UseDebuggingNewOperator
  211060. };
  211061. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211062. const StringArray MidiOutput::getDevices()
  211063. {
  211064. StringArray s;
  211065. const int num = midiOutGetNumDevs();
  211066. for (int i = 0; i < num; ++i)
  211067. {
  211068. MIDIOUTCAPS mc;
  211069. zerostruct (mc);
  211070. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211071. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211072. }
  211073. return s;
  211074. }
  211075. int MidiOutput::getDefaultDeviceIndex()
  211076. {
  211077. const int num = midiOutGetNumDevs();
  211078. int n = 0;
  211079. for (int i = 0; i < num; ++i)
  211080. {
  211081. MIDIOUTCAPS mc;
  211082. zerostruct (mc);
  211083. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211084. {
  211085. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211086. return n;
  211087. ++n;
  211088. }
  211089. }
  211090. return 0;
  211091. }
  211092. MidiOutput* MidiOutput::openDevice (int index)
  211093. {
  211094. UINT deviceId = MIDI_MAPPER;
  211095. const int num = midiOutGetNumDevs();
  211096. int i, n = 0;
  211097. for (i = 0; i < num; ++i)
  211098. {
  211099. MIDIOUTCAPS mc;
  211100. zerostruct (mc);
  211101. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211102. {
  211103. // use the microsoft sw synth as a default - best not to allow deviceId
  211104. // to be MIDI_MAPPER, or else device sharing breaks
  211105. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211106. deviceId = i;
  211107. if (index == n)
  211108. {
  211109. deviceId = i;
  211110. break;
  211111. }
  211112. ++n;
  211113. }
  211114. }
  211115. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211116. {
  211117. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211118. if (han != 0 && han->deviceId == deviceId)
  211119. {
  211120. han->refCount++;
  211121. MidiOutput* const out = new MidiOutput();
  211122. out->internal = han;
  211123. return out;
  211124. }
  211125. }
  211126. for (i = 4; --i >= 0;)
  211127. {
  211128. HMIDIOUT h = 0;
  211129. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211130. if (res == MMSYSERR_NOERROR)
  211131. {
  211132. MidiOutHandle* const han = new MidiOutHandle();
  211133. han->deviceId = deviceId;
  211134. han->refCount = 1;
  211135. han->handle = h;
  211136. MidiOutHandle::activeHandles.add (han);
  211137. MidiOutput* const out = new MidiOutput();
  211138. out->internal = han;
  211139. return out;
  211140. }
  211141. else if (res == MMSYSERR_ALLOCATED)
  211142. {
  211143. Sleep (100);
  211144. }
  211145. else
  211146. {
  211147. break;
  211148. }
  211149. }
  211150. return 0;
  211151. }
  211152. MidiOutput::~MidiOutput()
  211153. {
  211154. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211155. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211156. {
  211157. midiOutClose (h->handle);
  211158. MidiOutHandle::activeHandles.removeValue (h);
  211159. delete h;
  211160. }
  211161. }
  211162. void MidiOutput::reset()
  211163. {
  211164. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211165. midiOutReset (h->handle);
  211166. }
  211167. bool MidiOutput::getVolume (float& leftVol,
  211168. float& rightVol)
  211169. {
  211170. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211171. DWORD n;
  211172. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211173. {
  211174. const unsigned short* const nn = (const unsigned short*) &n;
  211175. rightVol = nn[0] / (float) 0xffff;
  211176. leftVol = nn[1] / (float) 0xffff;
  211177. return true;
  211178. }
  211179. else
  211180. {
  211181. rightVol = leftVol = 1.0f;
  211182. return false;
  211183. }
  211184. }
  211185. void MidiOutput::setVolume (float leftVol,
  211186. float rightVol)
  211187. {
  211188. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211189. DWORD n;
  211190. unsigned short* const nn = (unsigned short*) &n;
  211191. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211192. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211193. midiOutSetVolume (handle->handle, n);
  211194. }
  211195. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211196. {
  211197. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211198. if (message.getRawDataSize() > 3
  211199. || message.isSysEx())
  211200. {
  211201. MIDIHDR h;
  211202. zerostruct (h);
  211203. h.lpData = (char*) message.getRawData();
  211204. h.dwBufferLength = message.getRawDataSize();
  211205. h.dwBytesRecorded = message.getRawDataSize();
  211206. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211207. {
  211208. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211209. if (res == MMSYSERR_NOERROR)
  211210. {
  211211. while ((h.dwFlags & MHDR_DONE) == 0)
  211212. Sleep (1);
  211213. int count = 500; // 1 sec timeout
  211214. while (--count >= 0)
  211215. {
  211216. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211217. if (res == MIDIERR_STILLPLAYING)
  211218. Sleep (2);
  211219. else
  211220. break;
  211221. }
  211222. }
  211223. }
  211224. }
  211225. else
  211226. {
  211227. midiOutShortMsg (handle->handle,
  211228. *(unsigned int*) message.getRawData());
  211229. }
  211230. }
  211231. #endif
  211232. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211233. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211234. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211235. // compiled on its own).
  211236. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211237. #undef WINDOWS
  211238. // #define ASIO_DEBUGGING
  211239. #ifdef ASIO_DEBUGGING
  211240. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211241. #else
  211242. #define log(a) {}
  211243. #endif
  211244. #ifdef ASIO_DEBUGGING
  211245. static void logError (const String& context, long error)
  211246. {
  211247. String err ("unknown error");
  211248. if (error == ASE_NotPresent)
  211249. err = "Not Present";
  211250. else if (error == ASE_HWMalfunction)
  211251. err = "Hardware Malfunction";
  211252. else if (error == ASE_InvalidParameter)
  211253. err = "Invalid Parameter";
  211254. else if (error == ASE_InvalidMode)
  211255. err = "Invalid Mode";
  211256. else if (error == ASE_SPNotAdvancing)
  211257. err = "Sample position not advancing";
  211258. else if (error == ASE_NoClock)
  211259. err = "No Clock";
  211260. else if (error == ASE_NoMemory)
  211261. err = "Out of memory";
  211262. log ("!!error: " + context + " - " + err);
  211263. }
  211264. #else
  211265. #define logError(a, b) {}
  211266. #endif
  211267. class ASIOAudioIODevice;
  211268. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211269. static const int maxASIOChannels = 160;
  211270. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211271. private Timer
  211272. {
  211273. public:
  211274. Component ourWindow;
  211275. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211276. const String& optionalDllForDirectLoading_)
  211277. : AudioIODevice (name_, "ASIO"),
  211278. asioObject (0),
  211279. classId (classId_),
  211280. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211281. currentBitDepth (16),
  211282. currentSampleRate (0),
  211283. isOpen_ (false),
  211284. isStarted (false),
  211285. postOutput (true),
  211286. insideControlPanelModalLoop (false),
  211287. shouldUsePreferredSize (false)
  211288. {
  211289. name = name_;
  211290. ourWindow.addToDesktop (0);
  211291. windowHandle = ourWindow.getWindowHandle();
  211292. jassert (currentASIODev [slotNumber] == 0);
  211293. currentASIODev [slotNumber] = this;
  211294. openDevice();
  211295. }
  211296. ~ASIOAudioIODevice()
  211297. {
  211298. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211299. if (currentASIODev[i] == this)
  211300. currentASIODev[i] = 0;
  211301. close();
  211302. log ("ASIO - exiting");
  211303. removeCurrentDriver();
  211304. }
  211305. void updateSampleRates()
  211306. {
  211307. // find a list of sample rates..
  211308. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211309. sampleRates.clear();
  211310. if (asioObject != 0)
  211311. {
  211312. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211313. {
  211314. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211315. if (err == 0)
  211316. {
  211317. sampleRates.add ((int) possibleSampleRates[index]);
  211318. log ("rate: " + String ((int) possibleSampleRates[index]));
  211319. }
  211320. else if (err != ASE_NoClock)
  211321. {
  211322. logError ("CanSampleRate", err);
  211323. }
  211324. }
  211325. if (sampleRates.size() == 0)
  211326. {
  211327. double cr = 0;
  211328. const long err = asioObject->getSampleRate (&cr);
  211329. log ("No sample rates supported - current rate: " + String ((int) cr));
  211330. if (err == 0)
  211331. sampleRates.add ((int) cr);
  211332. }
  211333. }
  211334. }
  211335. const StringArray getOutputChannelNames()
  211336. {
  211337. return outputChannelNames;
  211338. }
  211339. const StringArray getInputChannelNames()
  211340. {
  211341. return inputChannelNames;
  211342. }
  211343. int getNumSampleRates()
  211344. {
  211345. return sampleRates.size();
  211346. }
  211347. double getSampleRate (int index)
  211348. {
  211349. return sampleRates [index];
  211350. }
  211351. int getNumBufferSizesAvailable()
  211352. {
  211353. return bufferSizes.size();
  211354. }
  211355. int getBufferSizeSamples (int index)
  211356. {
  211357. return bufferSizes [index];
  211358. }
  211359. int getDefaultBufferSize()
  211360. {
  211361. return preferredSize;
  211362. }
  211363. const String open (const BigInteger& inputChannels,
  211364. const BigInteger& outputChannels,
  211365. double sr,
  211366. int bufferSizeSamples)
  211367. {
  211368. close();
  211369. currentCallback = 0;
  211370. if (bufferSizeSamples <= 0)
  211371. shouldUsePreferredSize = true;
  211372. if (asioObject == 0 || ! isASIOOpen)
  211373. {
  211374. log ("Warning: device not open");
  211375. const String err (openDevice());
  211376. if (asioObject == 0 || ! isASIOOpen)
  211377. return err;
  211378. }
  211379. isStarted = false;
  211380. bufferIndex = -1;
  211381. long err = 0;
  211382. long newPreferredSize = 0;
  211383. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211384. minSize = 0;
  211385. maxSize = 0;
  211386. newPreferredSize = 0;
  211387. granularity = 0;
  211388. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211389. {
  211390. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211391. shouldUsePreferredSize = true;
  211392. preferredSize = newPreferredSize;
  211393. }
  211394. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211395. // dynamic changes to the buffer size...
  211396. shouldUsePreferredSize = shouldUsePreferredSize
  211397. || getName().containsIgnoreCase ("Digidesign");
  211398. if (shouldUsePreferredSize)
  211399. {
  211400. log ("Using preferred size for buffer..");
  211401. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211402. {
  211403. bufferSizeSamples = preferredSize;
  211404. }
  211405. else
  211406. {
  211407. bufferSizeSamples = 1024;
  211408. logError ("GetBufferSize1", err);
  211409. }
  211410. shouldUsePreferredSize = false;
  211411. }
  211412. int sampleRate = roundDoubleToInt (sr);
  211413. currentSampleRate = sampleRate;
  211414. currentBlockSizeSamples = bufferSizeSamples;
  211415. currentChansOut.clear();
  211416. currentChansIn.clear();
  211417. zeromem (inBuffers, sizeof (inBuffers));
  211418. zeromem (outBuffers, sizeof (outBuffers));
  211419. updateSampleRates();
  211420. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211421. sampleRate = sampleRates[0];
  211422. jassert (sampleRate != 0);
  211423. if (sampleRate == 0)
  211424. sampleRate = 44100;
  211425. long numSources = 32;
  211426. ASIOClockSource clocks[32];
  211427. zeromem (clocks, sizeof (clocks));
  211428. asioObject->getClockSources (clocks, &numSources);
  211429. bool isSourceSet = false;
  211430. // careful not to remove this loop because it does more than just logging!
  211431. int i;
  211432. for (i = 0; i < numSources; ++i)
  211433. {
  211434. String s ("clock: ");
  211435. s += clocks[i].name;
  211436. if (clocks[i].isCurrentSource)
  211437. {
  211438. isSourceSet = true;
  211439. s << " (cur)";
  211440. }
  211441. log (s);
  211442. }
  211443. if (numSources > 1 && ! isSourceSet)
  211444. {
  211445. log ("setting clock source");
  211446. asioObject->setClockSource (clocks[0].index);
  211447. Thread::sleep (20);
  211448. }
  211449. else
  211450. {
  211451. if (numSources == 0)
  211452. {
  211453. log ("ASIO - no clock sources!");
  211454. }
  211455. }
  211456. double cr = 0;
  211457. err = asioObject->getSampleRate (&cr);
  211458. if (err == 0)
  211459. {
  211460. currentSampleRate = cr;
  211461. }
  211462. else
  211463. {
  211464. logError ("GetSampleRate", err);
  211465. currentSampleRate = 0;
  211466. }
  211467. error = String::empty;
  211468. needToReset = false;
  211469. isReSync = false;
  211470. err = 0;
  211471. bool buffersCreated = false;
  211472. if (currentSampleRate != sampleRate)
  211473. {
  211474. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211475. err = asioObject->setSampleRate (sampleRate);
  211476. if (err == ASE_NoClock && numSources > 0)
  211477. {
  211478. log ("trying to set a clock source..");
  211479. Thread::sleep (10);
  211480. err = asioObject->setClockSource (clocks[0].index);
  211481. if (err != 0)
  211482. {
  211483. logError ("SetClock", err);
  211484. }
  211485. Thread::sleep (10);
  211486. err = asioObject->setSampleRate (sampleRate);
  211487. }
  211488. }
  211489. if (err == 0)
  211490. {
  211491. currentSampleRate = sampleRate;
  211492. if (needToReset)
  211493. {
  211494. if (isReSync)
  211495. {
  211496. log ("Resync request");
  211497. }
  211498. log ("! Resetting ASIO after sample rate change");
  211499. removeCurrentDriver();
  211500. loadDriver();
  211501. const String error (initDriver());
  211502. if (error.isNotEmpty())
  211503. {
  211504. log ("ASIOInit: " + error);
  211505. }
  211506. needToReset = false;
  211507. isReSync = false;
  211508. }
  211509. numActiveInputChans = 0;
  211510. numActiveOutputChans = 0;
  211511. ASIOBufferInfo* info = bufferInfos;
  211512. int i;
  211513. for (i = 0; i < totalNumInputChans; ++i)
  211514. {
  211515. if (inputChannels[i])
  211516. {
  211517. currentChansIn.setBit (i);
  211518. info->isInput = 1;
  211519. info->channelNum = i;
  211520. info->buffers[0] = info->buffers[1] = 0;
  211521. ++info;
  211522. ++numActiveInputChans;
  211523. }
  211524. }
  211525. for (i = 0; i < totalNumOutputChans; ++i)
  211526. {
  211527. if (outputChannels[i])
  211528. {
  211529. currentChansOut.setBit (i);
  211530. info->isInput = 0;
  211531. info->channelNum = i;
  211532. info->buffers[0] = info->buffers[1] = 0;
  211533. ++info;
  211534. ++numActiveOutputChans;
  211535. }
  211536. }
  211537. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211538. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211539. if (currentASIODev[0] == this)
  211540. {
  211541. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211542. callbacks.asioMessage = &asioMessagesCallback0;
  211543. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211544. }
  211545. else if (currentASIODev[1] == this)
  211546. {
  211547. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211548. callbacks.asioMessage = &asioMessagesCallback1;
  211549. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211550. }
  211551. else if (currentASIODev[2] == this)
  211552. {
  211553. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211554. callbacks.asioMessage = &asioMessagesCallback2;
  211555. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211556. }
  211557. else
  211558. {
  211559. jassertfalse;
  211560. }
  211561. log ("disposing buffers");
  211562. err = asioObject->disposeBuffers();
  211563. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211564. err = asioObject->createBuffers (bufferInfos,
  211565. totalBuffers,
  211566. currentBlockSizeSamples,
  211567. &callbacks);
  211568. if (err != 0)
  211569. {
  211570. currentBlockSizeSamples = preferredSize;
  211571. logError ("create buffers 2", err);
  211572. asioObject->disposeBuffers();
  211573. err = asioObject->createBuffers (bufferInfos,
  211574. totalBuffers,
  211575. currentBlockSizeSamples,
  211576. &callbacks);
  211577. }
  211578. if (err == 0)
  211579. {
  211580. buffersCreated = true;
  211581. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211582. int n = 0;
  211583. Array <int> types;
  211584. currentBitDepth = 16;
  211585. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211586. {
  211587. if (inputChannels[i])
  211588. {
  211589. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211590. ASIOChannelInfo channelInfo;
  211591. zerostruct (channelInfo);
  211592. channelInfo.channel = i;
  211593. channelInfo.isInput = 1;
  211594. asioObject->getChannelInfo (&channelInfo);
  211595. types.addIfNotAlreadyThere (channelInfo.type);
  211596. typeToFormatParameters (channelInfo.type,
  211597. inputChannelBitDepths[n],
  211598. inputChannelBytesPerSample[n],
  211599. inputChannelIsFloat[n],
  211600. inputChannelLittleEndian[n]);
  211601. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211602. ++n;
  211603. }
  211604. }
  211605. jassert (numActiveInputChans == n);
  211606. n = 0;
  211607. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211608. {
  211609. if (outputChannels[i])
  211610. {
  211611. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211612. ASIOChannelInfo channelInfo;
  211613. zerostruct (channelInfo);
  211614. channelInfo.channel = i;
  211615. channelInfo.isInput = 0;
  211616. asioObject->getChannelInfo (&channelInfo);
  211617. types.addIfNotAlreadyThere (channelInfo.type);
  211618. typeToFormatParameters (channelInfo.type,
  211619. outputChannelBitDepths[n],
  211620. outputChannelBytesPerSample[n],
  211621. outputChannelIsFloat[n],
  211622. outputChannelLittleEndian[n]);
  211623. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211624. ++n;
  211625. }
  211626. }
  211627. jassert (numActiveOutputChans == n);
  211628. for (i = types.size(); --i >= 0;)
  211629. {
  211630. log ("channel format: " + String (types[i]));
  211631. }
  211632. jassert (n <= totalBuffers);
  211633. for (i = 0; i < numActiveOutputChans; ++i)
  211634. {
  211635. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211636. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211637. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211638. {
  211639. log ("!! Null buffers");
  211640. }
  211641. else
  211642. {
  211643. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211644. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211645. }
  211646. }
  211647. inputLatency = outputLatency = 0;
  211648. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211649. {
  211650. log ("ASIO - no latencies");
  211651. }
  211652. else
  211653. {
  211654. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211655. }
  211656. isOpen_ = true;
  211657. log ("starting ASIO");
  211658. calledback = false;
  211659. err = asioObject->start();
  211660. if (err != 0)
  211661. {
  211662. isOpen_ = false;
  211663. log ("ASIO - stop on failure");
  211664. Thread::sleep (10);
  211665. asioObject->stop();
  211666. error = "Can't start device";
  211667. Thread::sleep (10);
  211668. }
  211669. else
  211670. {
  211671. int count = 300;
  211672. while (--count > 0 && ! calledback)
  211673. Thread::sleep (10);
  211674. isStarted = true;
  211675. if (! calledback)
  211676. {
  211677. error = "Device didn't start correctly";
  211678. log ("ASIO didn't callback - stopping..");
  211679. asioObject->stop();
  211680. }
  211681. }
  211682. }
  211683. else
  211684. {
  211685. error = "Can't create i/o buffers";
  211686. }
  211687. }
  211688. else
  211689. {
  211690. error = "Can't set sample rate: ";
  211691. error << sampleRate;
  211692. }
  211693. if (error.isNotEmpty())
  211694. {
  211695. logError (error, err);
  211696. if (asioObject != 0 && buffersCreated)
  211697. asioObject->disposeBuffers();
  211698. Thread::sleep (20);
  211699. isStarted = false;
  211700. isOpen_ = false;
  211701. const String errorCopy (error);
  211702. close(); // (this resets the error string)
  211703. error = errorCopy;
  211704. }
  211705. needToReset = false;
  211706. isReSync = false;
  211707. return error;
  211708. }
  211709. void close()
  211710. {
  211711. error = String::empty;
  211712. stopTimer();
  211713. stop();
  211714. if (isASIOOpen && isOpen_)
  211715. {
  211716. const ScopedLock sl (callbackLock);
  211717. isOpen_ = false;
  211718. isStarted = false;
  211719. needToReset = false;
  211720. isReSync = false;
  211721. log ("ASIO - stopping");
  211722. if (asioObject != 0)
  211723. {
  211724. Thread::sleep (20);
  211725. asioObject->stop();
  211726. Thread::sleep (10);
  211727. asioObject->disposeBuffers();
  211728. }
  211729. Thread::sleep (10);
  211730. }
  211731. }
  211732. bool isOpen()
  211733. {
  211734. return isOpen_ || insideControlPanelModalLoop;
  211735. }
  211736. int getCurrentBufferSizeSamples()
  211737. {
  211738. return currentBlockSizeSamples;
  211739. }
  211740. double getCurrentSampleRate()
  211741. {
  211742. return currentSampleRate;
  211743. }
  211744. const BigInteger getActiveOutputChannels() const
  211745. {
  211746. return currentChansOut;
  211747. }
  211748. const BigInteger getActiveInputChannels() const
  211749. {
  211750. return currentChansIn;
  211751. }
  211752. int getCurrentBitDepth()
  211753. {
  211754. return currentBitDepth;
  211755. }
  211756. int getOutputLatencyInSamples()
  211757. {
  211758. return outputLatency + currentBlockSizeSamples / 4;
  211759. }
  211760. int getInputLatencyInSamples()
  211761. {
  211762. return inputLatency + currentBlockSizeSamples / 4;
  211763. }
  211764. void start (AudioIODeviceCallback* callback)
  211765. {
  211766. if (callback != 0)
  211767. {
  211768. callback->audioDeviceAboutToStart (this);
  211769. const ScopedLock sl (callbackLock);
  211770. currentCallback = callback;
  211771. }
  211772. }
  211773. void stop()
  211774. {
  211775. AudioIODeviceCallback* const lastCallback = currentCallback;
  211776. {
  211777. const ScopedLock sl (callbackLock);
  211778. currentCallback = 0;
  211779. }
  211780. if (lastCallback != 0)
  211781. lastCallback->audioDeviceStopped();
  211782. }
  211783. bool isPlaying()
  211784. {
  211785. return isASIOOpen && (currentCallback != 0);
  211786. }
  211787. const String getLastError()
  211788. {
  211789. return error;
  211790. }
  211791. bool hasControlPanel() const
  211792. {
  211793. return true;
  211794. }
  211795. bool showControlPanel()
  211796. {
  211797. log ("ASIO - showing control panel");
  211798. Component modalWindow (String::empty);
  211799. modalWindow.setOpaque (true);
  211800. modalWindow.addToDesktop (0);
  211801. modalWindow.enterModalState();
  211802. bool done = false;
  211803. JUCE_TRY
  211804. {
  211805. // are there are devices that need to be closed before showing their control panel?
  211806. // close();
  211807. insideControlPanelModalLoop = true;
  211808. const uint32 started = Time::getMillisecondCounter();
  211809. if (asioObject != 0)
  211810. {
  211811. asioObject->controlPanel();
  211812. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211813. log ("spent: " + String (spent));
  211814. if (spent > 300)
  211815. {
  211816. shouldUsePreferredSize = true;
  211817. done = true;
  211818. }
  211819. }
  211820. }
  211821. JUCE_CATCH_ALL
  211822. insideControlPanelModalLoop = false;
  211823. return done;
  211824. }
  211825. void resetRequest() throw()
  211826. {
  211827. needToReset = true;
  211828. }
  211829. void resyncRequest() throw()
  211830. {
  211831. needToReset = true;
  211832. isReSync = true;
  211833. }
  211834. void timerCallback()
  211835. {
  211836. if (! insideControlPanelModalLoop)
  211837. {
  211838. stopTimer();
  211839. // used to cause a reset
  211840. log ("! ASIO restart request!");
  211841. if (isOpen_)
  211842. {
  211843. AudioIODeviceCallback* const oldCallback = currentCallback;
  211844. close();
  211845. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  211846. currentSampleRate, currentBlockSizeSamples);
  211847. if (oldCallback != 0)
  211848. start (oldCallback);
  211849. }
  211850. }
  211851. else
  211852. {
  211853. startTimer (100);
  211854. }
  211855. }
  211856. juce_UseDebuggingNewOperator
  211857. private:
  211858. IASIO* volatile asioObject;
  211859. ASIOCallbacks callbacks;
  211860. void* windowHandle;
  211861. CLSID classId;
  211862. const String optionalDllForDirectLoading;
  211863. String error;
  211864. long totalNumInputChans, totalNumOutputChans;
  211865. StringArray inputChannelNames, outputChannelNames;
  211866. Array<int> sampleRates, bufferSizes;
  211867. long inputLatency, outputLatency;
  211868. long minSize, maxSize, preferredSize, granularity;
  211869. int volatile currentBlockSizeSamples;
  211870. int volatile currentBitDepth;
  211871. double volatile currentSampleRate;
  211872. BigInteger currentChansOut, currentChansIn;
  211873. AudioIODeviceCallback* volatile currentCallback;
  211874. CriticalSection callbackLock;
  211875. ASIOBufferInfo bufferInfos [maxASIOChannels];
  211876. float* inBuffers [maxASIOChannels];
  211877. float* outBuffers [maxASIOChannels];
  211878. int inputChannelBitDepths [maxASIOChannels];
  211879. int outputChannelBitDepths [maxASIOChannels];
  211880. int inputChannelBytesPerSample [maxASIOChannels];
  211881. int outputChannelBytesPerSample [maxASIOChannels];
  211882. bool inputChannelIsFloat [maxASIOChannels];
  211883. bool outputChannelIsFloat [maxASIOChannels];
  211884. bool inputChannelLittleEndian [maxASIOChannels];
  211885. bool outputChannelLittleEndian [maxASIOChannels];
  211886. WaitableEvent event1;
  211887. HeapBlock <float> tempBuffer;
  211888. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  211889. bool isOpen_, isStarted;
  211890. bool volatile isASIOOpen;
  211891. bool volatile calledback;
  211892. bool volatile littleEndian, postOutput, needToReset, isReSync;
  211893. bool volatile insideControlPanelModalLoop;
  211894. bool volatile shouldUsePreferredSize;
  211895. void removeCurrentDriver()
  211896. {
  211897. if (asioObject != 0)
  211898. {
  211899. asioObject->Release();
  211900. asioObject = 0;
  211901. }
  211902. }
  211903. bool loadDriver()
  211904. {
  211905. removeCurrentDriver();
  211906. JUCE_TRY
  211907. {
  211908. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  211909. classId, (void**) &asioObject) == S_OK)
  211910. {
  211911. return true;
  211912. }
  211913. // If a class isn't registered but we have a path for it, we can fallback to
  211914. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  211915. if (optionalDllForDirectLoading.isNotEmpty())
  211916. {
  211917. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  211918. if (h != 0)
  211919. {
  211920. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  211921. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  211922. if (dllGetClassObject != 0)
  211923. {
  211924. IClassFactory* classFactory = 0;
  211925. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  211926. if (classFactory != 0)
  211927. {
  211928. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  211929. classFactory->Release();
  211930. }
  211931. return asioObject != 0;
  211932. }
  211933. }
  211934. }
  211935. }
  211936. JUCE_CATCH_ALL
  211937. asioObject = 0;
  211938. return false;
  211939. }
  211940. const String initDriver()
  211941. {
  211942. if (asioObject != 0)
  211943. {
  211944. char buffer [256];
  211945. zeromem (buffer, sizeof (buffer));
  211946. if (! asioObject->init (windowHandle))
  211947. {
  211948. asioObject->getErrorMessage (buffer);
  211949. return String (buffer, sizeof (buffer) - 1);
  211950. }
  211951. // just in case any daft drivers expect this to be called..
  211952. asioObject->getDriverName (buffer);
  211953. return String::empty;
  211954. }
  211955. return "No Driver";
  211956. }
  211957. const String openDevice()
  211958. {
  211959. // use this in case the driver starts opening dialog boxes..
  211960. Component modalWindow (String::empty);
  211961. modalWindow.setOpaque (true);
  211962. modalWindow.addToDesktop (0);
  211963. modalWindow.enterModalState();
  211964. // open the device and get its info..
  211965. log ("opening ASIO device: " + getName());
  211966. needToReset = false;
  211967. isReSync = false;
  211968. outputChannelNames.clear();
  211969. inputChannelNames.clear();
  211970. bufferSizes.clear();
  211971. sampleRates.clear();
  211972. isASIOOpen = false;
  211973. isOpen_ = false;
  211974. totalNumInputChans = 0;
  211975. totalNumOutputChans = 0;
  211976. numActiveInputChans = 0;
  211977. numActiveOutputChans = 0;
  211978. currentCallback = 0;
  211979. error = String::empty;
  211980. if (getName().isEmpty())
  211981. return error;
  211982. long err = 0;
  211983. if (loadDriver())
  211984. {
  211985. if ((error = initDriver()).isEmpty())
  211986. {
  211987. numActiveInputChans = 0;
  211988. numActiveOutputChans = 0;
  211989. totalNumInputChans = 0;
  211990. totalNumOutputChans = 0;
  211991. if (asioObject != 0
  211992. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  211993. {
  211994. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  211995. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211996. {
  211997. // find a list of buffer sizes..
  211998. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  211999. if (granularity >= 0)
  212000. {
  212001. granularity = jmax (1, (int) granularity);
  212002. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212003. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212004. }
  212005. else if (granularity < 0)
  212006. {
  212007. for (int i = 0; i < 18; ++i)
  212008. {
  212009. const int s = (1 << i);
  212010. if (s >= minSize && s <= maxSize)
  212011. bufferSizes.add (s);
  212012. }
  212013. }
  212014. if (! bufferSizes.contains (preferredSize))
  212015. bufferSizes.insert (0, preferredSize);
  212016. double currentRate = 0;
  212017. asioObject->getSampleRate (&currentRate);
  212018. if (currentRate <= 0.0 || currentRate > 192001.0)
  212019. {
  212020. log ("setting sample rate");
  212021. err = asioObject->setSampleRate (44100.0);
  212022. if (err != 0)
  212023. {
  212024. logError ("setting sample rate", err);
  212025. }
  212026. asioObject->getSampleRate (&currentRate);
  212027. }
  212028. currentSampleRate = currentRate;
  212029. postOutput = (asioObject->outputReady() == 0);
  212030. if (postOutput)
  212031. {
  212032. log ("ASIO outputReady = ok");
  212033. }
  212034. updateSampleRates();
  212035. // ..because cubase does it at this point
  212036. inputLatency = outputLatency = 0;
  212037. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212038. {
  212039. log ("ASIO - no latencies");
  212040. }
  212041. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212042. // create some dummy buffers now.. because cubase does..
  212043. numActiveInputChans = 0;
  212044. numActiveOutputChans = 0;
  212045. ASIOBufferInfo* info = bufferInfos;
  212046. int i, numChans = 0;
  212047. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212048. {
  212049. info->isInput = 1;
  212050. info->channelNum = i;
  212051. info->buffers[0] = info->buffers[1] = 0;
  212052. ++info;
  212053. ++numChans;
  212054. }
  212055. const int outputBufferIndex = numChans;
  212056. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212057. {
  212058. info->isInput = 0;
  212059. info->channelNum = i;
  212060. info->buffers[0] = info->buffers[1] = 0;
  212061. ++info;
  212062. ++numChans;
  212063. }
  212064. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212065. if (currentASIODev[0] == this)
  212066. {
  212067. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212068. callbacks.asioMessage = &asioMessagesCallback0;
  212069. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212070. }
  212071. else if (currentASIODev[1] == this)
  212072. {
  212073. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212074. callbacks.asioMessage = &asioMessagesCallback1;
  212075. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212076. }
  212077. else if (currentASIODev[2] == this)
  212078. {
  212079. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212080. callbacks.asioMessage = &asioMessagesCallback2;
  212081. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212082. }
  212083. else
  212084. {
  212085. jassertfalse;
  212086. }
  212087. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212088. if (preferredSize > 0)
  212089. {
  212090. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212091. if (err != 0)
  212092. {
  212093. logError ("dummy buffers", err);
  212094. }
  212095. }
  212096. long newInps = 0, newOuts = 0;
  212097. asioObject->getChannels (&newInps, &newOuts);
  212098. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212099. {
  212100. totalNumInputChans = newInps;
  212101. totalNumOutputChans = newOuts;
  212102. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212103. }
  212104. updateSampleRates();
  212105. ASIOChannelInfo channelInfo;
  212106. channelInfo.type = 0;
  212107. for (i = 0; i < totalNumInputChans; ++i)
  212108. {
  212109. zerostruct (channelInfo);
  212110. channelInfo.channel = i;
  212111. channelInfo.isInput = 1;
  212112. asioObject->getChannelInfo (&channelInfo);
  212113. inputChannelNames.add (String (channelInfo.name));
  212114. }
  212115. for (i = 0; i < totalNumOutputChans; ++i)
  212116. {
  212117. zerostruct (channelInfo);
  212118. channelInfo.channel = i;
  212119. channelInfo.isInput = 0;
  212120. asioObject->getChannelInfo (&channelInfo);
  212121. outputChannelNames.add (String (channelInfo.name));
  212122. typeToFormatParameters (channelInfo.type,
  212123. outputChannelBitDepths[i],
  212124. outputChannelBytesPerSample[i],
  212125. outputChannelIsFloat[i],
  212126. outputChannelLittleEndian[i]);
  212127. if (i < 2)
  212128. {
  212129. // clear the channels that are used with the dummy stuff
  212130. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212131. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212132. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212133. }
  212134. }
  212135. outputChannelNames.trim();
  212136. inputChannelNames.trim();
  212137. outputChannelNames.appendNumbersToDuplicates (false, true);
  212138. inputChannelNames.appendNumbersToDuplicates (false, true);
  212139. // start and stop because cubase does it..
  212140. asioObject->getLatencies (&inputLatency, &outputLatency);
  212141. if ((err = asioObject->start()) != 0)
  212142. {
  212143. // ignore an error here, as it might start later after setting other stuff up
  212144. logError ("ASIO start", err);
  212145. }
  212146. Thread::sleep (100);
  212147. asioObject->stop();
  212148. }
  212149. else
  212150. {
  212151. error = "Can't detect buffer sizes";
  212152. }
  212153. }
  212154. else
  212155. {
  212156. error = "Can't detect asio channels";
  212157. }
  212158. }
  212159. }
  212160. else
  212161. {
  212162. error = "No such device";
  212163. }
  212164. if (error.isNotEmpty())
  212165. {
  212166. logError (error, err);
  212167. if (asioObject != 0)
  212168. asioObject->disposeBuffers();
  212169. removeCurrentDriver();
  212170. isASIOOpen = false;
  212171. }
  212172. else
  212173. {
  212174. isASIOOpen = true;
  212175. log ("ASIO device open");
  212176. }
  212177. isOpen_ = false;
  212178. needToReset = false;
  212179. isReSync = false;
  212180. return error;
  212181. }
  212182. void callback (const long index)
  212183. {
  212184. if (isStarted)
  212185. {
  212186. bufferIndex = index;
  212187. processBuffer();
  212188. }
  212189. else
  212190. {
  212191. if (postOutput && (asioObject != 0))
  212192. asioObject->outputReady();
  212193. }
  212194. calledback = true;
  212195. }
  212196. void processBuffer()
  212197. {
  212198. const ASIOBufferInfo* const infos = bufferInfos;
  212199. const int bi = bufferIndex;
  212200. const ScopedLock sl (callbackLock);
  212201. if (needToReset)
  212202. {
  212203. needToReset = false;
  212204. if (isReSync)
  212205. {
  212206. log ("! ASIO resync");
  212207. isReSync = false;
  212208. }
  212209. else
  212210. {
  212211. startTimer (20);
  212212. }
  212213. }
  212214. if (bi >= 0)
  212215. {
  212216. const int samps = currentBlockSizeSamples;
  212217. if (currentCallback != 0)
  212218. {
  212219. int i;
  212220. for (i = 0; i < numActiveInputChans; ++i)
  212221. {
  212222. float* const dst = inBuffers[i];
  212223. jassert (dst != 0);
  212224. const char* const src = (const char*) (infos[i].buffers[bi]);
  212225. if (inputChannelIsFloat[i])
  212226. {
  212227. memcpy (dst, src, samps * sizeof (float));
  212228. }
  212229. else
  212230. {
  212231. jassert (dst == tempBuffer + (samps * i));
  212232. switch (inputChannelBitDepths[i])
  212233. {
  212234. case 16:
  212235. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212236. samps, inputChannelLittleEndian[i]);
  212237. break;
  212238. case 24:
  212239. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212240. samps, inputChannelLittleEndian[i]);
  212241. break;
  212242. case 32:
  212243. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212244. samps, inputChannelLittleEndian[i]);
  212245. break;
  212246. case 64:
  212247. jassertfalse;
  212248. break;
  212249. }
  212250. }
  212251. }
  212252. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  212253. numActiveInputChans,
  212254. outBuffers,
  212255. numActiveOutputChans,
  212256. samps);
  212257. for (i = 0; i < numActiveOutputChans; ++i)
  212258. {
  212259. float* const src = outBuffers[i];
  212260. jassert (src != 0);
  212261. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212262. if (outputChannelIsFloat[i])
  212263. {
  212264. memcpy (dst, src, samps * sizeof (float));
  212265. }
  212266. else
  212267. {
  212268. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212269. switch (outputChannelBitDepths[i])
  212270. {
  212271. case 16:
  212272. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212273. samps, outputChannelLittleEndian[i]);
  212274. break;
  212275. case 24:
  212276. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212277. samps, outputChannelLittleEndian[i]);
  212278. break;
  212279. case 32:
  212280. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212281. samps, outputChannelLittleEndian[i]);
  212282. break;
  212283. case 64:
  212284. jassertfalse;
  212285. break;
  212286. }
  212287. }
  212288. }
  212289. }
  212290. else
  212291. {
  212292. for (int i = 0; i < numActiveOutputChans; ++i)
  212293. {
  212294. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212295. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212296. }
  212297. }
  212298. }
  212299. if (postOutput)
  212300. asioObject->outputReady();
  212301. }
  212302. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212303. {
  212304. if (currentASIODev[0] != 0)
  212305. currentASIODev[0]->callback (index);
  212306. return 0;
  212307. }
  212308. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212309. {
  212310. if (currentASIODev[1] != 0)
  212311. currentASIODev[1]->callback (index);
  212312. return 0;
  212313. }
  212314. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212315. {
  212316. if (currentASIODev[2] != 0)
  212317. currentASIODev[2]->callback (index);
  212318. return 0;
  212319. }
  212320. static void bufferSwitchCallback0 (long index, long)
  212321. {
  212322. if (currentASIODev[0] != 0)
  212323. currentASIODev[0]->callback (index);
  212324. }
  212325. static void bufferSwitchCallback1 (long index, long)
  212326. {
  212327. if (currentASIODev[1] != 0)
  212328. currentASIODev[1]->callback (index);
  212329. }
  212330. static void bufferSwitchCallback2 (long index, long)
  212331. {
  212332. if (currentASIODev[2] != 0)
  212333. currentASIODev[2]->callback (index);
  212334. }
  212335. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212336. {
  212337. return asioMessagesCallback (selector, value, 0);
  212338. }
  212339. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212340. {
  212341. return asioMessagesCallback (selector, value, 1);
  212342. }
  212343. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212344. {
  212345. return asioMessagesCallback (selector, value, 2);
  212346. }
  212347. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212348. {
  212349. switch (selector)
  212350. {
  212351. case kAsioSelectorSupported:
  212352. if (value == kAsioResetRequest
  212353. || value == kAsioEngineVersion
  212354. || value == kAsioResyncRequest
  212355. || value == kAsioLatenciesChanged
  212356. || value == kAsioSupportsInputMonitor)
  212357. return 1;
  212358. break;
  212359. case kAsioBufferSizeChange:
  212360. break;
  212361. case kAsioResetRequest:
  212362. if (currentASIODev[deviceIndex] != 0)
  212363. currentASIODev[deviceIndex]->resetRequest();
  212364. return 1;
  212365. case kAsioResyncRequest:
  212366. if (currentASIODev[deviceIndex] != 0)
  212367. currentASIODev[deviceIndex]->resyncRequest();
  212368. return 1;
  212369. case kAsioLatenciesChanged:
  212370. return 1;
  212371. case kAsioEngineVersion:
  212372. return 2;
  212373. case kAsioSupportsTimeInfo:
  212374. case kAsioSupportsTimeCode:
  212375. return 0;
  212376. }
  212377. return 0;
  212378. }
  212379. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212380. {
  212381. }
  212382. static void convertInt16ToFloat (const char* src,
  212383. float* dest,
  212384. const int srcStrideBytes,
  212385. int numSamples,
  212386. const bool littleEndian) throw()
  212387. {
  212388. const double g = 1.0 / 32768.0;
  212389. if (littleEndian)
  212390. {
  212391. while (--numSamples >= 0)
  212392. {
  212393. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212394. src += srcStrideBytes;
  212395. }
  212396. }
  212397. else
  212398. {
  212399. while (--numSamples >= 0)
  212400. {
  212401. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212402. src += srcStrideBytes;
  212403. }
  212404. }
  212405. }
  212406. static void convertFloatToInt16 (const float* src,
  212407. char* dest,
  212408. const int dstStrideBytes,
  212409. int numSamples,
  212410. const bool littleEndian) throw()
  212411. {
  212412. const double maxVal = (double) 0x7fff;
  212413. if (littleEndian)
  212414. {
  212415. while (--numSamples >= 0)
  212416. {
  212417. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212418. dest += dstStrideBytes;
  212419. }
  212420. }
  212421. else
  212422. {
  212423. while (--numSamples >= 0)
  212424. {
  212425. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212426. dest += dstStrideBytes;
  212427. }
  212428. }
  212429. }
  212430. static void convertInt24ToFloat (const char* src,
  212431. float* dest,
  212432. const int srcStrideBytes,
  212433. int numSamples,
  212434. const bool littleEndian) throw()
  212435. {
  212436. const double g = 1.0 / 0x7fffff;
  212437. if (littleEndian)
  212438. {
  212439. while (--numSamples >= 0)
  212440. {
  212441. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212442. src += srcStrideBytes;
  212443. }
  212444. }
  212445. else
  212446. {
  212447. while (--numSamples >= 0)
  212448. {
  212449. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212450. src += srcStrideBytes;
  212451. }
  212452. }
  212453. }
  212454. static void convertFloatToInt24 (const float* src,
  212455. char* dest,
  212456. const int dstStrideBytes,
  212457. int numSamples,
  212458. const bool littleEndian) throw()
  212459. {
  212460. const double maxVal = (double) 0x7fffff;
  212461. if (littleEndian)
  212462. {
  212463. while (--numSamples >= 0)
  212464. {
  212465. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212466. dest += dstStrideBytes;
  212467. }
  212468. }
  212469. else
  212470. {
  212471. while (--numSamples >= 0)
  212472. {
  212473. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212474. dest += dstStrideBytes;
  212475. }
  212476. }
  212477. }
  212478. static void convertInt32ToFloat (const char* src,
  212479. float* dest,
  212480. const int srcStrideBytes,
  212481. int numSamples,
  212482. const bool littleEndian) throw()
  212483. {
  212484. const double g = 1.0 / 0x7fffffff;
  212485. if (littleEndian)
  212486. {
  212487. while (--numSamples >= 0)
  212488. {
  212489. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212490. src += srcStrideBytes;
  212491. }
  212492. }
  212493. else
  212494. {
  212495. while (--numSamples >= 0)
  212496. {
  212497. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212498. src += srcStrideBytes;
  212499. }
  212500. }
  212501. }
  212502. static void convertFloatToInt32 (const float* src,
  212503. char* dest,
  212504. const int dstStrideBytes,
  212505. int numSamples,
  212506. const bool littleEndian) throw()
  212507. {
  212508. const double maxVal = (double) 0x7fffffff;
  212509. if (littleEndian)
  212510. {
  212511. while (--numSamples >= 0)
  212512. {
  212513. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212514. dest += dstStrideBytes;
  212515. }
  212516. }
  212517. else
  212518. {
  212519. while (--numSamples >= 0)
  212520. {
  212521. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212522. dest += dstStrideBytes;
  212523. }
  212524. }
  212525. }
  212526. static void typeToFormatParameters (const long type,
  212527. int& bitDepth,
  212528. int& byteStride,
  212529. bool& formatIsFloat,
  212530. bool& littleEndian) throw()
  212531. {
  212532. bitDepth = 0;
  212533. littleEndian = false;
  212534. formatIsFloat = false;
  212535. switch (type)
  212536. {
  212537. case ASIOSTInt16MSB:
  212538. case ASIOSTInt16LSB:
  212539. case ASIOSTInt32MSB16:
  212540. case ASIOSTInt32LSB16:
  212541. bitDepth = 16; break;
  212542. case ASIOSTFloat32MSB:
  212543. case ASIOSTFloat32LSB:
  212544. formatIsFloat = true;
  212545. bitDepth = 32; break;
  212546. case ASIOSTInt32MSB:
  212547. case ASIOSTInt32LSB:
  212548. bitDepth = 32; break;
  212549. case ASIOSTInt24MSB:
  212550. case ASIOSTInt24LSB:
  212551. case ASIOSTInt32MSB24:
  212552. case ASIOSTInt32LSB24:
  212553. case ASIOSTInt32MSB18:
  212554. case ASIOSTInt32MSB20:
  212555. case ASIOSTInt32LSB18:
  212556. case ASIOSTInt32LSB20:
  212557. bitDepth = 24; break;
  212558. case ASIOSTFloat64MSB:
  212559. case ASIOSTFloat64LSB:
  212560. default:
  212561. bitDepth = 64;
  212562. break;
  212563. }
  212564. switch (type)
  212565. {
  212566. case ASIOSTInt16MSB:
  212567. case ASIOSTInt32MSB16:
  212568. case ASIOSTFloat32MSB:
  212569. case ASIOSTFloat64MSB:
  212570. case ASIOSTInt32MSB:
  212571. case ASIOSTInt32MSB18:
  212572. case ASIOSTInt32MSB20:
  212573. case ASIOSTInt32MSB24:
  212574. case ASIOSTInt24MSB:
  212575. littleEndian = false; break;
  212576. case ASIOSTInt16LSB:
  212577. case ASIOSTInt32LSB16:
  212578. case ASIOSTFloat32LSB:
  212579. case ASIOSTFloat64LSB:
  212580. case ASIOSTInt32LSB:
  212581. case ASIOSTInt32LSB18:
  212582. case ASIOSTInt32LSB20:
  212583. case ASIOSTInt32LSB24:
  212584. case ASIOSTInt24LSB:
  212585. littleEndian = true; break;
  212586. default:
  212587. break;
  212588. }
  212589. switch (type)
  212590. {
  212591. case ASIOSTInt16LSB:
  212592. case ASIOSTInt16MSB:
  212593. byteStride = 2; break;
  212594. case ASIOSTInt24LSB:
  212595. case ASIOSTInt24MSB:
  212596. byteStride = 3; break;
  212597. case ASIOSTInt32MSB16:
  212598. case ASIOSTInt32LSB16:
  212599. case ASIOSTInt32MSB:
  212600. case ASIOSTInt32MSB18:
  212601. case ASIOSTInt32MSB20:
  212602. case ASIOSTInt32MSB24:
  212603. case ASIOSTInt32LSB:
  212604. case ASIOSTInt32LSB18:
  212605. case ASIOSTInt32LSB20:
  212606. case ASIOSTInt32LSB24:
  212607. case ASIOSTFloat32LSB:
  212608. case ASIOSTFloat32MSB:
  212609. byteStride = 4; break;
  212610. case ASIOSTFloat64MSB:
  212611. case ASIOSTFloat64LSB:
  212612. byteStride = 8; break;
  212613. default:
  212614. break;
  212615. }
  212616. }
  212617. };
  212618. class ASIOAudioIODeviceType : public AudioIODeviceType
  212619. {
  212620. public:
  212621. ASIOAudioIODeviceType()
  212622. : AudioIODeviceType ("ASIO"),
  212623. hasScanned (false)
  212624. {
  212625. CoInitialize (0);
  212626. }
  212627. ~ASIOAudioIODeviceType()
  212628. {
  212629. }
  212630. void scanForDevices()
  212631. {
  212632. hasScanned = true;
  212633. deviceNames.clear();
  212634. classIds.clear();
  212635. HKEY hk = 0;
  212636. int index = 0;
  212637. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212638. {
  212639. for (;;)
  212640. {
  212641. char name [256];
  212642. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212643. {
  212644. addDriverInfo (name, hk);
  212645. }
  212646. else
  212647. {
  212648. break;
  212649. }
  212650. }
  212651. RegCloseKey (hk);
  212652. }
  212653. }
  212654. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212655. {
  212656. jassert (hasScanned); // need to call scanForDevices() before doing this
  212657. return deviceNames;
  212658. }
  212659. int getDefaultDeviceIndex (bool) const
  212660. {
  212661. jassert (hasScanned); // need to call scanForDevices() before doing this
  212662. for (int i = deviceNames.size(); --i >= 0;)
  212663. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212664. return i; // asio4all is a safe choice for a default..
  212665. #if JUCE_DEBUG
  212666. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212667. return 1; // (the digi m-box driver crashes the app when you run
  212668. // it in the debugger, which can be a bit annoying)
  212669. #endif
  212670. return 0;
  212671. }
  212672. static int findFreeSlot()
  212673. {
  212674. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212675. if (currentASIODev[i] == 0)
  212676. return i;
  212677. jassertfalse; // unfortunately you can only have a finite number
  212678. // of ASIO devices open at the same time..
  212679. return -1;
  212680. }
  212681. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212682. {
  212683. jassert (hasScanned); // need to call scanForDevices() before doing this
  212684. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212685. }
  212686. bool hasSeparateInputsAndOutputs() const { return false; }
  212687. AudioIODevice* createDevice (const String& outputDeviceName,
  212688. const String& inputDeviceName)
  212689. {
  212690. // ASIO can't open two different devices for input and output - they must be the same one.
  212691. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212692. jassert (hasScanned); // need to call scanForDevices() before doing this
  212693. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212694. : inputDeviceName);
  212695. if (index >= 0)
  212696. {
  212697. const int freeSlot = findFreeSlot();
  212698. if (freeSlot >= 0)
  212699. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212700. }
  212701. return 0;
  212702. }
  212703. juce_UseDebuggingNewOperator
  212704. private:
  212705. StringArray deviceNames;
  212706. OwnedArray <CLSID> classIds;
  212707. bool hasScanned;
  212708. static bool checkClassIsOk (const String& classId)
  212709. {
  212710. HKEY hk = 0;
  212711. bool ok = false;
  212712. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212713. {
  212714. int index = 0;
  212715. for (;;)
  212716. {
  212717. WCHAR buf [512];
  212718. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212719. {
  212720. if (classId.equalsIgnoreCase (buf))
  212721. {
  212722. HKEY subKey, pathKey;
  212723. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212724. {
  212725. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212726. {
  212727. WCHAR pathName [1024];
  212728. DWORD dtype = REG_SZ;
  212729. DWORD dsize = sizeof (pathName);
  212730. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212731. ok = File (pathName).exists();
  212732. RegCloseKey (pathKey);
  212733. }
  212734. RegCloseKey (subKey);
  212735. }
  212736. break;
  212737. }
  212738. }
  212739. else
  212740. {
  212741. break;
  212742. }
  212743. }
  212744. RegCloseKey (hk);
  212745. }
  212746. return ok;
  212747. }
  212748. void addDriverInfo (const String& keyName, HKEY hk)
  212749. {
  212750. HKEY subKey;
  212751. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212752. {
  212753. WCHAR buf [256];
  212754. zerostruct (buf);
  212755. DWORD dtype = REG_SZ;
  212756. DWORD dsize = sizeof (buf);
  212757. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212758. {
  212759. if (dsize > 0 && checkClassIsOk (buf))
  212760. {
  212761. CLSID classId;
  212762. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212763. {
  212764. dtype = REG_SZ;
  212765. dsize = sizeof (buf);
  212766. String deviceName;
  212767. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212768. deviceName = buf;
  212769. else
  212770. deviceName = keyName;
  212771. log ("found " + deviceName);
  212772. deviceNames.add (deviceName);
  212773. classIds.add (new CLSID (classId));
  212774. }
  212775. }
  212776. RegCloseKey (subKey);
  212777. }
  212778. }
  212779. }
  212780. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212781. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212782. };
  212783. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212784. {
  212785. return new ASIOAudioIODeviceType();
  212786. }
  212787. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212788. void* guid,
  212789. const String& optionalDllForDirectLoading)
  212790. {
  212791. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212792. if (freeSlot < 0)
  212793. return 0;
  212794. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212795. }
  212796. #undef log
  212797. #endif
  212798. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212799. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212800. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212801. // compiled on its own).
  212802. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212803. END_JUCE_NAMESPACE
  212804. extern "C"
  212805. {
  212806. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212807. typedef struct typeDSBUFFERDESC
  212808. {
  212809. DWORD dwSize;
  212810. DWORD dwFlags;
  212811. DWORD dwBufferBytes;
  212812. DWORD dwReserved;
  212813. LPWAVEFORMATEX lpwfxFormat;
  212814. GUID guid3DAlgorithm;
  212815. } DSBUFFERDESC;
  212816. struct IDirectSoundBuffer;
  212817. #undef INTERFACE
  212818. #define INTERFACE IDirectSound
  212819. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  212820. {
  212821. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212822. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212823. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212824. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  212825. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212826. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  212827. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  212828. STDMETHOD(Compact) (THIS) PURE;
  212829. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  212830. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  212831. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212832. };
  212833. #undef INTERFACE
  212834. #define INTERFACE IDirectSoundBuffer
  212835. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  212836. {
  212837. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212838. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212839. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212840. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212841. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212842. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212843. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  212844. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  212845. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  212846. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212847. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  212848. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212849. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  212850. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  212851. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  212852. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  212853. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  212854. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  212855. STDMETHOD(Stop) (THIS) PURE;
  212856. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212857. STDMETHOD(Restore) (THIS) PURE;
  212858. };
  212859. typedef struct typeDSCBUFFERDESC
  212860. {
  212861. DWORD dwSize;
  212862. DWORD dwFlags;
  212863. DWORD dwBufferBytes;
  212864. DWORD dwReserved;
  212865. LPWAVEFORMATEX lpwfxFormat;
  212866. } DSCBUFFERDESC;
  212867. struct IDirectSoundCaptureBuffer;
  212868. #undef INTERFACE
  212869. #define INTERFACE IDirectSoundCapture
  212870. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  212871. {
  212872. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212873. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212874. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212875. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  212876. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212877. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212878. };
  212879. #undef INTERFACE
  212880. #define INTERFACE IDirectSoundCaptureBuffer
  212881. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  212882. {
  212883. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212884. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212885. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212886. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212887. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212888. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212889. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212890. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  212891. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212892. STDMETHOD(Start) (THIS_ DWORD) PURE;
  212893. STDMETHOD(Stop) (THIS) PURE;
  212894. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212895. };
  212896. };
  212897. BEGIN_JUCE_NAMESPACE
  212898. static const String getDSErrorMessage (HRESULT hr)
  212899. {
  212900. const char* result = 0;
  212901. switch (hr)
  212902. {
  212903. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  212904. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  212905. case E_INVALIDARG: result = "Invalid parameter"; break;
  212906. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  212907. case E_FAIL: result = "Generic error"; break;
  212908. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  212909. case E_OUTOFMEMORY: result = "Out of memory"; break;
  212910. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  212911. case E_NOTIMPL: result = "Unsupported function"; break;
  212912. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  212913. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  212914. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  212915. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  212916. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  212917. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  212918. case E_NOINTERFACE: result = "No interface"; break;
  212919. case S_OK: result = "No error"; break;
  212920. default: return "Unknown error: " + String ((int) hr);
  212921. }
  212922. return result;
  212923. }
  212924. #define DS_DEBUGGING 1
  212925. #ifdef DS_DEBUGGING
  212926. #define CATCH JUCE_CATCH_EXCEPTION
  212927. #undef log
  212928. #define log(a) Logger::writeToLog(a);
  212929. #undef logError
  212930. #define logError(a) logDSError(a, __LINE__);
  212931. static void logDSError (HRESULT hr, int lineNum)
  212932. {
  212933. if (hr != S_OK)
  212934. {
  212935. String error ("DS error at line ");
  212936. error << lineNum << " - " << getDSErrorMessage (hr);
  212937. log (error);
  212938. }
  212939. }
  212940. #else
  212941. #define CATCH JUCE_CATCH_ALL
  212942. #define log(a)
  212943. #define logError(a)
  212944. #endif
  212945. #define DSOUND_FUNCTION(functionName, params) \
  212946. typedef HRESULT (WINAPI *type##functionName) params; \
  212947. static type##functionName ds##functionName = 0;
  212948. #define DSOUND_FUNCTION_LOAD(functionName) \
  212949. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  212950. jassert (ds##functionName != 0);
  212951. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  212952. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  212953. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  212954. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  212955. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212956. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212957. static void initialiseDSoundFunctions()
  212958. {
  212959. if (dsDirectSoundCreate == 0)
  212960. {
  212961. HMODULE h = LoadLibraryA ("dsound.dll");
  212962. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  212963. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  212964. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  212965. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  212966. }
  212967. }
  212968. class DSoundInternalOutChannel
  212969. {
  212970. String name;
  212971. LPGUID guid;
  212972. int sampleRate, bufferSizeSamples;
  212973. float* leftBuffer;
  212974. float* rightBuffer;
  212975. IDirectSound* pDirectSound;
  212976. IDirectSoundBuffer* pOutputBuffer;
  212977. DWORD writeOffset;
  212978. int totalBytesPerBuffer;
  212979. int bytesPerBuffer;
  212980. unsigned int lastPlayCursor;
  212981. public:
  212982. int bitDepth;
  212983. bool doneFlag;
  212984. DSoundInternalOutChannel (const String& name_,
  212985. LPGUID guid_,
  212986. int rate,
  212987. int bufferSize,
  212988. float* left,
  212989. float* right)
  212990. : name (name_),
  212991. guid (guid_),
  212992. sampleRate (rate),
  212993. bufferSizeSamples (bufferSize),
  212994. leftBuffer (left),
  212995. rightBuffer (right),
  212996. pDirectSound (0),
  212997. pOutputBuffer (0),
  212998. bitDepth (16)
  212999. {
  213000. }
  213001. ~DSoundInternalOutChannel()
  213002. {
  213003. close();
  213004. }
  213005. void close()
  213006. {
  213007. HRESULT hr;
  213008. if (pOutputBuffer != 0)
  213009. {
  213010. JUCE_TRY
  213011. {
  213012. log ("closing dsound out: " + name);
  213013. hr = pOutputBuffer->Stop();
  213014. logError (hr);
  213015. }
  213016. CATCH
  213017. JUCE_TRY
  213018. {
  213019. hr = pOutputBuffer->Release();
  213020. logError (hr);
  213021. }
  213022. CATCH
  213023. pOutputBuffer = 0;
  213024. }
  213025. if (pDirectSound != 0)
  213026. {
  213027. JUCE_TRY
  213028. {
  213029. hr = pDirectSound->Release();
  213030. logError (hr);
  213031. }
  213032. CATCH
  213033. pDirectSound = 0;
  213034. }
  213035. }
  213036. const String open()
  213037. {
  213038. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213039. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213040. pDirectSound = 0;
  213041. pOutputBuffer = 0;
  213042. writeOffset = 0;
  213043. String error;
  213044. HRESULT hr = E_NOINTERFACE;
  213045. if (dsDirectSoundCreate != 0)
  213046. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213047. if (hr == S_OK)
  213048. {
  213049. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213050. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213051. const int numChannels = 2;
  213052. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213053. logError (hr);
  213054. if (hr == S_OK)
  213055. {
  213056. IDirectSoundBuffer* pPrimaryBuffer;
  213057. DSBUFFERDESC primaryDesc;
  213058. zerostruct (primaryDesc);
  213059. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213060. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213061. primaryDesc.dwBufferBytes = 0;
  213062. primaryDesc.lpwfxFormat = 0;
  213063. log ("opening dsound out step 2");
  213064. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213065. logError (hr);
  213066. if (hr == S_OK)
  213067. {
  213068. WAVEFORMATEX wfFormat;
  213069. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213070. wfFormat.nChannels = (unsigned short) numChannels;
  213071. wfFormat.nSamplesPerSec = sampleRate;
  213072. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213073. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213074. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213075. wfFormat.cbSize = 0;
  213076. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213077. logError (hr);
  213078. if (hr == S_OK)
  213079. {
  213080. DSBUFFERDESC secondaryDesc;
  213081. zerostruct (secondaryDesc);
  213082. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213083. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213084. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213085. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213086. secondaryDesc.lpwfxFormat = &wfFormat;
  213087. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213088. logError (hr);
  213089. if (hr == S_OK)
  213090. {
  213091. log ("opening dsound out step 3");
  213092. DWORD dwDataLen;
  213093. unsigned char* pDSBuffData;
  213094. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213095. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213096. logError (hr);
  213097. if (hr == S_OK)
  213098. {
  213099. zeromem (pDSBuffData, dwDataLen);
  213100. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213101. if (hr == S_OK)
  213102. {
  213103. hr = pOutputBuffer->SetCurrentPosition (0);
  213104. if (hr == S_OK)
  213105. {
  213106. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213107. if (hr == S_OK)
  213108. return String::empty;
  213109. }
  213110. }
  213111. }
  213112. }
  213113. }
  213114. }
  213115. }
  213116. }
  213117. error = getDSErrorMessage (hr);
  213118. close();
  213119. return error;
  213120. }
  213121. void synchronisePosition()
  213122. {
  213123. if (pOutputBuffer != 0)
  213124. {
  213125. DWORD playCursor;
  213126. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213127. }
  213128. }
  213129. bool service()
  213130. {
  213131. if (pOutputBuffer == 0)
  213132. return true;
  213133. DWORD playCursor, writeCursor;
  213134. for (;;)
  213135. {
  213136. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213137. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213138. {
  213139. pOutputBuffer->Restore();
  213140. continue;
  213141. }
  213142. if (hr == S_OK)
  213143. break;
  213144. logError (hr);
  213145. jassertfalse;
  213146. return true;
  213147. }
  213148. int playWriteGap = writeCursor - playCursor;
  213149. if (playWriteGap < 0)
  213150. playWriteGap += totalBytesPerBuffer;
  213151. int bytesEmpty = playCursor - writeOffset;
  213152. if (bytesEmpty < 0)
  213153. bytesEmpty += totalBytesPerBuffer;
  213154. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213155. {
  213156. writeOffset = writeCursor;
  213157. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213158. }
  213159. if (bytesEmpty >= bytesPerBuffer)
  213160. {
  213161. LPBYTE lpbuf1 = 0;
  213162. LPBYTE lpbuf2 = 0;
  213163. DWORD dwSize1 = 0;
  213164. DWORD dwSize2 = 0;
  213165. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  213166. bytesPerBuffer,
  213167. (void**) &lpbuf1, &dwSize1,
  213168. (void**) &lpbuf2, &dwSize2, 0);
  213169. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213170. {
  213171. pOutputBuffer->Restore();
  213172. hr = pOutputBuffer->Lock (writeOffset,
  213173. bytesPerBuffer,
  213174. (void**) &lpbuf1, &dwSize1,
  213175. (void**) &lpbuf2, &dwSize2, 0);
  213176. }
  213177. if (hr == S_OK)
  213178. {
  213179. if (bitDepth == 16)
  213180. {
  213181. const float gainL = 32767.0f;
  213182. const float gainR = 32767.0f;
  213183. int* dest = (int*)lpbuf1;
  213184. const float* left = leftBuffer;
  213185. const float* right = rightBuffer;
  213186. int samples1 = dwSize1 >> 2;
  213187. int samples2 = dwSize2 >> 2;
  213188. if (left == 0)
  213189. {
  213190. while (--samples1 >= 0)
  213191. {
  213192. int r = roundToInt (gainR * *right++);
  213193. if (r < -32768)
  213194. r = -32768;
  213195. else if (r > 32767)
  213196. r = 32767;
  213197. *dest++ = (r << 16);
  213198. }
  213199. dest = (int*)lpbuf2;
  213200. while (--samples2 >= 0)
  213201. {
  213202. int r = roundToInt (gainR * *right++);
  213203. if (r < -32768)
  213204. r = -32768;
  213205. else if (r > 32767)
  213206. r = 32767;
  213207. *dest++ = (r << 16);
  213208. }
  213209. }
  213210. else if (right == 0)
  213211. {
  213212. while (--samples1 >= 0)
  213213. {
  213214. int l = roundToInt (gainL * *left++);
  213215. if (l < -32768)
  213216. l = -32768;
  213217. else if (l > 32767)
  213218. l = 32767;
  213219. l &= 0xffff;
  213220. *dest++ = l;
  213221. }
  213222. dest = (int*)lpbuf2;
  213223. while (--samples2 >= 0)
  213224. {
  213225. int l = roundToInt (gainL * *left++);
  213226. if (l < -32768)
  213227. l = -32768;
  213228. else if (l > 32767)
  213229. l = 32767;
  213230. l &= 0xffff;
  213231. *dest++ = l;
  213232. }
  213233. }
  213234. else
  213235. {
  213236. while (--samples1 >= 0)
  213237. {
  213238. int l = roundToInt (gainL * *left++);
  213239. if (l < -32768)
  213240. l = -32768;
  213241. else if (l > 32767)
  213242. l = 32767;
  213243. l &= 0xffff;
  213244. int r = roundToInt (gainR * *right++);
  213245. if (r < -32768)
  213246. r = -32768;
  213247. else if (r > 32767)
  213248. r = 32767;
  213249. *dest++ = (r << 16) | l;
  213250. }
  213251. dest = (int*)lpbuf2;
  213252. while (--samples2 >= 0)
  213253. {
  213254. int l = roundToInt (gainL * *left++);
  213255. if (l < -32768)
  213256. l = -32768;
  213257. else if (l > 32767)
  213258. l = 32767;
  213259. l &= 0xffff;
  213260. int r = roundToInt (gainR * *right++);
  213261. if (r < -32768)
  213262. r = -32768;
  213263. else if (r > 32767)
  213264. r = 32767;
  213265. *dest++ = (r << 16) | l;
  213266. }
  213267. }
  213268. }
  213269. else
  213270. {
  213271. jassertfalse;
  213272. }
  213273. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213274. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213275. }
  213276. else
  213277. {
  213278. jassertfalse;
  213279. logError (hr);
  213280. }
  213281. bytesEmpty -= bytesPerBuffer;
  213282. return true;
  213283. }
  213284. else
  213285. {
  213286. return false;
  213287. }
  213288. }
  213289. };
  213290. struct DSoundInternalInChannel
  213291. {
  213292. String name;
  213293. LPGUID guid;
  213294. int sampleRate, bufferSizeSamples;
  213295. float* leftBuffer;
  213296. float* rightBuffer;
  213297. IDirectSound* pDirectSound;
  213298. IDirectSoundCapture* pDirectSoundCapture;
  213299. IDirectSoundCaptureBuffer* pInputBuffer;
  213300. public:
  213301. unsigned int readOffset;
  213302. int bytesPerBuffer, totalBytesPerBuffer;
  213303. int bitDepth;
  213304. bool doneFlag;
  213305. DSoundInternalInChannel (const String& name_,
  213306. LPGUID guid_,
  213307. int rate,
  213308. int bufferSize,
  213309. float* left,
  213310. float* right)
  213311. : name (name_),
  213312. guid (guid_),
  213313. sampleRate (rate),
  213314. bufferSizeSamples (bufferSize),
  213315. leftBuffer (left),
  213316. rightBuffer (right),
  213317. pDirectSound (0),
  213318. pDirectSoundCapture (0),
  213319. pInputBuffer (0),
  213320. bitDepth (16)
  213321. {
  213322. }
  213323. ~DSoundInternalInChannel()
  213324. {
  213325. close();
  213326. }
  213327. void close()
  213328. {
  213329. HRESULT hr;
  213330. if (pInputBuffer != 0)
  213331. {
  213332. JUCE_TRY
  213333. {
  213334. log ("closing dsound in: " + name);
  213335. hr = pInputBuffer->Stop();
  213336. logError (hr);
  213337. }
  213338. CATCH
  213339. JUCE_TRY
  213340. {
  213341. hr = pInputBuffer->Release();
  213342. logError (hr);
  213343. }
  213344. CATCH
  213345. pInputBuffer = 0;
  213346. }
  213347. if (pDirectSoundCapture != 0)
  213348. {
  213349. JUCE_TRY
  213350. {
  213351. hr = pDirectSoundCapture->Release();
  213352. logError (hr);
  213353. }
  213354. CATCH
  213355. pDirectSoundCapture = 0;
  213356. }
  213357. if (pDirectSound != 0)
  213358. {
  213359. JUCE_TRY
  213360. {
  213361. hr = pDirectSound->Release();
  213362. logError (hr);
  213363. }
  213364. CATCH
  213365. pDirectSound = 0;
  213366. }
  213367. }
  213368. const String open()
  213369. {
  213370. log ("opening dsound in device: " + name
  213371. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213372. pDirectSound = 0;
  213373. pDirectSoundCapture = 0;
  213374. pInputBuffer = 0;
  213375. readOffset = 0;
  213376. totalBytesPerBuffer = 0;
  213377. String error;
  213378. HRESULT hr = E_NOINTERFACE;
  213379. if (dsDirectSoundCaptureCreate != 0)
  213380. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213381. logError (hr);
  213382. if (hr == S_OK)
  213383. {
  213384. const int numChannels = 2;
  213385. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213386. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213387. WAVEFORMATEX wfFormat;
  213388. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213389. wfFormat.nChannels = (unsigned short)numChannels;
  213390. wfFormat.nSamplesPerSec = sampleRate;
  213391. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213392. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213393. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213394. wfFormat.cbSize = 0;
  213395. DSCBUFFERDESC captureDesc;
  213396. zerostruct (captureDesc);
  213397. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213398. captureDesc.dwFlags = 0;
  213399. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213400. captureDesc.lpwfxFormat = &wfFormat;
  213401. log ("opening dsound in step 2");
  213402. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213403. logError (hr);
  213404. if (hr == S_OK)
  213405. {
  213406. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213407. logError (hr);
  213408. if (hr == S_OK)
  213409. return String::empty;
  213410. }
  213411. }
  213412. error = getDSErrorMessage (hr);
  213413. close();
  213414. return error;
  213415. }
  213416. void synchronisePosition()
  213417. {
  213418. if (pInputBuffer != 0)
  213419. {
  213420. DWORD capturePos;
  213421. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213422. }
  213423. }
  213424. bool service()
  213425. {
  213426. if (pInputBuffer == 0)
  213427. return true;
  213428. DWORD capturePos, readPos;
  213429. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213430. logError (hr);
  213431. if (hr != S_OK)
  213432. return true;
  213433. int bytesFilled = readPos - readOffset;
  213434. if (bytesFilled < 0)
  213435. bytesFilled += totalBytesPerBuffer;
  213436. if (bytesFilled >= bytesPerBuffer)
  213437. {
  213438. LPBYTE lpbuf1 = 0;
  213439. LPBYTE lpbuf2 = 0;
  213440. DWORD dwsize1 = 0;
  213441. DWORD dwsize2 = 0;
  213442. HRESULT hr = pInputBuffer->Lock (readOffset,
  213443. bytesPerBuffer,
  213444. (void**) &lpbuf1, &dwsize1,
  213445. (void**) &lpbuf2, &dwsize2, 0);
  213446. if (hr == S_OK)
  213447. {
  213448. if (bitDepth == 16)
  213449. {
  213450. const float g = 1.0f / 32768.0f;
  213451. float* destL = leftBuffer;
  213452. float* destR = rightBuffer;
  213453. int samples1 = dwsize1 >> 2;
  213454. int samples2 = dwsize2 >> 2;
  213455. const short* src = (const short*)lpbuf1;
  213456. if (destL == 0)
  213457. {
  213458. while (--samples1 >= 0)
  213459. {
  213460. ++src;
  213461. *destR++ = *src++ * g;
  213462. }
  213463. src = (const short*)lpbuf2;
  213464. while (--samples2 >= 0)
  213465. {
  213466. ++src;
  213467. *destR++ = *src++ * g;
  213468. }
  213469. }
  213470. else if (destR == 0)
  213471. {
  213472. while (--samples1 >= 0)
  213473. {
  213474. *destL++ = *src++ * g;
  213475. ++src;
  213476. }
  213477. src = (const short*)lpbuf2;
  213478. while (--samples2 >= 0)
  213479. {
  213480. *destL++ = *src++ * g;
  213481. ++src;
  213482. }
  213483. }
  213484. else
  213485. {
  213486. while (--samples1 >= 0)
  213487. {
  213488. *destL++ = *src++ * g;
  213489. *destR++ = *src++ * g;
  213490. }
  213491. src = (const short*)lpbuf2;
  213492. while (--samples2 >= 0)
  213493. {
  213494. *destL++ = *src++ * g;
  213495. *destR++ = *src++ * g;
  213496. }
  213497. }
  213498. }
  213499. else
  213500. {
  213501. jassertfalse;
  213502. }
  213503. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213504. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213505. }
  213506. else
  213507. {
  213508. logError (hr);
  213509. jassertfalse;
  213510. }
  213511. bytesFilled -= bytesPerBuffer;
  213512. return true;
  213513. }
  213514. else
  213515. {
  213516. return false;
  213517. }
  213518. }
  213519. };
  213520. class DSoundAudioIODevice : public AudioIODevice,
  213521. public Thread
  213522. {
  213523. public:
  213524. DSoundAudioIODevice (const String& deviceName,
  213525. const int outputDeviceIndex_,
  213526. const int inputDeviceIndex_)
  213527. : AudioIODevice (deviceName, "DirectSound"),
  213528. Thread ("Juce DSound"),
  213529. isOpen_ (false),
  213530. isStarted (false),
  213531. outputDeviceIndex (outputDeviceIndex_),
  213532. inputDeviceIndex (inputDeviceIndex_),
  213533. totalSamplesOut (0),
  213534. sampleRate (0.0),
  213535. inputBuffers (1, 1),
  213536. outputBuffers (1, 1),
  213537. callback (0),
  213538. bufferSizeSamples (0)
  213539. {
  213540. if (outputDeviceIndex_ >= 0)
  213541. {
  213542. outChannels.add (TRANS("Left"));
  213543. outChannels.add (TRANS("Right"));
  213544. }
  213545. if (inputDeviceIndex_ >= 0)
  213546. {
  213547. inChannels.add (TRANS("Left"));
  213548. inChannels.add (TRANS("Right"));
  213549. }
  213550. }
  213551. ~DSoundAudioIODevice()
  213552. {
  213553. close();
  213554. }
  213555. const StringArray getOutputChannelNames()
  213556. {
  213557. return outChannels;
  213558. }
  213559. const StringArray getInputChannelNames()
  213560. {
  213561. return inChannels;
  213562. }
  213563. int getNumSampleRates()
  213564. {
  213565. return 4;
  213566. }
  213567. double getSampleRate (int index)
  213568. {
  213569. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213570. return samps [jlimit (0, 3, index)];
  213571. }
  213572. int getNumBufferSizesAvailable()
  213573. {
  213574. return 50;
  213575. }
  213576. int getBufferSizeSamples (int index)
  213577. {
  213578. int n = 64;
  213579. for (int i = 0; i < index; ++i)
  213580. n += (n < 512) ? 32
  213581. : ((n < 1024) ? 64
  213582. : ((n < 2048) ? 128 : 256));
  213583. return n;
  213584. }
  213585. int getDefaultBufferSize()
  213586. {
  213587. return 2560;
  213588. }
  213589. const String open (const BigInteger& inputChannels,
  213590. const BigInteger& outputChannels,
  213591. double sampleRate,
  213592. int bufferSizeSamples)
  213593. {
  213594. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213595. isOpen_ = lastError.isEmpty();
  213596. return lastError;
  213597. }
  213598. void close()
  213599. {
  213600. stop();
  213601. if (isOpen_)
  213602. {
  213603. closeDevice();
  213604. isOpen_ = false;
  213605. }
  213606. }
  213607. bool isOpen()
  213608. {
  213609. return isOpen_ && isThreadRunning();
  213610. }
  213611. int getCurrentBufferSizeSamples()
  213612. {
  213613. return bufferSizeSamples;
  213614. }
  213615. double getCurrentSampleRate()
  213616. {
  213617. return sampleRate;
  213618. }
  213619. int getCurrentBitDepth()
  213620. {
  213621. int i, bits = 256;
  213622. for (i = inChans.size(); --i >= 0;)
  213623. bits = jmin (bits, inChans[i]->bitDepth);
  213624. for (i = outChans.size(); --i >= 0;)
  213625. bits = jmin (bits, outChans[i]->bitDepth);
  213626. if (bits > 32)
  213627. bits = 16;
  213628. return bits;
  213629. }
  213630. const BigInteger getActiveOutputChannels() const
  213631. {
  213632. return enabledOutputs;
  213633. }
  213634. const BigInteger getActiveInputChannels() const
  213635. {
  213636. return enabledInputs;
  213637. }
  213638. int getOutputLatencyInSamples()
  213639. {
  213640. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213641. }
  213642. int getInputLatencyInSamples()
  213643. {
  213644. return getOutputLatencyInSamples();
  213645. }
  213646. void start (AudioIODeviceCallback* call)
  213647. {
  213648. if (isOpen_ && call != 0 && ! isStarted)
  213649. {
  213650. if (! isThreadRunning())
  213651. {
  213652. // something gone wrong and the thread's stopped..
  213653. isOpen_ = false;
  213654. return;
  213655. }
  213656. call->audioDeviceAboutToStart (this);
  213657. const ScopedLock sl (startStopLock);
  213658. callback = call;
  213659. isStarted = true;
  213660. }
  213661. }
  213662. void stop()
  213663. {
  213664. if (isStarted)
  213665. {
  213666. AudioIODeviceCallback* const callbackLocal = callback;
  213667. {
  213668. const ScopedLock sl (startStopLock);
  213669. isStarted = false;
  213670. }
  213671. if (callbackLocal != 0)
  213672. callbackLocal->audioDeviceStopped();
  213673. }
  213674. }
  213675. bool isPlaying()
  213676. {
  213677. return isStarted && isOpen_ && isThreadRunning();
  213678. }
  213679. const String getLastError()
  213680. {
  213681. return lastError;
  213682. }
  213683. juce_UseDebuggingNewOperator
  213684. StringArray inChannels, outChannels;
  213685. int outputDeviceIndex, inputDeviceIndex;
  213686. private:
  213687. bool isOpen_;
  213688. bool isStarted;
  213689. String lastError;
  213690. OwnedArray <DSoundInternalInChannel> inChans;
  213691. OwnedArray <DSoundInternalOutChannel> outChans;
  213692. WaitableEvent startEvent;
  213693. int bufferSizeSamples;
  213694. int volatile totalSamplesOut;
  213695. int64 volatile lastBlockTime;
  213696. double sampleRate;
  213697. BigInteger enabledInputs, enabledOutputs;
  213698. AudioSampleBuffer inputBuffers, outputBuffers;
  213699. AudioIODeviceCallback* callback;
  213700. CriticalSection startStopLock;
  213701. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213702. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213703. const String openDevice (const BigInteger& inputChannels,
  213704. const BigInteger& outputChannels,
  213705. double sampleRate_,
  213706. int bufferSizeSamples_);
  213707. void closeDevice()
  213708. {
  213709. isStarted = false;
  213710. stopThread (5000);
  213711. inChans.clear();
  213712. outChans.clear();
  213713. inputBuffers.setSize (1, 1);
  213714. outputBuffers.setSize (1, 1);
  213715. }
  213716. void resync()
  213717. {
  213718. if (! threadShouldExit())
  213719. {
  213720. sleep (5);
  213721. int i;
  213722. for (i = 0; i < outChans.size(); ++i)
  213723. outChans.getUnchecked(i)->synchronisePosition();
  213724. for (i = 0; i < inChans.size(); ++i)
  213725. inChans.getUnchecked(i)->synchronisePosition();
  213726. }
  213727. }
  213728. public:
  213729. void run()
  213730. {
  213731. while (! threadShouldExit())
  213732. {
  213733. if (wait (100))
  213734. break;
  213735. }
  213736. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213737. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213738. while (! threadShouldExit())
  213739. {
  213740. int numToDo = 0;
  213741. uint32 startTime = Time::getMillisecondCounter();
  213742. int i;
  213743. for (i = inChans.size(); --i >= 0;)
  213744. {
  213745. inChans.getUnchecked(i)->doneFlag = false;
  213746. ++numToDo;
  213747. }
  213748. for (i = outChans.size(); --i >= 0;)
  213749. {
  213750. outChans.getUnchecked(i)->doneFlag = false;
  213751. ++numToDo;
  213752. }
  213753. if (numToDo > 0)
  213754. {
  213755. const int maxCount = 3;
  213756. int count = maxCount;
  213757. for (;;)
  213758. {
  213759. for (i = inChans.size(); --i >= 0;)
  213760. {
  213761. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213762. if ((! in->doneFlag) && in->service())
  213763. {
  213764. in->doneFlag = true;
  213765. --numToDo;
  213766. }
  213767. }
  213768. for (i = outChans.size(); --i >= 0;)
  213769. {
  213770. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213771. if ((! out->doneFlag) && out->service())
  213772. {
  213773. out->doneFlag = true;
  213774. --numToDo;
  213775. }
  213776. }
  213777. if (numToDo <= 0)
  213778. break;
  213779. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213780. {
  213781. resync();
  213782. break;
  213783. }
  213784. if (--count <= 0)
  213785. {
  213786. Sleep (1);
  213787. count = maxCount;
  213788. }
  213789. if (threadShouldExit())
  213790. return;
  213791. }
  213792. }
  213793. else
  213794. {
  213795. sleep (1);
  213796. }
  213797. const ScopedLock sl (startStopLock);
  213798. if (isStarted)
  213799. {
  213800. JUCE_TRY
  213801. {
  213802. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213803. inputBuffers.getNumChannels(),
  213804. outputBuffers.getArrayOfChannels(),
  213805. outputBuffers.getNumChannels(),
  213806. bufferSizeSamples);
  213807. }
  213808. JUCE_CATCH_EXCEPTION
  213809. totalSamplesOut += bufferSizeSamples;
  213810. }
  213811. else
  213812. {
  213813. outputBuffers.clear();
  213814. totalSamplesOut = 0;
  213815. sleep (1);
  213816. }
  213817. }
  213818. }
  213819. };
  213820. class DSoundAudioIODeviceType : public AudioIODeviceType
  213821. {
  213822. public:
  213823. DSoundAudioIODeviceType()
  213824. : AudioIODeviceType ("DirectSound"),
  213825. hasScanned (false)
  213826. {
  213827. initialiseDSoundFunctions();
  213828. }
  213829. ~DSoundAudioIODeviceType()
  213830. {
  213831. }
  213832. void scanForDevices()
  213833. {
  213834. hasScanned = true;
  213835. outputDeviceNames.clear();
  213836. outputGuids.clear();
  213837. inputDeviceNames.clear();
  213838. inputGuids.clear();
  213839. if (dsDirectSoundEnumerateW != 0)
  213840. {
  213841. dsDirectSoundEnumerateW (outputEnumProcW, this);
  213842. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  213843. }
  213844. }
  213845. const StringArray getDeviceNames (bool wantInputNames) const
  213846. {
  213847. jassert (hasScanned); // need to call scanForDevices() before doing this
  213848. return wantInputNames ? inputDeviceNames
  213849. : outputDeviceNames;
  213850. }
  213851. int getDefaultDeviceIndex (bool /*forInput*/) const
  213852. {
  213853. jassert (hasScanned); // need to call scanForDevices() before doing this
  213854. return 0;
  213855. }
  213856. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  213857. {
  213858. jassert (hasScanned); // need to call scanForDevices() before doing this
  213859. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  213860. if (d == 0)
  213861. return -1;
  213862. return asInput ? d->inputDeviceIndex
  213863. : d->outputDeviceIndex;
  213864. }
  213865. bool hasSeparateInputsAndOutputs() const { return true; }
  213866. AudioIODevice* createDevice (const String& outputDeviceName,
  213867. const String& inputDeviceName)
  213868. {
  213869. jassert (hasScanned); // need to call scanForDevices() before doing this
  213870. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  213871. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  213872. if (outputIndex >= 0 || inputIndex >= 0)
  213873. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  213874. : inputDeviceName,
  213875. outputIndex, inputIndex);
  213876. return 0;
  213877. }
  213878. juce_UseDebuggingNewOperator
  213879. StringArray outputDeviceNames;
  213880. OwnedArray <GUID> outputGuids;
  213881. StringArray inputDeviceNames;
  213882. OwnedArray <GUID> inputGuids;
  213883. private:
  213884. bool hasScanned;
  213885. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  213886. {
  213887. desc = desc.trim();
  213888. if (desc.isNotEmpty())
  213889. {
  213890. const String origDesc (desc);
  213891. int n = 2;
  213892. while (outputDeviceNames.contains (desc))
  213893. desc = origDesc + " (" + String (n++) + ")";
  213894. outputDeviceNames.add (desc);
  213895. if (lpGUID != 0)
  213896. outputGuids.add (new GUID (*lpGUID));
  213897. else
  213898. outputGuids.add (0);
  213899. }
  213900. return TRUE;
  213901. }
  213902. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213903. {
  213904. return ((DSoundAudioIODeviceType*) object)
  213905. ->outputEnumProc (lpGUID, String (description));
  213906. }
  213907. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213908. {
  213909. return ((DSoundAudioIODeviceType*) object)
  213910. ->outputEnumProc (lpGUID, String (description));
  213911. }
  213912. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  213913. {
  213914. desc = desc.trim();
  213915. if (desc.isNotEmpty())
  213916. {
  213917. const String origDesc (desc);
  213918. int n = 2;
  213919. while (inputDeviceNames.contains (desc))
  213920. desc = origDesc + " (" + String (n++) + ")";
  213921. inputDeviceNames.add (desc);
  213922. if (lpGUID != 0)
  213923. inputGuids.add (new GUID (*lpGUID));
  213924. else
  213925. inputGuids.add (0);
  213926. }
  213927. return TRUE;
  213928. }
  213929. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213930. {
  213931. return ((DSoundAudioIODeviceType*) object)
  213932. ->inputEnumProc (lpGUID, String (description));
  213933. }
  213934. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213935. {
  213936. return ((DSoundAudioIODeviceType*) object)
  213937. ->inputEnumProc (lpGUID, String (description));
  213938. }
  213939. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  213940. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  213941. };
  213942. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  213943. const BigInteger& outputChannels,
  213944. double sampleRate_,
  213945. int bufferSizeSamples_)
  213946. {
  213947. closeDevice();
  213948. totalSamplesOut = 0;
  213949. sampleRate = sampleRate_;
  213950. if (bufferSizeSamples_ <= 0)
  213951. bufferSizeSamples_ = 960; // use as a default size if none is set.
  213952. bufferSizeSamples = bufferSizeSamples_ & ~7;
  213953. DSoundAudioIODeviceType dlh;
  213954. dlh.scanForDevices();
  213955. enabledInputs = inputChannels;
  213956. enabledInputs.setRange (inChannels.size(),
  213957. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  213958. false);
  213959. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  213960. inputBuffers.clear();
  213961. int i, numIns = 0;
  213962. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  213963. {
  213964. float* left = 0;
  213965. if (enabledInputs[i])
  213966. left = inputBuffers.getSampleData (numIns++);
  213967. float* right = 0;
  213968. if (enabledInputs[i + 1])
  213969. right = inputBuffers.getSampleData (numIns++);
  213970. if (left != 0 || right != 0)
  213971. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  213972. dlh.inputGuids [inputDeviceIndex],
  213973. (int) sampleRate, bufferSizeSamples,
  213974. left, right));
  213975. }
  213976. enabledOutputs = outputChannels;
  213977. enabledOutputs.setRange (outChannels.size(),
  213978. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  213979. false);
  213980. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  213981. outputBuffers.clear();
  213982. int numOuts = 0;
  213983. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  213984. {
  213985. float* left = 0;
  213986. if (enabledOutputs[i])
  213987. left = outputBuffers.getSampleData (numOuts++);
  213988. float* right = 0;
  213989. if (enabledOutputs[i + 1])
  213990. right = outputBuffers.getSampleData (numOuts++);
  213991. if (left != 0 || right != 0)
  213992. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  213993. dlh.outputGuids [outputDeviceIndex],
  213994. (int) sampleRate, bufferSizeSamples,
  213995. left, right));
  213996. }
  213997. String error;
  213998. // boost our priority while opening the devices to try to get better sync between them
  213999. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214000. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214001. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214002. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214003. for (i = 0; i < outChans.size(); ++i)
  214004. {
  214005. error = outChans[i]->open();
  214006. if (error.isNotEmpty())
  214007. {
  214008. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214009. break;
  214010. }
  214011. }
  214012. if (error.isEmpty())
  214013. {
  214014. for (i = 0; i < inChans.size(); ++i)
  214015. {
  214016. error = inChans[i]->open();
  214017. if (error.isNotEmpty())
  214018. {
  214019. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214020. break;
  214021. }
  214022. }
  214023. }
  214024. if (error.isEmpty())
  214025. {
  214026. totalSamplesOut = 0;
  214027. for (i = 0; i < outChans.size(); ++i)
  214028. outChans.getUnchecked(i)->synchronisePosition();
  214029. for (i = 0; i < inChans.size(); ++i)
  214030. inChans.getUnchecked(i)->synchronisePosition();
  214031. startThread (9);
  214032. sleep (10);
  214033. notify();
  214034. }
  214035. else
  214036. {
  214037. log (error);
  214038. }
  214039. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214040. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214041. return error;
  214042. }
  214043. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214044. {
  214045. return new DSoundAudioIODeviceType();
  214046. }
  214047. #undef log
  214048. #endif
  214049. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214050. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214051. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214052. // compiled on its own).
  214053. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214054. #if 1
  214055. const String getAudioErrorDesc (HRESULT hr)
  214056. {
  214057. const char* e = 0;
  214058. switch (hr)
  214059. {
  214060. case E_POINTER: e = "E_POINTER"; break;
  214061. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  214062. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  214063. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214064. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214065. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214066. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  214067. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214068. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  214069. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214070. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  214071. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  214072. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214073. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214074. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214075. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214076. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214077. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214078. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214079. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214080. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214081. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214082. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214083. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  214084. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214085. default: return String::toHexString ((int) hr);
  214086. }
  214087. return e;
  214088. }
  214089. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  214090. #define OK(a) wasapi_checkResult(a)
  214091. static bool wasapi_checkResult (HRESULT hr)
  214092. {
  214093. logFailure (hr);
  214094. return SUCCEEDED (hr);
  214095. }
  214096. #else
  214097. #define logFailure(hr) {}
  214098. #define OK(a) SUCCEEDED(a)
  214099. #endif
  214100. static const String wasapi_getDeviceID (IMMDevice* const device)
  214101. {
  214102. String s;
  214103. WCHAR* deviceId = 0;
  214104. if (OK (device->GetId (&deviceId)))
  214105. {
  214106. s = String (deviceId);
  214107. CoTaskMemFree (deviceId);
  214108. }
  214109. return s;
  214110. }
  214111. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  214112. {
  214113. EDataFlow flow = eRender;
  214114. ComSmartPtr <IMMEndpoint> endPoint;
  214115. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  214116. (void) OK (endPoint->GetDataFlow (&flow));
  214117. return flow;
  214118. }
  214119. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214120. {
  214121. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214122. }
  214123. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214124. {
  214125. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214126. : sizeof (WAVEFORMATEX));
  214127. }
  214128. class WASAPIDeviceBase
  214129. {
  214130. public:
  214131. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214132. : device (device_),
  214133. sampleRate (0),
  214134. numChannels (0),
  214135. actualNumChannels (0),
  214136. defaultSampleRate (0),
  214137. minBufferSize (0),
  214138. defaultBufferSize (0),
  214139. latencySamples (0),
  214140. useExclusiveMode (useExclusiveMode_)
  214141. {
  214142. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214143. ComSmartPtr <IAudioClient> tempClient (createClient());
  214144. if (tempClient == 0)
  214145. return;
  214146. REFERENCE_TIME defaultPeriod, minPeriod;
  214147. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214148. return;
  214149. WAVEFORMATEX* mixFormat = 0;
  214150. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  214151. return;
  214152. WAVEFORMATEXTENSIBLE format;
  214153. wasapi_copyWavFormat (format, mixFormat);
  214154. CoTaskMemFree (mixFormat);
  214155. actualNumChannels = numChannels = format.Format.nChannels;
  214156. defaultSampleRate = format.Format.nSamplesPerSec;
  214157. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  214158. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  214159. rates.addUsingDefaultSort (defaultSampleRate);
  214160. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214161. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214162. {
  214163. if (ratesToTest[i] == defaultSampleRate)
  214164. continue;
  214165. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214166. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214167. (WAVEFORMATEX*) &format, 0)))
  214168. if (! rates.contains (ratesToTest[i]))
  214169. rates.addUsingDefaultSort (ratesToTest[i]);
  214170. }
  214171. }
  214172. ~WASAPIDeviceBase()
  214173. {
  214174. device = 0;
  214175. CloseHandle (clientEvent);
  214176. }
  214177. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214178. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214179. {
  214180. sampleRate = newSampleRate;
  214181. channels = newChannels;
  214182. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214183. numChannels = channels.getHighestBit() + 1;
  214184. if (numChannels == 0)
  214185. return true;
  214186. client = createClient();
  214187. if (client != 0
  214188. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214189. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214190. {
  214191. channelMaps.clear();
  214192. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214193. if (channels[i])
  214194. channelMaps.add (i);
  214195. REFERENCE_TIME latency;
  214196. if (OK (client->GetStreamLatency (&latency)))
  214197. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  214198. (void) OK (client->GetBufferSize (&actualBufferSize));
  214199. return OK (client->SetEventHandle (clientEvent));
  214200. }
  214201. return false;
  214202. }
  214203. void closeClient()
  214204. {
  214205. if (client != 0)
  214206. client->Stop();
  214207. client = 0;
  214208. ResetEvent (clientEvent);
  214209. }
  214210. ComSmartPtr <IMMDevice> device;
  214211. ComSmartPtr <IAudioClient> client;
  214212. double sampleRate, defaultSampleRate;
  214213. int numChannels, actualNumChannels;
  214214. int minBufferSize, defaultBufferSize, latencySamples;
  214215. const bool useExclusiveMode;
  214216. Array <double> rates;
  214217. HANDLE clientEvent;
  214218. BigInteger channels;
  214219. AudioDataConverters::DataFormat dataFormat;
  214220. Array <int> channelMaps;
  214221. UINT32 actualBufferSize;
  214222. int bytesPerSample;
  214223. private:
  214224. const ComSmartPtr <IAudioClient> createClient()
  214225. {
  214226. ComSmartPtr <IAudioClient> client;
  214227. if (device != 0)
  214228. {
  214229. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  214230. logFailure (hr);
  214231. }
  214232. return client;
  214233. }
  214234. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214235. {
  214236. WAVEFORMATEXTENSIBLE format;
  214237. zerostruct (format);
  214238. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214239. {
  214240. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214241. }
  214242. else
  214243. {
  214244. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214245. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214246. }
  214247. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214248. format.Format.nChannels = (WORD) numChannels;
  214249. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214250. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214251. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214252. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214253. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214254. switch (numChannels)
  214255. {
  214256. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214257. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214258. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214259. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214260. 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;
  214261. default: break;
  214262. }
  214263. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214264. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214265. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214266. logFailure (hr);
  214267. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214268. {
  214269. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214270. hr = S_OK;
  214271. }
  214272. CoTaskMemFree (nearestFormat);
  214273. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214274. if (useExclusiveMode)
  214275. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214276. GUID session;
  214277. if (hr == S_OK
  214278. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214279. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214280. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214281. {
  214282. actualNumChannels = format.Format.nChannels;
  214283. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214284. bytesPerSample = format.Format.wBitsPerSample / 8;
  214285. dataFormat = isFloat ? AudioDataConverters::float32LE
  214286. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214287. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214288. : AudioDataConverters::int16LE)));
  214289. return true;
  214290. }
  214291. return false;
  214292. }
  214293. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214294. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214295. };
  214296. class WASAPIInputDevice : public WASAPIDeviceBase
  214297. {
  214298. public:
  214299. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214300. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214301. reservoir (1, 1)
  214302. {
  214303. }
  214304. ~WASAPIInputDevice()
  214305. {
  214306. close();
  214307. }
  214308. bool open (const double newSampleRate, const BigInteger& newChannels)
  214309. {
  214310. reservoirSize = 0;
  214311. reservoirCapacity = 16384;
  214312. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214313. return openClient (newSampleRate, newChannels)
  214314. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214315. }
  214316. void close()
  214317. {
  214318. closeClient();
  214319. captureClient = 0;
  214320. reservoir.setSize (0);
  214321. }
  214322. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214323. {
  214324. if (numChannels <= 0)
  214325. return;
  214326. int offset = 0;
  214327. while (bufferSize > 0)
  214328. {
  214329. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214330. {
  214331. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214332. for (int i = 0; i < numDestBuffers; ++i)
  214333. {
  214334. float* const dest = destBuffers[i] + offset;
  214335. const int srcChan = channelMaps.getUnchecked(i);
  214336. switch (dataFormat)
  214337. {
  214338. case AudioDataConverters::float32LE:
  214339. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214340. break;
  214341. case AudioDataConverters::int32LE:
  214342. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214343. break;
  214344. case AudioDataConverters::int24LE:
  214345. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214346. break;
  214347. case AudioDataConverters::int16LE:
  214348. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214349. break;
  214350. default: jassertfalse; break;
  214351. }
  214352. }
  214353. bufferSize -= samplesToDo;
  214354. offset += samplesToDo;
  214355. reservoirSize -= samplesToDo;
  214356. }
  214357. else
  214358. {
  214359. UINT32 packetLength = 0;
  214360. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214361. break;
  214362. if (packetLength == 0)
  214363. {
  214364. if (thread.threadShouldExit())
  214365. break;
  214366. Thread::sleep (1);
  214367. continue;
  214368. }
  214369. uint8* inputData = 0;
  214370. UINT32 numSamplesAvailable;
  214371. DWORD flags;
  214372. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214373. {
  214374. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214375. for (int i = 0; i < numDestBuffers; ++i)
  214376. {
  214377. float* const dest = destBuffers[i] + offset;
  214378. const int srcChan = channelMaps.getUnchecked(i);
  214379. switch (dataFormat)
  214380. {
  214381. case AudioDataConverters::float32LE:
  214382. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214383. break;
  214384. case AudioDataConverters::int32LE:
  214385. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214386. break;
  214387. case AudioDataConverters::int24LE:
  214388. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214389. break;
  214390. case AudioDataConverters::int16LE:
  214391. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214392. break;
  214393. default: jassertfalse; break;
  214394. }
  214395. }
  214396. bufferSize -= samplesToDo;
  214397. offset += samplesToDo;
  214398. if (samplesToDo < (int) numSamplesAvailable)
  214399. {
  214400. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214401. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214402. bytesPerSample * actualNumChannels * reservoirSize);
  214403. }
  214404. captureClient->ReleaseBuffer (numSamplesAvailable);
  214405. }
  214406. }
  214407. }
  214408. }
  214409. ComSmartPtr <IAudioCaptureClient> captureClient;
  214410. MemoryBlock reservoir;
  214411. int reservoirSize, reservoirCapacity;
  214412. private:
  214413. WASAPIInputDevice (const WASAPIInputDevice&);
  214414. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214415. };
  214416. class WASAPIOutputDevice : public WASAPIDeviceBase
  214417. {
  214418. public:
  214419. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214420. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214421. {
  214422. }
  214423. ~WASAPIOutputDevice()
  214424. {
  214425. close();
  214426. }
  214427. bool open (const double newSampleRate, const BigInteger& newChannels)
  214428. {
  214429. return openClient (newSampleRate, newChannels)
  214430. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214431. }
  214432. void close()
  214433. {
  214434. closeClient();
  214435. renderClient = 0;
  214436. }
  214437. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214438. {
  214439. if (numChannels <= 0)
  214440. return;
  214441. int offset = 0;
  214442. while (bufferSize > 0)
  214443. {
  214444. UINT32 padding = 0;
  214445. if (! OK (client->GetCurrentPadding (&padding)))
  214446. return;
  214447. int samplesToDo = useExclusiveMode ? bufferSize
  214448. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214449. if (samplesToDo <= 0)
  214450. {
  214451. if (thread.threadShouldExit())
  214452. break;
  214453. Thread::sleep (0);
  214454. continue;
  214455. }
  214456. uint8* outputData = 0;
  214457. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214458. {
  214459. for (int i = 0; i < numSrcBuffers; ++i)
  214460. {
  214461. const float* const source = srcBuffers[i] + offset;
  214462. const int destChan = channelMaps.getUnchecked(i);
  214463. switch (dataFormat)
  214464. {
  214465. case AudioDataConverters::float32LE:
  214466. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214467. break;
  214468. case AudioDataConverters::int32LE:
  214469. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214470. break;
  214471. case AudioDataConverters::int24LE:
  214472. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214473. break;
  214474. case AudioDataConverters::int16LE:
  214475. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214476. break;
  214477. default: jassertfalse; break;
  214478. }
  214479. }
  214480. renderClient->ReleaseBuffer (samplesToDo, 0);
  214481. offset += samplesToDo;
  214482. bufferSize -= samplesToDo;
  214483. }
  214484. }
  214485. }
  214486. ComSmartPtr <IAudioRenderClient> renderClient;
  214487. private:
  214488. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214489. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214490. };
  214491. class WASAPIAudioIODevice : public AudioIODevice,
  214492. public Thread
  214493. {
  214494. public:
  214495. WASAPIAudioIODevice (const String& deviceName,
  214496. const String& outputDeviceId_,
  214497. const String& inputDeviceId_,
  214498. const bool useExclusiveMode_)
  214499. : AudioIODevice (deviceName, "Windows Audio"),
  214500. Thread ("Juce WASAPI"),
  214501. isOpen_ (false),
  214502. isStarted (false),
  214503. outputDevice (0),
  214504. outputDeviceId (outputDeviceId_),
  214505. inputDevice (0),
  214506. inputDeviceId (inputDeviceId_),
  214507. useExclusiveMode (useExclusiveMode_),
  214508. currentBufferSizeSamples (0),
  214509. currentSampleRate (0),
  214510. callback (0)
  214511. {
  214512. }
  214513. ~WASAPIAudioIODevice()
  214514. {
  214515. close();
  214516. deleteAndZero (inputDevice);
  214517. deleteAndZero (outputDevice);
  214518. }
  214519. bool initialise()
  214520. {
  214521. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214522. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214523. latencyIn = latencyOut = 0;
  214524. Array <double> ratesIn, ratesOut;
  214525. if (createDevices())
  214526. {
  214527. jassert (inputDevice != 0 || outputDevice != 0);
  214528. if (inputDevice != 0 && outputDevice != 0)
  214529. {
  214530. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214531. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214532. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214533. sampleRates = inputDevice->rates;
  214534. sampleRates.removeValuesNotIn (outputDevice->rates);
  214535. }
  214536. else
  214537. {
  214538. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214539. defaultSampleRate = d->defaultSampleRate;
  214540. minBufferSize = d->minBufferSize;
  214541. defaultBufferSize = d->defaultBufferSize;
  214542. sampleRates = d->rates;
  214543. }
  214544. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214545. if (minBufferSize != defaultBufferSize)
  214546. bufferSizes.addUsingDefaultSort (minBufferSize);
  214547. int n = 64;
  214548. for (int i = 0; i < 40; ++i)
  214549. {
  214550. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214551. bufferSizes.addUsingDefaultSort (n);
  214552. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214553. }
  214554. return true;
  214555. }
  214556. return false;
  214557. }
  214558. const StringArray getOutputChannelNames()
  214559. {
  214560. StringArray outChannels;
  214561. if (outputDevice != 0)
  214562. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214563. outChannels.add ("Output channel " + String (i));
  214564. return outChannels;
  214565. }
  214566. const StringArray getInputChannelNames()
  214567. {
  214568. StringArray inChannels;
  214569. if (inputDevice != 0)
  214570. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214571. inChannels.add ("Input channel " + String (i));
  214572. return inChannels;
  214573. }
  214574. int getNumSampleRates() { return sampleRates.size(); }
  214575. double getSampleRate (int index) { return sampleRates [index]; }
  214576. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214577. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214578. int getDefaultBufferSize() { return defaultBufferSize; }
  214579. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214580. double getCurrentSampleRate() { return currentSampleRate; }
  214581. int getCurrentBitDepth() { return 32; }
  214582. int getOutputLatencyInSamples() { return latencyOut; }
  214583. int getInputLatencyInSamples() { return latencyIn; }
  214584. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214585. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214586. const String getLastError() { return lastError; }
  214587. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214588. double sampleRate, int bufferSizeSamples)
  214589. {
  214590. close();
  214591. lastError = String::empty;
  214592. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214593. {
  214594. lastError = "The input and output devices don't share a common sample rate!";
  214595. return lastError;
  214596. }
  214597. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214598. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214599. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214600. {
  214601. lastError = "Couldn't open the input device!";
  214602. return lastError;
  214603. }
  214604. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214605. {
  214606. close();
  214607. lastError = "Couldn't open the output device!";
  214608. return lastError;
  214609. }
  214610. if (inputDevice != 0)
  214611. ResetEvent (inputDevice->clientEvent);
  214612. if (outputDevice != 0)
  214613. ResetEvent (outputDevice->clientEvent);
  214614. startThread (8);
  214615. Thread::sleep (5);
  214616. if (inputDevice != 0 && inputDevice->client != 0)
  214617. {
  214618. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214619. HRESULT hr = inputDevice->client->Start();
  214620. logFailure (hr); //xxx handle this
  214621. }
  214622. if (outputDevice != 0 && outputDevice->client != 0)
  214623. {
  214624. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214625. HRESULT hr = outputDevice->client->Start();
  214626. logFailure (hr); //xxx handle this
  214627. }
  214628. isOpen_ = true;
  214629. return lastError;
  214630. }
  214631. void close()
  214632. {
  214633. stop();
  214634. if (inputDevice != 0)
  214635. SetEvent (inputDevice->clientEvent);
  214636. if (outputDevice != 0)
  214637. SetEvent (outputDevice->clientEvent);
  214638. stopThread (5000);
  214639. if (inputDevice != 0)
  214640. inputDevice->close();
  214641. if (outputDevice != 0)
  214642. outputDevice->close();
  214643. isOpen_ = false;
  214644. }
  214645. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214646. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214647. void start (AudioIODeviceCallback* call)
  214648. {
  214649. if (isOpen_ && call != 0 && ! isStarted)
  214650. {
  214651. if (! isThreadRunning())
  214652. {
  214653. // something's gone wrong and the thread's stopped..
  214654. isOpen_ = false;
  214655. return;
  214656. }
  214657. call->audioDeviceAboutToStart (this);
  214658. const ScopedLock sl (startStopLock);
  214659. callback = call;
  214660. isStarted = true;
  214661. }
  214662. }
  214663. void stop()
  214664. {
  214665. if (isStarted)
  214666. {
  214667. AudioIODeviceCallback* const callbackLocal = callback;
  214668. {
  214669. const ScopedLock sl (startStopLock);
  214670. isStarted = false;
  214671. }
  214672. if (callbackLocal != 0)
  214673. callbackLocal->audioDeviceStopped();
  214674. }
  214675. }
  214676. void setMMThreadPriority()
  214677. {
  214678. DynamicLibraryLoader dll ("avrt.dll");
  214679. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214680. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214681. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214682. {
  214683. DWORD dummy = 0;
  214684. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214685. if (h != 0)
  214686. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214687. }
  214688. }
  214689. void run()
  214690. {
  214691. setMMThreadPriority();
  214692. const int bufferSize = currentBufferSizeSamples;
  214693. HANDLE events[2];
  214694. int numEvents = 0;
  214695. if (inputDevice != 0)
  214696. events [numEvents++] = inputDevice->clientEvent;
  214697. if (outputDevice != 0)
  214698. events [numEvents++] = outputDevice->clientEvent;
  214699. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214700. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214701. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214702. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214703. float** const inputBuffers = ins.getArrayOfChannels();
  214704. float** const outputBuffers = outs.getArrayOfChannels();
  214705. ins.clear();
  214706. while (! threadShouldExit())
  214707. {
  214708. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214709. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214710. if (result == WAIT_TIMEOUT)
  214711. continue;
  214712. if (threadShouldExit())
  214713. break;
  214714. if (inputDevice != 0)
  214715. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214716. // Make the callback..
  214717. {
  214718. const ScopedLock sl (startStopLock);
  214719. if (isStarted)
  214720. {
  214721. JUCE_TRY
  214722. {
  214723. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214724. numInputBuffers,
  214725. outputBuffers,
  214726. numOutputBuffers,
  214727. bufferSize);
  214728. }
  214729. JUCE_CATCH_EXCEPTION
  214730. }
  214731. else
  214732. {
  214733. outs.clear();
  214734. }
  214735. }
  214736. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214737. continue;
  214738. if (outputDevice != 0)
  214739. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214740. }
  214741. }
  214742. juce_UseDebuggingNewOperator
  214743. String outputDeviceId, inputDeviceId;
  214744. String lastError;
  214745. private:
  214746. // Device stats...
  214747. WASAPIInputDevice* inputDevice;
  214748. WASAPIOutputDevice* outputDevice;
  214749. const bool useExclusiveMode;
  214750. double defaultSampleRate;
  214751. int minBufferSize, defaultBufferSize;
  214752. int latencyIn, latencyOut;
  214753. Array <double> sampleRates;
  214754. Array <int> bufferSizes;
  214755. // Active state...
  214756. bool isOpen_, isStarted;
  214757. int currentBufferSizeSamples;
  214758. double currentSampleRate;
  214759. AudioIODeviceCallback* callback;
  214760. CriticalSection startStopLock;
  214761. bool createDevices()
  214762. {
  214763. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214764. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214765. return false;
  214766. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214767. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214768. return false;
  214769. UINT32 numDevices = 0;
  214770. if (! OK (deviceCollection->GetCount (&numDevices)))
  214771. return false;
  214772. for (UINT32 i = 0; i < numDevices; ++i)
  214773. {
  214774. ComSmartPtr <IMMDevice> device;
  214775. if (! OK (deviceCollection->Item (i, &device)))
  214776. continue;
  214777. const String deviceId (wasapi_getDeviceID (device));
  214778. if (deviceId.isEmpty())
  214779. continue;
  214780. const EDataFlow flow = wasapi_getDataFlow (device);
  214781. if (deviceId == inputDeviceId && flow == eCapture)
  214782. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214783. else if (deviceId == outputDeviceId && flow == eRender)
  214784. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214785. }
  214786. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214787. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214788. }
  214789. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214790. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214791. };
  214792. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214793. {
  214794. public:
  214795. WASAPIAudioIODeviceType()
  214796. : AudioIODeviceType ("Windows Audio"),
  214797. hasScanned (false)
  214798. {
  214799. }
  214800. ~WASAPIAudioIODeviceType()
  214801. {
  214802. }
  214803. void scanForDevices()
  214804. {
  214805. hasScanned = true;
  214806. outputDeviceNames.clear();
  214807. inputDeviceNames.clear();
  214808. outputDeviceIds.clear();
  214809. inputDeviceIds.clear();
  214810. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214811. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214812. return;
  214813. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214814. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  214815. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214816. UINT32 numDevices = 0;
  214817. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  214818. && OK (deviceCollection->GetCount (&numDevices))))
  214819. return;
  214820. for (UINT32 i = 0; i < numDevices; ++i)
  214821. {
  214822. ComSmartPtr <IMMDevice> device;
  214823. if (! OK (deviceCollection->Item (i, &device)))
  214824. continue;
  214825. const String deviceId (wasapi_getDeviceID (device));
  214826. DWORD state = 0;
  214827. if (! OK (device->GetState (&state)))
  214828. continue;
  214829. if (state != DEVICE_STATE_ACTIVE)
  214830. continue;
  214831. String name;
  214832. {
  214833. ComSmartPtr <IPropertyStore> properties;
  214834. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  214835. continue;
  214836. PROPVARIANT value;
  214837. PropVariantInit (&value);
  214838. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  214839. name = value.pwszVal;
  214840. PropVariantClear (&value);
  214841. }
  214842. const EDataFlow flow = wasapi_getDataFlow (device);
  214843. if (flow == eRender)
  214844. {
  214845. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  214846. outputDeviceIds.insert (index, deviceId);
  214847. outputDeviceNames.insert (index, name);
  214848. }
  214849. else if (flow == eCapture)
  214850. {
  214851. const int index = (deviceId == defaultCapture) ? 0 : -1;
  214852. inputDeviceIds.insert (index, deviceId);
  214853. inputDeviceNames.insert (index, name);
  214854. }
  214855. }
  214856. inputDeviceNames.appendNumbersToDuplicates (false, false);
  214857. outputDeviceNames.appendNumbersToDuplicates (false, false);
  214858. }
  214859. const StringArray getDeviceNames (bool wantInputNames) const
  214860. {
  214861. jassert (hasScanned); // need to call scanForDevices() before doing this
  214862. return wantInputNames ? inputDeviceNames
  214863. : outputDeviceNames;
  214864. }
  214865. int getDefaultDeviceIndex (bool /*forInput*/) const
  214866. {
  214867. jassert (hasScanned); // need to call scanForDevices() before doing this
  214868. return 0;
  214869. }
  214870. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214871. {
  214872. jassert (hasScanned); // need to call scanForDevices() before doing this
  214873. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  214874. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  214875. : outputDeviceIds.indexOf (d->outputDeviceId));
  214876. }
  214877. bool hasSeparateInputsAndOutputs() const { return true; }
  214878. AudioIODevice* createDevice (const String& outputDeviceName,
  214879. const String& inputDeviceName)
  214880. {
  214881. jassert (hasScanned); // need to call scanForDevices() before doing this
  214882. const bool useExclusiveMode = false;
  214883. ScopedPointer<WASAPIAudioIODevice> device;
  214884. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214885. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214886. if (outputIndex >= 0 || inputIndex >= 0)
  214887. {
  214888. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214889. : inputDeviceName,
  214890. outputDeviceIds [outputIndex],
  214891. inputDeviceIds [inputIndex],
  214892. useExclusiveMode);
  214893. if (! device->initialise())
  214894. device = 0;
  214895. }
  214896. return device.release();
  214897. }
  214898. juce_UseDebuggingNewOperator
  214899. StringArray outputDeviceNames, outputDeviceIds;
  214900. StringArray inputDeviceNames, inputDeviceIds;
  214901. private:
  214902. bool hasScanned;
  214903. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  214904. {
  214905. String s;
  214906. IMMDevice* dev = 0;
  214907. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  214908. eMultimedia, &dev)))
  214909. {
  214910. WCHAR* deviceId = 0;
  214911. if (OK (dev->GetId (&deviceId)))
  214912. {
  214913. s = String (deviceId);
  214914. CoTaskMemFree (deviceId);
  214915. }
  214916. dev->Release();
  214917. }
  214918. return s;
  214919. }
  214920. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  214921. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  214922. };
  214923. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  214924. {
  214925. return new WASAPIAudioIODeviceType();
  214926. }
  214927. #undef logFailure
  214928. #undef OK
  214929. #endif
  214930. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  214931. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  214932. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214933. // compiled on its own).
  214934. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  214935. class DShowCameraDeviceInteral : public ChangeBroadcaster
  214936. {
  214937. public:
  214938. DShowCameraDeviceInteral (CameraDevice* const owner_,
  214939. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  214940. const ComSmartPtr <IBaseFilter>& filter_,
  214941. int minWidth, int minHeight,
  214942. int maxWidth, int maxHeight)
  214943. : owner (owner_),
  214944. captureGraphBuilder (captureGraphBuilder_),
  214945. filter (filter_),
  214946. ok (false),
  214947. imageNeedsFlipping (false),
  214948. width (0),
  214949. height (0),
  214950. activeUsers (0),
  214951. recordNextFrameTime (false)
  214952. {
  214953. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  214954. if (FAILED (hr))
  214955. return;
  214956. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  214957. if (FAILED (hr))
  214958. return;
  214959. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  214960. if (FAILED (hr))
  214961. return;
  214962. {
  214963. ComSmartPtr <IAMStreamConfig> streamConfig;
  214964. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  214965. IID_IAMStreamConfig, (void**) &streamConfig);
  214966. if (streamConfig != 0)
  214967. {
  214968. getVideoSizes (streamConfig);
  214969. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  214970. return;
  214971. }
  214972. }
  214973. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  214974. if (FAILED (hr))
  214975. return;
  214976. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  214977. if (FAILED (hr))
  214978. return;
  214979. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  214980. if (FAILED (hr))
  214981. return;
  214982. if (! connectFilters (filter, smartTee))
  214983. return;
  214984. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  214985. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  214986. if (FAILED (hr))
  214987. return;
  214988. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  214989. if (FAILED (hr))
  214990. return;
  214991. AM_MEDIA_TYPE mt;
  214992. zerostruct (mt);
  214993. mt.majortype = MEDIATYPE_Video;
  214994. mt.subtype = MEDIASUBTYPE_RGB24;
  214995. mt.formattype = FORMAT_VideoInfo;
  214996. sampleGrabber->SetMediaType (&mt);
  214997. callback = new GrabberCallback (*this);
  214998. sampleGrabber->SetCallback (callback, 1);
  214999. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215000. if (FAILED (hr))
  215001. return;
  215002. ComSmartPtr <IPin> grabberInputPin;
  215003. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  215004. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  215005. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  215006. return;
  215007. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215008. if (FAILED (hr))
  215009. return;
  215010. zerostruct (mt);
  215011. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215012. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215013. width = pVih->bmiHeader.biWidth;
  215014. height = pVih->bmiHeader.biHeight;
  215015. ComSmartPtr <IBaseFilter> nullFilter;
  215016. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215017. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215018. if (connectFilters (sampleGrabberBase, nullFilter)
  215019. && addGraphToRot())
  215020. {
  215021. activeImage = Image (Image::RGB, width, height, true);
  215022. loadingImage = Image (Image::RGB, width, height, true);
  215023. ok = true;
  215024. }
  215025. }
  215026. ~DShowCameraDeviceInteral()
  215027. {
  215028. if (mediaControl != 0)
  215029. mediaControl->Stop();
  215030. removeGraphFromRot();
  215031. for (int i = viewerComps.size(); --i >= 0;)
  215032. viewerComps.getUnchecked(i)->ownerDeleted();
  215033. callback = 0;
  215034. graphBuilder = 0;
  215035. sampleGrabber = 0;
  215036. mediaControl = 0;
  215037. filter = 0;
  215038. captureGraphBuilder = 0;
  215039. smartTee = 0;
  215040. smartTeePreviewOutputPin = 0;
  215041. smartTeeCaptureOutputPin = 0;
  215042. asfWriter = 0;
  215043. }
  215044. void addUser()
  215045. {
  215046. if (ok && activeUsers++ == 0)
  215047. mediaControl->Run();
  215048. }
  215049. void removeUser()
  215050. {
  215051. if (ok && --activeUsers == 0)
  215052. mediaControl->Stop();
  215053. }
  215054. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215055. {
  215056. if (recordNextFrameTime)
  215057. {
  215058. const double defaultCameraLatency = 0.1;
  215059. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215060. recordNextFrameTime = false;
  215061. ComSmartPtr <IPin> pin;
  215062. if (getPin (filter, PINDIR_OUTPUT, &pin))
  215063. {
  215064. ComSmartPtr <IAMPushSource> pushSource;
  215065. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  215066. if (pushSource != 0)
  215067. {
  215068. REFERENCE_TIME latency = 0;
  215069. hr = pushSource->GetLatency (&latency);
  215070. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215071. }
  215072. }
  215073. }
  215074. {
  215075. const int lineStride = width * 3;
  215076. const ScopedLock sl (imageSwapLock);
  215077. {
  215078. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215079. for (int i = 0; i < height; ++i)
  215080. memcpy (destData.getLinePointer ((height - 1) - i),
  215081. buffer + lineStride * i,
  215082. lineStride);
  215083. }
  215084. imageNeedsFlipping = true;
  215085. }
  215086. if (listeners.size() > 0)
  215087. callListeners (loadingImage);
  215088. sendChangeMessage (this);
  215089. }
  215090. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215091. {
  215092. if (imageNeedsFlipping)
  215093. {
  215094. const ScopedLock sl (imageSwapLock);
  215095. swapVariables (loadingImage, activeImage);
  215096. imageNeedsFlipping = false;
  215097. }
  215098. RectanglePlacement rp (RectanglePlacement::centred);
  215099. double dx = 0, dy = 0, dw = width, dh = height;
  215100. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215101. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215102. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215103. g.saveState();
  215104. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215105. g.fillAll (Colours::black);
  215106. g.restoreState();
  215107. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215108. }
  215109. bool createFileCaptureFilter (const File& file)
  215110. {
  215111. removeFileCaptureFilter();
  215112. file.deleteFile();
  215113. mediaControl->Stop();
  215114. firstRecordedTime = Time();
  215115. recordNextFrameTime = true;
  215116. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215117. if (SUCCEEDED (hr))
  215118. {
  215119. ComSmartPtr <IFileSinkFilter> fileSink;
  215120. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  215121. if (SUCCEEDED (hr))
  215122. {
  215123. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215124. if (SUCCEEDED (hr))
  215125. {
  215126. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215127. if (SUCCEEDED (hr))
  215128. {
  215129. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215130. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  215131. asfConfig->SetIndexMode (true);
  215132. ComSmartPtr <IWMProfileManager> profileManager;
  215133. hr = WMCreateProfileManager (&profileManager);
  215134. // This gibberish is the DirectShow profile for a video-only wmv file.
  215135. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  215136. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215137. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215138. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  215139. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  215140. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215141. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  215142. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  215143. prof = prof.replace ("$WIDTH", String (width))
  215144. .replace ("$HEIGHT", String (height));
  215145. ComSmartPtr <IWMProfile> currentProfile;
  215146. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  215147. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215148. if (SUCCEEDED (hr))
  215149. {
  215150. ComSmartPtr <IPin> asfWriterInputPin;
  215151. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  215152. {
  215153. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215154. if (SUCCEEDED (hr)
  215155. && ok && activeUsers > 0
  215156. && SUCCEEDED (mediaControl->Run()))
  215157. {
  215158. return true;
  215159. }
  215160. }
  215161. }
  215162. }
  215163. }
  215164. }
  215165. }
  215166. removeFileCaptureFilter();
  215167. if (ok && activeUsers > 0)
  215168. mediaControl->Run();
  215169. return false;
  215170. }
  215171. void removeFileCaptureFilter()
  215172. {
  215173. mediaControl->Stop();
  215174. if (asfWriter != 0)
  215175. {
  215176. graphBuilder->RemoveFilter (asfWriter);
  215177. asfWriter = 0;
  215178. }
  215179. if (ok && activeUsers > 0)
  215180. mediaControl->Run();
  215181. }
  215182. void addListener (CameraImageListener* listenerToAdd)
  215183. {
  215184. const ScopedLock sl (listenerLock);
  215185. if (listeners.size() == 0)
  215186. addUser();
  215187. listeners.addIfNotAlreadyThere (listenerToAdd);
  215188. }
  215189. void removeListener (CameraImageListener* listenerToRemove)
  215190. {
  215191. const ScopedLock sl (listenerLock);
  215192. listeners.removeValue (listenerToRemove);
  215193. if (listeners.size() == 0)
  215194. removeUser();
  215195. }
  215196. void callListeners (const Image& image)
  215197. {
  215198. const ScopedLock sl (listenerLock);
  215199. for (int i = listeners.size(); --i >= 0;)
  215200. {
  215201. CameraImageListener* const l = listeners[i];
  215202. if (l != 0)
  215203. l->imageReceived (image);
  215204. }
  215205. }
  215206. class DShowCaptureViewerComp : public Component,
  215207. public ChangeListener
  215208. {
  215209. public:
  215210. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215211. : owner (owner_)
  215212. {
  215213. setOpaque (true);
  215214. owner->addChangeListener (this);
  215215. owner->addUser();
  215216. owner->viewerComps.add (this);
  215217. setSize (owner_->width, owner_->height);
  215218. }
  215219. ~DShowCaptureViewerComp()
  215220. {
  215221. if (owner != 0)
  215222. {
  215223. owner->viewerComps.removeValue (this);
  215224. owner->removeUser();
  215225. owner->removeChangeListener (this);
  215226. }
  215227. }
  215228. void ownerDeleted()
  215229. {
  215230. owner = 0;
  215231. }
  215232. void paint (Graphics& g)
  215233. {
  215234. g.setColour (Colours::black);
  215235. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215236. if (owner != 0)
  215237. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215238. else
  215239. g.fillAll (Colours::black);
  215240. }
  215241. void changeListenerCallback (void*)
  215242. {
  215243. repaint();
  215244. }
  215245. private:
  215246. DShowCameraDeviceInteral* owner;
  215247. };
  215248. bool ok;
  215249. int width, height;
  215250. Time firstRecordedTime;
  215251. Array <DShowCaptureViewerComp*> viewerComps;
  215252. private:
  215253. CameraDevice* const owner;
  215254. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215255. ComSmartPtr <IBaseFilter> filter;
  215256. ComSmartPtr <IBaseFilter> smartTee;
  215257. ComSmartPtr <IGraphBuilder> graphBuilder;
  215258. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215259. ComSmartPtr <IMediaControl> mediaControl;
  215260. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215261. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215262. ComSmartPtr <IBaseFilter> asfWriter;
  215263. int activeUsers;
  215264. Array <int> widths, heights;
  215265. DWORD graphRegistrationID;
  215266. CriticalSection imageSwapLock;
  215267. bool imageNeedsFlipping;
  215268. Image loadingImage;
  215269. Image activeImage;
  215270. bool recordNextFrameTime;
  215271. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215272. {
  215273. widths.clear();
  215274. heights.clear();
  215275. int count = 0, size = 0;
  215276. streamConfig->GetNumberOfCapabilities (&count, &size);
  215277. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215278. {
  215279. for (int i = 0; i < count; ++i)
  215280. {
  215281. VIDEO_STREAM_CONFIG_CAPS scc;
  215282. AM_MEDIA_TYPE* config;
  215283. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215284. if (SUCCEEDED (hr))
  215285. {
  215286. const int w = scc.InputSize.cx;
  215287. const int h = scc.InputSize.cy;
  215288. bool duplicate = false;
  215289. for (int j = widths.size(); --j >= 0;)
  215290. {
  215291. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215292. {
  215293. duplicate = true;
  215294. break;
  215295. }
  215296. }
  215297. if (! duplicate)
  215298. {
  215299. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215300. widths.add (w);
  215301. heights.add (h);
  215302. }
  215303. deleteMediaType (config);
  215304. }
  215305. }
  215306. }
  215307. }
  215308. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215309. const int minWidth, const int minHeight,
  215310. const int maxWidth, const int maxHeight)
  215311. {
  215312. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215313. streamConfig->GetNumberOfCapabilities (&count, &size);
  215314. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215315. {
  215316. AM_MEDIA_TYPE* config;
  215317. VIDEO_STREAM_CONFIG_CAPS scc;
  215318. for (int i = 0; i < count; ++i)
  215319. {
  215320. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215321. if (SUCCEEDED (hr))
  215322. {
  215323. if (scc.InputSize.cx >= minWidth
  215324. && scc.InputSize.cy >= minHeight
  215325. && scc.InputSize.cx <= maxWidth
  215326. && scc.InputSize.cy <= maxHeight)
  215327. {
  215328. int area = scc.InputSize.cx * scc.InputSize.cy;
  215329. if (area > bestArea)
  215330. {
  215331. bestIndex = i;
  215332. bestArea = area;
  215333. }
  215334. }
  215335. deleteMediaType (config);
  215336. }
  215337. }
  215338. if (bestIndex >= 0)
  215339. {
  215340. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215341. hr = streamConfig->SetFormat (config);
  215342. deleteMediaType (config);
  215343. return SUCCEEDED (hr);
  215344. }
  215345. }
  215346. return false;
  215347. }
  215348. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215349. {
  215350. ComSmartPtr <IEnumPins> enumerator;
  215351. ComSmartPtr <IPin> pin;
  215352. filter->EnumPins (&enumerator);
  215353. while (enumerator->Next (1, &pin, 0) == S_OK)
  215354. {
  215355. PIN_DIRECTION dir;
  215356. pin->QueryDirection (&dir);
  215357. if (wantedDirection == dir)
  215358. {
  215359. PIN_INFO info;
  215360. zerostruct (info);
  215361. pin->QueryPinInfo (&info);
  215362. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215363. {
  215364. pin->AddRef();
  215365. *result = pin;
  215366. return true;
  215367. }
  215368. }
  215369. }
  215370. return false;
  215371. }
  215372. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215373. {
  215374. ComSmartPtr <IPin> in, out;
  215375. return getPin (first, PINDIR_OUTPUT, &out)
  215376. && getPin (second, PINDIR_INPUT, &in)
  215377. && SUCCEEDED (graphBuilder->Connect (out, in));
  215378. }
  215379. bool addGraphToRot()
  215380. {
  215381. ComSmartPtr <IRunningObjectTable> rot;
  215382. if (FAILED (GetRunningObjectTable (0, &rot)))
  215383. return false;
  215384. ComSmartPtr <IMoniker> moniker;
  215385. WCHAR buffer[128];
  215386. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215387. if (FAILED (hr))
  215388. return false;
  215389. graphRegistrationID = 0;
  215390. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215391. }
  215392. void removeGraphFromRot()
  215393. {
  215394. ComSmartPtr <IRunningObjectTable> rot;
  215395. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215396. rot->Revoke (graphRegistrationID);
  215397. }
  215398. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215399. {
  215400. if (pmt->cbFormat != 0)
  215401. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215402. if (pmt->pUnk != 0)
  215403. pmt->pUnk->Release();
  215404. CoTaskMemFree (pmt);
  215405. }
  215406. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215407. {
  215408. public:
  215409. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215410. : owner (owner_)
  215411. {
  215412. }
  215413. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215414. {
  215415. return E_FAIL;
  215416. }
  215417. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215418. {
  215419. owner.handleFrame (time, buffer, bufferSize);
  215420. return S_OK;
  215421. }
  215422. private:
  215423. DShowCameraDeviceInteral& owner;
  215424. GrabberCallback (const GrabberCallback&);
  215425. GrabberCallback& operator= (const GrabberCallback&);
  215426. };
  215427. ComSmartPtr <GrabberCallback> callback;
  215428. Array <CameraImageListener*> listeners;
  215429. CriticalSection listenerLock;
  215430. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215431. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215432. };
  215433. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215434. : name (name_)
  215435. {
  215436. isRecording = false;
  215437. }
  215438. CameraDevice::~CameraDevice()
  215439. {
  215440. stopRecording();
  215441. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215442. internal = 0;
  215443. }
  215444. Component* CameraDevice::createViewerComponent()
  215445. {
  215446. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215447. }
  215448. const String CameraDevice::getFileExtension()
  215449. {
  215450. return ".wmv";
  215451. }
  215452. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215453. {
  215454. stopRecording();
  215455. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215456. d->addUser();
  215457. isRecording = d->createFileCaptureFilter (file);
  215458. }
  215459. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215460. {
  215461. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215462. return d->firstRecordedTime;
  215463. }
  215464. void CameraDevice::stopRecording()
  215465. {
  215466. if (isRecording)
  215467. {
  215468. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215469. d->removeFileCaptureFilter();
  215470. d->removeUser();
  215471. isRecording = false;
  215472. }
  215473. }
  215474. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  215475. {
  215476. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215477. if (listenerToAdd != 0)
  215478. d->addListener (listenerToAdd);
  215479. }
  215480. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  215481. {
  215482. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215483. if (listenerToRemove != 0)
  215484. d->removeListener (listenerToRemove);
  215485. }
  215486. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215487. const int deviceIndexToOpen,
  215488. String& name)
  215489. {
  215490. int index = 0;
  215491. ComSmartPtr <IBaseFilter> result;
  215492. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215493. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215494. if (SUCCEEDED (hr))
  215495. {
  215496. ComSmartPtr <IEnumMoniker> enumerator;
  215497. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215498. if (SUCCEEDED (hr) && enumerator != 0)
  215499. {
  215500. ComSmartPtr <IBaseFilter> captureFilter;
  215501. ComSmartPtr <IMoniker> moniker;
  215502. ULONG fetched;
  215503. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215504. {
  215505. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215506. if (SUCCEEDED (hr))
  215507. {
  215508. ComSmartPtr <IPropertyBag> propertyBag;
  215509. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215510. if (SUCCEEDED (hr))
  215511. {
  215512. VARIANT var;
  215513. var.vt = VT_BSTR;
  215514. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215515. propertyBag = 0;
  215516. if (SUCCEEDED (hr))
  215517. {
  215518. if (names != 0)
  215519. names->add (var.bstrVal);
  215520. if (index == deviceIndexToOpen)
  215521. {
  215522. name = var.bstrVal;
  215523. result = captureFilter;
  215524. captureFilter = 0;
  215525. break;
  215526. }
  215527. ++index;
  215528. }
  215529. moniker = 0;
  215530. }
  215531. captureFilter = 0;
  215532. }
  215533. }
  215534. }
  215535. }
  215536. return result;
  215537. }
  215538. const StringArray CameraDevice::getAvailableDevices()
  215539. {
  215540. StringArray devs;
  215541. String dummy;
  215542. enumerateCameras (&devs, -1, dummy);
  215543. return devs;
  215544. }
  215545. CameraDevice* CameraDevice::openDevice (int index,
  215546. int minWidth, int minHeight,
  215547. int maxWidth, int maxHeight)
  215548. {
  215549. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215550. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215551. if (SUCCEEDED (hr))
  215552. {
  215553. String name;
  215554. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215555. if (filter != 0)
  215556. {
  215557. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215558. DShowCameraDeviceInteral* const intern
  215559. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215560. minWidth, minHeight, maxWidth, maxHeight);
  215561. cam->internal = intern;
  215562. if (intern->ok)
  215563. return cam.release();
  215564. }
  215565. }
  215566. return 0;
  215567. }
  215568. #endif
  215569. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215570. #endif
  215571. // Auto-link the other win32 libs that are needed by library calls..
  215572. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215573. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215574. // Auto-links to various win32 libs that are needed by library calls..
  215575. #pragma comment(lib, "kernel32.lib")
  215576. #pragma comment(lib, "user32.lib")
  215577. #pragma comment(lib, "shell32.lib")
  215578. #pragma comment(lib, "gdi32.lib")
  215579. #pragma comment(lib, "vfw32.lib")
  215580. #pragma comment(lib, "comdlg32.lib")
  215581. #pragma comment(lib, "winmm.lib")
  215582. #pragma comment(lib, "wininet.lib")
  215583. #pragma comment(lib, "ole32.lib")
  215584. #pragma comment(lib, "oleaut32.lib")
  215585. #pragma comment(lib, "advapi32.lib")
  215586. #pragma comment(lib, "ws2_32.lib")
  215587. #pragma comment(lib, "comsupp.lib")
  215588. #pragma comment(lib, "version.lib")
  215589. #if JUCE_OPENGL
  215590. #pragma comment(lib, "OpenGL32.Lib")
  215591. #pragma comment(lib, "GlU32.Lib")
  215592. #endif
  215593. #if JUCE_QUICKTIME
  215594. #pragma comment (lib, "QTMLClient.lib")
  215595. #endif
  215596. #if JUCE_USE_CAMERA
  215597. #pragma comment (lib, "Strmiids.lib")
  215598. #pragma comment (lib, "wmvcore.lib")
  215599. #endif
  215600. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215601. #endif
  215602. END_JUCE_NAMESPACE
  215603. #endif
  215604. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215605. #endif
  215606. #if JUCE_LINUX
  215607. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215608. /*
  215609. This file wraps together all the mac-specific code, so that
  215610. we can include all the native headers just once, and compile all our
  215611. platform-specific stuff in one big lump, keeping it out of the way of
  215612. the rest of the codebase.
  215613. */
  215614. #if JUCE_LINUX
  215615. BEGIN_JUCE_NAMESPACE
  215616. #define JUCE_INCLUDED_FILE 1
  215617. // Now include the actual code files..
  215618. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215619. /*
  215620. This file contains posix routines that are common to both the Linux and Mac builds.
  215621. It gets included directly in the cpp files for these platforms.
  215622. */
  215623. CriticalSection::CriticalSection() throw()
  215624. {
  215625. pthread_mutexattr_t atts;
  215626. pthread_mutexattr_init (&atts);
  215627. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215628. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215629. pthread_mutex_init (&internal, &atts);
  215630. }
  215631. CriticalSection::~CriticalSection() throw()
  215632. {
  215633. pthread_mutex_destroy (&internal);
  215634. }
  215635. void CriticalSection::enter() const throw()
  215636. {
  215637. pthread_mutex_lock (&internal);
  215638. }
  215639. bool CriticalSection::tryEnter() const throw()
  215640. {
  215641. return pthread_mutex_trylock (&internal) == 0;
  215642. }
  215643. void CriticalSection::exit() const throw()
  215644. {
  215645. pthread_mutex_unlock (&internal);
  215646. }
  215647. class WaitableEventImpl
  215648. {
  215649. public:
  215650. WaitableEventImpl (const bool manualReset_)
  215651. : triggered (false),
  215652. manualReset (manualReset_)
  215653. {
  215654. pthread_cond_init (&condition, 0);
  215655. pthread_mutexattr_t atts;
  215656. pthread_mutexattr_init (&atts);
  215657. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215658. pthread_mutex_init (&mutex, &atts);
  215659. }
  215660. ~WaitableEventImpl()
  215661. {
  215662. pthread_cond_destroy (&condition);
  215663. pthread_mutex_destroy (&mutex);
  215664. }
  215665. bool wait (const int timeOutMillisecs) throw()
  215666. {
  215667. pthread_mutex_lock (&mutex);
  215668. if (! triggered)
  215669. {
  215670. if (timeOutMillisecs < 0)
  215671. {
  215672. do
  215673. {
  215674. pthread_cond_wait (&condition, &mutex);
  215675. }
  215676. while (! triggered);
  215677. }
  215678. else
  215679. {
  215680. struct timeval now;
  215681. gettimeofday (&now, 0);
  215682. struct timespec time;
  215683. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215684. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215685. if (time.tv_nsec >= 1000000000)
  215686. {
  215687. time.tv_nsec -= 1000000000;
  215688. time.tv_sec++;
  215689. }
  215690. do
  215691. {
  215692. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215693. {
  215694. pthread_mutex_unlock (&mutex);
  215695. return false;
  215696. }
  215697. }
  215698. while (! triggered);
  215699. }
  215700. }
  215701. if (! manualReset)
  215702. triggered = false;
  215703. pthread_mutex_unlock (&mutex);
  215704. return true;
  215705. }
  215706. void signal() throw()
  215707. {
  215708. pthread_mutex_lock (&mutex);
  215709. triggered = true;
  215710. pthread_cond_broadcast (&condition);
  215711. pthread_mutex_unlock (&mutex);
  215712. }
  215713. void reset() throw()
  215714. {
  215715. pthread_mutex_lock (&mutex);
  215716. triggered = false;
  215717. pthread_mutex_unlock (&mutex);
  215718. }
  215719. private:
  215720. pthread_cond_t condition;
  215721. pthread_mutex_t mutex;
  215722. bool triggered;
  215723. const bool manualReset;
  215724. WaitableEventImpl (const WaitableEventImpl&);
  215725. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215726. };
  215727. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215728. : internal (new WaitableEventImpl (manualReset))
  215729. {
  215730. }
  215731. WaitableEvent::~WaitableEvent() throw()
  215732. {
  215733. delete static_cast <WaitableEventImpl*> (internal);
  215734. }
  215735. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215736. {
  215737. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215738. }
  215739. void WaitableEvent::signal() const throw()
  215740. {
  215741. static_cast <WaitableEventImpl*> (internal)->signal();
  215742. }
  215743. void WaitableEvent::reset() const throw()
  215744. {
  215745. static_cast <WaitableEventImpl*> (internal)->reset();
  215746. }
  215747. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215748. {
  215749. struct timespec time;
  215750. time.tv_sec = millisecs / 1000;
  215751. time.tv_nsec = (millisecs % 1000) * 1000000;
  215752. nanosleep (&time, 0);
  215753. }
  215754. const juce_wchar File::separator = '/';
  215755. const String File::separatorString ("/");
  215756. const File File::getCurrentWorkingDirectory()
  215757. {
  215758. HeapBlock<char> heapBuffer;
  215759. char localBuffer [1024];
  215760. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215761. int bufferSize = 4096;
  215762. while (cwd == 0 && errno == ERANGE)
  215763. {
  215764. heapBuffer.malloc (bufferSize);
  215765. cwd = getcwd (heapBuffer, bufferSize - 1);
  215766. bufferSize += 1024;
  215767. }
  215768. return File (String::fromUTF8 (cwd));
  215769. }
  215770. bool File::setAsCurrentWorkingDirectory() const
  215771. {
  215772. return chdir (getFullPathName().toUTF8()) == 0;
  215773. }
  215774. static bool juce_stat (const String& fileName, struct stat& info)
  215775. {
  215776. return fileName.isNotEmpty()
  215777. && (stat (fileName.toUTF8(), &info) == 0);
  215778. }
  215779. bool File::isDirectory() const
  215780. {
  215781. struct stat info;
  215782. return fullPath.isEmpty()
  215783. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215784. }
  215785. bool File::exists() const
  215786. {
  215787. return fullPath.isNotEmpty()
  215788. && access (fullPath.toUTF8(), F_OK) == 0;
  215789. }
  215790. bool File::existsAsFile() const
  215791. {
  215792. return exists() && ! isDirectory();
  215793. }
  215794. int64 File::getSize() const
  215795. {
  215796. struct stat info;
  215797. return juce_stat (fullPath, info) ? info.st_size : 0;
  215798. }
  215799. bool File::hasWriteAccess() const
  215800. {
  215801. if (exists())
  215802. return access (fullPath.toUTF8(), W_OK) == 0;
  215803. if ((! isDirectory()) && fullPath.containsChar (separator))
  215804. return getParentDirectory().hasWriteAccess();
  215805. return false;
  215806. }
  215807. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215808. {
  215809. struct stat info;
  215810. const int res = stat (fullPath.toUTF8(), &info);
  215811. if (res != 0)
  215812. return false;
  215813. info.st_mode &= 0777; // Just permissions
  215814. if (shouldBeReadOnly)
  215815. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215816. else
  215817. // Give everybody write permission?
  215818. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215819. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  215820. }
  215821. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  215822. {
  215823. modificationTime = 0;
  215824. accessTime = 0;
  215825. creationTime = 0;
  215826. struct stat info;
  215827. const int res = stat (fullPath.toUTF8(), &info);
  215828. if (res == 0)
  215829. {
  215830. modificationTime = (int64) info.st_mtime * 1000;
  215831. accessTime = (int64) info.st_atime * 1000;
  215832. creationTime = (int64) info.st_ctime * 1000;
  215833. }
  215834. }
  215835. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  215836. {
  215837. struct utimbuf times;
  215838. times.actime = (time_t) (accessTime / 1000);
  215839. times.modtime = (time_t) (modificationTime / 1000);
  215840. return utime (fullPath.toUTF8(), &times) == 0;
  215841. }
  215842. bool File::deleteFile() const
  215843. {
  215844. if (! exists())
  215845. return true;
  215846. else if (isDirectory())
  215847. return rmdir (fullPath.toUTF8()) == 0;
  215848. else
  215849. return remove (fullPath.toUTF8()) == 0;
  215850. }
  215851. bool File::moveInternal (const File& dest) const
  215852. {
  215853. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  215854. return true;
  215855. if (hasWriteAccess() && copyInternal (dest))
  215856. {
  215857. if (deleteFile())
  215858. return true;
  215859. dest.deleteFile();
  215860. }
  215861. return false;
  215862. }
  215863. void File::createDirectoryInternal (const String& fileName) const
  215864. {
  215865. mkdir (fileName.toUTF8(), 0777);
  215866. }
  215867. void* juce_fileOpen (const File& file, bool forWriting)
  215868. {
  215869. int flags = O_RDONLY;
  215870. if (forWriting)
  215871. {
  215872. if (file.exists())
  215873. {
  215874. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  215875. if (f != -1)
  215876. lseek (f, 0, SEEK_END);
  215877. return (void*) f;
  215878. }
  215879. else
  215880. {
  215881. flags = O_RDWR + O_CREAT;
  215882. }
  215883. }
  215884. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  215885. }
  215886. void juce_fileClose (void* handle)
  215887. {
  215888. if (handle != 0)
  215889. close ((int) (pointer_sized_int) handle);
  215890. }
  215891. int juce_fileRead (void* handle, void* buffer, int size)
  215892. {
  215893. if (handle != 0)
  215894. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  215895. return 0;
  215896. }
  215897. int juce_fileWrite (void* handle, const void* buffer, int size)
  215898. {
  215899. if (handle != 0)
  215900. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  215901. return 0;
  215902. }
  215903. int64 juce_fileSetPosition (void* handle, int64 pos)
  215904. {
  215905. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215906. return pos;
  215907. return -1;
  215908. }
  215909. int64 FileOutputStream::getPositionInternal() const
  215910. {
  215911. if (fileHandle != 0)
  215912. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  215913. return -1;
  215914. }
  215915. void FileOutputStream::flushInternal()
  215916. {
  215917. if (fileHandle != 0)
  215918. fsync ((int) (pointer_sized_int) fileHandle);
  215919. }
  215920. const File juce_getExecutableFile()
  215921. {
  215922. Dl_info exeInfo;
  215923. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  215924. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  215925. }
  215926. // if this file doesn't exist, find a parent of it that does..
  215927. static bool juce_doStatFS (File f, struct statfs& result)
  215928. {
  215929. for (int i = 5; --i >= 0;)
  215930. {
  215931. if (f.exists())
  215932. break;
  215933. f = f.getParentDirectory();
  215934. }
  215935. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215936. }
  215937. int64 File::getBytesFreeOnVolume() const
  215938. {
  215939. struct statfs buf;
  215940. if (juce_doStatFS (*this, buf))
  215941. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  215942. return 0;
  215943. }
  215944. int64 File::getVolumeTotalSize() const
  215945. {
  215946. struct statfs buf;
  215947. if (juce_doStatFS (*this, buf))
  215948. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  215949. return 0;
  215950. }
  215951. const String File::getVolumeLabel() const
  215952. {
  215953. #if JUCE_MAC
  215954. struct VolAttrBuf
  215955. {
  215956. u_int32_t length;
  215957. attrreference_t mountPointRef;
  215958. char mountPointSpace [MAXPATHLEN];
  215959. } attrBuf;
  215960. struct attrlist attrList;
  215961. zerostruct (attrList);
  215962. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  215963. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  215964. File f (*this);
  215965. for (;;)
  215966. {
  215967. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  215968. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  215969. (int) attrBuf.mountPointRef.attr_length);
  215970. const File parent (f.getParentDirectory());
  215971. if (f == parent)
  215972. break;
  215973. f = parent;
  215974. }
  215975. #endif
  215976. return String::empty;
  215977. }
  215978. int File::getVolumeSerialNumber() const
  215979. {
  215980. return 0; // xxx
  215981. }
  215982. void juce_runSystemCommand (const String& command)
  215983. {
  215984. int result = system (command.toUTF8());
  215985. (void) result;
  215986. }
  215987. const String juce_getOutputFromCommand (const String& command)
  215988. {
  215989. // slight bodge here, as we just pipe the output into a temp file and read it...
  215990. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  215991. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  215992. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  215993. String result (tempFile.loadFileAsString());
  215994. tempFile.deleteFile();
  215995. return result;
  215996. }
  215997. class InterProcessLock::Pimpl
  215998. {
  215999. public:
  216000. Pimpl (const String& name, const int timeOutMillisecs)
  216001. : handle (0), refCount (1)
  216002. {
  216003. #if JUCE_MAC
  216004. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216005. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216006. #else
  216007. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216008. #endif
  216009. temp.create();
  216010. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216011. if (handle != 0)
  216012. {
  216013. struct flock fl;
  216014. zerostruct (fl);
  216015. fl.l_whence = SEEK_SET;
  216016. fl.l_type = F_WRLCK;
  216017. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216018. for (;;)
  216019. {
  216020. const int result = fcntl (handle, F_SETLK, &fl);
  216021. if (result >= 0)
  216022. return;
  216023. if (errno != EINTR)
  216024. {
  216025. if (timeOutMillisecs == 0
  216026. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216027. break;
  216028. Thread::sleep (10);
  216029. }
  216030. }
  216031. }
  216032. closeFile();
  216033. }
  216034. ~Pimpl()
  216035. {
  216036. closeFile();
  216037. }
  216038. void closeFile()
  216039. {
  216040. if (handle != 0)
  216041. {
  216042. struct flock fl;
  216043. zerostruct (fl);
  216044. fl.l_whence = SEEK_SET;
  216045. fl.l_type = F_UNLCK;
  216046. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216047. {}
  216048. close (handle);
  216049. handle = 0;
  216050. }
  216051. }
  216052. int handle, refCount;
  216053. };
  216054. InterProcessLock::InterProcessLock (const String& name_)
  216055. : name (name_)
  216056. {
  216057. }
  216058. InterProcessLock::~InterProcessLock()
  216059. {
  216060. }
  216061. bool InterProcessLock::enter (const int timeOutMillisecs)
  216062. {
  216063. const ScopedLock sl (lock);
  216064. if (pimpl == 0)
  216065. {
  216066. pimpl = new Pimpl (name, timeOutMillisecs);
  216067. if (pimpl->handle == 0)
  216068. pimpl = 0;
  216069. }
  216070. else
  216071. {
  216072. pimpl->refCount++;
  216073. }
  216074. return pimpl != 0;
  216075. }
  216076. void InterProcessLock::exit()
  216077. {
  216078. const ScopedLock sl (lock);
  216079. // Trying to release the lock too many times!
  216080. jassert (pimpl != 0);
  216081. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216082. pimpl = 0;
  216083. }
  216084. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216085. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216086. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216087. // compiled on its own).
  216088. #if JUCE_INCLUDED_FILE
  216089. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  216090. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  216091. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  216092. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  216093. bool File::copyInternal (const File& dest) const
  216094. {
  216095. FileInputStream in (*this);
  216096. if (dest.deleteFile())
  216097. {
  216098. {
  216099. FileOutputStream out (dest);
  216100. if (out.failedToOpen())
  216101. return false;
  216102. if (out.writeFromInputStream (in, -1) == getSize())
  216103. return true;
  216104. }
  216105. dest.deleteFile();
  216106. }
  216107. return false;
  216108. }
  216109. void File::findFileSystemRoots (Array<File>& destArray)
  216110. {
  216111. destArray.add (File ("/"));
  216112. }
  216113. bool File::isOnCDRomDrive() const
  216114. {
  216115. struct statfs buf;
  216116. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216117. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  216118. }
  216119. bool File::isOnHardDisk() const
  216120. {
  216121. struct statfs buf;
  216122. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216123. {
  216124. switch (buf.f_type)
  216125. {
  216126. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216127. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216128. case U_NFS_SUPER_MAGIC: // Network NFS
  216129. case U_SMB_SUPER_MAGIC: // Network Samba
  216130. return false;
  216131. default:
  216132. // Assume anything else is a hard-disk (but note it could
  216133. // be a RAM disk. There isn't a good way of determining
  216134. // this for sure)
  216135. return true;
  216136. }
  216137. }
  216138. // Assume so if this fails for some reason
  216139. return true;
  216140. }
  216141. bool File::isOnRemovableDrive() const
  216142. {
  216143. jassertfalse; // xxx not implemented for linux!
  216144. return false;
  216145. }
  216146. bool File::isHidden() const
  216147. {
  216148. return getFileName().startsWithChar ('.');
  216149. }
  216150. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216151. const File File::getSpecialLocation (const SpecialLocationType type)
  216152. {
  216153. switch (type)
  216154. {
  216155. case userHomeDirectory:
  216156. {
  216157. const char* homeDir = getenv ("HOME");
  216158. if (homeDir == 0)
  216159. {
  216160. struct passwd* const pw = getpwuid (getuid());
  216161. if (pw != 0)
  216162. homeDir = pw->pw_dir;
  216163. }
  216164. return File (String::fromUTF8 (homeDir));
  216165. }
  216166. case userDocumentsDirectory:
  216167. case userMusicDirectory:
  216168. case userMoviesDirectory:
  216169. case userApplicationDataDirectory:
  216170. return File ("~");
  216171. case userDesktopDirectory:
  216172. return File ("~/Desktop");
  216173. case commonApplicationDataDirectory:
  216174. return File ("/var");
  216175. case globalApplicationsDirectory:
  216176. return File ("/usr");
  216177. case tempDirectory:
  216178. {
  216179. File tmp ("/var/tmp");
  216180. if (! tmp.isDirectory())
  216181. {
  216182. tmp = "/tmp";
  216183. if (! tmp.isDirectory())
  216184. tmp = File::getCurrentWorkingDirectory();
  216185. }
  216186. return tmp;
  216187. }
  216188. case invokedExecutableFile:
  216189. if (juce_Argv0 != 0)
  216190. return File (String::fromUTF8 (juce_Argv0));
  216191. // deliberate fall-through...
  216192. case currentExecutableFile:
  216193. case currentApplicationFile:
  216194. return juce_getExecutableFile();
  216195. default:
  216196. jassertfalse; // unknown type?
  216197. break;
  216198. }
  216199. return File::nonexistent;
  216200. }
  216201. const String File::getVersion() const
  216202. {
  216203. return String::empty; // xxx not yet implemented
  216204. }
  216205. const File File::getLinkedTarget() const
  216206. {
  216207. char buffer [4096];
  216208. size_t numChars = readlink (getFullPathName().toUTF8(),
  216209. buffer, sizeof (buffer));
  216210. if (numChars > 0 && numChars <= sizeof (buffer))
  216211. return File (String::fromUTF8 (buffer, (int) numChars));
  216212. return *this;
  216213. }
  216214. bool File::moveToTrash() const
  216215. {
  216216. if (! exists())
  216217. return true;
  216218. File trashCan ("~/.Trash");
  216219. if (! trashCan.isDirectory())
  216220. trashCan = "~/.local/share/Trash/files";
  216221. if (! trashCan.isDirectory())
  216222. return false;
  216223. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216224. getFileExtension()));
  216225. }
  216226. class DirectoryIterator::NativeIterator::Pimpl
  216227. {
  216228. public:
  216229. Pimpl (const File& directory, const String& wildCard_)
  216230. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216231. wildCard (wildCard_),
  216232. dir (opendir (directory.getFullPathName().toUTF8()))
  216233. {
  216234. if (wildCard == "*.*")
  216235. wildCard = "*";
  216236. wildcardUTF8 = wildCard.toUTF8();
  216237. }
  216238. ~Pimpl()
  216239. {
  216240. if (dir != 0)
  216241. closedir (dir);
  216242. }
  216243. bool next (String& filenameFound,
  216244. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216245. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216246. {
  216247. if (dir == 0)
  216248. return false;
  216249. for (;;)
  216250. {
  216251. struct dirent* const de = readdir (dir);
  216252. if (de == 0)
  216253. return false;
  216254. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216255. {
  216256. filenameFound = String::fromUTF8 (de->d_name);
  216257. const String path (parentDir + filenameFound);
  216258. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216259. {
  216260. struct stat info;
  216261. const bool statOk = juce_stat (path, info);
  216262. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216263. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216264. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216265. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216266. }
  216267. if (isHidden != 0)
  216268. *isHidden = filenameFound.startsWithChar ('.');
  216269. if (isReadOnly != 0)
  216270. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216271. return true;
  216272. }
  216273. }
  216274. }
  216275. private:
  216276. String parentDir, wildCard;
  216277. const char* wildcardUTF8;
  216278. DIR* dir;
  216279. Pimpl (const Pimpl&);
  216280. Pimpl& operator= (const Pimpl&);
  216281. };
  216282. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216283. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216284. {
  216285. }
  216286. DirectoryIterator::NativeIterator::~NativeIterator()
  216287. {
  216288. }
  216289. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216290. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216291. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216292. {
  216293. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216294. }
  216295. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216296. {
  216297. String cmdString (fileName.replace (" ", "\\ ",false));
  216298. cmdString << " " << parameters;
  216299. if (URL::isProbablyAWebsiteURL (fileName)
  216300. || cmdString.startsWithIgnoreCase ("file:")
  216301. || URL::isProbablyAnEmailAddress (fileName))
  216302. {
  216303. // create a command that tries to launch a bunch of likely browsers
  216304. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216305. StringArray cmdLines;
  216306. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216307. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216308. cmdString = cmdLines.joinIntoString (" || ");
  216309. }
  216310. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216311. const int cpid = fork();
  216312. if (cpid == 0)
  216313. {
  216314. setsid();
  216315. // Child process
  216316. execve (argv[0], (char**) argv, environ);
  216317. exit (0);
  216318. }
  216319. return cpid >= 0;
  216320. }
  216321. void File::revealToUser() const
  216322. {
  216323. if (isDirectory())
  216324. startAsProcess();
  216325. else if (getParentDirectory().exists())
  216326. getParentDirectory().startAsProcess();
  216327. }
  216328. #endif
  216329. /*** End of inlined file: juce_linux_Files.cpp ***/
  216330. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216331. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216332. // compiled on its own).
  216333. #if JUCE_INCLUDED_FILE
  216334. struct NamedPipeInternal
  216335. {
  216336. String pipeInName, pipeOutName;
  216337. int pipeIn, pipeOut;
  216338. bool volatile createdPipe, blocked, stopReadOperation;
  216339. static void signalHandler (int) {}
  216340. };
  216341. void NamedPipe::cancelPendingReads()
  216342. {
  216343. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216344. {
  216345. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216346. intern->stopReadOperation = true;
  216347. char buffer [1] = { 0 };
  216348. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216349. (void) bytesWritten;
  216350. int timeout = 2000;
  216351. while (intern->blocked && --timeout >= 0)
  216352. Thread::sleep (2);
  216353. intern->stopReadOperation = false;
  216354. }
  216355. }
  216356. void NamedPipe::close()
  216357. {
  216358. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216359. if (intern != 0)
  216360. {
  216361. internal = 0;
  216362. if (intern->pipeIn != -1)
  216363. ::close (intern->pipeIn);
  216364. if (intern->pipeOut != -1)
  216365. ::close (intern->pipeOut);
  216366. if (intern->createdPipe)
  216367. {
  216368. unlink (intern->pipeInName.toUTF8());
  216369. unlink (intern->pipeOutName.toUTF8());
  216370. }
  216371. delete intern;
  216372. }
  216373. }
  216374. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216375. {
  216376. close();
  216377. NamedPipeInternal* const intern = new NamedPipeInternal();
  216378. internal = intern;
  216379. intern->createdPipe = createPipe;
  216380. intern->blocked = false;
  216381. intern->stopReadOperation = false;
  216382. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216383. siginterrupt (SIGPIPE, 1);
  216384. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216385. intern->pipeInName = pipePath + "_in";
  216386. intern->pipeOutName = pipePath + "_out";
  216387. intern->pipeIn = -1;
  216388. intern->pipeOut = -1;
  216389. if (createPipe)
  216390. {
  216391. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216392. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216393. {
  216394. delete intern;
  216395. internal = 0;
  216396. return false;
  216397. }
  216398. }
  216399. return true;
  216400. }
  216401. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216402. {
  216403. int bytesRead = -1;
  216404. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216405. if (intern != 0)
  216406. {
  216407. intern->blocked = true;
  216408. if (intern->pipeIn == -1)
  216409. {
  216410. if (intern->createdPipe)
  216411. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216412. else
  216413. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216414. if (intern->pipeIn == -1)
  216415. {
  216416. intern->blocked = false;
  216417. return -1;
  216418. }
  216419. }
  216420. bytesRead = 0;
  216421. char* p = (char*) destBuffer;
  216422. while (bytesRead < maxBytesToRead)
  216423. {
  216424. const int bytesThisTime = maxBytesToRead - bytesRead;
  216425. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216426. if (numRead <= 0 || intern->stopReadOperation)
  216427. {
  216428. bytesRead = -1;
  216429. break;
  216430. }
  216431. bytesRead += numRead;
  216432. p += bytesRead;
  216433. }
  216434. intern->blocked = false;
  216435. }
  216436. return bytesRead;
  216437. }
  216438. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216439. {
  216440. int bytesWritten = -1;
  216441. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216442. if (intern != 0)
  216443. {
  216444. if (intern->pipeOut == -1)
  216445. {
  216446. if (intern->createdPipe)
  216447. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216448. else
  216449. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216450. if (intern->pipeOut == -1)
  216451. {
  216452. return -1;
  216453. }
  216454. }
  216455. const char* p = (const char*) sourceBuffer;
  216456. bytesWritten = 0;
  216457. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216458. while (bytesWritten < numBytesToWrite
  216459. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216460. {
  216461. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216462. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216463. if (numWritten <= 0)
  216464. {
  216465. bytesWritten = -1;
  216466. break;
  216467. }
  216468. bytesWritten += numWritten;
  216469. p += bytesWritten;
  216470. }
  216471. }
  216472. return bytesWritten;
  216473. }
  216474. #endif
  216475. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216476. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216477. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216478. // compiled on its own).
  216479. #if JUCE_INCLUDED_FILE
  216480. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216481. {
  216482. int numResults = 0;
  216483. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216484. if (s != -1)
  216485. {
  216486. char buf [1024];
  216487. struct ifconf ifc;
  216488. ifc.ifc_len = sizeof (buf);
  216489. ifc.ifc_buf = buf;
  216490. ioctl (s, SIOCGIFCONF, &ifc);
  216491. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216492. {
  216493. struct ifreq ifr;
  216494. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216495. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216496. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216497. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216498. && numResults < maxNum)
  216499. {
  216500. int64 a = 0;
  216501. for (int j = 6; --j >= 0;)
  216502. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216503. *addresses++ = a;
  216504. ++numResults;
  216505. }
  216506. }
  216507. close (s);
  216508. }
  216509. return numResults;
  216510. }
  216511. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216512. const String& emailSubject,
  216513. const String& bodyText,
  216514. const StringArray& filesToAttach)
  216515. {
  216516. jassertfalse; // xxx todo
  216517. return false;
  216518. }
  216519. /** A HTTP input stream that uses sockets.
  216520. */
  216521. class JUCE_HTTPSocketStream
  216522. {
  216523. public:
  216524. JUCE_HTTPSocketStream()
  216525. : readPosition (0),
  216526. socketHandle (-1),
  216527. levelsOfRedirection (0),
  216528. timeoutSeconds (15)
  216529. {
  216530. }
  216531. ~JUCE_HTTPSocketStream()
  216532. {
  216533. closeSocket();
  216534. }
  216535. bool open (const String& url,
  216536. const String& headers,
  216537. const MemoryBlock& postData,
  216538. const bool isPost,
  216539. URL::OpenStreamProgressCallback* callback,
  216540. void* callbackContext,
  216541. int timeOutMs)
  216542. {
  216543. closeSocket();
  216544. uint32 timeOutTime = Time::getMillisecondCounter();
  216545. if (timeOutMs == 0)
  216546. timeOutTime += 60000;
  216547. else if (timeOutMs < 0)
  216548. timeOutTime = 0xffffffff;
  216549. else
  216550. timeOutTime += timeOutMs;
  216551. String hostName, hostPath;
  216552. int hostPort;
  216553. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216554. return false;
  216555. const struct hostent* host = 0;
  216556. int port = 0;
  216557. String proxyName, proxyPath;
  216558. int proxyPort = 0;
  216559. String proxyURL (getenv ("http_proxy"));
  216560. if (proxyURL.startsWithIgnoreCase ("http://"))
  216561. {
  216562. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216563. return false;
  216564. host = gethostbyname (proxyName.toUTF8());
  216565. port = proxyPort;
  216566. }
  216567. else
  216568. {
  216569. host = gethostbyname (hostName.toUTF8());
  216570. port = hostPort;
  216571. }
  216572. if (host == 0)
  216573. return false;
  216574. struct sockaddr_in address;
  216575. zerostruct (address);
  216576. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216577. address.sin_family = host->h_addrtype;
  216578. address.sin_port = htons (port);
  216579. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216580. if (socketHandle == -1)
  216581. return false;
  216582. int receiveBufferSize = 16384;
  216583. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216584. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216585. #if JUCE_MAC
  216586. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216587. #endif
  216588. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216589. {
  216590. closeSocket();
  216591. return false;
  216592. }
  216593. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216594. proxyName, proxyPort,
  216595. hostPath, url,
  216596. headers, postData,
  216597. isPost));
  216598. size_t totalHeaderSent = 0;
  216599. while (totalHeaderSent < requestHeader.getSize())
  216600. {
  216601. if (Time::getMillisecondCounter() > timeOutTime)
  216602. {
  216603. closeSocket();
  216604. return false;
  216605. }
  216606. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216607. if (send (socketHandle,
  216608. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216609. numToSend, 0)
  216610. != numToSend)
  216611. {
  216612. closeSocket();
  216613. return false;
  216614. }
  216615. totalHeaderSent += numToSend;
  216616. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216617. {
  216618. closeSocket();
  216619. return false;
  216620. }
  216621. }
  216622. const String responseHeader (readResponse (timeOutTime));
  216623. if (responseHeader.isNotEmpty())
  216624. {
  216625. //DBG (responseHeader);
  216626. headerLines.clear();
  216627. headerLines.addLines (responseHeader);
  216628. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216629. .substring (0, 3).getIntValue();
  216630. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216631. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216632. String location (findHeaderItem (headerLines, "Location:"));
  216633. if (statusCode >= 300 && statusCode < 400
  216634. && location.isNotEmpty())
  216635. {
  216636. if (! location.startsWithIgnoreCase ("http://"))
  216637. location = "http://" + location;
  216638. if (levelsOfRedirection++ < 3)
  216639. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216640. }
  216641. else
  216642. {
  216643. levelsOfRedirection = 0;
  216644. return true;
  216645. }
  216646. }
  216647. closeSocket();
  216648. return false;
  216649. }
  216650. int read (void* buffer, int bytesToRead)
  216651. {
  216652. fd_set readbits;
  216653. FD_ZERO (&readbits);
  216654. FD_SET (socketHandle, &readbits);
  216655. struct timeval tv;
  216656. tv.tv_sec = timeoutSeconds;
  216657. tv.tv_usec = 0;
  216658. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216659. return 0; // (timeout)
  216660. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216661. readPosition += bytesRead;
  216662. return bytesRead;
  216663. }
  216664. int readPosition;
  216665. StringArray headerLines;
  216666. juce_UseDebuggingNewOperator
  216667. private:
  216668. int socketHandle, levelsOfRedirection;
  216669. const int timeoutSeconds;
  216670. void closeSocket()
  216671. {
  216672. if (socketHandle >= 0)
  216673. close (socketHandle);
  216674. socketHandle = -1;
  216675. }
  216676. const MemoryBlock createRequestHeader (const String& hostName,
  216677. const int hostPort,
  216678. const String& proxyName,
  216679. const int proxyPort,
  216680. const String& hostPath,
  216681. const String& originalURL,
  216682. const String& headers,
  216683. const MemoryBlock& postData,
  216684. const bool isPost)
  216685. {
  216686. String header (isPost ? "POST " : "GET ");
  216687. if (proxyName.isEmpty())
  216688. {
  216689. header << hostPath << " HTTP/1.0\r\nHost: "
  216690. << hostName << ':' << hostPort;
  216691. }
  216692. else
  216693. {
  216694. header << originalURL << " HTTP/1.0\r\nHost: "
  216695. << proxyName << ':' << proxyPort;
  216696. }
  216697. header << "\r\nUser-Agent: JUCE/"
  216698. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216699. << "\r\nConnection: Close\r\nContent-Length: "
  216700. << postData.getSize() << "\r\n"
  216701. << headers << "\r\n";
  216702. MemoryBlock mb;
  216703. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216704. mb.append (postData.getData(), postData.getSize());
  216705. return mb;
  216706. }
  216707. const String readResponse (const uint32 timeOutTime)
  216708. {
  216709. int bytesRead = 0, numConsecutiveLFs = 0;
  216710. MemoryBlock buffer (1024, true);
  216711. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216712. && Time::getMillisecondCounter() <= timeOutTime)
  216713. {
  216714. fd_set readbits;
  216715. FD_ZERO (&readbits);
  216716. FD_SET (socketHandle, &readbits);
  216717. struct timeval tv;
  216718. tv.tv_sec = timeoutSeconds;
  216719. tv.tv_usec = 0;
  216720. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216721. return String::empty; // (timeout)
  216722. buffer.ensureSize (bytesRead + 8, true);
  216723. char* const dest = (char*) buffer.getData() + bytesRead;
  216724. if (recv (socketHandle, dest, 1, 0) == -1)
  216725. return String::empty;
  216726. const char lastByte = *dest;
  216727. ++bytesRead;
  216728. if (lastByte == '\n')
  216729. ++numConsecutiveLFs;
  216730. else if (lastByte != '\r')
  216731. numConsecutiveLFs = 0;
  216732. }
  216733. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216734. if (header.startsWithIgnoreCase ("HTTP/"))
  216735. return header.trimEnd();
  216736. return String::empty;
  216737. }
  216738. static bool decomposeURL (const String& url,
  216739. String& host, String& path, int& port)
  216740. {
  216741. if (! url.startsWithIgnoreCase ("http://"))
  216742. return false;
  216743. const int nextSlash = url.indexOfChar (7, '/');
  216744. int nextColon = url.indexOfChar (7, ':');
  216745. if (nextColon > nextSlash && nextSlash > 0)
  216746. nextColon = -1;
  216747. if (nextColon >= 0)
  216748. {
  216749. host = url.substring (7, nextColon);
  216750. if (nextSlash >= 0)
  216751. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216752. else
  216753. port = url.substring (nextColon + 1).getIntValue();
  216754. }
  216755. else
  216756. {
  216757. port = 80;
  216758. if (nextSlash >= 0)
  216759. host = url.substring (7, nextSlash);
  216760. else
  216761. host = url.substring (7);
  216762. }
  216763. if (nextSlash >= 0)
  216764. path = url.substring (nextSlash);
  216765. else
  216766. path = "/";
  216767. return true;
  216768. }
  216769. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216770. {
  216771. for (int i = 0; i < lines.size(); ++i)
  216772. if (lines[i].startsWithIgnoreCase (itemName))
  216773. return lines[i].substring (itemName.length()).trim();
  216774. return String::empty;
  216775. }
  216776. };
  216777. void* juce_openInternetFile (const String& url,
  216778. const String& headers,
  216779. const MemoryBlock& postData,
  216780. const bool isPost,
  216781. URL::OpenStreamProgressCallback* callback,
  216782. void* callbackContext,
  216783. int timeOutMs)
  216784. {
  216785. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216786. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216787. return s.release();
  216788. return 0;
  216789. }
  216790. void juce_closeInternetFile (void* handle)
  216791. {
  216792. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216793. }
  216794. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216795. {
  216796. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216797. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216798. }
  216799. int64 juce_getInternetFileContentLength (void* handle)
  216800. {
  216801. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216802. if (s != 0)
  216803. {
  216804. //xxx todo
  216805. jassertfalse
  216806. }
  216807. return -1;
  216808. }
  216809. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216810. {
  216811. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216812. if (s != 0)
  216813. {
  216814. for (int i = 0; i < s->headerLines.size(); ++i)
  216815. {
  216816. const String& headersEntry = s->headerLines[i];
  216817. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  216818. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  216819. const String previousValue (headers [key]);
  216820. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  216821. }
  216822. }
  216823. }
  216824. int juce_seekInInternetFile (void* handle, int newPosition)
  216825. {
  216826. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216827. return s != 0 ? s->readPosition : 0;
  216828. }
  216829. #endif
  216830. /*** End of inlined file: juce_linux_Network.cpp ***/
  216831. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  216832. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216833. // compiled on its own).
  216834. #if JUCE_INCLUDED_FILE
  216835. void Logger::outputDebugString (const String& text)
  216836. {
  216837. std::cerr << text << std::endl;
  216838. }
  216839. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  216840. {
  216841. return Linux;
  216842. }
  216843. const String SystemStats::getOperatingSystemName()
  216844. {
  216845. return "Linux";
  216846. }
  216847. bool SystemStats::isOperatingSystem64Bit()
  216848. {
  216849. #if JUCE_64BIT
  216850. return true;
  216851. #else
  216852. //xxx not sure how to find this out?..
  216853. return false;
  216854. #endif
  216855. }
  216856. static const String juce_getCpuInfo (const char* const key)
  216857. {
  216858. StringArray lines;
  216859. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  216860. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  216861. if (lines[i].startsWithIgnoreCase (key))
  216862. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  216863. return String::empty;
  216864. }
  216865. const String SystemStats::getCpuVendor()
  216866. {
  216867. return juce_getCpuInfo ("vendor_id");
  216868. }
  216869. int SystemStats::getCpuSpeedInMegaherz()
  216870. {
  216871. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  216872. }
  216873. int SystemStats::getMemorySizeInMegabytes()
  216874. {
  216875. struct sysinfo sysi;
  216876. if (sysinfo (&sysi) == 0)
  216877. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  216878. return 0;
  216879. }
  216880. int SystemStats::getPageSize()
  216881. {
  216882. return sysconf (_SC_PAGESIZE);
  216883. }
  216884. const String SystemStats::getLogonName()
  216885. {
  216886. const char* user = getenv ("USER");
  216887. if (user == 0)
  216888. {
  216889. struct passwd* const pw = getpwuid (getuid());
  216890. if (pw != 0)
  216891. user = pw->pw_name;
  216892. }
  216893. return String::fromUTF8 (user);
  216894. }
  216895. const String SystemStats::getFullUserName()
  216896. {
  216897. return getLogonName();
  216898. }
  216899. void SystemStats::initialiseStats()
  216900. {
  216901. const String flags (juce_getCpuInfo ("flags"));
  216902. cpuFlags.hasMMX = flags.contains ("mmx");
  216903. cpuFlags.hasSSE = flags.contains ("sse");
  216904. cpuFlags.hasSSE2 = flags.contains ("sse2");
  216905. cpuFlags.has3DNow = flags.contains ("3dnow");
  216906. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  216907. }
  216908. void PlatformUtilities::fpuReset()
  216909. {
  216910. }
  216911. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  216912. {
  216913. if (gettimeofday (t, 0) != 0)
  216914. return false;
  216915. static unsigned int calibrate = 0;
  216916. static bool calibrated = false;
  216917. if (! calibrated)
  216918. {
  216919. calibrated = true;
  216920. struct sysinfo sysi;
  216921. if (sysinfo (&sysi) == 0)
  216922. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  216923. }
  216924. t->tv_sec -= calibrate;
  216925. return true;
  216926. }
  216927. uint32 juce_millisecondsSinceStartup() throw()
  216928. {
  216929. timeval t;
  216930. if (juce_getTimeSinceStartup (&t))
  216931. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  216932. return 0;
  216933. }
  216934. int64 Time::getHighResolutionTicks() throw()
  216935. {
  216936. timeval t;
  216937. if (juce_getTimeSinceStartup (&t))
  216938. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  216939. return 0;
  216940. }
  216941. int64 Time::getHighResolutionTicksPerSecond() throw()
  216942. {
  216943. return 1000000; // (microseconds)
  216944. }
  216945. double Time::getMillisecondCounterHiRes() throw()
  216946. {
  216947. return getHighResolutionTicks() * 0.001;
  216948. }
  216949. bool Time::setSystemTimeToThisTime() const
  216950. {
  216951. timeval t;
  216952. t.tv_sec = millisSinceEpoch % 1000000;
  216953. t.tv_usec = millisSinceEpoch - t.tv_sec;
  216954. return settimeofday (&t, 0) ? false : true;
  216955. }
  216956. #endif
  216957. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  216958. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  216959. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216960. // compiled on its own).
  216961. #if JUCE_INCLUDED_FILE
  216962. /*
  216963. Note that a lot of methods that you'd expect to find in this file actually
  216964. live in juce_posix_SharedCode.h!
  216965. */
  216966. void JUCE_API juce_threadEntryPoint (void*);
  216967. void* threadEntryProc (void* value)
  216968. {
  216969. juce_threadEntryPoint (value);
  216970. return 0;
  216971. }
  216972. void* juce_createThread (void* userData)
  216973. {
  216974. pthread_t handle = 0;
  216975. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216976. {
  216977. pthread_detach (handle);
  216978. return (void*) handle;
  216979. }
  216980. return 0;
  216981. }
  216982. void juce_killThread (void* handle)
  216983. {
  216984. if (handle != 0)
  216985. pthread_cancel ((pthread_t) handle);
  216986. }
  216987. void juce_setCurrentThreadName (const String& /*name*/)
  216988. {
  216989. }
  216990. Thread::ThreadID Thread::getCurrentThreadId()
  216991. {
  216992. return (ThreadID) pthread_self();
  216993. }
  216994. /* This is all a bit non-ideal... the trouble is that on Linux you
  216995. need to call setpriority to affect the dynamic priority for
  216996. non-realtime processes, but this requires the pid, which is not
  216997. accessible from the pthread_t. We could get it by calling getpid
  216998. once each thread has started, but then we would need a list of
  216999. running threads etc etc.
  217000. Also there is no such thing as IDLE priority on Linux.
  217001. For the moment, map idle, low and normal process priorities to
  217002. SCHED_OTHER, with the thread priority ignored for these classes.
  217003. Map high priority processes to the lower half of the SCHED_RR
  217004. range, and realtime to the upper half.
  217005. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  217006. priority of the current thread
  217007. */
  217008. bool juce_setThreadPriority (void* handle, int priority)
  217009. {
  217010. struct sched_param param;
  217011. int policy;
  217012. if (handle == 0)
  217013. handle = (void*) pthread_self();
  217014. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  217015. && policy != SCHED_OTHER)
  217016. {
  217017. int minp = sched_get_priority_min (policy);
  217018. int maxp = sched_get_priority_max (policy);
  217019. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  217020. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  217021. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  217022. else
  217023. param.sched_priority = minp + pri; // (high)
  217024. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  217025. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217026. }
  217027. return false;
  217028. }
  217029. /* Remove this macro if you're having problems compiling the cpu affinity
  217030. calls (the API for these has changed about quite a bit in various Linux
  217031. versions, and a lot of distros seem to ship with obsolete versions)
  217032. */
  217033. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217034. #define SUPPORT_AFFINITIES 1
  217035. #endif
  217036. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217037. {
  217038. #if SUPPORT_AFFINITIES
  217039. cpu_set_t affinity;
  217040. CPU_ZERO (&affinity);
  217041. for (int i = 0; i < 32; ++i)
  217042. if ((affinityMask & (1 << i)) != 0)
  217043. CPU_SET (i, &affinity);
  217044. /*
  217045. N.B. If this line causes a compile error, then you've probably not got the latest
  217046. version of glibc installed.
  217047. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217048. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217049. */
  217050. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217051. sched_yield();
  217052. #else
  217053. /* affinities aren't supported because either the appropriate header files weren't found,
  217054. or the SUPPORT_AFFINITIES macro was turned off
  217055. */
  217056. jassertfalse;
  217057. #endif
  217058. }
  217059. void Thread::yield()
  217060. {
  217061. sched_yield();
  217062. }
  217063. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217064. void Process::setPriority (ProcessPriority prior)
  217065. {
  217066. struct sched_param param;
  217067. int policy, maxp, minp;
  217068. const int p = (int) prior;
  217069. if (p <= 1)
  217070. policy = SCHED_OTHER;
  217071. else
  217072. policy = SCHED_RR;
  217073. minp = sched_get_priority_min (policy);
  217074. maxp = sched_get_priority_max (policy);
  217075. if (p < 2)
  217076. param.sched_priority = 0;
  217077. else if (p == 2 )
  217078. // Set to middle of lower realtime priority range
  217079. param.sched_priority = minp + (maxp - minp) / 4;
  217080. else
  217081. // Set to middle of higher realtime priority range
  217082. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217083. pthread_setschedparam (pthread_self(), policy, &param);
  217084. }
  217085. void Process::terminate()
  217086. {
  217087. exit (0);
  217088. }
  217089. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  217090. {
  217091. static char testResult = 0;
  217092. if (testResult == 0)
  217093. {
  217094. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217095. if (testResult >= 0)
  217096. {
  217097. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217098. testResult = 1;
  217099. }
  217100. }
  217101. return testResult < 0;
  217102. }
  217103. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217104. {
  217105. return juce_isRunningUnderDebugger();
  217106. }
  217107. void Process::raisePrivilege()
  217108. {
  217109. // If running suid root, change effective user
  217110. // to root
  217111. if (geteuid() != 0 && getuid() == 0)
  217112. {
  217113. setreuid (geteuid(), getuid());
  217114. setregid (getegid(), getgid());
  217115. }
  217116. }
  217117. void Process::lowerPrivilege()
  217118. {
  217119. // If runing suid root, change effective user
  217120. // back to real user
  217121. if (geteuid() == 0 && getuid() != 0)
  217122. {
  217123. setreuid (geteuid(), getuid());
  217124. setregid (getegid(), getgid());
  217125. }
  217126. }
  217127. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217128. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217129. {
  217130. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217131. }
  217132. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217133. {
  217134. dlclose(handle);
  217135. }
  217136. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217137. {
  217138. return dlsym (libraryHandle, procedureName.toCString());
  217139. }
  217140. #endif
  217141. #endif
  217142. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217143. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217144. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217145. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217146. // compiled on its own).
  217147. #if JUCE_INCLUDED_FILE
  217148. #if JUCE_DEBUG
  217149. #define JUCE_DEBUG_XERRORS 1
  217150. #endif
  217151. extern Display* display;
  217152. extern Window juce_messageWindowHandle;
  217153. namespace ClipboardHelpers
  217154. {
  217155. static String localClipboardContent;
  217156. static Atom atom_UTF8_STRING;
  217157. static Atom atom_CLIPBOARD;
  217158. static Atom atom_TARGETS;
  217159. static void initSelectionAtoms()
  217160. {
  217161. static bool isInitialised = false;
  217162. if (! isInitialised)
  217163. {
  217164. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217165. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217166. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217167. }
  217168. }
  217169. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217170. // works only for strings shorter than 1000000 bytes
  217171. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217172. {
  217173. String returnData;
  217174. char* clipData;
  217175. Atom actualType;
  217176. int actualFormat;
  217177. unsigned long numItems, bytesLeft;
  217178. if (XGetWindowProperty (display, window, prop,
  217179. 0L /* offset */, 1000000 /* length (max) */, False,
  217180. AnyPropertyType /* format */,
  217181. &actualType, &actualFormat, &numItems, &bytesLeft,
  217182. (unsigned char**) &clipData) == Success)
  217183. {
  217184. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217185. returnData = String::fromUTF8 (clipData, numItems);
  217186. else if (actualType == XA_STRING && actualFormat == 8)
  217187. returnData = String (clipData, numItems);
  217188. if (clipData != 0)
  217189. XFree (clipData);
  217190. jassert (bytesLeft == 0 || numItems == 1000000);
  217191. }
  217192. XDeleteProperty (display, window, prop);
  217193. return returnData;
  217194. }
  217195. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217196. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217197. {
  217198. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217199. // The selection owner will be asked to set the JUCE_SEL property on the
  217200. // juce_messageWindowHandle with the selection content
  217201. XConvertSelection (display, selection, requestedFormat, property_name,
  217202. juce_messageWindowHandle, CurrentTime);
  217203. int count = 50; // will wait at most for 200 ms
  217204. while (--count >= 0)
  217205. {
  217206. XEvent event;
  217207. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217208. {
  217209. if (event.xselection.property == property_name)
  217210. {
  217211. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217212. selectionContent = readWindowProperty (event.xselection.requestor,
  217213. event.xselection.property,
  217214. requestedFormat);
  217215. return true;
  217216. }
  217217. else
  217218. {
  217219. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217220. }
  217221. }
  217222. // not very elegant.. we could do a select() or something like that...
  217223. // however clipboard content requesting is inherently slow on x11, it
  217224. // often takes 50ms or more so...
  217225. Thread::sleep (4);
  217226. }
  217227. return false;
  217228. }
  217229. }
  217230. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217231. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217232. {
  217233. ClipboardHelpers::initSelectionAtoms();
  217234. // the selection content is sent to the target window as a window property
  217235. XSelectionEvent reply;
  217236. reply.type = SelectionNotify;
  217237. reply.display = evt.display;
  217238. reply.requestor = evt.requestor;
  217239. reply.selection = evt.selection;
  217240. reply.target = evt.target;
  217241. reply.property = None; // == "fail"
  217242. reply.time = evt.time;
  217243. HeapBlock <char> data;
  217244. int propertyFormat = 0, numDataItems = 0;
  217245. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217246. {
  217247. if (evt.target == XA_STRING)
  217248. {
  217249. // format data according to system locale
  217250. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217251. data.calloc (numDataItems + 1);
  217252. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217253. propertyFormat = 8; // bits/item
  217254. }
  217255. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217256. {
  217257. // translate to utf8
  217258. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217259. data.calloc (numDataItems + 1);
  217260. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217261. propertyFormat = 8; // bits/item
  217262. }
  217263. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217264. {
  217265. // another application wants to know what we are able to send
  217266. numDataItems = 2;
  217267. propertyFormat = 32; // atoms are 32-bit
  217268. data.calloc (numDataItems * 4);
  217269. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217270. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217271. atoms[1] = XA_STRING;
  217272. }
  217273. }
  217274. else
  217275. {
  217276. DBG ("requested unsupported clipboard");
  217277. }
  217278. if (data != 0)
  217279. {
  217280. const int maxReasonableSelectionSize = 1000000;
  217281. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217282. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217283. {
  217284. XChangeProperty (evt.display, evt.requestor,
  217285. evt.property, evt.target,
  217286. propertyFormat /* 8 or 32 */, PropModeReplace,
  217287. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217288. reply.property = evt.property; // " == success"
  217289. }
  217290. }
  217291. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217292. }
  217293. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217294. {
  217295. ClipboardHelpers::initSelectionAtoms();
  217296. ClipboardHelpers::localClipboardContent = clipText;
  217297. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217298. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217299. }
  217300. const String SystemClipboard::getTextFromClipboard()
  217301. {
  217302. ClipboardHelpers::initSelectionAtoms();
  217303. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217304. level" clipboard that is supposed to be filled by ctrl-C
  217305. etc). When a clipboard manager is running, the content of this
  217306. selection is preserved even when the original selection owner
  217307. exits.
  217308. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217309. filled by good old x11 apps such as xterm)
  217310. */
  217311. String content;
  217312. Atom selection = XA_PRIMARY;
  217313. Window selectionOwner = None;
  217314. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217315. {
  217316. selection = ClipboardHelpers::atom_CLIPBOARD;
  217317. selectionOwner = XGetSelectionOwner (display, selection);
  217318. }
  217319. if (selectionOwner != None)
  217320. {
  217321. if (selectionOwner == juce_messageWindowHandle)
  217322. {
  217323. content = ClipboardHelpers::localClipboardContent;
  217324. }
  217325. else
  217326. {
  217327. // first try: we want an utf8 string
  217328. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217329. if (! ok)
  217330. {
  217331. // second chance, ask for a good old locale-dependent string ..
  217332. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217333. }
  217334. }
  217335. }
  217336. return content;
  217337. }
  217338. #endif
  217339. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217340. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217341. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217342. // compiled on its own).
  217343. #if JUCE_INCLUDED_FILE
  217344. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217345. #define JUCE_DEBUG_XERRORS 1
  217346. #endif
  217347. Display* display = 0;
  217348. Window juce_messageWindowHandle = None;
  217349. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217350. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217351. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217352. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217353. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217354. class InternalMessageQueue
  217355. {
  217356. public:
  217357. InternalMessageQueue()
  217358. : bytesInSocket (0),
  217359. totalEventCount (0)
  217360. {
  217361. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217362. (void) ret; jassert (ret == 0);
  217363. //setNonBlocking (fd[0]);
  217364. //setNonBlocking (fd[1]);
  217365. }
  217366. ~InternalMessageQueue()
  217367. {
  217368. close (fd[0]);
  217369. close (fd[1]);
  217370. clearSingletonInstance();
  217371. }
  217372. void postMessage (Message* msg)
  217373. {
  217374. const int maxBytesInSocketQueue = 128;
  217375. ScopedLock sl (lock);
  217376. queue.add (msg);
  217377. if (bytesInSocket < maxBytesInSocketQueue)
  217378. {
  217379. ++bytesInSocket;
  217380. ScopedUnlock ul (lock);
  217381. const unsigned char x = 0xff;
  217382. size_t bytesWritten = write (fd[0], &x, 1);
  217383. (void) bytesWritten;
  217384. }
  217385. }
  217386. bool isEmpty() const
  217387. {
  217388. ScopedLock sl (lock);
  217389. return queue.size() == 0;
  217390. }
  217391. bool dispatchNextEvent()
  217392. {
  217393. // This alternates between giving priority to XEvents or internal messages,
  217394. // to keep everything running smoothly..
  217395. if ((++totalEventCount & 1) != 0)
  217396. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217397. else
  217398. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217399. }
  217400. // Wait for an event (either XEvent, or an internal Message)
  217401. bool sleepUntilEvent (const int timeoutMs)
  217402. {
  217403. if (! isEmpty())
  217404. return true;
  217405. if (display != 0)
  217406. {
  217407. ScopedXLock xlock;
  217408. if (XPending (display))
  217409. return true;
  217410. }
  217411. struct timeval tv;
  217412. tv.tv_sec = 0;
  217413. tv.tv_usec = timeoutMs * 1000;
  217414. int fd0 = getWaitHandle();
  217415. int fdmax = fd0;
  217416. fd_set readset;
  217417. FD_ZERO (&readset);
  217418. FD_SET (fd0, &readset);
  217419. if (display != 0)
  217420. {
  217421. ScopedXLock xlock;
  217422. int fd1 = XConnectionNumber (display);
  217423. FD_SET (fd1, &readset);
  217424. fdmax = jmax (fd0, fd1);
  217425. }
  217426. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217427. return (ret > 0); // ret <= 0 if error or timeout
  217428. }
  217429. struct MessageThreadFuncCall
  217430. {
  217431. enum { uniqueID = 0x73774623 };
  217432. MessageCallbackFunction* func;
  217433. void* parameter;
  217434. void* result;
  217435. CriticalSection lock;
  217436. WaitableEvent event;
  217437. };
  217438. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217439. private:
  217440. CriticalSection lock;
  217441. OwnedArray <Message> queue;
  217442. int fd[2];
  217443. int bytesInSocket;
  217444. int totalEventCount;
  217445. int getWaitHandle() const throw() { return fd[1]; }
  217446. static bool setNonBlocking (int handle)
  217447. {
  217448. int socketFlags = fcntl (handle, F_GETFL, 0);
  217449. if (socketFlags == -1)
  217450. return false;
  217451. socketFlags |= O_NONBLOCK;
  217452. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217453. }
  217454. static bool dispatchNextXEvent()
  217455. {
  217456. if (display == 0)
  217457. return false;
  217458. XEvent evt;
  217459. {
  217460. ScopedXLock xlock;
  217461. if (! XPending (display))
  217462. return false;
  217463. XNextEvent (display, &evt);
  217464. }
  217465. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217466. juce_handleSelectionRequest (evt.xselectionrequest);
  217467. else if (evt.xany.window != juce_messageWindowHandle)
  217468. juce_windowMessageReceive (&evt);
  217469. return true;
  217470. }
  217471. Message* popNextMessage()
  217472. {
  217473. ScopedLock sl (lock);
  217474. if (bytesInSocket > 0)
  217475. {
  217476. --bytesInSocket;
  217477. ScopedUnlock ul (lock);
  217478. unsigned char x;
  217479. size_t numBytes = read (fd[1], &x, 1);
  217480. (void) numBytes;
  217481. }
  217482. return queue.removeAndReturn (0);
  217483. }
  217484. bool dispatchNextInternalMessage()
  217485. {
  217486. ScopedPointer <Message> msg (popNextMessage());
  217487. if (msg == 0)
  217488. return false;
  217489. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217490. {
  217491. // Handle callback message
  217492. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217493. call->result = (*(call->func)) (call->parameter);
  217494. call->event.signal();
  217495. }
  217496. else
  217497. {
  217498. // Handle "normal" messages
  217499. MessageManager::getInstance()->deliverMessage (msg.release());
  217500. }
  217501. return true;
  217502. }
  217503. };
  217504. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217505. namespace LinuxErrorHandling
  217506. {
  217507. static bool errorOccurred = false;
  217508. static bool keyboardBreakOccurred = false;
  217509. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217510. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217511. // Usually happens when client-server connection is broken
  217512. static int ioErrorHandler (Display* display)
  217513. {
  217514. DBG ("ERROR: connection to X server broken.. terminating.");
  217515. if (JUCEApplication::getInstance() != 0)
  217516. MessageManager::getInstance()->stopDispatchLoop();
  217517. errorOccurred = true;
  217518. return 0;
  217519. }
  217520. // A protocol error has occurred
  217521. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217522. {
  217523. #if JUCE_DEBUG_XERRORS
  217524. char errorStr[64] = { 0 };
  217525. char requestStr[64] = { 0 };
  217526. XGetErrorText (display, event->error_code, errorStr, 64);
  217527. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217528. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217529. #endif
  217530. return 0;
  217531. }
  217532. static void installXErrorHandlers()
  217533. {
  217534. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217535. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217536. }
  217537. static void removeXErrorHandlers()
  217538. {
  217539. XSetIOErrorHandler (oldIOErrorHandler);
  217540. oldIOErrorHandler = 0;
  217541. XSetErrorHandler (oldErrorHandler);
  217542. oldErrorHandler = 0;
  217543. }
  217544. static void keyboardBreakSignalHandler (int sig)
  217545. {
  217546. if (sig == SIGINT)
  217547. keyboardBreakOccurred = true;
  217548. }
  217549. static void installKeyboardBreakHandler()
  217550. {
  217551. struct sigaction saction;
  217552. sigset_t maskSet;
  217553. sigemptyset (&maskSet);
  217554. saction.sa_handler = keyboardBreakSignalHandler;
  217555. saction.sa_mask = maskSet;
  217556. saction.sa_flags = 0;
  217557. sigaction (SIGINT, &saction, 0);
  217558. }
  217559. }
  217560. void MessageManager::doPlatformSpecificInitialisation()
  217561. {
  217562. // Initialise xlib for multiple thread support
  217563. static bool initThreadCalled = false;
  217564. if (! initThreadCalled)
  217565. {
  217566. if (! XInitThreads())
  217567. {
  217568. // This is fatal! Print error and closedown
  217569. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217570. if (JUCEApplication::getInstance() != 0)
  217571. Process::terminate();
  217572. return;
  217573. }
  217574. initThreadCalled = true;
  217575. }
  217576. LinuxErrorHandling::installXErrorHandlers();
  217577. LinuxErrorHandling::installKeyboardBreakHandler();
  217578. // Create the internal message queue
  217579. InternalMessageQueue::getInstance();
  217580. // Try to connect to a display
  217581. String displayName (getenv ("DISPLAY"));
  217582. if (displayName.isEmpty())
  217583. displayName = ":0.0";
  217584. display = XOpenDisplay (displayName.toCString());
  217585. if (display != 0) // This is not fatal! we can run headless.
  217586. {
  217587. // Create a context to store user data associated with Windows we create in WindowDriver
  217588. windowHandleXContext = XUniqueContext();
  217589. // We're only interested in client messages for this window, which are always sent
  217590. XSetWindowAttributes swa;
  217591. swa.event_mask = NoEventMask;
  217592. // Create our message window (this will never be mapped)
  217593. const int screen = DefaultScreen (display);
  217594. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217595. 0, 0, 1, 1, 0, 0, InputOnly,
  217596. DefaultVisual (display, screen),
  217597. CWEventMask, &swa);
  217598. }
  217599. }
  217600. void MessageManager::doPlatformSpecificShutdown()
  217601. {
  217602. InternalMessageQueue::deleteInstance();
  217603. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217604. {
  217605. XDestroyWindow (display, juce_messageWindowHandle);
  217606. XCloseDisplay (display);
  217607. juce_messageWindowHandle = 0;
  217608. display = 0;
  217609. LinuxErrorHandling::removeXErrorHandlers();
  217610. }
  217611. }
  217612. bool juce_postMessageToSystemQueue (Message* message)
  217613. {
  217614. if (LinuxErrorHandling::errorOccurred)
  217615. return false;
  217616. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  217617. return true;
  217618. }
  217619. void MessageManager::broadcastMessage (const String& value) throw()
  217620. {
  217621. /* TODO */
  217622. }
  217623. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217624. void* parameter)
  217625. {
  217626. if (LinuxErrorHandling::errorOccurred)
  217627. return 0;
  217628. if (isThisTheMessageThread())
  217629. return func (parameter);
  217630. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217631. messageCallContext.func = func;
  217632. messageCallContext.parameter = parameter;
  217633. InternalMessageQueue::getInstanceWithoutCreating()
  217634. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217635. 0, 0, &messageCallContext));
  217636. // Wait for it to complete before continuing
  217637. messageCallContext.event.wait();
  217638. return messageCallContext.result;
  217639. }
  217640. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217641. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217642. {
  217643. while (! LinuxErrorHandling::errorOccurred)
  217644. {
  217645. if (LinuxErrorHandling::keyboardBreakOccurred)
  217646. {
  217647. LinuxErrorHandling::errorOccurred = true;
  217648. if (JUCEApplication::getInstance() != 0)
  217649. Process::terminate();
  217650. break;
  217651. }
  217652. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217653. return true;
  217654. if (returnIfNoPendingMessages)
  217655. break;
  217656. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217657. }
  217658. return false;
  217659. }
  217660. #endif
  217661. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217662. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217663. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217664. // compiled on its own).
  217665. #if JUCE_INCLUDED_FILE
  217666. class FreeTypeFontFace
  217667. {
  217668. public:
  217669. enum FontStyle
  217670. {
  217671. Plain = 0,
  217672. Bold = 1,
  217673. Italic = 2
  217674. };
  217675. FreeTypeFontFace (const String& familyName)
  217676. : hasSerif (false),
  217677. monospaced (false)
  217678. {
  217679. family = familyName;
  217680. }
  217681. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217682. {
  217683. if (names [(int) style].fileName.isEmpty())
  217684. {
  217685. names [(int) style].fileName = name;
  217686. names [(int) style].faceIndex = faceIndex;
  217687. }
  217688. }
  217689. const String& getFamilyName() const throw() { return family; }
  217690. const String& getFileName (const int style, int& faceIndex) const throw()
  217691. {
  217692. faceIndex = names[style].faceIndex;
  217693. return names[style].fileName;
  217694. }
  217695. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217696. bool getMonospaced() const throw() { return monospaced; }
  217697. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217698. bool getSerif() const throw() { return hasSerif; }
  217699. private:
  217700. String family;
  217701. struct FontNameIndex
  217702. {
  217703. String fileName;
  217704. int faceIndex;
  217705. };
  217706. FontNameIndex names[4];
  217707. bool hasSerif, monospaced;
  217708. };
  217709. class FreeTypeInterface : public DeletedAtShutdown
  217710. {
  217711. public:
  217712. FreeTypeInterface()
  217713. : ftLib (0),
  217714. lastFace (0),
  217715. lastBold (false),
  217716. lastItalic (false)
  217717. {
  217718. if (FT_Init_FreeType (&ftLib) != 0)
  217719. {
  217720. ftLib = 0;
  217721. DBG ("Failed to initialize FreeType");
  217722. }
  217723. StringArray fontDirs;
  217724. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217725. fontDirs.removeEmptyStrings (true);
  217726. if (fontDirs.size() == 0)
  217727. {
  217728. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217729. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217730. if (fontsInfo != 0)
  217731. {
  217732. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217733. {
  217734. fontDirs.add (e->getAllSubText().trim());
  217735. }
  217736. }
  217737. }
  217738. if (fontDirs.size() == 0)
  217739. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217740. for (int i = 0; i < fontDirs.size(); ++i)
  217741. enumerateFaces (fontDirs[i]);
  217742. }
  217743. ~FreeTypeInterface()
  217744. {
  217745. if (lastFace != 0)
  217746. FT_Done_Face (lastFace);
  217747. if (ftLib != 0)
  217748. FT_Done_FreeType (ftLib);
  217749. clearSingletonInstance();
  217750. }
  217751. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217752. {
  217753. for (int i = 0; i < faces.size(); i++)
  217754. if (faces[i]->getFamilyName() == familyName)
  217755. return faces[i];
  217756. if (! create)
  217757. return 0;
  217758. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217759. faces.add (newFace);
  217760. return newFace;
  217761. }
  217762. // Enumerate all font faces available in a given directory
  217763. void enumerateFaces (const String& path)
  217764. {
  217765. File dirPath (path);
  217766. if (path.isEmpty() || ! dirPath.isDirectory())
  217767. return;
  217768. DirectoryIterator di (dirPath, true);
  217769. while (di.next())
  217770. {
  217771. File possible (di.getFile());
  217772. if (possible.hasFileExtension ("ttf")
  217773. || possible.hasFileExtension ("pfb")
  217774. || possible.hasFileExtension ("pcf"))
  217775. {
  217776. FT_Face face;
  217777. int faceIndex = 0;
  217778. int numFaces = 0;
  217779. do
  217780. {
  217781. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217782. faceIndex, &face) == 0)
  217783. {
  217784. if (faceIndex == 0)
  217785. numFaces = face->num_faces;
  217786. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217787. {
  217788. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217789. int style = (int) FreeTypeFontFace::Plain;
  217790. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217791. style |= (int) FreeTypeFontFace::Bold;
  217792. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217793. style |= (int) FreeTypeFontFace::Italic;
  217794. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217795. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217796. // Surely there must be a better way to do this?
  217797. const String name (face->family_name);
  217798. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217799. || name.containsIgnoreCase ("Verdana")
  217800. || name.containsIgnoreCase ("Arial")));
  217801. }
  217802. FT_Done_Face (face);
  217803. }
  217804. ++faceIndex;
  217805. }
  217806. while (faceIndex < numFaces);
  217807. }
  217808. }
  217809. }
  217810. // Create a FreeType face object for a given font
  217811. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217812. {
  217813. FT_Face face = 0;
  217814. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  217815. {
  217816. face = lastFace;
  217817. }
  217818. else
  217819. {
  217820. if (lastFace != 0)
  217821. {
  217822. FT_Done_Face (lastFace);
  217823. lastFace = 0;
  217824. }
  217825. lastFontName = fontName;
  217826. lastBold = bold;
  217827. lastItalic = italic;
  217828. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  217829. if (ftFace != 0)
  217830. {
  217831. int style = (int) FreeTypeFontFace::Plain;
  217832. if (bold)
  217833. style |= (int) FreeTypeFontFace::Bold;
  217834. if (italic)
  217835. style |= (int) FreeTypeFontFace::Italic;
  217836. int faceIndex;
  217837. String fileName (ftFace->getFileName (style, faceIndex));
  217838. if (fileName.isEmpty())
  217839. {
  217840. style ^= (int) FreeTypeFontFace::Bold;
  217841. fileName = ftFace->getFileName (style, faceIndex);
  217842. if (fileName.isEmpty())
  217843. {
  217844. style ^= (int) FreeTypeFontFace::Bold;
  217845. style ^= (int) FreeTypeFontFace::Italic;
  217846. fileName = ftFace->getFileName (style, faceIndex);
  217847. if (! fileName.length())
  217848. {
  217849. style ^= (int) FreeTypeFontFace::Bold;
  217850. fileName = ftFace->getFileName (style, faceIndex);
  217851. }
  217852. }
  217853. }
  217854. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  217855. {
  217856. face = lastFace;
  217857. // If there isn't a unicode charmap then select the first one.
  217858. if (FT_Select_Charmap (face, ft_encoding_unicode))
  217859. FT_Set_Charmap (face, face->charmaps[0]);
  217860. }
  217861. }
  217862. }
  217863. return face;
  217864. }
  217865. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  217866. {
  217867. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  217868. const float height = (float) (face->ascender - face->descender);
  217869. const float scaleX = 1.0f / height;
  217870. const float scaleY = -1.0f / height;
  217871. Path destShape;
  217872. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  217873. || face->glyph->format != ft_glyph_format_outline)
  217874. {
  217875. return false;
  217876. }
  217877. const FT_Outline* const outline = &face->glyph->outline;
  217878. const short* const contours = outline->contours;
  217879. const char* const tags = outline->tags;
  217880. FT_Vector* const points = outline->points;
  217881. for (int c = 0; c < outline->n_contours; c++)
  217882. {
  217883. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  217884. const int endPoint = contours[c];
  217885. for (int p = startPoint; p <= endPoint; p++)
  217886. {
  217887. const float x = scaleX * points[p].x;
  217888. const float y = scaleY * points[p].y;
  217889. if (p == startPoint)
  217890. {
  217891. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217892. {
  217893. float x2 = scaleX * points [endPoint].x;
  217894. float y2 = scaleY * points [endPoint].y;
  217895. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  217896. {
  217897. x2 = (x + x2) * 0.5f;
  217898. y2 = (y + y2) * 0.5f;
  217899. }
  217900. destShape.startNewSubPath (x2, y2);
  217901. }
  217902. else
  217903. {
  217904. destShape.startNewSubPath (x, y);
  217905. }
  217906. }
  217907. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  217908. {
  217909. if (p != startPoint)
  217910. destShape.lineTo (x, y);
  217911. }
  217912. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217913. {
  217914. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  217915. float x2 = scaleX * points [nextIndex].x;
  217916. float y2 = scaleY * points [nextIndex].y;
  217917. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  217918. {
  217919. x2 = (x + x2) * 0.5f;
  217920. y2 = (y + y2) * 0.5f;
  217921. }
  217922. else
  217923. {
  217924. ++p;
  217925. }
  217926. destShape.quadraticTo (x, y, x2, y2);
  217927. }
  217928. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  217929. {
  217930. if (p >= endPoint)
  217931. return false;
  217932. const int next1 = p + 1;
  217933. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  217934. const float x2 = scaleX * points [next1].x;
  217935. const float y2 = scaleY * points [next1].y;
  217936. const float x3 = scaleX * points [next2].x;
  217937. const float y3 = scaleY * points [next2].y;
  217938. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  217939. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  217940. return false;
  217941. destShape.cubicTo (x, y, x2, y2, x3, y3);
  217942. p += 2;
  217943. }
  217944. }
  217945. destShape.closeSubPath();
  217946. }
  217947. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  217948. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  217949. addKerning (face, dest, character, glyphIndex);
  217950. return true;
  217951. }
  217952. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  217953. {
  217954. const float height = (float) (face->ascender - face->descender);
  217955. uint32 rightGlyphIndex;
  217956. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  217957. while (rightGlyphIndex != 0)
  217958. {
  217959. FT_Vector kerning;
  217960. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  217961. {
  217962. if (kerning.x != 0)
  217963. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  217964. }
  217965. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  217966. }
  217967. }
  217968. // Add a glyph to a font
  217969. bool addGlyphToFont (const uint32 character, const String& fontName,
  217970. bool bold, bool italic, CustomTypeface& dest)
  217971. {
  217972. FT_Face face = createFT_Face (fontName, bold, italic);
  217973. return face != 0 && addGlyph (face, dest, character);
  217974. }
  217975. void getFamilyNames (StringArray& familyNames) const
  217976. {
  217977. for (int i = 0; i < faces.size(); i++)
  217978. familyNames.add (faces[i]->getFamilyName());
  217979. }
  217980. void getMonospacedNames (StringArray& monoSpaced) const
  217981. {
  217982. for (int i = 0; i < faces.size(); i++)
  217983. if (faces[i]->getMonospaced())
  217984. monoSpaced.add (faces[i]->getFamilyName());
  217985. }
  217986. void getSerifNames (StringArray& serif) const
  217987. {
  217988. for (int i = 0; i < faces.size(); i++)
  217989. if (faces[i]->getSerif())
  217990. serif.add (faces[i]->getFamilyName());
  217991. }
  217992. void getSansSerifNames (StringArray& sansSerif) const
  217993. {
  217994. for (int i = 0; i < faces.size(); i++)
  217995. if (! faces[i]->getSerif())
  217996. sansSerif.add (faces[i]->getFamilyName());
  217997. }
  217998. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  217999. private:
  218000. FT_Library ftLib;
  218001. FT_Face lastFace;
  218002. String lastFontName;
  218003. bool lastBold, lastItalic;
  218004. OwnedArray<FreeTypeFontFace> faces;
  218005. };
  218006. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218007. class FreetypeTypeface : public CustomTypeface
  218008. {
  218009. public:
  218010. FreetypeTypeface (const Font& font)
  218011. {
  218012. FT_Face face = FreeTypeInterface::getInstance()
  218013. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218014. if (face == 0)
  218015. {
  218016. #if JUCE_DEBUG
  218017. String msg ("Failed to create typeface: ");
  218018. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218019. DBG (msg);
  218020. #endif
  218021. }
  218022. else
  218023. {
  218024. setCharacteristics (font.getTypefaceName(),
  218025. face->ascender / (float) (face->ascender - face->descender),
  218026. font.isBold(), font.isItalic(),
  218027. L' ');
  218028. }
  218029. }
  218030. bool loadGlyphIfPossible (juce_wchar character)
  218031. {
  218032. return FreeTypeInterface::getInstance()
  218033. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218034. }
  218035. };
  218036. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218037. {
  218038. return new FreetypeTypeface (font);
  218039. }
  218040. const StringArray Font::findAllTypefaceNames()
  218041. {
  218042. StringArray s;
  218043. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218044. s.sort (true);
  218045. return s;
  218046. }
  218047. static const String pickBestFont (const StringArray& names,
  218048. const char* const choicesString)
  218049. {
  218050. StringArray choices;
  218051. choices.addTokens (String (choicesString), ",", String::empty);
  218052. choices.trim();
  218053. choices.removeEmptyStrings();
  218054. int i, j;
  218055. for (j = 0; j < choices.size(); ++j)
  218056. if (names.contains (choices[j], true))
  218057. return choices[j];
  218058. for (j = 0; j < choices.size(); ++j)
  218059. for (i = 0; i < names.size(); i++)
  218060. if (names[i].startsWithIgnoreCase (choices[j]))
  218061. return names[i];
  218062. for (j = 0; j < choices.size(); ++j)
  218063. for (i = 0; i < names.size(); i++)
  218064. if (names[i].containsIgnoreCase (choices[j]))
  218065. return names[i];
  218066. return names[0];
  218067. }
  218068. static const String linux_getDefaultSansSerifFontName()
  218069. {
  218070. StringArray allFonts;
  218071. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218072. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218073. }
  218074. static const String linux_getDefaultSerifFontName()
  218075. {
  218076. StringArray allFonts;
  218077. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218078. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218079. }
  218080. static const String linux_getDefaultMonospacedFontName()
  218081. {
  218082. StringArray allFonts;
  218083. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218084. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218085. }
  218086. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  218087. {
  218088. defaultSans = linux_getDefaultSansSerifFontName();
  218089. defaultSerif = linux_getDefaultSerifFontName();
  218090. defaultFixed = linux_getDefaultMonospacedFontName();
  218091. }
  218092. #endif
  218093. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218094. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218095. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218096. // compiled on its own).
  218097. #if JUCE_INCLUDED_FILE
  218098. // These are defined in juce_linux_Messaging.cpp
  218099. extern Display* display;
  218100. extern XContext windowHandleXContext;
  218101. namespace Atoms
  218102. {
  218103. enum ProtocolItems
  218104. {
  218105. TAKE_FOCUS = 0,
  218106. DELETE_WINDOW = 1,
  218107. PING = 2
  218108. };
  218109. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218110. ActiveWin, Pid, WindowType, WindowState,
  218111. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218112. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218113. XdndActionDescription, XdndActionCopy,
  218114. allowedActions[5],
  218115. allowedMimeTypes[2];
  218116. const unsigned long DndVersion = 3;
  218117. static void initialiseAtoms()
  218118. {
  218119. static bool atomsInitialised = false;
  218120. if (! atomsInitialised)
  218121. {
  218122. atomsInitialised = true;
  218123. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218124. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218125. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218126. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218127. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218128. State = XInternAtom (display, "WM_STATE", True);
  218129. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218130. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218131. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218132. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218133. XdndAware = XInternAtom (display, "XdndAware", False);
  218134. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218135. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218136. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218137. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218138. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218139. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218140. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218141. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218142. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218143. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218144. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218145. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218146. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218147. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218148. allowedActions[1] = XdndActionCopy;
  218149. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218150. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218151. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218152. }
  218153. }
  218154. }
  218155. namespace Keys
  218156. {
  218157. enum MouseButtons
  218158. {
  218159. NoButton = 0,
  218160. LeftButton = 1,
  218161. MiddleButton = 2,
  218162. RightButton = 3,
  218163. WheelUp = 4,
  218164. WheelDown = 5
  218165. };
  218166. static int AltMask = 0;
  218167. static int NumLockMask = 0;
  218168. static bool numLock = false;
  218169. static bool capsLock = false;
  218170. static char keyStates [32];
  218171. static const int extendedKeyModifier = 0x10000000;
  218172. }
  218173. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218174. {
  218175. int keysym;
  218176. if (keyCode & Keys::extendedKeyModifier)
  218177. {
  218178. keysym = 0xff00 | (keyCode & 0xff);
  218179. }
  218180. else
  218181. {
  218182. keysym = keyCode;
  218183. if (keysym == (XK_Tab & 0xff)
  218184. || keysym == (XK_Return & 0xff)
  218185. || keysym == (XK_Escape & 0xff)
  218186. || keysym == (XK_BackSpace & 0xff))
  218187. {
  218188. keysym |= 0xff00;
  218189. }
  218190. }
  218191. ScopedXLock xlock;
  218192. const int keycode = XKeysymToKeycode (display, keysym);
  218193. const int keybyte = keycode >> 3;
  218194. const int keybit = (1 << (keycode & 7));
  218195. return (Keys::keyStates [keybyte] & keybit) != 0;
  218196. }
  218197. #if JUCE_USE_XSHM
  218198. namespace XSHMHelpers
  218199. {
  218200. static int trappedErrorCode = 0;
  218201. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218202. {
  218203. trappedErrorCode = err->error_code;
  218204. return 0;
  218205. }
  218206. static bool isShmAvailable() throw()
  218207. {
  218208. static bool isChecked = false;
  218209. static bool isAvailable = false;
  218210. if (! isChecked)
  218211. {
  218212. isChecked = true;
  218213. int major, minor;
  218214. Bool pixmaps;
  218215. ScopedXLock xlock;
  218216. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218217. {
  218218. trappedErrorCode = 0;
  218219. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218220. XShmSegmentInfo segmentInfo;
  218221. zerostruct (segmentInfo);
  218222. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218223. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218224. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218225. xImage->bytes_per_line * xImage->height,
  218226. IPC_CREAT | 0777)) >= 0)
  218227. {
  218228. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218229. if (segmentInfo.shmaddr != (void*) -1)
  218230. {
  218231. segmentInfo.readOnly = False;
  218232. xImage->data = segmentInfo.shmaddr;
  218233. XSync (display, False);
  218234. if (XShmAttach (display, &segmentInfo) != 0)
  218235. {
  218236. XSync (display, False);
  218237. XShmDetach (display, &segmentInfo);
  218238. isAvailable = true;
  218239. }
  218240. }
  218241. XFlush (display);
  218242. XDestroyImage (xImage);
  218243. shmdt (segmentInfo.shmaddr);
  218244. }
  218245. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218246. XSetErrorHandler (oldHandler);
  218247. if (trappedErrorCode != 0)
  218248. isAvailable = false;
  218249. }
  218250. }
  218251. return isAvailable;
  218252. }
  218253. }
  218254. #endif
  218255. #if JUCE_USE_XRENDER
  218256. namespace XRender
  218257. {
  218258. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218259. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218260. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218261. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218262. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218263. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218264. static tXRenderFindFormat xRenderFindFormat = 0;
  218265. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218266. static bool isAvailable()
  218267. {
  218268. static bool hasLoaded = false;
  218269. if (! hasLoaded)
  218270. {
  218271. ScopedXLock xlock;
  218272. hasLoaded = true;
  218273. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218274. if (h != 0)
  218275. {
  218276. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218277. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218278. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218279. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218280. }
  218281. if (xRenderQueryVersion != 0
  218282. && xRenderFindStandardFormat != 0
  218283. && xRenderFindFormat != 0
  218284. && xRenderFindVisualFormat != 0)
  218285. {
  218286. int major, minor;
  218287. if (xRenderQueryVersion (display, &major, &minor))
  218288. return true;
  218289. }
  218290. xRenderQueryVersion = 0;
  218291. }
  218292. return xRenderQueryVersion != 0;
  218293. }
  218294. static XRenderPictFormat* findPictureFormat()
  218295. {
  218296. ScopedXLock xlock;
  218297. XRenderPictFormat* pictFormat = 0;
  218298. if (isAvailable())
  218299. {
  218300. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218301. if (pictFormat == 0)
  218302. {
  218303. XRenderPictFormat desiredFormat;
  218304. desiredFormat.type = PictTypeDirect;
  218305. desiredFormat.depth = 32;
  218306. desiredFormat.direct.alphaMask = 0xff;
  218307. desiredFormat.direct.redMask = 0xff;
  218308. desiredFormat.direct.greenMask = 0xff;
  218309. desiredFormat.direct.blueMask = 0xff;
  218310. desiredFormat.direct.alpha = 24;
  218311. desiredFormat.direct.red = 16;
  218312. desiredFormat.direct.green = 8;
  218313. desiredFormat.direct.blue = 0;
  218314. pictFormat = xRenderFindFormat (display,
  218315. PictFormatType | PictFormatDepth
  218316. | PictFormatRedMask | PictFormatRed
  218317. | PictFormatGreenMask | PictFormatGreen
  218318. | PictFormatBlueMask | PictFormatBlue
  218319. | PictFormatAlphaMask | PictFormatAlpha,
  218320. &desiredFormat,
  218321. 0);
  218322. }
  218323. }
  218324. return pictFormat;
  218325. }
  218326. }
  218327. #endif
  218328. namespace Visuals
  218329. {
  218330. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218331. {
  218332. ScopedXLock xlock;
  218333. Visual* visual = 0;
  218334. int numVisuals = 0;
  218335. long desiredMask = VisualNoMask;
  218336. XVisualInfo desiredVisual;
  218337. desiredVisual.screen = DefaultScreen (display);
  218338. desiredVisual.depth = desiredDepth;
  218339. desiredMask = VisualScreenMask | VisualDepthMask;
  218340. if (desiredDepth == 32)
  218341. {
  218342. desiredVisual.c_class = TrueColor;
  218343. desiredVisual.red_mask = 0x00FF0000;
  218344. desiredVisual.green_mask = 0x0000FF00;
  218345. desiredVisual.blue_mask = 0x000000FF;
  218346. desiredVisual.bits_per_rgb = 8;
  218347. desiredMask |= VisualClassMask;
  218348. desiredMask |= VisualRedMaskMask;
  218349. desiredMask |= VisualGreenMaskMask;
  218350. desiredMask |= VisualBlueMaskMask;
  218351. desiredMask |= VisualBitsPerRGBMask;
  218352. }
  218353. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218354. desiredMask,
  218355. &desiredVisual,
  218356. &numVisuals);
  218357. if (xvinfos != 0)
  218358. {
  218359. for (int i = 0; i < numVisuals; i++)
  218360. {
  218361. if (xvinfos[i].depth == desiredDepth)
  218362. {
  218363. visual = xvinfos[i].visual;
  218364. break;
  218365. }
  218366. }
  218367. XFree (xvinfos);
  218368. }
  218369. return visual;
  218370. }
  218371. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218372. {
  218373. Visual* visual = 0;
  218374. if (desiredDepth == 32)
  218375. {
  218376. #if JUCE_USE_XSHM
  218377. if (XSHMHelpers::isShmAvailable())
  218378. {
  218379. #if JUCE_USE_XRENDER
  218380. if (XRender::isAvailable())
  218381. {
  218382. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218383. if (pictFormat != 0)
  218384. {
  218385. int numVisuals = 0;
  218386. XVisualInfo desiredVisual;
  218387. desiredVisual.screen = DefaultScreen (display);
  218388. desiredVisual.depth = 32;
  218389. desiredVisual.bits_per_rgb = 8;
  218390. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218391. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218392. &desiredVisual, &numVisuals);
  218393. if (xvinfos != 0)
  218394. {
  218395. for (int i = 0; i < numVisuals; ++i)
  218396. {
  218397. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218398. if (pictVisualFormat != 0
  218399. && pictVisualFormat->type == PictTypeDirect
  218400. && pictVisualFormat->direct.alphaMask)
  218401. {
  218402. visual = xvinfos[i].visual;
  218403. matchedDepth = 32;
  218404. break;
  218405. }
  218406. }
  218407. XFree (xvinfos);
  218408. }
  218409. }
  218410. }
  218411. #endif
  218412. if (visual == 0)
  218413. {
  218414. visual = findVisualWithDepth (32);
  218415. if (visual != 0)
  218416. matchedDepth = 32;
  218417. }
  218418. }
  218419. #endif
  218420. }
  218421. if (visual == 0 && desiredDepth >= 24)
  218422. {
  218423. visual = findVisualWithDepth (24);
  218424. if (visual != 0)
  218425. matchedDepth = 24;
  218426. }
  218427. if (visual == 0 && desiredDepth >= 16)
  218428. {
  218429. visual = findVisualWithDepth (16);
  218430. if (visual != 0)
  218431. matchedDepth = 16;
  218432. }
  218433. return visual;
  218434. }
  218435. }
  218436. class XBitmapImage : public Image::SharedImage
  218437. {
  218438. public:
  218439. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218440. const bool clearImage, const int imageDepth_, Visual* visual)
  218441. : Image::SharedImage (format_, w, h),
  218442. imageDepth (imageDepth_),
  218443. gc (None)
  218444. {
  218445. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218446. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218447. lineStride = ((w * pixelStride + 3) & ~3);
  218448. ScopedXLock xlock;
  218449. #if JUCE_USE_XSHM
  218450. usingXShm = false;
  218451. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218452. {
  218453. zerostruct (segmentInfo);
  218454. segmentInfo.shmid = -1;
  218455. segmentInfo.shmaddr = (char *) -1;
  218456. segmentInfo.readOnly = False;
  218457. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218458. if (xImage != 0)
  218459. {
  218460. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218461. xImage->bytes_per_line * xImage->height,
  218462. IPC_CREAT | 0777)) >= 0)
  218463. {
  218464. if (segmentInfo.shmid != -1)
  218465. {
  218466. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218467. if (segmentInfo.shmaddr != (void*) -1)
  218468. {
  218469. segmentInfo.readOnly = False;
  218470. xImage->data = segmentInfo.shmaddr;
  218471. imageData = (uint8*) segmentInfo.shmaddr;
  218472. if (XShmAttach (display, &segmentInfo) != 0)
  218473. usingXShm = true;
  218474. else
  218475. jassertfalse;
  218476. }
  218477. else
  218478. {
  218479. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218480. }
  218481. }
  218482. }
  218483. }
  218484. }
  218485. if (! usingXShm)
  218486. #endif
  218487. {
  218488. imageDataAllocated.malloc (lineStride * h);
  218489. imageData = imageDataAllocated;
  218490. if (format_ == Image::ARGB && clearImage)
  218491. zeromem (imageData, h * lineStride);
  218492. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218493. xImage->width = w;
  218494. xImage->height = h;
  218495. xImage->xoffset = 0;
  218496. xImage->format = ZPixmap;
  218497. xImage->data = (char*) imageData;
  218498. xImage->byte_order = ImageByteOrder (display);
  218499. xImage->bitmap_unit = BitmapUnit (display);
  218500. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218501. xImage->bitmap_pad = 32;
  218502. xImage->depth = pixelStride * 8;
  218503. xImage->bytes_per_line = lineStride;
  218504. xImage->bits_per_pixel = pixelStride * 8;
  218505. xImage->red_mask = 0x00FF0000;
  218506. xImage->green_mask = 0x0000FF00;
  218507. xImage->blue_mask = 0x000000FF;
  218508. if (imageDepth == 16)
  218509. {
  218510. const int pixelStride = 2;
  218511. const int lineStride = ((w * pixelStride + 3) & ~3);
  218512. imageData16Bit.malloc (lineStride * h);
  218513. xImage->data = imageData16Bit;
  218514. xImage->bitmap_pad = 16;
  218515. xImage->depth = pixelStride * 8;
  218516. xImage->bytes_per_line = lineStride;
  218517. xImage->bits_per_pixel = pixelStride * 8;
  218518. xImage->red_mask = visual->red_mask;
  218519. xImage->green_mask = visual->green_mask;
  218520. xImage->blue_mask = visual->blue_mask;
  218521. }
  218522. if (! XInitImage (xImage))
  218523. jassertfalse;
  218524. }
  218525. }
  218526. ~XBitmapImage()
  218527. {
  218528. ScopedXLock xlock;
  218529. if (gc != None)
  218530. XFreeGC (display, gc);
  218531. #if JUCE_USE_XSHM
  218532. if (usingXShm)
  218533. {
  218534. XShmDetach (display, &segmentInfo);
  218535. XFlush (display);
  218536. XDestroyImage (xImage);
  218537. shmdt (segmentInfo.shmaddr);
  218538. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218539. }
  218540. else
  218541. #endif
  218542. {
  218543. xImage->data = 0;
  218544. XDestroyImage (xImage);
  218545. }
  218546. }
  218547. Image::ImageType getType() const { return Image::NativeImage; }
  218548. LowLevelGraphicsContext* createLowLevelContext()
  218549. {
  218550. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218551. }
  218552. SharedImage* clone()
  218553. {
  218554. jassertfalse;
  218555. return 0;
  218556. }
  218557. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218558. {
  218559. ScopedXLock xlock;
  218560. if (gc == None)
  218561. {
  218562. XGCValues gcvalues;
  218563. gcvalues.foreground = None;
  218564. gcvalues.background = None;
  218565. gcvalues.function = GXcopy;
  218566. gcvalues.plane_mask = AllPlanes;
  218567. gcvalues.clip_mask = None;
  218568. gcvalues.graphics_exposures = False;
  218569. gc = XCreateGC (display, window,
  218570. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218571. &gcvalues);
  218572. }
  218573. if (imageDepth == 16)
  218574. {
  218575. const uint32 rMask = xImage->red_mask;
  218576. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218577. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218578. const uint32 gMask = xImage->green_mask;
  218579. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218580. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218581. const uint32 bMask = xImage->blue_mask;
  218582. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218583. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218584. const Image::BitmapData srcData (Image (this), 0, 0, width, height);
  218585. for (int y = sy; y < sy + dh; ++y)
  218586. {
  218587. const uint8* p = srcData.getPixelPointer (sx, y);
  218588. for (int x = sx; x < sx + dw; ++x)
  218589. {
  218590. const PixelRGB* const pixel = (const PixelRGB*) p;
  218591. p += srcData.pixelStride;
  218592. XPutPixel (xImage, x, y,
  218593. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218594. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218595. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218596. }
  218597. }
  218598. }
  218599. // blit results to screen.
  218600. #if JUCE_USE_XSHM
  218601. if (usingXShm)
  218602. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218603. else
  218604. #endif
  218605. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218606. }
  218607. juce_UseDebuggingNewOperator
  218608. private:
  218609. XImage* xImage;
  218610. const int imageDepth;
  218611. HeapBlock <uint8> imageDataAllocated;
  218612. HeapBlock <char> imageData16Bit;
  218613. GC gc;
  218614. #if JUCE_USE_XSHM
  218615. XShmSegmentInfo segmentInfo;
  218616. bool usingXShm;
  218617. #endif
  218618. static int getShiftNeeded (const uint32 mask) throw()
  218619. {
  218620. for (int i = 32; --i >= 0;)
  218621. if (((mask >> i) & 1) != 0)
  218622. return i - 7;
  218623. jassertfalse;
  218624. return 0;
  218625. }
  218626. };
  218627. class LinuxComponentPeer : public ComponentPeer
  218628. {
  218629. public:
  218630. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218631. : ComponentPeer (component, windowStyleFlags),
  218632. windowH (0),
  218633. parentWindow (0),
  218634. wx (0),
  218635. wy (0),
  218636. ww (0),
  218637. wh (0),
  218638. fullScreen (false),
  218639. mapped (false),
  218640. visual (0),
  218641. depth (0)
  218642. {
  218643. // it's dangerous to create a window on a thread other than the message thread..
  218644. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218645. repainter = new LinuxRepaintManager (this);
  218646. createWindow();
  218647. setTitle (component->getName());
  218648. }
  218649. ~LinuxComponentPeer()
  218650. {
  218651. // it's dangerous to delete a window on a thread other than the message thread..
  218652. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218653. deleteIconPixmaps();
  218654. destroyWindow();
  218655. windowH = 0;
  218656. }
  218657. void* getNativeHandle() const
  218658. {
  218659. return (void*) windowH;
  218660. }
  218661. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218662. {
  218663. XPointer peer = 0;
  218664. ScopedXLock xlock;
  218665. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218666. {
  218667. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218668. peer = 0;
  218669. }
  218670. return (LinuxComponentPeer*) peer;
  218671. }
  218672. void setVisible (bool shouldBeVisible)
  218673. {
  218674. ScopedXLock xlock;
  218675. if (shouldBeVisible)
  218676. XMapWindow (display, windowH);
  218677. else
  218678. XUnmapWindow (display, windowH);
  218679. }
  218680. void setTitle (const String& title)
  218681. {
  218682. setWindowTitle (windowH, title);
  218683. }
  218684. void setPosition (int x, int y)
  218685. {
  218686. setBounds (x, y, ww, wh, false);
  218687. }
  218688. void setSize (int w, int h)
  218689. {
  218690. setBounds (wx, wy, w, h, false);
  218691. }
  218692. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218693. {
  218694. fullScreen = isNowFullScreen;
  218695. if (windowH != 0)
  218696. {
  218697. Component::SafePointer<Component> deletionChecker (component);
  218698. wx = x;
  218699. wy = y;
  218700. ww = jmax (1, w);
  218701. wh = jmax (1, h);
  218702. ScopedXLock xlock;
  218703. // Make sure the Window manager does what we want
  218704. XSizeHints* hints = XAllocSizeHints();
  218705. hints->flags = USSize | USPosition;
  218706. hints->width = ww;
  218707. hints->height = wh;
  218708. hints->x = wx;
  218709. hints->y = wy;
  218710. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218711. {
  218712. hints->min_width = hints->max_width = hints->width;
  218713. hints->min_height = hints->max_height = hints->height;
  218714. hints->flags |= PMinSize | PMaxSize;
  218715. }
  218716. XSetWMNormalHints (display, windowH, hints);
  218717. XFree (hints);
  218718. XMoveResizeWindow (display, windowH,
  218719. wx - windowBorder.getLeft(),
  218720. wy - windowBorder.getTop(), ww, wh);
  218721. if (deletionChecker != 0)
  218722. {
  218723. updateBorderSize();
  218724. handleMovedOrResized();
  218725. }
  218726. }
  218727. }
  218728. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218729. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218730. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218731. {
  218732. return relativePosition + getScreenPosition();
  218733. }
  218734. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218735. {
  218736. return screenPosition - getScreenPosition();
  218737. }
  218738. void setMinimised (bool shouldBeMinimised)
  218739. {
  218740. if (shouldBeMinimised)
  218741. {
  218742. Window root = RootWindow (display, DefaultScreen (display));
  218743. XClientMessageEvent clientMsg;
  218744. clientMsg.display = display;
  218745. clientMsg.window = windowH;
  218746. clientMsg.type = ClientMessage;
  218747. clientMsg.format = 32;
  218748. clientMsg.message_type = Atoms::ChangeState;
  218749. clientMsg.data.l[0] = IconicState;
  218750. ScopedXLock xlock;
  218751. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218752. }
  218753. else
  218754. {
  218755. setVisible (true);
  218756. }
  218757. }
  218758. bool isMinimised() const
  218759. {
  218760. bool minimised = false;
  218761. unsigned char* stateProp;
  218762. unsigned long nitems, bytesLeft;
  218763. Atom actualType;
  218764. int actualFormat;
  218765. ScopedXLock xlock;
  218766. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218767. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218768. &stateProp) == Success
  218769. && actualType == Atoms::State
  218770. && actualFormat == 32
  218771. && nitems > 0)
  218772. {
  218773. if (((unsigned long*) stateProp)[0] == IconicState)
  218774. minimised = true;
  218775. XFree (stateProp);
  218776. }
  218777. return minimised;
  218778. }
  218779. void setFullScreen (const bool shouldBeFullScreen)
  218780. {
  218781. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218782. setMinimised (false);
  218783. if (fullScreen != shouldBeFullScreen)
  218784. {
  218785. if (shouldBeFullScreen)
  218786. r = Desktop::getInstance().getMainMonitorArea();
  218787. if (! r.isEmpty())
  218788. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218789. getComponent()->repaint();
  218790. }
  218791. }
  218792. bool isFullScreen() const
  218793. {
  218794. return fullScreen;
  218795. }
  218796. bool isChildWindowOf (Window possibleParent) const
  218797. {
  218798. Window* windowList = 0;
  218799. uint32 windowListSize = 0;
  218800. Window parent, root;
  218801. ScopedXLock xlock;
  218802. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218803. {
  218804. if (windowList != 0)
  218805. XFree (windowList);
  218806. return parent == possibleParent;
  218807. }
  218808. return false;
  218809. }
  218810. bool isFrontWindow() const
  218811. {
  218812. Window* windowList = 0;
  218813. uint32 windowListSize = 0;
  218814. bool result = false;
  218815. ScopedXLock xlock;
  218816. Window parent, root = RootWindow (display, DefaultScreen (display));
  218817. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  218818. {
  218819. for (int i = windowListSize; --i >= 0;)
  218820. {
  218821. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  218822. if (peer != 0)
  218823. {
  218824. result = (peer == this);
  218825. break;
  218826. }
  218827. }
  218828. }
  218829. if (windowList != 0)
  218830. XFree (windowList);
  218831. return result;
  218832. }
  218833. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  218834. {
  218835. int x = position.getX();
  218836. int y = position.getY();
  218837. if (((unsigned int) x) >= (unsigned int) ww
  218838. || ((unsigned int) y) >= (unsigned int) wh)
  218839. return false;
  218840. bool inFront = false;
  218841. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  218842. {
  218843. Component* const c = Desktop::getInstance().getComponent (i);
  218844. if (inFront)
  218845. {
  218846. if (c->contains (x + wx - c->getScreenX(),
  218847. y + wy - c->getScreenY()))
  218848. {
  218849. return false;
  218850. }
  218851. }
  218852. else if (c == getComponent())
  218853. {
  218854. inFront = true;
  218855. }
  218856. }
  218857. if (trueIfInAChildWindow)
  218858. return true;
  218859. ::Window root, child;
  218860. unsigned int bw, depth;
  218861. int wx, wy, w, h;
  218862. ScopedXLock xlock;
  218863. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  218864. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  218865. &bw, &depth))
  218866. {
  218867. return false;
  218868. }
  218869. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  218870. return false;
  218871. return child == None;
  218872. }
  218873. const BorderSize getFrameSize() const
  218874. {
  218875. return BorderSize();
  218876. }
  218877. bool setAlwaysOnTop (bool alwaysOnTop)
  218878. {
  218879. return false;
  218880. }
  218881. void toFront (bool makeActive)
  218882. {
  218883. if (makeActive)
  218884. {
  218885. setVisible (true);
  218886. grabFocus();
  218887. }
  218888. XEvent ev;
  218889. ev.xclient.type = ClientMessage;
  218890. ev.xclient.serial = 0;
  218891. ev.xclient.send_event = True;
  218892. ev.xclient.message_type = Atoms::ActiveWin;
  218893. ev.xclient.window = windowH;
  218894. ev.xclient.format = 32;
  218895. ev.xclient.data.l[0] = 2;
  218896. ev.xclient.data.l[1] = CurrentTime;
  218897. ev.xclient.data.l[2] = 0;
  218898. ev.xclient.data.l[3] = 0;
  218899. ev.xclient.data.l[4] = 0;
  218900. {
  218901. ScopedXLock xlock;
  218902. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  218903. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  218904. XWindowAttributes attr;
  218905. XGetWindowAttributes (display, windowH, &attr);
  218906. if (component->isAlwaysOnTop())
  218907. XRaiseWindow (display, windowH);
  218908. XSync (display, False);
  218909. }
  218910. handleBroughtToFront();
  218911. }
  218912. void toBehind (ComponentPeer* other)
  218913. {
  218914. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  218915. jassert (otherPeer != 0); // wrong type of window?
  218916. if (otherPeer != 0)
  218917. {
  218918. setMinimised (false);
  218919. Window newStack[] = { otherPeer->windowH, windowH };
  218920. ScopedXLock xlock;
  218921. XRestackWindows (display, newStack, 2);
  218922. }
  218923. }
  218924. bool isFocused() const
  218925. {
  218926. int revert = 0;
  218927. Window focusedWindow = 0;
  218928. ScopedXLock xlock;
  218929. XGetInputFocus (display, &focusedWindow, &revert);
  218930. return focusedWindow == windowH;
  218931. }
  218932. void grabFocus()
  218933. {
  218934. XWindowAttributes atts;
  218935. ScopedXLock xlock;
  218936. if (windowH != 0
  218937. && XGetWindowAttributes (display, windowH, &atts)
  218938. && atts.map_state == IsViewable
  218939. && ! isFocused())
  218940. {
  218941. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  218942. isActiveApplication = true;
  218943. }
  218944. }
  218945. void textInputRequired (const Point<int>&)
  218946. {
  218947. }
  218948. void repaint (const Rectangle<int>& area)
  218949. {
  218950. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  218951. }
  218952. void performAnyPendingRepaintsNow()
  218953. {
  218954. repainter->performAnyPendingRepaintsNow();
  218955. }
  218956. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  218957. {
  218958. ScopedXLock xlock;
  218959. const int width = image.getWidth();
  218960. const int height = image.getHeight();
  218961. HeapBlock <char> colour (width * height);
  218962. int index = 0;
  218963. for (int y = 0; y < height; ++y)
  218964. for (int x = 0; x < width; ++x)
  218965. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  218966. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  218967. 0, colour.getData(),
  218968. width, height, 32, 0);
  218969. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  218970. width, height, 24);
  218971. GC gc = XCreateGC (display, pixmap, 0, 0);
  218972. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  218973. XFreeGC (display, gc);
  218974. return pixmap;
  218975. }
  218976. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  218977. {
  218978. ScopedXLock xlock;
  218979. const int width = image.getWidth();
  218980. const int height = image.getHeight();
  218981. const int stride = (width + 7) >> 3;
  218982. HeapBlock <char> mask;
  218983. mask.calloc (stride * height);
  218984. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218985. for (int y = 0; y < height; ++y)
  218986. {
  218987. for (int x = 0; x < width; ++x)
  218988. {
  218989. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218990. const int offset = y * stride + (x >> 3);
  218991. if (image.getPixelAt (x, y).getAlpha() >= 128)
  218992. mask[offset] |= bit;
  218993. }
  218994. }
  218995. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  218996. mask.getData(), width, height, 1, 0, 1);
  218997. }
  218998. void setIcon (const Image& newIcon)
  218999. {
  219000. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219001. HeapBlock <unsigned long> data (dataSize);
  219002. int index = 0;
  219003. data[index++] = newIcon.getWidth();
  219004. data[index++] = newIcon.getHeight();
  219005. for (int y = 0; y < newIcon.getHeight(); ++y)
  219006. for (int x = 0; x < newIcon.getWidth(); ++x)
  219007. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219008. ScopedXLock xlock;
  219009. XChangeProperty (display, windowH,
  219010. XInternAtom (display, "_NET_WM_ICON", False),
  219011. XA_CARDINAL, 32, PropModeReplace,
  219012. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219013. deleteIconPixmaps();
  219014. XWMHints* wmHints = XGetWMHints (display, windowH);
  219015. if (wmHints == 0)
  219016. wmHints = XAllocWMHints();
  219017. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219018. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  219019. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  219020. XSetWMHints (display, windowH, wmHints);
  219021. XFree (wmHints);
  219022. XSync (display, False);
  219023. }
  219024. void deleteIconPixmaps()
  219025. {
  219026. ScopedXLock xlock;
  219027. XWMHints* wmHints = XGetWMHints (display, windowH);
  219028. if (wmHints != 0)
  219029. {
  219030. if ((wmHints->flags & IconPixmapHint) != 0)
  219031. {
  219032. wmHints->flags &= ~IconPixmapHint;
  219033. XFreePixmap (display, wmHints->icon_pixmap);
  219034. }
  219035. if ((wmHints->flags & IconMaskHint) != 0)
  219036. {
  219037. wmHints->flags &= ~IconMaskHint;
  219038. XFreePixmap (display, wmHints->icon_mask);
  219039. }
  219040. XSetWMHints (display, windowH, wmHints);
  219041. XFree (wmHints);
  219042. }
  219043. }
  219044. void handleWindowMessage (XEvent* event)
  219045. {
  219046. switch (event->xany.type)
  219047. {
  219048. case 2: // 'KeyPress'
  219049. {
  219050. ScopedXLock xlock;
  219051. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  219052. updateKeyStates (keyEvent->keycode, true);
  219053. char utf8 [64];
  219054. zeromem (utf8, sizeof (utf8));
  219055. KeySym sym;
  219056. {
  219057. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219058. ::setlocale (LC_ALL, "");
  219059. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219060. ::setlocale (LC_ALL, oldLocale);
  219061. }
  219062. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219063. int keyCode = (int) unicodeChar;
  219064. if (keyCode < 0x20)
  219065. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219066. const ModifierKeys oldMods (currentModifiers);
  219067. bool keyPressed = false;
  219068. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219069. if ((sym & 0xff00) == 0xff00)
  219070. {
  219071. // Translate keypad
  219072. if (sym == XK_KP_Divide)
  219073. keyCode = XK_slash;
  219074. else if (sym == XK_KP_Multiply)
  219075. keyCode = XK_asterisk;
  219076. else if (sym == XK_KP_Subtract)
  219077. keyCode = XK_hyphen;
  219078. else if (sym == XK_KP_Add)
  219079. keyCode = XK_plus;
  219080. else if (sym == XK_KP_Enter)
  219081. keyCode = XK_Return;
  219082. else if (sym == XK_KP_Decimal)
  219083. keyCode = Keys::numLock ? XK_period : XK_Delete;
  219084. else if (sym == XK_KP_0)
  219085. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  219086. else if (sym == XK_KP_1)
  219087. keyCode = Keys::numLock ? XK_1 : XK_End;
  219088. else if (sym == XK_KP_2)
  219089. keyCode = Keys::numLock ? XK_2 : XK_Down;
  219090. else if (sym == XK_KP_3)
  219091. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  219092. else if (sym == XK_KP_4)
  219093. keyCode = Keys::numLock ? XK_4 : XK_Left;
  219094. else if (sym == XK_KP_5)
  219095. keyCode = XK_5;
  219096. else if (sym == XK_KP_6)
  219097. keyCode = Keys::numLock ? XK_6 : XK_Right;
  219098. else if (sym == XK_KP_7)
  219099. keyCode = Keys::numLock ? XK_7 : XK_Home;
  219100. else if (sym == XK_KP_8)
  219101. keyCode = Keys::numLock ? XK_8 : XK_Up;
  219102. else if (sym == XK_KP_9)
  219103. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  219104. switch (sym)
  219105. {
  219106. case XK_Left:
  219107. case XK_Right:
  219108. case XK_Up:
  219109. case XK_Down:
  219110. case XK_Page_Up:
  219111. case XK_Page_Down:
  219112. case XK_End:
  219113. case XK_Home:
  219114. case XK_Delete:
  219115. case XK_Insert:
  219116. keyPressed = true;
  219117. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219118. break;
  219119. case XK_Tab:
  219120. case XK_Return:
  219121. case XK_Escape:
  219122. case XK_BackSpace:
  219123. keyPressed = true;
  219124. keyCode &= 0xff;
  219125. break;
  219126. default:
  219127. {
  219128. if (sym >= XK_F1 && sym <= XK_F16)
  219129. {
  219130. keyPressed = true;
  219131. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219132. }
  219133. break;
  219134. }
  219135. }
  219136. }
  219137. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219138. keyPressed = true;
  219139. if (oldMods != currentModifiers)
  219140. handleModifierKeysChange();
  219141. if (keyDownChange)
  219142. handleKeyUpOrDown (true);
  219143. if (keyPressed)
  219144. handleKeyPress (keyCode, unicodeChar);
  219145. break;
  219146. }
  219147. case KeyRelease:
  219148. {
  219149. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  219150. updateKeyStates (keyEvent->keycode, false);
  219151. ScopedXLock xlock;
  219152. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219153. const ModifierKeys oldMods (currentModifiers);
  219154. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219155. if (oldMods != currentModifiers)
  219156. handleModifierKeysChange();
  219157. if (keyDownChange)
  219158. handleKeyUpOrDown (false);
  219159. break;
  219160. }
  219161. case ButtonPress:
  219162. {
  219163. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  219164. updateKeyModifiers (buttonPressEvent->state);
  219165. bool buttonMsg = false;
  219166. const int map = pointerMap [buttonPressEvent->button - Button1];
  219167. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219168. {
  219169. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219170. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219171. }
  219172. if (map == Keys::LeftButton)
  219173. {
  219174. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219175. buttonMsg = true;
  219176. }
  219177. else if (map == Keys::RightButton)
  219178. {
  219179. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219180. buttonMsg = true;
  219181. }
  219182. else if (map == Keys::MiddleButton)
  219183. {
  219184. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219185. buttonMsg = true;
  219186. }
  219187. if (buttonMsg)
  219188. {
  219189. toFront (true);
  219190. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219191. getEventTime (buttonPressEvent->time));
  219192. }
  219193. clearLastMousePos();
  219194. break;
  219195. }
  219196. case ButtonRelease:
  219197. {
  219198. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  219199. updateKeyModifiers (buttonRelEvent->state);
  219200. const int map = pointerMap [buttonRelEvent->button - Button1];
  219201. if (map == Keys::LeftButton)
  219202. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219203. else if (map == Keys::RightButton)
  219204. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219205. else if (map == Keys::MiddleButton)
  219206. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219207. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219208. getEventTime (buttonRelEvent->time));
  219209. clearLastMousePos();
  219210. break;
  219211. }
  219212. case MotionNotify:
  219213. {
  219214. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  219215. updateKeyModifiers (movedEvent->state);
  219216. const Point<int> mousePos (Desktop::getMousePosition());
  219217. if (lastMousePos != mousePos)
  219218. {
  219219. lastMousePos = mousePos;
  219220. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219221. {
  219222. Window wRoot = 0, wParent = 0;
  219223. {
  219224. ScopedXLock xlock;
  219225. unsigned int numChildren;
  219226. Window* wChild = 0;
  219227. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219228. }
  219229. if (wParent != 0
  219230. && wParent != windowH
  219231. && wParent != wRoot)
  219232. {
  219233. parentWindow = wParent;
  219234. updateBounds();
  219235. }
  219236. else
  219237. {
  219238. parentWindow = 0;
  219239. }
  219240. }
  219241. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219242. }
  219243. break;
  219244. }
  219245. case EnterNotify:
  219246. {
  219247. clearLastMousePos();
  219248. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219249. if (! currentModifiers.isAnyMouseButtonDown())
  219250. {
  219251. updateKeyModifiers (enterEvent->state);
  219252. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219253. }
  219254. break;
  219255. }
  219256. case LeaveNotify:
  219257. {
  219258. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219259. // Suppress the normal leave if we've got a pointer grab, or if
  219260. // it's a bogus one caused by clicking a mouse button when running
  219261. // in a Window manager
  219262. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219263. || leaveEvent->mode == NotifyUngrab)
  219264. {
  219265. updateKeyModifiers (leaveEvent->state);
  219266. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219267. }
  219268. break;
  219269. }
  219270. case FocusIn:
  219271. {
  219272. isActiveApplication = true;
  219273. if (isFocused())
  219274. handleFocusGain();
  219275. break;
  219276. }
  219277. case FocusOut:
  219278. {
  219279. isActiveApplication = false;
  219280. if (! isFocused())
  219281. handleFocusLoss();
  219282. break;
  219283. }
  219284. case Expose:
  219285. {
  219286. // Batch together all pending expose events
  219287. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219288. XEvent nextEvent;
  219289. ScopedXLock xlock;
  219290. if (exposeEvent->window != windowH)
  219291. {
  219292. Window child;
  219293. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219294. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219295. &child);
  219296. }
  219297. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219298. exposeEvent->width, exposeEvent->height));
  219299. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219300. {
  219301. XPeekEvent (display, (XEvent*) &nextEvent);
  219302. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219303. break;
  219304. XNextEvent (display, (XEvent*) &nextEvent);
  219305. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219306. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219307. nextExposeEvent->width, nextExposeEvent->height));
  219308. }
  219309. break;
  219310. }
  219311. case CirculateNotify:
  219312. case CreateNotify:
  219313. case DestroyNotify:
  219314. // Think we can ignore these
  219315. break;
  219316. case ConfigureNotify:
  219317. {
  219318. updateBounds();
  219319. updateBorderSize();
  219320. handleMovedOrResized();
  219321. // if the native title bar is dragged, need to tell any active menus, etc.
  219322. if ((styleFlags & windowHasTitleBar) != 0
  219323. && component->isCurrentlyBlockedByAnotherModalComponent())
  219324. {
  219325. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219326. if (currentModalComp != 0)
  219327. currentModalComp->inputAttemptWhenModal();
  219328. }
  219329. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219330. if (confEvent->window == windowH
  219331. && confEvent->above != 0
  219332. && isFrontWindow())
  219333. {
  219334. handleBroughtToFront();
  219335. }
  219336. break;
  219337. }
  219338. case ReparentNotify:
  219339. {
  219340. parentWindow = 0;
  219341. Window wRoot = 0;
  219342. Window* wChild = 0;
  219343. unsigned int numChildren;
  219344. {
  219345. ScopedXLock xlock;
  219346. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219347. }
  219348. if (parentWindow == windowH || parentWindow == wRoot)
  219349. parentWindow = 0;
  219350. updateBounds();
  219351. updateBorderSize();
  219352. handleMovedOrResized();
  219353. break;
  219354. }
  219355. case GravityNotify:
  219356. {
  219357. updateBounds();
  219358. updateBorderSize();
  219359. handleMovedOrResized();
  219360. break;
  219361. }
  219362. case MapNotify:
  219363. mapped = true;
  219364. handleBroughtToFront();
  219365. break;
  219366. case UnmapNotify:
  219367. mapped = false;
  219368. break;
  219369. case MappingNotify:
  219370. {
  219371. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219372. if (mappingEvent->request != MappingPointer)
  219373. {
  219374. // Deal with modifier/keyboard mapping
  219375. ScopedXLock xlock;
  219376. XRefreshKeyboardMapping (mappingEvent);
  219377. updateModifierMappings();
  219378. }
  219379. break;
  219380. }
  219381. case ClientMessage:
  219382. {
  219383. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219384. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219385. {
  219386. const Atom atom = (Atom) clientMsg->data.l[0];
  219387. if (atom == Atoms::ProtocolList [Atoms::PING])
  219388. {
  219389. Window root = RootWindow (display, DefaultScreen (display));
  219390. event->xclient.window = root;
  219391. XSendEvent (display, root, False, NoEventMask, event);
  219392. XFlush (display);
  219393. }
  219394. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219395. {
  219396. XWindowAttributes atts;
  219397. ScopedXLock xlock;
  219398. if (clientMsg->window != 0
  219399. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219400. {
  219401. if (atts.map_state == IsViewable)
  219402. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219403. }
  219404. }
  219405. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219406. {
  219407. handleUserClosingWindow();
  219408. }
  219409. }
  219410. else if (clientMsg->message_type == Atoms::XdndEnter)
  219411. {
  219412. handleDragAndDropEnter (clientMsg);
  219413. }
  219414. else if (clientMsg->message_type == Atoms::XdndLeave)
  219415. {
  219416. resetDragAndDrop();
  219417. }
  219418. else if (clientMsg->message_type == Atoms::XdndPosition)
  219419. {
  219420. handleDragAndDropPosition (clientMsg);
  219421. }
  219422. else if (clientMsg->message_type == Atoms::XdndDrop)
  219423. {
  219424. handleDragAndDropDrop (clientMsg);
  219425. }
  219426. else if (clientMsg->message_type == Atoms::XdndStatus)
  219427. {
  219428. handleDragAndDropStatus (clientMsg);
  219429. }
  219430. else if (clientMsg->message_type == Atoms::XdndFinished)
  219431. {
  219432. resetDragAndDrop();
  219433. }
  219434. break;
  219435. }
  219436. case SelectionNotify:
  219437. handleDragAndDropSelection (event);
  219438. break;
  219439. case SelectionClear:
  219440. case SelectionRequest:
  219441. break;
  219442. default:
  219443. #if JUCE_USE_XSHM
  219444. {
  219445. ScopedXLock xlock;
  219446. if (event->xany.type == XShmGetEventBase (display))
  219447. repainter->notifyPaintCompleted();
  219448. }
  219449. #endif
  219450. break;
  219451. }
  219452. }
  219453. void showMouseCursor (Cursor cursor) throw()
  219454. {
  219455. ScopedXLock xlock;
  219456. XDefineCursor (display, windowH, cursor);
  219457. }
  219458. void setTaskBarIcon (const Image& image)
  219459. {
  219460. ScopedXLock xlock;
  219461. taskbarImage = image;
  219462. Screen* const screen = XDefaultScreenOfDisplay (display);
  219463. const int screenNumber = XScreenNumberOfScreen (screen);
  219464. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219465. screenAtom << screenNumber;
  219466. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219467. XGrabServer (display);
  219468. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219469. if (managerWin != None)
  219470. XSelectInput (display, managerWin, StructureNotifyMask);
  219471. XUngrabServer (display);
  219472. XFlush (display);
  219473. if (managerWin != None)
  219474. {
  219475. XEvent ev;
  219476. zerostruct (ev);
  219477. ev.xclient.type = ClientMessage;
  219478. ev.xclient.window = managerWin;
  219479. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219480. ev.xclient.format = 32;
  219481. ev.xclient.data.l[0] = CurrentTime;
  219482. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219483. ev.xclient.data.l[2] = windowH;
  219484. ev.xclient.data.l[3] = 0;
  219485. ev.xclient.data.l[4] = 0;
  219486. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219487. XSync (display, False);
  219488. }
  219489. // For older KDE's ...
  219490. long atomData = 1;
  219491. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219492. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219493. // For more recent KDE's...
  219494. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219495. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219496. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219497. XSizeHints* hints = XAllocSizeHints();
  219498. hints->flags = PMinSize;
  219499. hints->min_width = 22;
  219500. hints->min_height = 22;
  219501. XSetWMNormalHints (display, windowH, hints);
  219502. XFree (hints);
  219503. }
  219504. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219505. juce_UseDebuggingNewOperator
  219506. bool dontRepaint;
  219507. static ModifierKeys currentModifiers;
  219508. static bool isActiveApplication;
  219509. private:
  219510. class LinuxRepaintManager : public Timer
  219511. {
  219512. public:
  219513. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219514. : peer (peer_),
  219515. lastTimeImageUsed (0)
  219516. {
  219517. #if JUCE_USE_XSHM
  219518. shmCompletedDrawing = true;
  219519. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219520. if (useARGBImagesForRendering)
  219521. {
  219522. ScopedXLock xlock;
  219523. XShmSegmentInfo segmentinfo;
  219524. XImage* const testImage
  219525. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219526. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219527. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219528. XDestroyImage (testImage);
  219529. }
  219530. #endif
  219531. }
  219532. ~LinuxRepaintManager()
  219533. {
  219534. }
  219535. void timerCallback()
  219536. {
  219537. #if JUCE_USE_XSHM
  219538. if (! shmCompletedDrawing)
  219539. return;
  219540. #endif
  219541. if (! regionsNeedingRepaint.isEmpty())
  219542. {
  219543. stopTimer();
  219544. performAnyPendingRepaintsNow();
  219545. }
  219546. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219547. {
  219548. stopTimer();
  219549. image = Image();
  219550. }
  219551. }
  219552. void repaint (const Rectangle<int>& area)
  219553. {
  219554. if (! isTimerRunning())
  219555. startTimer (repaintTimerPeriod);
  219556. regionsNeedingRepaint.add (area);
  219557. }
  219558. void performAnyPendingRepaintsNow()
  219559. {
  219560. #if JUCE_USE_XSHM
  219561. if (! shmCompletedDrawing)
  219562. {
  219563. startTimer (repaintTimerPeriod);
  219564. return;
  219565. }
  219566. #endif
  219567. peer->clearMaskedRegion();
  219568. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219569. regionsNeedingRepaint.clear();
  219570. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219571. if (! totalArea.isEmpty())
  219572. {
  219573. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219574. || image.getHeight() < totalArea.getHeight())
  219575. {
  219576. #if JUCE_USE_XSHM
  219577. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219578. : Image::RGB,
  219579. #else
  219580. image = Image (new XBitmapImage (Image::RGB,
  219581. #endif
  219582. (totalArea.getWidth() + 31) & ~31,
  219583. (totalArea.getHeight() + 31) & ~31,
  219584. false, peer->depth, peer->visual));
  219585. }
  219586. startTimer (repaintTimerPeriod);
  219587. RectangleList adjustedList (originalRepaintRegion);
  219588. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219589. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219590. if (peer->depth == 32)
  219591. {
  219592. RectangleList::Iterator i (originalRepaintRegion);
  219593. while (i.next())
  219594. image.clear (*i.getRectangle() - totalArea.getPosition());
  219595. }
  219596. peer->handlePaint (context);
  219597. if (! peer->maskedRegion.isEmpty())
  219598. originalRepaintRegion.subtract (peer->maskedRegion);
  219599. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219600. {
  219601. #if JUCE_USE_XSHM
  219602. shmCompletedDrawing = false;
  219603. #endif
  219604. const Rectangle<int>& r = *i.getRectangle();
  219605. static_cast<XBitmapImage*> (image.getSharedImage())
  219606. ->blitToWindow (peer->windowH,
  219607. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219608. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219609. }
  219610. }
  219611. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219612. startTimer (repaintTimerPeriod);
  219613. }
  219614. #if JUCE_USE_XSHM
  219615. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219616. #endif
  219617. private:
  219618. enum { repaintTimerPeriod = 1000 / 100 };
  219619. LinuxComponentPeer* const peer;
  219620. Image image;
  219621. uint32 lastTimeImageUsed;
  219622. RectangleList regionsNeedingRepaint;
  219623. #if JUCE_USE_XSHM
  219624. bool useARGBImagesForRendering, shmCompletedDrawing;
  219625. #endif
  219626. LinuxRepaintManager (const LinuxRepaintManager&);
  219627. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219628. };
  219629. ScopedPointer <LinuxRepaintManager> repainter;
  219630. friend class LinuxRepaintManager;
  219631. Window windowH, parentWindow;
  219632. int wx, wy, ww, wh;
  219633. Image taskbarImage;
  219634. bool fullScreen, mapped;
  219635. Visual* visual;
  219636. int depth;
  219637. BorderSize windowBorder;
  219638. struct MotifWmHints
  219639. {
  219640. unsigned long flags;
  219641. unsigned long functions;
  219642. unsigned long decorations;
  219643. long input_mode;
  219644. unsigned long status;
  219645. };
  219646. static void updateKeyStates (const int keycode, const bool press) throw()
  219647. {
  219648. const int keybyte = keycode >> 3;
  219649. const int keybit = (1 << (keycode & 7));
  219650. if (press)
  219651. Keys::keyStates [keybyte] |= keybit;
  219652. else
  219653. Keys::keyStates [keybyte] &= ~keybit;
  219654. }
  219655. static void updateKeyModifiers (const int status) throw()
  219656. {
  219657. int keyMods = 0;
  219658. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219659. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219660. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219661. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219662. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219663. Keys::capsLock = ((status & LockMask) != 0);
  219664. }
  219665. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219666. {
  219667. int modifier = 0;
  219668. bool isModifier = true;
  219669. switch (sym)
  219670. {
  219671. case XK_Shift_L:
  219672. case XK_Shift_R:
  219673. modifier = ModifierKeys::shiftModifier;
  219674. break;
  219675. case XK_Control_L:
  219676. case XK_Control_R:
  219677. modifier = ModifierKeys::ctrlModifier;
  219678. break;
  219679. case XK_Alt_L:
  219680. case XK_Alt_R:
  219681. modifier = ModifierKeys::altModifier;
  219682. break;
  219683. case XK_Num_Lock:
  219684. if (press)
  219685. Keys::numLock = ! Keys::numLock;
  219686. break;
  219687. case XK_Caps_Lock:
  219688. if (press)
  219689. Keys::capsLock = ! Keys::capsLock;
  219690. break;
  219691. case XK_Scroll_Lock:
  219692. break;
  219693. default:
  219694. isModifier = false;
  219695. break;
  219696. }
  219697. if (modifier != 0)
  219698. {
  219699. if (press)
  219700. currentModifiers = currentModifiers.withFlags (modifier);
  219701. else
  219702. currentModifiers = currentModifiers.withoutFlags (modifier);
  219703. }
  219704. return isModifier;
  219705. }
  219706. // Alt and Num lock are not defined by standard X
  219707. // modifier constants: check what they're mapped to
  219708. static void updateModifierMappings() throw()
  219709. {
  219710. ScopedXLock xlock;
  219711. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219712. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219713. Keys::AltMask = 0;
  219714. Keys::NumLockMask = 0;
  219715. XModifierKeymap* mapping = XGetModifierMapping (display);
  219716. if (mapping)
  219717. {
  219718. for (int i = 0; i < 8; i++)
  219719. {
  219720. if (mapping->modifiermap [i << 1] == altLeftCode)
  219721. Keys::AltMask = 1 << i;
  219722. else if (mapping->modifiermap [i << 1] == numLockCode)
  219723. Keys::NumLockMask = 1 << i;
  219724. }
  219725. XFreeModifiermap (mapping);
  219726. }
  219727. }
  219728. void removeWindowDecorations (Window wndH)
  219729. {
  219730. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219731. if (hints != None)
  219732. {
  219733. MotifWmHints motifHints;
  219734. zerostruct (motifHints);
  219735. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219736. motifHints.decorations = 0;
  219737. ScopedXLock xlock;
  219738. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219739. (unsigned char*) &motifHints, 4);
  219740. }
  219741. hints = XInternAtom (display, "_WIN_HINTS", True);
  219742. if (hints != None)
  219743. {
  219744. long gnomeHints = 0;
  219745. ScopedXLock xlock;
  219746. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219747. (unsigned char*) &gnomeHints, 1);
  219748. }
  219749. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219750. if (hints != None)
  219751. {
  219752. long kwmHints = 2; /*KDE_tinyDecoration*/
  219753. ScopedXLock xlock;
  219754. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219755. (unsigned char*) &kwmHints, 1);
  219756. }
  219757. }
  219758. void addWindowButtons (Window wndH)
  219759. {
  219760. ScopedXLock xlock;
  219761. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219762. if (hints != None)
  219763. {
  219764. MotifWmHints motifHints;
  219765. zerostruct (motifHints);
  219766. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219767. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219768. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219769. if ((styleFlags & windowHasCloseButton) != 0)
  219770. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219771. if ((styleFlags & windowHasMinimiseButton) != 0)
  219772. {
  219773. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219774. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219775. }
  219776. if ((styleFlags & windowHasMaximiseButton) != 0)
  219777. {
  219778. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219779. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219780. }
  219781. if ((styleFlags & windowIsResizable) != 0)
  219782. {
  219783. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219784. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219785. }
  219786. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219787. }
  219788. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219789. if (hints != None)
  219790. {
  219791. int netHints [6];
  219792. int num = 0;
  219793. if ((styleFlags & windowIsResizable) != 0)
  219794. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219795. if ((styleFlags & windowHasMaximiseButton) != 0)
  219796. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219797. if ((styleFlags & windowHasMinimiseButton) != 0)
  219798. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219799. if ((styleFlags & windowHasCloseButton) != 0)
  219800. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219801. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219802. }
  219803. }
  219804. void setWindowType()
  219805. {
  219806. int netHints [2];
  219807. int numHints = 0;
  219808. if ((styleFlags & windowIsTemporary) != 0
  219809. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219810. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219811. else
  219812. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219813. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219814. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  219815. (unsigned char*) &netHints, numHints);
  219816. numHints = 0;
  219817. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  219818. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  219819. if (component->isAlwaysOnTop())
  219820. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  219821. if (numHints > 0)
  219822. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  219823. (unsigned char*) &netHints, numHints);
  219824. }
  219825. void createWindow()
  219826. {
  219827. ScopedXLock xlock;
  219828. Atoms::initialiseAtoms();
  219829. resetDragAndDrop();
  219830. // Get defaults for various properties
  219831. const int screen = DefaultScreen (display);
  219832. Window root = RootWindow (display, screen);
  219833. // Try to obtain a 32-bit visual or fallback to 24 or 16
  219834. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  219835. if (visual == 0)
  219836. {
  219837. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  219838. Process::terminate();
  219839. }
  219840. // Create and install a colormap suitable fr our visual
  219841. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  219842. XInstallColormap (display, colormap);
  219843. // Set up the window attributes
  219844. XSetWindowAttributes swa;
  219845. swa.border_pixel = 0;
  219846. swa.background_pixmap = None;
  219847. swa.colormap = colormap;
  219848. swa.event_mask = getAllEventsMask();
  219849. windowH = XCreateWindow (display, root,
  219850. 0, 0, 1, 1,
  219851. 0, depth, InputOutput, visual,
  219852. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  219853. &swa);
  219854. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  219855. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  219856. GrabModeAsync, GrabModeAsync, None, None);
  219857. // Set the window context to identify the window handle object
  219858. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  219859. {
  219860. // Failed
  219861. jassertfalse;
  219862. Logger::outputDebugString ("Failed to create context information for window.\n");
  219863. XDestroyWindow (display, windowH);
  219864. windowH = 0;
  219865. return;
  219866. }
  219867. // Set window manager hints
  219868. XWMHints* wmHints = XAllocWMHints();
  219869. wmHints->flags = InputHint | StateHint;
  219870. wmHints->input = True; // Locally active input model
  219871. wmHints->initial_state = NormalState;
  219872. XSetWMHints (display, windowH, wmHints);
  219873. XFree (wmHints);
  219874. // Set the window type
  219875. setWindowType();
  219876. // Define decoration
  219877. if ((styleFlags & windowHasTitleBar) == 0)
  219878. removeWindowDecorations (windowH);
  219879. else
  219880. addWindowButtons (windowH);
  219881. // Set window name
  219882. setWindowTitle (windowH, getComponent()->getName());
  219883. // Associate the PID, allowing to be shut down when something goes wrong
  219884. unsigned long pid = getpid();
  219885. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  219886. (unsigned char*) &pid, 1);
  219887. // Set window manager protocols
  219888. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  219889. (unsigned char*) Atoms::ProtocolList, 2);
  219890. // Set drag and drop flags
  219891. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  219892. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  219893. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  219894. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  219895. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  219896. (const unsigned char*) "", 0);
  219897. unsigned long dndVersion = Atoms::DndVersion;
  219898. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  219899. (const unsigned char*) &dndVersion, 1);
  219900. // Initialise the pointer and keyboard mapping
  219901. // This is not the same as the logical pointer mapping the X server uses:
  219902. // we don't mess with this.
  219903. static bool mappingInitialised = false;
  219904. if (! mappingInitialised)
  219905. {
  219906. mappingInitialised = true;
  219907. const int numButtons = XGetPointerMapping (display, 0, 0);
  219908. if (numButtons == 2)
  219909. {
  219910. pointerMap[0] = Keys::LeftButton;
  219911. pointerMap[1] = Keys::RightButton;
  219912. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  219913. }
  219914. else if (numButtons >= 3)
  219915. {
  219916. pointerMap[0] = Keys::LeftButton;
  219917. pointerMap[1] = Keys::MiddleButton;
  219918. pointerMap[2] = Keys::RightButton;
  219919. if (numButtons >= 5)
  219920. {
  219921. pointerMap[3] = Keys::WheelUp;
  219922. pointerMap[4] = Keys::WheelDown;
  219923. }
  219924. }
  219925. updateModifierMappings();
  219926. }
  219927. }
  219928. void destroyWindow()
  219929. {
  219930. ScopedXLock xlock;
  219931. XPointer handlePointer;
  219932. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  219933. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  219934. XDestroyWindow (display, windowH);
  219935. // Wait for it to complete and then remove any events for this
  219936. // window from the event queue.
  219937. XSync (display, false);
  219938. XEvent event;
  219939. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  219940. {}
  219941. }
  219942. static int getAllEventsMask() throw()
  219943. {
  219944. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  219945. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  219946. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  219947. }
  219948. static int64 getEventTime (::Time t)
  219949. {
  219950. static int64 eventTimeOffset = 0x12345678;
  219951. const int64 thisMessageTime = t;
  219952. if (eventTimeOffset == 0x12345678)
  219953. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  219954. return eventTimeOffset + thisMessageTime;
  219955. }
  219956. static void setWindowTitle (Window xwin, const String& title)
  219957. {
  219958. XTextProperty nameProperty;
  219959. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219960. ScopedXLock xlock;
  219961. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219962. {
  219963. XSetWMName (display, xwin, &nameProperty);
  219964. XSetWMIconName (display, xwin, &nameProperty);
  219965. XFree (nameProperty.value);
  219966. }
  219967. }
  219968. void updateBorderSize()
  219969. {
  219970. if ((styleFlags & windowHasTitleBar) == 0)
  219971. {
  219972. windowBorder = BorderSize (0);
  219973. }
  219974. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  219975. {
  219976. ScopedXLock xlock;
  219977. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  219978. if (hints != None)
  219979. {
  219980. unsigned char* data = 0;
  219981. unsigned long nitems, bytesLeft;
  219982. Atom actualType;
  219983. int actualFormat;
  219984. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  219985. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  219986. &data) == Success)
  219987. {
  219988. const unsigned long* const sizes = (const unsigned long*) data;
  219989. if (actualFormat == 32)
  219990. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  219991. (int) sizes[3], (int) sizes[1]);
  219992. XFree (data);
  219993. }
  219994. }
  219995. }
  219996. }
  219997. void updateBounds()
  219998. {
  219999. jassert (windowH != 0);
  220000. if (windowH != 0)
  220001. {
  220002. Window root, child;
  220003. unsigned int bw, depth;
  220004. ScopedXLock xlock;
  220005. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220006. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220007. &bw, &depth))
  220008. {
  220009. wx = wy = ww = wh = 0;
  220010. }
  220011. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220012. {
  220013. wx = wy = 0;
  220014. }
  220015. }
  220016. }
  220017. void resetDragAndDrop()
  220018. {
  220019. dragAndDropFiles.clear();
  220020. lastDropPos = Point<int> (-1, -1);
  220021. dragAndDropCurrentMimeType = 0;
  220022. dragAndDropSourceWindow = 0;
  220023. srcMimeTypeAtomList.clear();
  220024. }
  220025. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220026. {
  220027. msg.type = ClientMessage;
  220028. msg.display = display;
  220029. msg.window = dragAndDropSourceWindow;
  220030. msg.format = 32;
  220031. msg.data.l[0] = windowH;
  220032. ScopedXLock xlock;
  220033. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220034. }
  220035. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220036. {
  220037. XClientMessageEvent msg;
  220038. zerostruct (msg);
  220039. msg.message_type = Atoms::XdndStatus;
  220040. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220041. msg.data.l[4] = dropAction;
  220042. sendDragAndDropMessage (msg);
  220043. }
  220044. void sendDragAndDropLeave()
  220045. {
  220046. XClientMessageEvent msg;
  220047. zerostruct (msg);
  220048. msg.message_type = Atoms::XdndLeave;
  220049. sendDragAndDropMessage (msg);
  220050. }
  220051. void sendDragAndDropFinish()
  220052. {
  220053. XClientMessageEvent msg;
  220054. zerostruct (msg);
  220055. msg.message_type = Atoms::XdndFinished;
  220056. sendDragAndDropMessage (msg);
  220057. }
  220058. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220059. {
  220060. if ((clientMsg->data.l[1] & 1) == 0)
  220061. {
  220062. sendDragAndDropLeave();
  220063. if (dragAndDropFiles.size() > 0)
  220064. handleFileDragExit (dragAndDropFiles);
  220065. dragAndDropFiles.clear();
  220066. }
  220067. }
  220068. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220069. {
  220070. if (dragAndDropSourceWindow == 0)
  220071. return;
  220072. dragAndDropSourceWindow = clientMsg->data.l[0];
  220073. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220074. (int) clientMsg->data.l[2] & 0xffff);
  220075. dropPos -= getScreenPosition();
  220076. if (lastDropPos != dropPos)
  220077. {
  220078. lastDropPos = dropPos;
  220079. dragAndDropTimestamp = clientMsg->data.l[3];
  220080. Atom targetAction = Atoms::XdndActionCopy;
  220081. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220082. {
  220083. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220084. {
  220085. targetAction = Atoms::allowedActions[i];
  220086. break;
  220087. }
  220088. }
  220089. sendDragAndDropStatus (true, targetAction);
  220090. if (dragAndDropFiles.size() == 0)
  220091. updateDraggedFileList (clientMsg);
  220092. if (dragAndDropFiles.size() > 0)
  220093. handleFileDragMove (dragAndDropFiles, dropPos);
  220094. }
  220095. }
  220096. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220097. {
  220098. if (dragAndDropFiles.size() == 0)
  220099. updateDraggedFileList (clientMsg);
  220100. const StringArray files (dragAndDropFiles);
  220101. const Point<int> lastPos (lastDropPos);
  220102. sendDragAndDropFinish();
  220103. resetDragAndDrop();
  220104. if (files.size() > 0)
  220105. handleFileDragDrop (files, lastPos);
  220106. }
  220107. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220108. {
  220109. dragAndDropFiles.clear();
  220110. srcMimeTypeAtomList.clear();
  220111. dragAndDropCurrentMimeType = 0;
  220112. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220113. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220114. {
  220115. dragAndDropSourceWindow = 0;
  220116. return;
  220117. }
  220118. dragAndDropSourceWindow = clientMsg->data.l[0];
  220119. if ((clientMsg->data.l[1] & 1) != 0)
  220120. {
  220121. Atom actual;
  220122. int format;
  220123. unsigned long count = 0, remaining = 0;
  220124. unsigned char* data = 0;
  220125. ScopedXLock xlock;
  220126. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220127. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220128. &count, &remaining, &data);
  220129. if (data != 0)
  220130. {
  220131. if (actual == XA_ATOM && format == 32 && count != 0)
  220132. {
  220133. const unsigned long* const types = (const unsigned long*) data;
  220134. for (unsigned int i = 0; i < count; ++i)
  220135. if (types[i] != None)
  220136. srcMimeTypeAtomList.add (types[i]);
  220137. }
  220138. XFree (data);
  220139. }
  220140. }
  220141. if (srcMimeTypeAtomList.size() == 0)
  220142. {
  220143. for (int i = 2; i < 5; ++i)
  220144. if (clientMsg->data.l[i] != None)
  220145. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220146. if (srcMimeTypeAtomList.size() == 0)
  220147. {
  220148. dragAndDropSourceWindow = 0;
  220149. return;
  220150. }
  220151. }
  220152. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220153. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220154. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220155. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220156. handleDragAndDropPosition (clientMsg);
  220157. }
  220158. void handleDragAndDropSelection (const XEvent* const evt)
  220159. {
  220160. dragAndDropFiles.clear();
  220161. if (evt->xselection.property != 0)
  220162. {
  220163. StringArray lines;
  220164. {
  220165. MemoryBlock dropData;
  220166. for (;;)
  220167. {
  220168. Atom actual;
  220169. uint8* data = 0;
  220170. unsigned long count = 0, remaining = 0;
  220171. int format = 0;
  220172. ScopedXLock xlock;
  220173. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220174. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220175. &format, &count, &remaining, &data) == Success)
  220176. {
  220177. dropData.append (data, count * format / 8);
  220178. XFree (data);
  220179. if (remaining == 0)
  220180. break;
  220181. }
  220182. else
  220183. {
  220184. XFree (data);
  220185. break;
  220186. }
  220187. }
  220188. lines.addLines (dropData.toString());
  220189. }
  220190. for (int i = 0; i < lines.size(); ++i)
  220191. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220192. dragAndDropFiles.trim();
  220193. dragAndDropFiles.removeEmptyStrings();
  220194. }
  220195. }
  220196. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220197. {
  220198. dragAndDropFiles.clear();
  220199. if (dragAndDropSourceWindow != None
  220200. && dragAndDropCurrentMimeType != 0)
  220201. {
  220202. dragAndDropTimestamp = clientMsg->data.l[2];
  220203. ScopedXLock xlock;
  220204. XConvertSelection (display,
  220205. Atoms::XdndSelection,
  220206. dragAndDropCurrentMimeType,
  220207. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220208. windowH,
  220209. dragAndDropTimestamp);
  220210. }
  220211. }
  220212. StringArray dragAndDropFiles;
  220213. int dragAndDropTimestamp;
  220214. Point<int> lastDropPos;
  220215. Atom dragAndDropCurrentMimeType;
  220216. Window dragAndDropSourceWindow;
  220217. Array <Atom> srcMimeTypeAtomList;
  220218. static int pointerMap[5];
  220219. static Point<int> lastMousePos;
  220220. static void clearLastMousePos() throw()
  220221. {
  220222. lastMousePos = Point<int> (0x100000, 0x100000);
  220223. }
  220224. };
  220225. ModifierKeys LinuxComponentPeer::currentModifiers;
  220226. bool LinuxComponentPeer::isActiveApplication = false;
  220227. int LinuxComponentPeer::pointerMap[5];
  220228. Point<int> LinuxComponentPeer::lastMousePos;
  220229. bool Process::isForegroundProcess()
  220230. {
  220231. return LinuxComponentPeer::isActiveApplication;
  220232. }
  220233. void ModifierKeys::updateCurrentModifiers() throw()
  220234. {
  220235. currentModifiers = LinuxComponentPeer::currentModifiers;
  220236. }
  220237. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220238. {
  220239. Window root, child;
  220240. int x, y, winx, winy;
  220241. unsigned int mask;
  220242. int mouseMods = 0;
  220243. ScopedXLock xlock;
  220244. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220245. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220246. {
  220247. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220248. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220249. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220250. }
  220251. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220252. return LinuxComponentPeer::currentModifiers;
  220253. }
  220254. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220255. {
  220256. if (enableOrDisable)
  220257. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220258. }
  220259. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220260. {
  220261. return new LinuxComponentPeer (this, styleFlags);
  220262. }
  220263. // (this callback is hooked up in the messaging code)
  220264. void juce_windowMessageReceive (XEvent* event)
  220265. {
  220266. if (event->xany.window != None)
  220267. {
  220268. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220269. if (ComponentPeer::isValidPeer (peer))
  220270. peer->handleWindowMessage (event);
  220271. }
  220272. else
  220273. {
  220274. switch (event->xany.type)
  220275. {
  220276. case KeymapNotify:
  220277. {
  220278. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220279. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220280. break;
  220281. }
  220282. default:
  220283. break;
  220284. }
  220285. }
  220286. }
  220287. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220288. {
  220289. if (display == 0)
  220290. return;
  220291. #if JUCE_USE_XINERAMA
  220292. int major_opcode, first_event, first_error;
  220293. ScopedXLock xlock;
  220294. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220295. {
  220296. typedef Bool (*tXineramaIsActive) (Display*);
  220297. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220298. static tXineramaIsActive xXineramaIsActive = 0;
  220299. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220300. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220301. {
  220302. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220303. if (h == 0)
  220304. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220305. if (h != 0)
  220306. {
  220307. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220308. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220309. }
  220310. }
  220311. if (xXineramaIsActive != 0
  220312. && xXineramaQueryScreens != 0
  220313. && xXineramaIsActive (display))
  220314. {
  220315. int numMonitors = 0;
  220316. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220317. if (screens != 0)
  220318. {
  220319. for (int i = numMonitors; --i >= 0;)
  220320. {
  220321. int index = screens[i].screen_number;
  220322. if (index >= 0)
  220323. {
  220324. while (monitorCoords.size() < index)
  220325. monitorCoords.add (Rectangle<int>());
  220326. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220327. screens[i].y_org,
  220328. screens[i].width,
  220329. screens[i].height));
  220330. }
  220331. }
  220332. XFree (screens);
  220333. }
  220334. }
  220335. }
  220336. if (monitorCoords.size() == 0)
  220337. #endif
  220338. {
  220339. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220340. if (hints != None)
  220341. {
  220342. const int numMonitors = ScreenCount (display);
  220343. for (int i = 0; i < numMonitors; ++i)
  220344. {
  220345. Window root = RootWindow (display, i);
  220346. unsigned long nitems, bytesLeft;
  220347. Atom actualType;
  220348. int actualFormat;
  220349. unsigned char* data = 0;
  220350. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220351. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220352. &data) == Success)
  220353. {
  220354. const long* const position = (const long*) data;
  220355. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220356. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220357. position[2], position[3]));
  220358. XFree (data);
  220359. }
  220360. }
  220361. }
  220362. if (monitorCoords.size() == 0)
  220363. {
  220364. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220365. DisplayHeight (display, DefaultScreen (display))));
  220366. }
  220367. }
  220368. }
  220369. void Desktop::createMouseInputSources()
  220370. {
  220371. mouseSources.add (new MouseInputSource (0, true));
  220372. }
  220373. bool Desktop::canUseSemiTransparentWindows() throw()
  220374. {
  220375. int matchedDepth = 0;
  220376. const int desiredDepth = 32;
  220377. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220378. && (matchedDepth == desiredDepth);
  220379. }
  220380. const Point<int> Desktop::getMousePosition()
  220381. {
  220382. Window root, child;
  220383. int x, y, winx, winy;
  220384. unsigned int mask;
  220385. ScopedXLock xlock;
  220386. if (XQueryPointer (display,
  220387. RootWindow (display, DefaultScreen (display)),
  220388. &root, &child,
  220389. &x, &y, &winx, &winy, &mask) == False)
  220390. {
  220391. // Pointer not on the default screen
  220392. x = y = -1;
  220393. }
  220394. return Point<int> (x, y);
  220395. }
  220396. void Desktop::setMousePosition (const Point<int>& newPosition)
  220397. {
  220398. ScopedXLock xlock;
  220399. Window root = RootWindow (display, DefaultScreen (display));
  220400. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220401. }
  220402. static bool screenSaverAllowed = true;
  220403. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220404. {
  220405. if (screenSaverAllowed != isEnabled)
  220406. {
  220407. screenSaverAllowed = isEnabled;
  220408. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220409. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220410. if (xScreenSaverSuspend == 0)
  220411. {
  220412. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220413. if (h != 0)
  220414. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220415. }
  220416. ScopedXLock xlock;
  220417. if (xScreenSaverSuspend != 0)
  220418. xScreenSaverSuspend (display, ! isEnabled);
  220419. }
  220420. }
  220421. bool Desktop::isScreenSaverEnabled()
  220422. {
  220423. return screenSaverAllowed;
  220424. }
  220425. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220426. {
  220427. ScopedXLock xlock;
  220428. const unsigned int imageW = image.getWidth();
  220429. const unsigned int imageH = image.getHeight();
  220430. #if JUCE_USE_XCURSOR
  220431. {
  220432. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220433. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220434. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220435. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220436. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220437. static tXcursorImageCreate xXcursorImageCreate = 0;
  220438. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220439. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220440. static bool hasBeenLoaded = false;
  220441. if (! hasBeenLoaded)
  220442. {
  220443. hasBeenLoaded = true;
  220444. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220445. if (h != 0)
  220446. {
  220447. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220448. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220449. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220450. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220451. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220452. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220453. || ! xXcursorSupportsARGB (display))
  220454. xXcursorSupportsARGB = 0;
  220455. }
  220456. }
  220457. if (xXcursorSupportsARGB != 0)
  220458. {
  220459. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220460. if (xcImage != 0)
  220461. {
  220462. xcImage->xhot = hotspotX;
  220463. xcImage->yhot = hotspotY;
  220464. XcursorPixel* dest = xcImage->pixels;
  220465. for (int y = 0; y < (int) imageH; ++y)
  220466. for (int x = 0; x < (int) imageW; ++x)
  220467. *dest++ = image.getPixelAt (x, y).getARGB();
  220468. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220469. xXcursorImageDestroy (xcImage);
  220470. if (result != 0)
  220471. return result;
  220472. }
  220473. }
  220474. }
  220475. #endif
  220476. Window root = RootWindow (display, DefaultScreen (display));
  220477. unsigned int cursorW, cursorH;
  220478. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220479. return 0;
  220480. Image im (Image::ARGB, cursorW, cursorH, true);
  220481. {
  220482. Graphics g (im);
  220483. if (imageW > cursorW || imageH > cursorH)
  220484. {
  220485. hotspotX = (hotspotX * cursorW) / imageW;
  220486. hotspotY = (hotspotY * cursorH) / imageH;
  220487. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220488. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220489. false);
  220490. }
  220491. else
  220492. {
  220493. g.drawImageAt (image, 0, 0);
  220494. }
  220495. }
  220496. const int stride = (cursorW + 7) >> 3;
  220497. HeapBlock <char> maskPlane, sourcePlane;
  220498. maskPlane.calloc (stride * cursorH);
  220499. sourcePlane.calloc (stride * cursorH);
  220500. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220501. for (int y = cursorH; --y >= 0;)
  220502. {
  220503. for (int x = cursorW; --x >= 0;)
  220504. {
  220505. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220506. const int offset = y * stride + (x >> 3);
  220507. const Colour c (im.getPixelAt (x, y));
  220508. if (c.getAlpha() >= 128)
  220509. maskPlane[offset] |= mask;
  220510. if (c.getBrightness() >= 0.5f)
  220511. sourcePlane[offset] |= mask;
  220512. }
  220513. }
  220514. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220515. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220516. XColor white, black;
  220517. black.red = black.green = black.blue = 0;
  220518. white.red = white.green = white.blue = 0xffff;
  220519. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220520. XFreePixmap (display, sourcePixmap);
  220521. XFreePixmap (display, maskPixmap);
  220522. return result;
  220523. }
  220524. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220525. {
  220526. ScopedXLock xlock;
  220527. if (cursorHandle != 0)
  220528. XFreeCursor (display, (Cursor) cursorHandle);
  220529. }
  220530. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220531. {
  220532. unsigned int shape;
  220533. switch (type)
  220534. {
  220535. case NormalCursor: return None; // Use parent cursor
  220536. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220537. case WaitCursor: shape = XC_watch; break;
  220538. case IBeamCursor: shape = XC_xterm; break;
  220539. case PointingHandCursor: shape = XC_hand2; break;
  220540. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220541. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220542. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220543. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220544. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220545. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220546. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220547. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220548. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220549. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220550. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220551. case CrosshairCursor: shape = XC_crosshair; break;
  220552. case DraggingHandCursor:
  220553. {
  220554. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220555. 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,
  220556. 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 };
  220557. const int dragHandDataSize = 99;
  220558. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220559. }
  220560. case CopyingCursor:
  220561. {
  220562. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220563. 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,
  220564. 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,
  220565. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220566. const int copyCursorSize = 119;
  220567. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220568. }
  220569. default:
  220570. jassertfalse;
  220571. return None;
  220572. }
  220573. ScopedXLock xlock;
  220574. return (void*) XCreateFontCursor (display, shape);
  220575. }
  220576. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220577. {
  220578. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220579. if (lp != 0)
  220580. lp->showMouseCursor ((Cursor) getHandle());
  220581. }
  220582. void MouseCursor::showInAllWindows() const
  220583. {
  220584. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220585. showInWindow (ComponentPeer::getPeer (i));
  220586. }
  220587. const Image juce_createIconForFile (const File& file)
  220588. {
  220589. return Image();
  220590. }
  220591. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220592. {
  220593. return createSoftwareImage (format, width, height, clearImage);
  220594. }
  220595. #if JUCE_OPENGL
  220596. class WindowedGLContext : public OpenGLContext
  220597. {
  220598. public:
  220599. WindowedGLContext (Component* const component,
  220600. const OpenGLPixelFormat& pixelFormat_,
  220601. GLXContext sharedContext)
  220602. : renderContext (0),
  220603. embeddedWindow (0),
  220604. pixelFormat (pixelFormat_),
  220605. swapInterval (0)
  220606. {
  220607. jassert (component != 0);
  220608. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220609. if (peer == 0)
  220610. return;
  220611. ScopedXLock xlock;
  220612. XSync (display, False);
  220613. GLint attribs [64];
  220614. int n = 0;
  220615. attribs[n++] = GLX_RGBA;
  220616. attribs[n++] = GLX_DOUBLEBUFFER;
  220617. attribs[n++] = GLX_RED_SIZE;
  220618. attribs[n++] = pixelFormat.redBits;
  220619. attribs[n++] = GLX_GREEN_SIZE;
  220620. attribs[n++] = pixelFormat.greenBits;
  220621. attribs[n++] = GLX_BLUE_SIZE;
  220622. attribs[n++] = pixelFormat.blueBits;
  220623. attribs[n++] = GLX_ALPHA_SIZE;
  220624. attribs[n++] = pixelFormat.alphaBits;
  220625. attribs[n++] = GLX_DEPTH_SIZE;
  220626. attribs[n++] = pixelFormat.depthBufferBits;
  220627. attribs[n++] = GLX_STENCIL_SIZE;
  220628. attribs[n++] = pixelFormat.stencilBufferBits;
  220629. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220630. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220631. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220632. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220633. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220634. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220635. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220636. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220637. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220638. attribs[n++] = None;
  220639. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220640. if (bestVisual == 0)
  220641. return;
  220642. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220643. Window windowH = (Window) peer->getNativeHandle();
  220644. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220645. XSetWindowAttributes swa;
  220646. swa.colormap = colourMap;
  220647. swa.border_pixel = 0;
  220648. swa.event_mask = ExposureMask | StructureNotifyMask;
  220649. embeddedWindow = XCreateWindow (display, windowH,
  220650. 0, 0, 1, 1, 0,
  220651. bestVisual->depth,
  220652. InputOutput,
  220653. bestVisual->visual,
  220654. CWBorderPixel | CWColormap | CWEventMask,
  220655. &swa);
  220656. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220657. XMapWindow (display, embeddedWindow);
  220658. XFreeColormap (display, colourMap);
  220659. XFree (bestVisual);
  220660. XSync (display, False);
  220661. }
  220662. ~WindowedGLContext()
  220663. {
  220664. makeInactive();
  220665. ScopedXLock xlock;
  220666. glXDestroyContext (display, renderContext);
  220667. XUnmapWindow (display, embeddedWindow);
  220668. XDestroyWindow (display, embeddedWindow);
  220669. }
  220670. bool makeActive() const throw()
  220671. {
  220672. jassert (renderContext != 0);
  220673. ScopedXLock xlock;
  220674. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220675. && XSync (display, False);
  220676. }
  220677. bool makeInactive() const throw()
  220678. {
  220679. ScopedXLock xlock;
  220680. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220681. }
  220682. bool isActive() const throw()
  220683. {
  220684. ScopedXLock xlock;
  220685. return glXGetCurrentContext() == renderContext;
  220686. }
  220687. const OpenGLPixelFormat getPixelFormat() const
  220688. {
  220689. return pixelFormat;
  220690. }
  220691. void* getRawContext() const throw()
  220692. {
  220693. return renderContext;
  220694. }
  220695. void updateWindowPosition (int x, int y, int w, int h, int)
  220696. {
  220697. ScopedXLock xlock;
  220698. XMoveResizeWindow (display, embeddedWindow,
  220699. x, y, jmax (1, w), jmax (1, h));
  220700. }
  220701. void swapBuffers()
  220702. {
  220703. ScopedXLock xlock;
  220704. glXSwapBuffers (display, embeddedWindow);
  220705. }
  220706. bool setSwapInterval (const int numFramesPerSwap)
  220707. {
  220708. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  220709. if (GLXSwapIntervalSGI != 0)
  220710. {
  220711. swapInterval = numFramesPerSwap;
  220712. GLXSwapIntervalSGI (numFramesPerSwap);
  220713. return true;
  220714. }
  220715. return false;
  220716. }
  220717. int getSwapInterval() const
  220718. {
  220719. return swapInterval;
  220720. }
  220721. void repaint()
  220722. {
  220723. }
  220724. juce_UseDebuggingNewOperator
  220725. GLXContext renderContext;
  220726. private:
  220727. Window embeddedWindow;
  220728. OpenGLPixelFormat pixelFormat;
  220729. int swapInterval;
  220730. WindowedGLContext (const WindowedGLContext&);
  220731. WindowedGLContext& operator= (const WindowedGLContext&);
  220732. };
  220733. OpenGLContext* OpenGLComponent::createContext()
  220734. {
  220735. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220736. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220737. return (c->renderContext != 0) ? c.release() : 0;
  220738. }
  220739. void juce_glViewport (const int w, const int h)
  220740. {
  220741. glViewport (0, 0, w, h);
  220742. }
  220743. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220744. OwnedArray <OpenGLPixelFormat>& results)
  220745. {
  220746. results.add (new OpenGLPixelFormat()); // xxx
  220747. }
  220748. #endif
  220749. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220750. {
  220751. jassertfalse; // not implemented!
  220752. return false;
  220753. }
  220754. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220755. {
  220756. jassertfalse; // not implemented!
  220757. return false;
  220758. }
  220759. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220760. {
  220761. if (! isOnDesktop ())
  220762. addToDesktop (0);
  220763. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220764. if (wp != 0)
  220765. {
  220766. wp->setTaskBarIcon (newImage);
  220767. setVisible (true);
  220768. toFront (false);
  220769. repaint();
  220770. }
  220771. }
  220772. void SystemTrayIconComponent::paint (Graphics& g)
  220773. {
  220774. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220775. if (wp != 0)
  220776. {
  220777. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220778. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220779. false);
  220780. }
  220781. }
  220782. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220783. {
  220784. // xxx not yet implemented!
  220785. }
  220786. void PlatformUtilities::beep()
  220787. {
  220788. std::cout << "\a" << std::flush;
  220789. }
  220790. bool AlertWindow::showNativeDialogBox (const String& title,
  220791. const String& bodyText,
  220792. bool isOkCancel)
  220793. {
  220794. // use a non-native one for the time being..
  220795. if (isOkCancel)
  220796. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220797. else
  220798. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220799. return true;
  220800. }
  220801. const int KeyPress::spaceKey = XK_space & 0xff;
  220802. const int KeyPress::returnKey = XK_Return & 0xff;
  220803. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220804. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220805. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  220806. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  220807. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  220808. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  220809. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  220810. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  220811. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  220812. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  220813. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  220814. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  220815. const int KeyPress::tabKey = XK_Tab & 0xff;
  220816. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  220817. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  220818. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  220819. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  220820. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  220821. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  220822. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  220823. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  220824. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  220825. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  220826. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  220827. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  220828. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  220829. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  220830. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  220831. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  220832. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  220833. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  220834. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  220835. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  220836. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  220837. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  220838. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  220839. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  220840. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  220841. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  220842. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  220843. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  220844. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  220845. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  220846. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  220847. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  220848. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  220849. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  220850. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  220851. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  220852. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  220853. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  220854. #endif
  220855. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  220856. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  220857. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220858. // compiled on its own).
  220859. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  220860. static const int maxNumChans = 64;
  220861. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  220862. {
  220863. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  220864. snd_pcm_hw_params_t* hwParams;
  220865. snd_pcm_hw_params_alloca (&hwParams);
  220866. for (int i = 0; ratesToTry[i] != 0; ++i)
  220867. {
  220868. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  220869. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  220870. {
  220871. rates.addIfNotAlreadyThere (ratesToTry[i]);
  220872. }
  220873. }
  220874. }
  220875. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  220876. {
  220877. snd_pcm_hw_params_t *params;
  220878. snd_pcm_hw_params_alloca (&params);
  220879. if (snd_pcm_hw_params_any (handle, params) >= 0)
  220880. {
  220881. snd_pcm_hw_params_get_channels_min (params, minChans);
  220882. snd_pcm_hw_params_get_channels_max (params, maxChans);
  220883. }
  220884. }
  220885. static void getDeviceProperties (const String& deviceID,
  220886. unsigned int& minChansOut,
  220887. unsigned int& maxChansOut,
  220888. unsigned int& minChansIn,
  220889. unsigned int& maxChansIn,
  220890. Array <int>& rates)
  220891. {
  220892. if (deviceID.isEmpty())
  220893. return;
  220894. snd_ctl_t* handle;
  220895. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  220896. {
  220897. snd_pcm_info_t* info;
  220898. snd_pcm_info_alloca (&info);
  220899. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  220900. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  220901. snd_pcm_info_set_subdevice (info, 0);
  220902. if (snd_ctl_pcm_info (handle, info) >= 0)
  220903. {
  220904. snd_pcm_t* pcmHandle;
  220905. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220906. {
  220907. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  220908. getDeviceSampleRates (pcmHandle, rates);
  220909. snd_pcm_close (pcmHandle);
  220910. }
  220911. }
  220912. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  220913. if (snd_ctl_pcm_info (handle, info) >= 0)
  220914. {
  220915. snd_pcm_t* pcmHandle;
  220916. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220917. {
  220918. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  220919. if (rates.size() == 0)
  220920. getDeviceSampleRates (pcmHandle, rates);
  220921. snd_pcm_close (pcmHandle);
  220922. }
  220923. }
  220924. snd_ctl_close (handle);
  220925. }
  220926. }
  220927. class ALSADevice
  220928. {
  220929. public:
  220930. ALSADevice (const String& deviceID,
  220931. const bool forInput)
  220932. : handle (0),
  220933. bitDepth (16),
  220934. numChannelsRunning (0),
  220935. isInput (forInput),
  220936. sampleFormat (AudioDataConverters::int16LE)
  220937. {
  220938. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  220939. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  220940. SND_PCM_ASYNC));
  220941. }
  220942. ~ALSADevice()
  220943. {
  220944. if (handle != 0)
  220945. snd_pcm_close (handle);
  220946. }
  220947. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  220948. {
  220949. if (handle == 0)
  220950. return false;
  220951. snd_pcm_hw_params_t* hwParams;
  220952. snd_pcm_hw_params_alloca (&hwParams);
  220953. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  220954. return false;
  220955. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  220956. isInterleaved = false;
  220957. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  220958. isInterleaved = true;
  220959. else
  220960. {
  220961. jassertfalse;
  220962. return false;
  220963. }
  220964. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  220965. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  220966. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  220967. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  220968. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  220969. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  220970. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  220971. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  220972. bitDepth = 0;
  220973. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  220974. {
  220975. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  220976. {
  220977. bitDepth = formatsToTry [i + 1];
  220978. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  220979. break;
  220980. }
  220981. }
  220982. if (bitDepth == 0)
  220983. {
  220984. error = "device doesn't support a compatible PCM format";
  220985. DBG ("ALSA error: " + error + "\n");
  220986. return false;
  220987. }
  220988. int dir = 0;
  220989. unsigned int periods = 4;
  220990. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  220991. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  220992. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  220993. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  220994. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  220995. || failed (snd_pcm_hw_params (handle, hwParams)))
  220996. {
  220997. return false;
  220998. }
  220999. snd_pcm_sw_params_t* swParams;
  221000. snd_pcm_sw_params_alloca (&swParams);
  221001. snd_pcm_uframes_t boundary;
  221002. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221003. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221004. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221005. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221006. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221007. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221008. || failed (snd_pcm_sw_params (handle, swParams)))
  221009. {
  221010. return false;
  221011. }
  221012. /*
  221013. #if JUCE_DEBUG
  221014. // enable this to dump the config of the devices that get opened
  221015. snd_output_t* out;
  221016. snd_output_stdio_attach (&out, stderr, 0);
  221017. snd_pcm_hw_params_dump (hwParams, out);
  221018. snd_pcm_sw_params_dump (swParams, out);
  221019. #endif
  221020. */
  221021. numChannelsRunning = numChannels;
  221022. return true;
  221023. }
  221024. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221025. {
  221026. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221027. float** const data = outputChannelBuffer.getArrayOfChannels();
  221028. if (isInterleaved)
  221029. {
  221030. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221031. float* interleaved = static_cast <float*> (scratch.getData());
  221032. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  221033. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221034. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  221035. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221036. return false;
  221037. }
  221038. else
  221039. {
  221040. for (int i = 0; i < numChannelsRunning; ++i)
  221041. if (data[i] != 0)
  221042. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  221043. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  221044. if (failed (num))
  221045. {
  221046. if (num == -EPIPE)
  221047. {
  221048. if (failed (snd_pcm_prepare (handle)))
  221049. return false;
  221050. }
  221051. else if (num != -ESTRPIPE)
  221052. return false;
  221053. }
  221054. }
  221055. return true;
  221056. }
  221057. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221058. {
  221059. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221060. float** const data = inputChannelBuffer.getArrayOfChannels();
  221061. if (isInterleaved)
  221062. {
  221063. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221064. float* interleaved = static_cast <float*> (scratch.getData());
  221065. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  221066. if (failed (num))
  221067. {
  221068. if (num == -EPIPE)
  221069. {
  221070. if (failed (snd_pcm_prepare (handle)))
  221071. return false;
  221072. }
  221073. else if (num != -ESTRPIPE)
  221074. return false;
  221075. }
  221076. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221077. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  221078. }
  221079. else
  221080. {
  221081. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221082. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221083. return false;
  221084. for (int i = 0; i < numChannelsRunning; ++i)
  221085. if (data[i] != 0)
  221086. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  221087. }
  221088. return true;
  221089. }
  221090. juce_UseDebuggingNewOperator
  221091. snd_pcm_t* handle;
  221092. String error;
  221093. int bitDepth, numChannelsRunning;
  221094. private:
  221095. const bool isInput;
  221096. bool isInterleaved;
  221097. MemoryBlock scratch;
  221098. AudioDataConverters::DataFormat sampleFormat;
  221099. bool failed (const int errorNum)
  221100. {
  221101. if (errorNum >= 0)
  221102. return false;
  221103. error = snd_strerror (errorNum);
  221104. DBG ("ALSA error: " + error + "\n");
  221105. return true;
  221106. }
  221107. };
  221108. class ALSAThread : public Thread
  221109. {
  221110. public:
  221111. ALSAThread (const String& inputId_,
  221112. const String& outputId_)
  221113. : Thread ("Juce ALSA"),
  221114. sampleRate (0),
  221115. bufferSize (0),
  221116. callback (0),
  221117. inputId (inputId_),
  221118. outputId (outputId_),
  221119. outputDevice (0),
  221120. inputDevice (0),
  221121. numCallbacks (0),
  221122. inputChannelBuffer (1, 1),
  221123. outputChannelBuffer (1, 1)
  221124. {
  221125. initialiseRatesAndChannels();
  221126. }
  221127. ~ALSAThread()
  221128. {
  221129. close();
  221130. }
  221131. void open (BigInteger inputChannels,
  221132. BigInteger outputChannels,
  221133. const double sampleRate_,
  221134. const int bufferSize_)
  221135. {
  221136. close();
  221137. error = String::empty;
  221138. sampleRate = sampleRate_;
  221139. bufferSize = bufferSize_;
  221140. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221141. inputChannelBuffer.clear();
  221142. inputChannelDataForCallback.clear();
  221143. currentInputChans.clear();
  221144. if (inputChannels.getHighestBit() >= 0)
  221145. {
  221146. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221147. {
  221148. if (inputChannels[i])
  221149. {
  221150. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221151. currentInputChans.setBit (i);
  221152. }
  221153. }
  221154. }
  221155. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221156. outputChannelBuffer.clear();
  221157. outputChannelDataForCallback.clear();
  221158. currentOutputChans.clear();
  221159. if (outputChannels.getHighestBit() >= 0)
  221160. {
  221161. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221162. {
  221163. if (outputChannels[i])
  221164. {
  221165. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221166. currentOutputChans.setBit (i);
  221167. }
  221168. }
  221169. }
  221170. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221171. {
  221172. outputDevice = new ALSADevice (outputId, false);
  221173. if (outputDevice->error.isNotEmpty())
  221174. {
  221175. error = outputDevice->error;
  221176. deleteAndZero (outputDevice);
  221177. return;
  221178. }
  221179. currentOutputChans.setRange (0, minChansOut, true);
  221180. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221181. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221182. bufferSize))
  221183. {
  221184. error = outputDevice->error;
  221185. deleteAndZero (outputDevice);
  221186. return;
  221187. }
  221188. }
  221189. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221190. {
  221191. inputDevice = new ALSADevice (inputId, true);
  221192. if (inputDevice->error.isNotEmpty())
  221193. {
  221194. error = inputDevice->error;
  221195. deleteAndZero (inputDevice);
  221196. return;
  221197. }
  221198. currentInputChans.setRange (0, minChansIn, true);
  221199. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221200. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221201. bufferSize))
  221202. {
  221203. error = inputDevice->error;
  221204. deleteAndZero (inputDevice);
  221205. return;
  221206. }
  221207. }
  221208. if (outputDevice == 0 && inputDevice == 0)
  221209. {
  221210. error = "no channels";
  221211. return;
  221212. }
  221213. if (outputDevice != 0 && inputDevice != 0)
  221214. {
  221215. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221216. }
  221217. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221218. return;
  221219. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221220. return;
  221221. startThread (9);
  221222. int count = 1000;
  221223. while (numCallbacks == 0)
  221224. {
  221225. sleep (5);
  221226. if (--count < 0 || ! isThreadRunning())
  221227. {
  221228. error = "device didn't start";
  221229. break;
  221230. }
  221231. }
  221232. }
  221233. void close()
  221234. {
  221235. stopThread (6000);
  221236. deleteAndZero (inputDevice);
  221237. deleteAndZero (outputDevice);
  221238. inputChannelBuffer.setSize (1, 1);
  221239. outputChannelBuffer.setSize (1, 1);
  221240. numCallbacks = 0;
  221241. }
  221242. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221243. {
  221244. const ScopedLock sl (callbackLock);
  221245. callback = newCallback;
  221246. }
  221247. void run()
  221248. {
  221249. while (! threadShouldExit())
  221250. {
  221251. if (inputDevice != 0)
  221252. {
  221253. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221254. {
  221255. DBG ("ALSA: read failure");
  221256. break;
  221257. }
  221258. }
  221259. if (threadShouldExit())
  221260. break;
  221261. {
  221262. const ScopedLock sl (callbackLock);
  221263. ++numCallbacks;
  221264. if (callback != 0)
  221265. {
  221266. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221267. inputChannelDataForCallback.size(),
  221268. outputChannelDataForCallback.getRawDataPointer(),
  221269. outputChannelDataForCallback.size(),
  221270. bufferSize);
  221271. }
  221272. else
  221273. {
  221274. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221275. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221276. }
  221277. }
  221278. if (outputDevice != 0)
  221279. {
  221280. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221281. if (threadShouldExit())
  221282. break;
  221283. failed (snd_pcm_avail_update (outputDevice->handle));
  221284. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221285. {
  221286. DBG ("ALSA: write failure");
  221287. break;
  221288. }
  221289. }
  221290. }
  221291. }
  221292. int getBitDepth() const throw()
  221293. {
  221294. if (outputDevice != 0)
  221295. return outputDevice->bitDepth;
  221296. if (inputDevice != 0)
  221297. return inputDevice->bitDepth;
  221298. return 16;
  221299. }
  221300. juce_UseDebuggingNewOperator
  221301. String error;
  221302. double sampleRate;
  221303. int bufferSize;
  221304. BigInteger currentInputChans, currentOutputChans;
  221305. Array <int> sampleRates;
  221306. StringArray channelNamesOut, channelNamesIn;
  221307. AudioIODeviceCallback* callback;
  221308. private:
  221309. const String inputId, outputId;
  221310. ALSADevice* outputDevice;
  221311. ALSADevice* inputDevice;
  221312. int numCallbacks;
  221313. CriticalSection callbackLock;
  221314. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221315. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221316. unsigned int minChansOut, maxChansOut;
  221317. unsigned int minChansIn, maxChansIn;
  221318. bool failed (const int errorNum)
  221319. {
  221320. if (errorNum >= 0)
  221321. return false;
  221322. error = snd_strerror (errorNum);
  221323. DBG ("ALSA error: " + error + "\n");
  221324. return true;
  221325. }
  221326. void initialiseRatesAndChannels()
  221327. {
  221328. sampleRates.clear();
  221329. channelNamesOut.clear();
  221330. channelNamesIn.clear();
  221331. minChansOut = 0;
  221332. maxChansOut = 0;
  221333. minChansIn = 0;
  221334. maxChansIn = 0;
  221335. unsigned int dummy = 0;
  221336. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221337. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221338. unsigned int i;
  221339. for (i = 0; i < maxChansOut; ++i)
  221340. channelNamesOut.add ("channel " + String ((int) i + 1));
  221341. for (i = 0; i < maxChansIn; ++i)
  221342. channelNamesIn.add ("channel " + String ((int) i + 1));
  221343. }
  221344. };
  221345. class ALSAAudioIODevice : public AudioIODevice
  221346. {
  221347. public:
  221348. ALSAAudioIODevice (const String& deviceName,
  221349. const String& inputId_,
  221350. const String& outputId_)
  221351. : AudioIODevice (deviceName, "ALSA"),
  221352. inputId (inputId_),
  221353. outputId (outputId_),
  221354. isOpen_ (false),
  221355. isStarted (false),
  221356. internal (new ALSAThread (inputId_, outputId_))
  221357. {
  221358. }
  221359. ~ALSAAudioIODevice()
  221360. {
  221361. }
  221362. const StringArray getOutputChannelNames()
  221363. {
  221364. return internal->channelNamesOut;
  221365. }
  221366. const StringArray getInputChannelNames()
  221367. {
  221368. return internal->channelNamesIn;
  221369. }
  221370. int getNumSampleRates()
  221371. {
  221372. return internal->sampleRates.size();
  221373. }
  221374. double getSampleRate (int index)
  221375. {
  221376. return internal->sampleRates [index];
  221377. }
  221378. int getNumBufferSizesAvailable()
  221379. {
  221380. return 50;
  221381. }
  221382. int getBufferSizeSamples (int index)
  221383. {
  221384. int n = 16;
  221385. for (int i = 0; i < index; ++i)
  221386. n += n < 64 ? 16
  221387. : (n < 512 ? 32
  221388. : (n < 1024 ? 64
  221389. : (n < 2048 ? 128 : 256)));
  221390. return n;
  221391. }
  221392. int getDefaultBufferSize()
  221393. {
  221394. return 512;
  221395. }
  221396. const String open (const BigInteger& inputChannels,
  221397. const BigInteger& outputChannels,
  221398. double sampleRate,
  221399. int bufferSizeSamples)
  221400. {
  221401. close();
  221402. if (bufferSizeSamples <= 0)
  221403. bufferSizeSamples = getDefaultBufferSize();
  221404. if (sampleRate <= 0)
  221405. {
  221406. for (int i = 0; i < getNumSampleRates(); ++i)
  221407. {
  221408. if (getSampleRate (i) >= 44100)
  221409. {
  221410. sampleRate = getSampleRate (i);
  221411. break;
  221412. }
  221413. }
  221414. }
  221415. internal->open (inputChannels, outputChannels,
  221416. sampleRate, bufferSizeSamples);
  221417. isOpen_ = internal->error.isEmpty();
  221418. return internal->error;
  221419. }
  221420. void close()
  221421. {
  221422. stop();
  221423. internal->close();
  221424. isOpen_ = false;
  221425. }
  221426. bool isOpen()
  221427. {
  221428. return isOpen_;
  221429. }
  221430. int getCurrentBufferSizeSamples()
  221431. {
  221432. return internal->bufferSize;
  221433. }
  221434. double getCurrentSampleRate()
  221435. {
  221436. return internal->sampleRate;
  221437. }
  221438. int getCurrentBitDepth()
  221439. {
  221440. return internal->getBitDepth();
  221441. }
  221442. const BigInteger getActiveOutputChannels() const
  221443. {
  221444. return internal->currentOutputChans;
  221445. }
  221446. const BigInteger getActiveInputChannels() const
  221447. {
  221448. return internal->currentInputChans;
  221449. }
  221450. int getOutputLatencyInSamples()
  221451. {
  221452. return 0;
  221453. }
  221454. int getInputLatencyInSamples()
  221455. {
  221456. return 0;
  221457. }
  221458. void start (AudioIODeviceCallback* callback)
  221459. {
  221460. if (! isOpen_)
  221461. callback = 0;
  221462. internal->setCallback (callback);
  221463. if (callback != 0)
  221464. callback->audioDeviceAboutToStart (this);
  221465. isStarted = (callback != 0);
  221466. }
  221467. void stop()
  221468. {
  221469. AudioIODeviceCallback* const oldCallback = internal->callback;
  221470. start (0);
  221471. if (oldCallback != 0)
  221472. oldCallback->audioDeviceStopped();
  221473. }
  221474. bool isPlaying()
  221475. {
  221476. return isStarted && internal->error.isEmpty();
  221477. }
  221478. const String getLastError()
  221479. {
  221480. return internal->error;
  221481. }
  221482. String inputId, outputId;
  221483. private:
  221484. bool isOpen_, isStarted;
  221485. ScopedPointer<ALSAThread> internal;
  221486. };
  221487. class ALSAAudioIODeviceType : public AudioIODeviceType
  221488. {
  221489. public:
  221490. ALSAAudioIODeviceType()
  221491. : AudioIODeviceType ("ALSA"),
  221492. hasScanned (false)
  221493. {
  221494. }
  221495. ~ALSAAudioIODeviceType()
  221496. {
  221497. }
  221498. void scanForDevices()
  221499. {
  221500. if (hasScanned)
  221501. return;
  221502. hasScanned = true;
  221503. inputNames.clear();
  221504. inputIds.clear();
  221505. outputNames.clear();
  221506. outputIds.clear();
  221507. snd_ctl_t* handle;
  221508. snd_ctl_card_info_t* info;
  221509. snd_ctl_card_info_alloca (&info);
  221510. int cardNum = -1;
  221511. while (outputIds.size() + inputIds.size() <= 32)
  221512. {
  221513. snd_card_next (&cardNum);
  221514. if (cardNum < 0)
  221515. break;
  221516. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221517. {
  221518. if (snd_ctl_card_info (handle, info) >= 0)
  221519. {
  221520. String cardId (snd_ctl_card_info_get_id (info));
  221521. if (cardId.removeCharacters ("0123456789").isEmpty())
  221522. cardId = String (cardNum);
  221523. int device = -1;
  221524. for (;;)
  221525. {
  221526. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221527. break;
  221528. String id, name;
  221529. id << "hw:" << cardId << ',' << device;
  221530. bool isInput, isOutput;
  221531. if (testDevice (id, isInput, isOutput))
  221532. {
  221533. name << snd_ctl_card_info_get_name (info);
  221534. if (name.isEmpty())
  221535. name = id;
  221536. if (isInput)
  221537. {
  221538. inputNames.add (name);
  221539. inputIds.add (id);
  221540. }
  221541. if (isOutput)
  221542. {
  221543. outputNames.add (name);
  221544. outputIds.add (id);
  221545. }
  221546. }
  221547. }
  221548. }
  221549. snd_ctl_close (handle);
  221550. }
  221551. }
  221552. inputNames.appendNumbersToDuplicates (false, true);
  221553. outputNames.appendNumbersToDuplicates (false, true);
  221554. }
  221555. const StringArray getDeviceNames (bool wantInputNames) const
  221556. {
  221557. jassert (hasScanned); // need to call scanForDevices() before doing this
  221558. return wantInputNames ? inputNames : outputNames;
  221559. }
  221560. int getDefaultDeviceIndex (bool forInput) const
  221561. {
  221562. jassert (hasScanned); // need to call scanForDevices() before doing this
  221563. return 0;
  221564. }
  221565. bool hasSeparateInputsAndOutputs() const { return true; }
  221566. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221567. {
  221568. jassert (hasScanned); // need to call scanForDevices() before doing this
  221569. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221570. if (d == 0)
  221571. return -1;
  221572. return asInput ? inputIds.indexOf (d->inputId)
  221573. : outputIds.indexOf (d->outputId);
  221574. }
  221575. AudioIODevice* createDevice (const String& outputDeviceName,
  221576. const String& inputDeviceName)
  221577. {
  221578. jassert (hasScanned); // need to call scanForDevices() before doing this
  221579. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221580. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221581. String deviceName (outputIndex >= 0 ? outputDeviceName
  221582. : inputDeviceName);
  221583. if (inputIndex >= 0 || outputIndex >= 0)
  221584. return new ALSAAudioIODevice (deviceName,
  221585. inputIds [inputIndex],
  221586. outputIds [outputIndex]);
  221587. return 0;
  221588. }
  221589. juce_UseDebuggingNewOperator
  221590. private:
  221591. StringArray inputNames, outputNames, inputIds, outputIds;
  221592. bool hasScanned;
  221593. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221594. {
  221595. unsigned int minChansOut = 0, maxChansOut = 0;
  221596. unsigned int minChansIn = 0, maxChansIn = 0;
  221597. Array <int> rates;
  221598. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221599. DBG ("ALSA device: " + id
  221600. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221601. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221602. + " rates=" + String (rates.size()));
  221603. isInput = maxChansIn > 0;
  221604. isOutput = maxChansOut > 0;
  221605. return (isInput || isOutput) && rates.size() > 0;
  221606. }
  221607. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221608. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221609. };
  221610. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221611. {
  221612. return new ALSAAudioIODeviceType();
  221613. }
  221614. #endif
  221615. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221616. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221617. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221618. // compiled on its own).
  221619. #ifdef JUCE_INCLUDED_FILE
  221620. #if JUCE_JACK
  221621. static void* juce_libjack_handle = 0;
  221622. void* juce_load_jack_function (const char* const name)
  221623. {
  221624. if (juce_libjack_handle == 0)
  221625. return 0;
  221626. return dlsym (juce_libjack_handle, name);
  221627. }
  221628. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221629. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221630. return_type fn_name argument_types { \
  221631. static fn_name##_ptr_t fn = 0; \
  221632. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221633. if (fn) return (*fn)arguments; \
  221634. else return 0; \
  221635. }
  221636. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221637. typedef void (*fn_name##_ptr_t)argument_types; \
  221638. void fn_name argument_types { \
  221639. static fn_name##_ptr_t fn = 0; \
  221640. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221641. if (fn) (*fn)arguments; \
  221642. }
  221643. 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));
  221644. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221645. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221646. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221647. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221648. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221649. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221650. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221651. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221652. 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));
  221653. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221654. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221655. 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));
  221656. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221657. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221658. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221659. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221660. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221661. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221662. #if JUCE_DEBUG
  221663. #define JACK_LOGGING_ENABLED 1
  221664. #endif
  221665. #if JACK_LOGGING_ENABLED
  221666. static void jack_Log (const String& s)
  221667. {
  221668. std::cerr << s << std::endl;
  221669. }
  221670. static void dumpJackErrorMessage (const jack_status_t status)
  221671. {
  221672. if (status & JackServerFailed || status & JackServerError)
  221673. jack_Log ("Unable to connect to JACK server");
  221674. if (status & JackVersionError)
  221675. jack_Log ("Client's protocol version does not match");
  221676. if (status & JackInvalidOption)
  221677. jack_Log ("The operation contained an invalid or unsupported option");
  221678. if (status & JackNameNotUnique)
  221679. jack_Log ("The desired client name was not unique");
  221680. if (status & JackNoSuchClient)
  221681. jack_Log ("Requested client does not exist");
  221682. if (status & JackInitFailure)
  221683. jack_Log ("Unable to initialize client");
  221684. }
  221685. #else
  221686. #define dumpJackErrorMessage(a) {}
  221687. #define jack_Log(...) {}
  221688. #endif
  221689. #ifndef JUCE_JACK_CLIENT_NAME
  221690. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221691. #endif
  221692. class JackAudioIODevice : public AudioIODevice
  221693. {
  221694. public:
  221695. JackAudioIODevice (const String& deviceName,
  221696. const String& inputId_,
  221697. const String& outputId_)
  221698. : AudioIODevice (deviceName, "JACK"),
  221699. inputId (inputId_),
  221700. outputId (outputId_),
  221701. isOpen_ (false),
  221702. callback (0),
  221703. totalNumberOfInputChannels (0),
  221704. totalNumberOfOutputChannels (0)
  221705. {
  221706. jassert (deviceName.isNotEmpty());
  221707. jack_status_t status;
  221708. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221709. if (client == 0)
  221710. {
  221711. dumpJackErrorMessage (status);
  221712. }
  221713. else
  221714. {
  221715. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221716. // open input ports
  221717. const StringArray inputChannels (getInputChannelNames());
  221718. for (int i = 0; i < inputChannels.size(); i++)
  221719. {
  221720. String inputName;
  221721. inputName << "in_" << ++totalNumberOfInputChannels;
  221722. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221723. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221724. }
  221725. // open output ports
  221726. const StringArray outputChannels (getOutputChannelNames());
  221727. for (int i = 0; i < outputChannels.size (); i++)
  221728. {
  221729. String outputName;
  221730. outputName << "out_" << ++totalNumberOfOutputChannels;
  221731. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221732. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221733. }
  221734. inChans.calloc (totalNumberOfInputChannels + 2);
  221735. outChans.calloc (totalNumberOfOutputChannels + 2);
  221736. }
  221737. }
  221738. ~JackAudioIODevice()
  221739. {
  221740. close();
  221741. if (client != 0)
  221742. {
  221743. JUCE_NAMESPACE::jack_client_close (client);
  221744. client = 0;
  221745. }
  221746. }
  221747. const StringArray getChannelNames (bool forInput) const
  221748. {
  221749. StringArray names;
  221750. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221751. forInput ? JackPortIsInput : JackPortIsOutput);
  221752. if (ports != 0)
  221753. {
  221754. int j = 0;
  221755. while (ports[j] != 0)
  221756. {
  221757. const String portName (ports [j++]);
  221758. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221759. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221760. }
  221761. free (ports);
  221762. }
  221763. return names;
  221764. }
  221765. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221766. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221767. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221768. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221769. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221770. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221771. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221772. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221773. double sampleRate, int bufferSizeSamples)
  221774. {
  221775. if (client == 0)
  221776. {
  221777. lastError = "No JACK client running";
  221778. return lastError;
  221779. }
  221780. lastError = String::empty;
  221781. close();
  221782. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221783. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221784. JUCE_NAMESPACE::jack_activate (client);
  221785. isOpen_ = true;
  221786. if (! inputChannels.isZero())
  221787. {
  221788. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221789. if (ports != 0)
  221790. {
  221791. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221792. for (int i = 0; i < numInputChannels; ++i)
  221793. {
  221794. const String portName (ports[i]);
  221795. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221796. {
  221797. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221798. if (error != 0)
  221799. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221800. }
  221801. }
  221802. free (ports);
  221803. }
  221804. }
  221805. if (! outputChannels.isZero())
  221806. {
  221807. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221808. if (ports != 0)
  221809. {
  221810. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  221811. for (int i = 0; i < numOutputChannels; ++i)
  221812. {
  221813. const String portName (ports[i]);
  221814. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221815. {
  221816. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  221817. if (error != 0)
  221818. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221819. }
  221820. }
  221821. free (ports);
  221822. }
  221823. }
  221824. return lastError;
  221825. }
  221826. void close()
  221827. {
  221828. stop();
  221829. if (client != 0)
  221830. {
  221831. JUCE_NAMESPACE::jack_deactivate (client);
  221832. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  221833. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  221834. }
  221835. isOpen_ = false;
  221836. }
  221837. void start (AudioIODeviceCallback* newCallback)
  221838. {
  221839. if (isOpen_ && newCallback != callback)
  221840. {
  221841. if (newCallback != 0)
  221842. newCallback->audioDeviceAboutToStart (this);
  221843. AudioIODeviceCallback* const oldCallback = callback;
  221844. {
  221845. const ScopedLock sl (callbackLock);
  221846. callback = newCallback;
  221847. }
  221848. if (oldCallback != 0)
  221849. oldCallback->audioDeviceStopped();
  221850. }
  221851. }
  221852. void stop()
  221853. {
  221854. start (0);
  221855. }
  221856. bool isOpen() { return isOpen_; }
  221857. bool isPlaying() { return callback != 0; }
  221858. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  221859. double getCurrentSampleRate() { return getSampleRate (0); }
  221860. int getCurrentBitDepth() { return 32; }
  221861. const String getLastError() { return lastError; }
  221862. const BigInteger getActiveOutputChannels() const
  221863. {
  221864. BigInteger outputBits;
  221865. for (int i = 0; i < outputPorts.size(); i++)
  221866. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  221867. outputBits.setBit (i);
  221868. return outputBits;
  221869. }
  221870. const BigInteger getActiveInputChannels() const
  221871. {
  221872. BigInteger inputBits;
  221873. for (int i = 0; i < inputPorts.size(); i++)
  221874. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  221875. inputBits.setBit (i);
  221876. return inputBits;
  221877. }
  221878. int getOutputLatencyInSamples()
  221879. {
  221880. int latency = 0;
  221881. for (int i = 0; i < outputPorts.size(); i++)
  221882. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  221883. return latency;
  221884. }
  221885. int getInputLatencyInSamples()
  221886. {
  221887. int latency = 0;
  221888. for (int i = 0; i < inputPorts.size(); i++)
  221889. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  221890. return latency;
  221891. }
  221892. String inputId, outputId;
  221893. private:
  221894. void process (const int numSamples)
  221895. {
  221896. int i, numActiveInChans = 0, numActiveOutChans = 0;
  221897. for (i = 0; i < totalNumberOfInputChannels; ++i)
  221898. {
  221899. jack_default_audio_sample_t* in
  221900. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  221901. if (in != 0)
  221902. inChans [numActiveInChans++] = (float*) in;
  221903. }
  221904. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  221905. {
  221906. jack_default_audio_sample_t* out
  221907. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  221908. if (out != 0)
  221909. outChans [numActiveOutChans++] = (float*) out;
  221910. }
  221911. const ScopedLock sl (callbackLock);
  221912. if (callback != 0)
  221913. {
  221914. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  221915. outChans, numActiveOutChans, numSamples);
  221916. }
  221917. else
  221918. {
  221919. for (i = 0; i < numActiveOutChans; ++i)
  221920. zeromem (outChans[i], sizeof (float) * numSamples);
  221921. }
  221922. }
  221923. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  221924. {
  221925. if (callbackArgument != 0)
  221926. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  221927. return 0;
  221928. }
  221929. static void threadInitCallback (void* callbackArgument)
  221930. {
  221931. jack_Log ("JackAudioIODevice::initialise");
  221932. }
  221933. static void shutdownCallback (void* callbackArgument)
  221934. {
  221935. jack_Log ("JackAudioIODevice::shutdown");
  221936. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  221937. if (device != 0)
  221938. {
  221939. device->client = 0;
  221940. device->close();
  221941. }
  221942. }
  221943. static void errorCallback (const char* msg)
  221944. {
  221945. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  221946. }
  221947. bool isOpen_;
  221948. jack_client_t* client;
  221949. String lastError;
  221950. AudioIODeviceCallback* callback;
  221951. CriticalSection callbackLock;
  221952. HeapBlock <float*> inChans, outChans;
  221953. int totalNumberOfInputChannels;
  221954. int totalNumberOfOutputChannels;
  221955. Array<void*> inputPorts, outputPorts;
  221956. };
  221957. class JackAudioIODeviceType : public AudioIODeviceType
  221958. {
  221959. public:
  221960. JackAudioIODeviceType()
  221961. : AudioIODeviceType ("JACK"),
  221962. hasScanned (false)
  221963. {
  221964. }
  221965. ~JackAudioIODeviceType()
  221966. {
  221967. }
  221968. void scanForDevices()
  221969. {
  221970. hasScanned = true;
  221971. inputNames.clear();
  221972. inputIds.clear();
  221973. outputNames.clear();
  221974. outputIds.clear();
  221975. if (juce_libjack_handle == 0)
  221976. {
  221977. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  221978. if (juce_libjack_handle == 0)
  221979. return;
  221980. }
  221981. // open a dummy client
  221982. jack_status_t status;
  221983. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  221984. if (client == 0)
  221985. {
  221986. dumpJackErrorMessage (status);
  221987. }
  221988. else
  221989. {
  221990. // scan for output devices
  221991. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221992. if (ports != 0)
  221993. {
  221994. int j = 0;
  221995. while (ports[j] != 0)
  221996. {
  221997. String clientName (ports[j]);
  221998. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221999. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222000. && ! inputNames.contains (clientName))
  222001. {
  222002. inputNames.add (clientName);
  222003. inputIds.add (ports [j]);
  222004. }
  222005. ++j;
  222006. }
  222007. free (ports);
  222008. }
  222009. // scan for input devices
  222010. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222011. if (ports != 0)
  222012. {
  222013. int j = 0;
  222014. while (ports[j] != 0)
  222015. {
  222016. String clientName (ports[j]);
  222017. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222018. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222019. && ! outputNames.contains (clientName))
  222020. {
  222021. outputNames.add (clientName);
  222022. outputIds.add (ports [j]);
  222023. }
  222024. ++j;
  222025. }
  222026. free (ports);
  222027. }
  222028. JUCE_NAMESPACE::jack_client_close (client);
  222029. }
  222030. }
  222031. const StringArray getDeviceNames (bool wantInputNames) const
  222032. {
  222033. jassert (hasScanned); // need to call scanForDevices() before doing this
  222034. return wantInputNames ? inputNames : outputNames;
  222035. }
  222036. int getDefaultDeviceIndex (bool forInput) const
  222037. {
  222038. jassert (hasScanned); // need to call scanForDevices() before doing this
  222039. return 0;
  222040. }
  222041. bool hasSeparateInputsAndOutputs() const { return true; }
  222042. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222043. {
  222044. jassert (hasScanned); // need to call scanForDevices() before doing this
  222045. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222046. if (d == 0)
  222047. return -1;
  222048. return asInput ? inputIds.indexOf (d->inputId)
  222049. : outputIds.indexOf (d->outputId);
  222050. }
  222051. AudioIODevice* createDevice (const String& outputDeviceName,
  222052. const String& inputDeviceName)
  222053. {
  222054. jassert (hasScanned); // need to call scanForDevices() before doing this
  222055. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222056. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222057. if (inputIndex >= 0 || outputIndex >= 0)
  222058. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222059. : inputDeviceName,
  222060. inputIds [inputIndex],
  222061. outputIds [outputIndex]);
  222062. return 0;
  222063. }
  222064. juce_UseDebuggingNewOperator
  222065. private:
  222066. StringArray inputNames, outputNames, inputIds, outputIds;
  222067. bool hasScanned;
  222068. JackAudioIODeviceType (const JackAudioIODeviceType&);
  222069. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  222070. };
  222071. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222072. {
  222073. return new JackAudioIODeviceType();
  222074. }
  222075. #else // if JACK is turned off..
  222076. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222077. #endif
  222078. #endif
  222079. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222080. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222081. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222082. // compiled on its own).
  222083. #if JUCE_INCLUDED_FILE
  222084. #if JUCE_ALSA
  222085. static snd_seq_t* iterateDevices (const bool forInput,
  222086. StringArray& deviceNamesFound,
  222087. const int deviceIndexToOpen)
  222088. {
  222089. snd_seq_t* returnedHandle = 0;
  222090. snd_seq_t* seqHandle;
  222091. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222092. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222093. {
  222094. snd_seq_system_info_t* systemInfo;
  222095. snd_seq_client_info_t* clientInfo;
  222096. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222097. {
  222098. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222099. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222100. {
  222101. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222102. while (--numClients >= 0 && returnedHandle == 0)
  222103. {
  222104. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222105. {
  222106. snd_seq_port_info_t* portInfo;
  222107. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222108. {
  222109. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222110. const int client = snd_seq_client_info_get_client (clientInfo);
  222111. snd_seq_port_info_set_client (portInfo, client);
  222112. snd_seq_port_info_set_port (portInfo, -1);
  222113. while (--numPorts >= 0)
  222114. {
  222115. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222116. && (snd_seq_port_info_get_capability (portInfo)
  222117. & (forInput ? SND_SEQ_PORT_CAP_READ
  222118. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222119. {
  222120. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222121. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222122. {
  222123. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222124. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222125. if (sourcePort != -1)
  222126. {
  222127. snd_seq_set_client_name (seqHandle,
  222128. forInput ? "Juce Midi Input"
  222129. : "Juce Midi Output");
  222130. const int portId
  222131. = snd_seq_create_simple_port (seqHandle,
  222132. forInput ? "Juce Midi In Port"
  222133. : "Juce Midi Out Port",
  222134. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222135. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222136. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222137. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222138. returnedHandle = seqHandle;
  222139. }
  222140. }
  222141. }
  222142. }
  222143. snd_seq_port_info_free (portInfo);
  222144. }
  222145. }
  222146. }
  222147. snd_seq_client_info_free (clientInfo);
  222148. }
  222149. snd_seq_system_info_free (systemInfo);
  222150. }
  222151. if (returnedHandle == 0)
  222152. snd_seq_close (seqHandle);
  222153. }
  222154. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222155. return returnedHandle;
  222156. }
  222157. static snd_seq_t* createDevice (const bool forInput,
  222158. const String& deviceNameToOpen)
  222159. {
  222160. snd_seq_t* seqHandle = 0;
  222161. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222162. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222163. {
  222164. snd_seq_set_client_name (seqHandle,
  222165. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222166. const int portId
  222167. = snd_seq_create_simple_port (seqHandle,
  222168. forInput ? "in"
  222169. : "out",
  222170. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222171. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222172. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222173. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222174. if (portId < 0)
  222175. {
  222176. snd_seq_close (seqHandle);
  222177. seqHandle = 0;
  222178. }
  222179. }
  222180. return seqHandle;
  222181. }
  222182. class MidiOutputDevice
  222183. {
  222184. public:
  222185. MidiOutputDevice (MidiOutput* const midiOutput_,
  222186. snd_seq_t* const seqHandle_)
  222187. :
  222188. midiOutput (midiOutput_),
  222189. seqHandle (seqHandle_),
  222190. maxEventSize (16 * 1024)
  222191. {
  222192. jassert (seqHandle != 0 && midiOutput != 0);
  222193. snd_midi_event_new (maxEventSize, &midiParser);
  222194. }
  222195. ~MidiOutputDevice()
  222196. {
  222197. snd_midi_event_free (midiParser);
  222198. snd_seq_close (seqHandle);
  222199. }
  222200. void sendMessageNow (const MidiMessage& message)
  222201. {
  222202. if (message.getRawDataSize() > maxEventSize)
  222203. {
  222204. maxEventSize = message.getRawDataSize();
  222205. snd_midi_event_free (midiParser);
  222206. snd_midi_event_new (maxEventSize, &midiParser);
  222207. }
  222208. snd_seq_event_t event;
  222209. snd_seq_ev_clear (&event);
  222210. snd_midi_event_encode (midiParser,
  222211. message.getRawData(),
  222212. message.getRawDataSize(),
  222213. &event);
  222214. snd_midi_event_reset_encode (midiParser);
  222215. snd_seq_ev_set_source (&event, 0);
  222216. snd_seq_ev_set_subs (&event);
  222217. snd_seq_ev_set_direct (&event);
  222218. snd_seq_event_output (seqHandle, &event);
  222219. snd_seq_drain_output (seqHandle);
  222220. }
  222221. juce_UseDebuggingNewOperator
  222222. private:
  222223. MidiOutput* const midiOutput;
  222224. snd_seq_t* const seqHandle;
  222225. snd_midi_event_t* midiParser;
  222226. int maxEventSize;
  222227. };
  222228. const StringArray MidiOutput::getDevices()
  222229. {
  222230. StringArray devices;
  222231. iterateDevices (false, devices, -1);
  222232. return devices;
  222233. }
  222234. int MidiOutput::getDefaultDeviceIndex()
  222235. {
  222236. return 0;
  222237. }
  222238. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222239. {
  222240. MidiOutput* newDevice = 0;
  222241. StringArray devices;
  222242. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222243. if (handle != 0)
  222244. {
  222245. newDevice = new MidiOutput();
  222246. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222247. }
  222248. return newDevice;
  222249. }
  222250. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222251. {
  222252. MidiOutput* newDevice = 0;
  222253. snd_seq_t* const handle = createDevice (false, deviceName);
  222254. if (handle != 0)
  222255. {
  222256. newDevice = new MidiOutput();
  222257. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222258. }
  222259. return newDevice;
  222260. }
  222261. MidiOutput::~MidiOutput()
  222262. {
  222263. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222264. delete device;
  222265. }
  222266. void MidiOutput::reset()
  222267. {
  222268. }
  222269. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222270. {
  222271. return false;
  222272. }
  222273. void MidiOutput::setVolume (float leftVol, float rightVol)
  222274. {
  222275. }
  222276. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222277. {
  222278. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222279. }
  222280. class MidiInputThread : public Thread
  222281. {
  222282. public:
  222283. MidiInputThread (MidiInput* const midiInput_,
  222284. snd_seq_t* const seqHandle_,
  222285. MidiInputCallback* const callback_)
  222286. : Thread ("Juce MIDI Input"),
  222287. midiInput (midiInput_),
  222288. seqHandle (seqHandle_),
  222289. callback (callback_)
  222290. {
  222291. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222292. }
  222293. ~MidiInputThread()
  222294. {
  222295. snd_seq_close (seqHandle);
  222296. }
  222297. void run()
  222298. {
  222299. const int maxEventSize = 16 * 1024;
  222300. snd_midi_event_t* midiParser;
  222301. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222302. {
  222303. HeapBlock <uint8> buffer (maxEventSize);
  222304. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222305. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222306. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222307. while (! threadShouldExit())
  222308. {
  222309. if (poll (pfd, numPfds, 500) > 0)
  222310. {
  222311. snd_seq_event_t* inputEvent = 0;
  222312. snd_seq_nonblock (seqHandle, 1);
  222313. do
  222314. {
  222315. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222316. {
  222317. // xxx what about SYSEXes that are too big for the buffer?
  222318. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222319. snd_midi_event_reset_decode (midiParser);
  222320. if (numBytes > 0)
  222321. {
  222322. const MidiMessage message ((const uint8*) buffer,
  222323. numBytes,
  222324. Time::getMillisecondCounter() * 0.001);
  222325. callback->handleIncomingMidiMessage (midiInput, message);
  222326. }
  222327. snd_seq_free_event (inputEvent);
  222328. }
  222329. }
  222330. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222331. snd_seq_free_event (inputEvent);
  222332. }
  222333. }
  222334. snd_midi_event_free (midiParser);
  222335. }
  222336. };
  222337. juce_UseDebuggingNewOperator
  222338. private:
  222339. MidiInput* const midiInput;
  222340. snd_seq_t* const seqHandle;
  222341. MidiInputCallback* const callback;
  222342. };
  222343. MidiInput::MidiInput (const String& name_)
  222344. : name (name_),
  222345. internal (0)
  222346. {
  222347. }
  222348. MidiInput::~MidiInput()
  222349. {
  222350. stop();
  222351. MidiInputThread* const thread = (MidiInputThread*) internal;
  222352. delete thread;
  222353. }
  222354. void MidiInput::start()
  222355. {
  222356. ((MidiInputThread*) internal)->startThread();
  222357. }
  222358. void MidiInput::stop()
  222359. {
  222360. ((MidiInputThread*) internal)->stopThread (3000);
  222361. }
  222362. int MidiInput::getDefaultDeviceIndex()
  222363. {
  222364. return 0;
  222365. }
  222366. const StringArray MidiInput::getDevices()
  222367. {
  222368. StringArray devices;
  222369. iterateDevices (true, devices, -1);
  222370. return devices;
  222371. }
  222372. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222373. {
  222374. MidiInput* newDevice = 0;
  222375. StringArray devices;
  222376. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222377. if (handle != 0)
  222378. {
  222379. newDevice = new MidiInput (devices [deviceIndex]);
  222380. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222381. }
  222382. return newDevice;
  222383. }
  222384. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222385. {
  222386. MidiInput* newDevice = 0;
  222387. snd_seq_t* const handle = createDevice (true, deviceName);
  222388. if (handle != 0)
  222389. {
  222390. newDevice = new MidiInput (deviceName);
  222391. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222392. }
  222393. return newDevice;
  222394. }
  222395. #else
  222396. // (These are just stub functions if ALSA is unavailable...)
  222397. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222398. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222399. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222400. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222401. MidiOutput::~MidiOutput() {}
  222402. void MidiOutput::reset() {}
  222403. bool MidiOutput::getVolume (float&, float&) { return false; }
  222404. void MidiOutput::setVolume (float, float) {}
  222405. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222406. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222407. MidiInput::~MidiInput() {}
  222408. void MidiInput::start() {}
  222409. void MidiInput::stop() {}
  222410. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222411. const StringArray MidiInput::getDevices() { return StringArray(); }
  222412. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222413. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222414. #endif
  222415. #endif
  222416. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222417. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222418. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222419. // compiled on its own).
  222420. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222421. AudioCDReader::AudioCDReader()
  222422. : AudioFormatReader (0, "CD Audio")
  222423. {
  222424. }
  222425. const StringArray AudioCDReader::getAvailableCDNames()
  222426. {
  222427. StringArray names;
  222428. return names;
  222429. }
  222430. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222431. {
  222432. return 0;
  222433. }
  222434. AudioCDReader::~AudioCDReader()
  222435. {
  222436. }
  222437. void AudioCDReader::refreshTrackLengths()
  222438. {
  222439. }
  222440. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222441. int64 startSampleInFile, int numSamples)
  222442. {
  222443. return false;
  222444. }
  222445. bool AudioCDReader::isCDStillPresent() const
  222446. {
  222447. return false;
  222448. }
  222449. int AudioCDReader::getNumTracks() const
  222450. {
  222451. return 0;
  222452. }
  222453. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222454. {
  222455. return 0;
  222456. }
  222457. bool AudioCDReader::isTrackAudio (int trackNum) const
  222458. {
  222459. return false;
  222460. }
  222461. void AudioCDReader::enableIndexScanning (bool b)
  222462. {
  222463. }
  222464. int AudioCDReader::getLastIndex() const
  222465. {
  222466. return 0;
  222467. }
  222468. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222469. {
  222470. return Array<int>();
  222471. }
  222472. int AudioCDReader::getCDDBId()
  222473. {
  222474. return 0;
  222475. }
  222476. #endif
  222477. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222478. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222479. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222480. // compiled on its own).
  222481. #if JUCE_INCLUDED_FILE
  222482. void FileChooser::showPlatformDialog (Array<File>& results,
  222483. const String& title,
  222484. const File& file,
  222485. const String& filters,
  222486. bool isDirectory,
  222487. bool selectsFiles,
  222488. bool isSave,
  222489. bool warnAboutOverwritingExistingFiles,
  222490. bool selectMultipleFiles,
  222491. FilePreviewComponent* previewComponent)
  222492. {
  222493. const String separator (":");
  222494. String command ("zenity --file-selection");
  222495. if (title.isNotEmpty())
  222496. command << " --title=\"" << title << "\"";
  222497. if (file != File::nonexistent)
  222498. command << " --filename=\"" << file.getFullPathName () << "\"";
  222499. if (isDirectory)
  222500. command << " --directory";
  222501. if (isSave)
  222502. command << " --save";
  222503. if (selectMultipleFiles)
  222504. command << " --multiple --separator=\"" << separator << "\"";
  222505. command << " 2>&1";
  222506. MemoryOutputStream result;
  222507. int status = -1;
  222508. FILE* stream = popen (command.toUTF8(), "r");
  222509. if (stream != 0)
  222510. {
  222511. for (;;)
  222512. {
  222513. char buffer [1024];
  222514. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222515. if (bytesRead <= 0)
  222516. break;
  222517. result.write (buffer, bytesRead);
  222518. }
  222519. status = pclose (stream);
  222520. }
  222521. if (status == 0)
  222522. {
  222523. StringArray tokens;
  222524. if (selectMultipleFiles)
  222525. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222526. else
  222527. tokens.add (result.toUTF8());
  222528. for (int i = 0; i < tokens.size(); i++)
  222529. results.add (File (tokens[i]));
  222530. return;
  222531. }
  222532. //xxx ain't got one!
  222533. jassertfalse;
  222534. }
  222535. #endif
  222536. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222537. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222538. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222539. // compiled on its own).
  222540. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222541. /*
  222542. Sorry.. This class isn't implemented on Linux!
  222543. */
  222544. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222545. : browser (0),
  222546. blankPageShown (false),
  222547. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222548. {
  222549. setOpaque (true);
  222550. }
  222551. WebBrowserComponent::~WebBrowserComponent()
  222552. {
  222553. }
  222554. void WebBrowserComponent::goToURL (const String& url,
  222555. const StringArray* headers,
  222556. const MemoryBlock* postData)
  222557. {
  222558. lastURL = url;
  222559. lastHeaders.clear();
  222560. if (headers != 0)
  222561. lastHeaders = *headers;
  222562. lastPostData.setSize (0);
  222563. if (postData != 0)
  222564. lastPostData = *postData;
  222565. blankPageShown = false;
  222566. }
  222567. void WebBrowserComponent::stop()
  222568. {
  222569. }
  222570. void WebBrowserComponent::goBack()
  222571. {
  222572. lastURL = String::empty;
  222573. blankPageShown = false;
  222574. }
  222575. void WebBrowserComponent::goForward()
  222576. {
  222577. lastURL = String::empty;
  222578. }
  222579. void WebBrowserComponent::refresh()
  222580. {
  222581. }
  222582. void WebBrowserComponent::paint (Graphics& g)
  222583. {
  222584. g.fillAll (Colours::white);
  222585. }
  222586. void WebBrowserComponent::checkWindowAssociation()
  222587. {
  222588. }
  222589. void WebBrowserComponent::reloadLastURL()
  222590. {
  222591. if (lastURL.isNotEmpty())
  222592. {
  222593. goToURL (lastURL, &lastHeaders, &lastPostData);
  222594. lastURL = String::empty;
  222595. }
  222596. }
  222597. void WebBrowserComponent::parentHierarchyChanged()
  222598. {
  222599. checkWindowAssociation();
  222600. }
  222601. void WebBrowserComponent::resized()
  222602. {
  222603. }
  222604. void WebBrowserComponent::visibilityChanged()
  222605. {
  222606. checkWindowAssociation();
  222607. }
  222608. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222609. {
  222610. return true;
  222611. }
  222612. #endif
  222613. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222614. #endif
  222615. END_JUCE_NAMESPACE
  222616. #endif
  222617. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222618. #endif
  222619. #if JUCE_MAC || JUCE_IPHONE
  222620. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222621. /*
  222622. This file wraps together all the mac-specific code, so that
  222623. we can include all the native headers just once, and compile all our
  222624. platform-specific stuff in one big lump, keeping it out of the way of
  222625. the rest of the codebase.
  222626. */
  222627. #if JUCE_MAC || JUCE_IPHONE
  222628. BEGIN_JUCE_NAMESPACE
  222629. #undef Point
  222630. #define JUCE_INCLUDED_FILE 1
  222631. // Now include the actual code files..
  222632. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222633. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222634. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222635. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222636. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222637. actually calling into a similarly named class in the other module's address space.
  222638. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222639. have unique names, and should avoid this problem.
  222640. If you're using the amalgamated version, you can just set this macro to something unique before
  222641. you include juce_amalgamated.cpp.
  222642. */
  222643. #ifndef JUCE_ObjCExtraSuffix
  222644. #define JUCE_ObjCExtraSuffix 3
  222645. #endif
  222646. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222647. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222648. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222649. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222650. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222651. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222652. // compiled on its own).
  222653. #if JUCE_INCLUDED_FILE
  222654. static const String nsStringToJuce (NSString* s)
  222655. {
  222656. return String::fromUTF8 ([s UTF8String]);
  222657. }
  222658. static NSString* juceStringToNS (const String& s)
  222659. {
  222660. return [NSString stringWithUTF8String: s.toUTF8()];
  222661. }
  222662. static const String convertUTF16ToString (const UniChar* utf16)
  222663. {
  222664. String s;
  222665. while (*utf16 != 0)
  222666. s += (juce_wchar) *utf16++;
  222667. return s;
  222668. }
  222669. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222670. {
  222671. String result;
  222672. if (cfString != 0)
  222673. {
  222674. CFRange range = { 0, CFStringGetLength (cfString) };
  222675. HeapBlock <UniChar> u (range.length + 1);
  222676. CFStringGetCharacters (cfString, range, u);
  222677. u[range.length] = 0;
  222678. result = convertUTF16ToString (u);
  222679. }
  222680. return result;
  222681. }
  222682. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222683. {
  222684. const int len = s.length();
  222685. HeapBlock <UniChar> temp (len + 2);
  222686. for (int i = 0; i <= len; ++i)
  222687. temp[i] = s[i];
  222688. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222689. }
  222690. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222691. {
  222692. #if JUCE_IPHONE
  222693. const ScopedAutoReleasePool pool;
  222694. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222695. #else
  222696. UnicodeMapping map;
  222697. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222698. kUnicodeNoSubset,
  222699. kTextEncodingDefaultFormat);
  222700. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222701. kUnicodeCanonicalCompVariant,
  222702. kTextEncodingDefaultFormat);
  222703. map.mappingVersion = kUnicodeUseLatestMapping;
  222704. UnicodeToTextInfo conversionInfo = 0;
  222705. String result;
  222706. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222707. {
  222708. const int len = s.length();
  222709. HeapBlock <UniChar> tempIn, tempOut;
  222710. tempIn.calloc (len + 2);
  222711. tempOut.calloc (len + 2);
  222712. for (int i = 0; i <= len; ++i)
  222713. tempIn[i] = s[i];
  222714. ByteCount bytesRead = 0;
  222715. ByteCount outputBufferSize = 0;
  222716. if (ConvertFromUnicodeToText (conversionInfo,
  222717. len * sizeof (UniChar), tempIn,
  222718. kUnicodeDefaultDirectionMask,
  222719. 0, 0, 0, 0,
  222720. len * sizeof (UniChar), &bytesRead,
  222721. &outputBufferSize, tempOut) == noErr)
  222722. {
  222723. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222724. juce_wchar* t = result;
  222725. unsigned int i;
  222726. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222727. t[i] = (juce_wchar) tempOut[i];
  222728. t[i] = 0;
  222729. }
  222730. DisposeUnicodeToTextInfo (&conversionInfo);
  222731. }
  222732. return result;
  222733. #endif
  222734. }
  222735. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222736. void SystemClipboard::copyTextToClipboard (const String& text)
  222737. {
  222738. #if JUCE_IPHONE
  222739. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222740. forPasteboardType: @"public.text"];
  222741. #else
  222742. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222743. owner: nil];
  222744. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222745. forType: NSStringPboardType];
  222746. #endif
  222747. }
  222748. const String SystemClipboard::getTextFromClipboard()
  222749. {
  222750. #if JUCE_IPHONE
  222751. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222752. #else
  222753. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222754. #endif
  222755. return text == 0 ? String::empty
  222756. : nsStringToJuce (text);
  222757. }
  222758. #endif
  222759. #endif
  222760. /*** End of inlined file: juce_mac_Strings.mm ***/
  222761. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222762. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222763. // compiled on its own).
  222764. #if JUCE_INCLUDED_FILE
  222765. namespace SystemStatsHelpers
  222766. {
  222767. static int64 highResTimerFrequency = 0;
  222768. static double highResTimerToMillisecRatio = 0;
  222769. #if JUCE_INTEL
  222770. static void juce_getCpuVendor (char* const v) throw()
  222771. {
  222772. int vendor[4];
  222773. zerostruct (vendor);
  222774. int dummy = 0;
  222775. asm ("mov %%ebx, %%esi \n\t"
  222776. "cpuid \n\t"
  222777. "xchg %%esi, %%ebx"
  222778. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222779. memcpy (v, vendor, 16);
  222780. }
  222781. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222782. {
  222783. unsigned int cpu = 0;
  222784. unsigned int ext = 0;
  222785. unsigned int family = 0;
  222786. unsigned int dummy = 0;
  222787. asm ("mov %%ebx, %%esi \n\t"
  222788. "cpuid \n\t"
  222789. "xchg %%esi, %%ebx"
  222790. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222791. familyModel = family;
  222792. extFeatures = ext;
  222793. return cpu;
  222794. }
  222795. #endif
  222796. }
  222797. void SystemStats::initialiseStats()
  222798. {
  222799. using namespace SystemStatsHelpers;
  222800. static bool initialised = false;
  222801. if (! initialised)
  222802. {
  222803. initialised = true;
  222804. #if JUCE_MAC
  222805. // extremely annoying: adding this line stops the apple menu items from working. Of
  222806. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  222807. // any events.
  222808. //NSApplicationLoad();
  222809. [NSApplication sharedApplication];
  222810. #endif
  222811. #if JUCE_INTEL
  222812. unsigned int familyModel, extFeatures;
  222813. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  222814. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  222815. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  222816. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  222817. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  222818. #else
  222819. cpuFlags.hasMMX = false;
  222820. cpuFlags.hasSSE = false;
  222821. cpuFlags.hasSSE2 = false;
  222822. cpuFlags.has3DNow = false;
  222823. #endif
  222824. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  222825. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  222826. #else
  222827. cpuFlags.numCpus = (int) MPProcessors();
  222828. #endif
  222829. mach_timebase_info_data_t timebase;
  222830. (void) mach_timebase_info (&timebase);
  222831. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  222832. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  222833. String s (SystemStats::getJUCEVersion());
  222834. rlimit lim;
  222835. getrlimit (RLIMIT_NOFILE, &lim);
  222836. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  222837. setrlimit (RLIMIT_NOFILE, &lim);
  222838. }
  222839. }
  222840. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  222841. {
  222842. return MacOSX;
  222843. }
  222844. const String SystemStats::getOperatingSystemName()
  222845. {
  222846. return "Mac OS X";
  222847. }
  222848. bool SystemStats::isOperatingSystem64Bit()
  222849. {
  222850. #if JUCE_64BIT
  222851. return true;
  222852. #else
  222853. //xxx not sure how to find this out?..
  222854. return false;
  222855. #endif
  222856. }
  222857. int SystemStats::getMemorySizeInMegabytes()
  222858. {
  222859. uint64 mem = 0;
  222860. size_t memSize = sizeof (mem);
  222861. int mib[] = { CTL_HW, HW_MEMSIZE };
  222862. sysctl (mib, 2, &mem, &memSize, 0, 0);
  222863. return (int) (mem / (1024 * 1024));
  222864. }
  222865. const String SystemStats::getCpuVendor()
  222866. {
  222867. #if JUCE_INTEL
  222868. char v [16];
  222869. SystemStatsHelpers::juce_getCpuVendor (v);
  222870. return String (v, 16);
  222871. #else
  222872. return String::empty;
  222873. #endif
  222874. }
  222875. int SystemStats::getCpuSpeedInMegaherz()
  222876. {
  222877. uint64 speedHz = 0;
  222878. size_t speedSize = sizeof (speedHz);
  222879. int mib[] = { CTL_HW, HW_CPU_FREQ };
  222880. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  222881. #if JUCE_BIG_ENDIAN
  222882. if (speedSize == 4)
  222883. speedHz >>= 32;
  222884. #endif
  222885. return (int) (speedHz / 1000000);
  222886. }
  222887. const String SystemStats::getLogonName()
  222888. {
  222889. return nsStringToJuce (NSUserName());
  222890. }
  222891. const String SystemStats::getFullUserName()
  222892. {
  222893. return nsStringToJuce (NSFullUserName());
  222894. }
  222895. uint32 juce_millisecondsSinceStartup() throw()
  222896. {
  222897. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  222898. }
  222899. double Time::getMillisecondCounterHiRes() throw()
  222900. {
  222901. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  222902. }
  222903. int64 Time::getHighResolutionTicks() throw()
  222904. {
  222905. return (int64) mach_absolute_time();
  222906. }
  222907. int64 Time::getHighResolutionTicksPerSecond() throw()
  222908. {
  222909. return SystemStatsHelpers::highResTimerFrequency;
  222910. }
  222911. bool Time::setSystemTimeToThisTime() const
  222912. {
  222913. jassertfalse;
  222914. return false;
  222915. }
  222916. int SystemStats::getPageSize()
  222917. {
  222918. return (int) NSPageSize();
  222919. }
  222920. void PlatformUtilities::fpuReset()
  222921. {
  222922. }
  222923. #endif
  222924. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  222925. /*** Start of inlined file: juce_mac_Network.mm ***/
  222926. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222927. // compiled on its own).
  222928. #if JUCE_INCLUDED_FILE
  222929. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  222930. {
  222931. #ifndef IFT_ETHER
  222932. #define IFT_ETHER 6
  222933. #endif
  222934. ifaddrs* addrs = 0;
  222935. int numResults = 0;
  222936. if (getifaddrs (&addrs) == 0)
  222937. {
  222938. const ifaddrs* cursor = addrs;
  222939. while (cursor != 0 && numResults < maxNum)
  222940. {
  222941. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  222942. if (sto->ss_family == AF_LINK)
  222943. {
  222944. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  222945. if (sadd->sdl_type == IFT_ETHER)
  222946. {
  222947. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  222948. uint64 a = 0;
  222949. for (int i = 6; --i >= 0;)
  222950. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  222951. *addresses++ = (int64) a;
  222952. ++numResults;
  222953. }
  222954. }
  222955. cursor = cursor->ifa_next;
  222956. }
  222957. freeifaddrs (addrs);
  222958. }
  222959. return numResults;
  222960. }
  222961. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  222962. const String& emailSubject,
  222963. const String& bodyText,
  222964. const StringArray& filesToAttach)
  222965. {
  222966. #if JUCE_IPHONE
  222967. //xxx probably need to use MFMailComposeViewController
  222968. jassertfalse;
  222969. return false;
  222970. #else
  222971. const ScopedAutoReleasePool pool;
  222972. String script;
  222973. script << "tell application \"Mail\"\r\n"
  222974. "set newMessage to make new outgoing message with properties {subject:\""
  222975. << emailSubject.replace ("\"", "\\\"")
  222976. << "\", content:\""
  222977. << bodyText.replace ("\"", "\\\"")
  222978. << "\" & return & return}\r\n"
  222979. "tell newMessage\r\n"
  222980. "set visible to true\r\n"
  222981. "set sender to \"sdfsdfsdfewf\"\r\n"
  222982. "make new to recipient at end of to recipients with properties {address:\""
  222983. << targetEmailAddress
  222984. << "\"}\r\n";
  222985. for (int i = 0; i < filesToAttach.size(); ++i)
  222986. {
  222987. script << "tell content\r\n"
  222988. "make new attachment with properties {file name:\""
  222989. << filesToAttach[i].replace ("\"", "\\\"")
  222990. << "\"} at after the last paragraph\r\n"
  222991. "end tell\r\n";
  222992. }
  222993. script << "end tell\r\n"
  222994. "end tell\r\n";
  222995. NSAppleScript* s = [[NSAppleScript alloc]
  222996. initWithSource: juceStringToNS (script)];
  222997. NSDictionary* error = 0;
  222998. const bool ok = [s executeAndReturnError: &error] != nil;
  222999. [s release];
  223000. return ok;
  223001. #endif
  223002. }
  223003. END_JUCE_NAMESPACE
  223004. using namespace JUCE_NAMESPACE;
  223005. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223006. @interface JuceURLConnection : NSObject
  223007. {
  223008. @public
  223009. NSURLRequest* request;
  223010. NSURLConnection* connection;
  223011. NSMutableData* data;
  223012. Thread* runLoopThread;
  223013. bool initialised, hasFailed, hasFinished;
  223014. int position;
  223015. int64 contentLength;
  223016. NSDictionary* headers;
  223017. NSLock* dataLock;
  223018. }
  223019. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223020. - (void) dealloc;
  223021. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223022. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223023. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223024. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223025. - (BOOL) isOpen;
  223026. - (int) read: (char*) dest numBytes: (int) num;
  223027. - (int) readPosition;
  223028. - (void) stop;
  223029. - (void) createConnection;
  223030. @end
  223031. class JuceURLConnectionMessageThread : public Thread
  223032. {
  223033. JuceURLConnection* owner;
  223034. public:
  223035. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223036. : Thread ("http connection"),
  223037. owner (owner_)
  223038. {
  223039. }
  223040. ~JuceURLConnectionMessageThread()
  223041. {
  223042. stopThread (10000);
  223043. }
  223044. void run()
  223045. {
  223046. [owner createConnection];
  223047. while (! threadShouldExit())
  223048. {
  223049. const ScopedAutoReleasePool pool;
  223050. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223051. }
  223052. }
  223053. };
  223054. @implementation JuceURLConnection
  223055. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223056. withCallback: (URL::OpenStreamProgressCallback*) callback
  223057. withContext: (void*) context;
  223058. {
  223059. [super init];
  223060. request = req;
  223061. [request retain];
  223062. data = [[NSMutableData data] retain];
  223063. dataLock = [[NSLock alloc] init];
  223064. connection = 0;
  223065. initialised = false;
  223066. hasFailed = false;
  223067. hasFinished = false;
  223068. contentLength = -1;
  223069. headers = 0;
  223070. runLoopThread = new JuceURLConnectionMessageThread (self);
  223071. runLoopThread->startThread();
  223072. while (runLoopThread->isThreadRunning() && ! initialised)
  223073. {
  223074. if (callback != 0)
  223075. callback (context, -1, (int) [[request HTTPBody] length]);
  223076. Thread::sleep (1);
  223077. }
  223078. return self;
  223079. }
  223080. - (void) dealloc
  223081. {
  223082. [self stop];
  223083. deleteAndZero (runLoopThread);
  223084. [connection release];
  223085. [data release];
  223086. [dataLock release];
  223087. [request release];
  223088. [headers release];
  223089. [super dealloc];
  223090. }
  223091. - (void) createConnection
  223092. {
  223093. NSUInteger oldRetainCount = [self retainCount];
  223094. connection = [[NSURLConnection alloc] initWithRequest: request
  223095. delegate: self];
  223096. if (oldRetainCount == [self retainCount])
  223097. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223098. if (connection == nil)
  223099. runLoopThread->signalThreadShouldExit();
  223100. }
  223101. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223102. {
  223103. (void) conn;
  223104. [dataLock lock];
  223105. [data setLength: 0];
  223106. [dataLock unlock];
  223107. initialised = true;
  223108. contentLength = [response expectedContentLength];
  223109. [headers release];
  223110. headers = 0;
  223111. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223112. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223113. }
  223114. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223115. {
  223116. (void) conn;
  223117. DBG (nsStringToJuce ([error description]));
  223118. hasFailed = true;
  223119. initialised = true;
  223120. if (runLoopThread != 0)
  223121. runLoopThread->signalThreadShouldExit();
  223122. }
  223123. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223124. {
  223125. (void) conn;
  223126. [dataLock lock];
  223127. [data appendData: newData];
  223128. [dataLock unlock];
  223129. initialised = true;
  223130. }
  223131. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223132. {
  223133. (void) conn;
  223134. hasFinished = true;
  223135. initialised = true;
  223136. if (runLoopThread != 0)
  223137. runLoopThread->signalThreadShouldExit();
  223138. }
  223139. - (BOOL) isOpen
  223140. {
  223141. return connection != 0 && ! hasFailed;
  223142. }
  223143. - (int) readPosition
  223144. {
  223145. return position;
  223146. }
  223147. - (int) read: (char*) dest numBytes: (int) numNeeded
  223148. {
  223149. int numDone = 0;
  223150. while (numNeeded > 0)
  223151. {
  223152. int available = jmin (numNeeded, (int) [data length]);
  223153. if (available > 0)
  223154. {
  223155. [dataLock lock];
  223156. [data getBytes: dest length: available];
  223157. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223158. [dataLock unlock];
  223159. numDone += available;
  223160. numNeeded -= available;
  223161. dest += available;
  223162. }
  223163. else
  223164. {
  223165. if (hasFailed || hasFinished)
  223166. break;
  223167. Thread::sleep (1);
  223168. }
  223169. }
  223170. position += numDone;
  223171. return numDone;
  223172. }
  223173. - (void) stop
  223174. {
  223175. [connection cancel];
  223176. if (runLoopThread != 0)
  223177. runLoopThread->stopThread (10000);
  223178. }
  223179. @end
  223180. BEGIN_JUCE_NAMESPACE
  223181. void* juce_openInternetFile (const String& url,
  223182. const String& headers,
  223183. const MemoryBlock& postData,
  223184. const bool isPost,
  223185. URL::OpenStreamProgressCallback* callback,
  223186. void* callbackContext,
  223187. int timeOutMs)
  223188. {
  223189. const ScopedAutoReleasePool pool;
  223190. NSMutableURLRequest* req = [NSMutableURLRequest
  223191. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223192. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223193. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223194. if (req == nil)
  223195. return 0;
  223196. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223197. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223198. StringArray headerLines;
  223199. headerLines.addLines (headers);
  223200. headerLines.removeEmptyStrings (true);
  223201. for (int i = 0; i < headerLines.size(); ++i)
  223202. {
  223203. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223204. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223205. if (key.isNotEmpty() && value.isNotEmpty())
  223206. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223207. }
  223208. if (isPost && postData.getSize() > 0)
  223209. {
  223210. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223211. length: postData.getSize()]];
  223212. }
  223213. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223214. withCallback: callback
  223215. withContext: callbackContext];
  223216. if ([s isOpen])
  223217. return s;
  223218. [s release];
  223219. return 0;
  223220. }
  223221. void juce_closeInternetFile (void* handle)
  223222. {
  223223. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223224. if (s != 0)
  223225. {
  223226. const ScopedAutoReleasePool pool;
  223227. [s stop];
  223228. [s release];
  223229. }
  223230. }
  223231. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223232. {
  223233. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223234. if (s != 0)
  223235. {
  223236. const ScopedAutoReleasePool pool;
  223237. return [s read: (char*) buffer numBytes: bytesToRead];
  223238. }
  223239. return 0;
  223240. }
  223241. int64 juce_getInternetFileContentLength (void* handle)
  223242. {
  223243. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223244. if (s != 0)
  223245. return s->contentLength;
  223246. return -1;
  223247. }
  223248. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223249. {
  223250. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223251. if (s != 0 && s->headers != 0)
  223252. {
  223253. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223254. NSString* key;
  223255. while ((key = [enumerator nextObject]) != nil)
  223256. headers.set (nsStringToJuce (key),
  223257. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223258. }
  223259. }
  223260. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223261. {
  223262. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223263. if (s != 0)
  223264. return [s readPosition];
  223265. return 0;
  223266. }
  223267. #endif
  223268. /*** End of inlined file: juce_mac_Network.mm ***/
  223269. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223270. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223271. // compiled on its own).
  223272. #if JUCE_INCLUDED_FILE
  223273. struct NamedPipeInternal
  223274. {
  223275. String pipeInName, pipeOutName;
  223276. int pipeIn, pipeOut;
  223277. bool volatile createdPipe, blocked, stopReadOperation;
  223278. static void signalHandler (int) {}
  223279. };
  223280. void NamedPipe::cancelPendingReads()
  223281. {
  223282. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223283. {
  223284. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223285. intern->stopReadOperation = true;
  223286. char buffer [1] = { 0 };
  223287. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223288. (void) bytesWritten;
  223289. int timeout = 2000;
  223290. while (intern->blocked && --timeout >= 0)
  223291. Thread::sleep (2);
  223292. intern->stopReadOperation = false;
  223293. }
  223294. }
  223295. void NamedPipe::close()
  223296. {
  223297. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223298. if (intern != 0)
  223299. {
  223300. internal = 0;
  223301. if (intern->pipeIn != -1)
  223302. ::close (intern->pipeIn);
  223303. if (intern->pipeOut != -1)
  223304. ::close (intern->pipeOut);
  223305. if (intern->createdPipe)
  223306. {
  223307. unlink (intern->pipeInName.toUTF8());
  223308. unlink (intern->pipeOutName.toUTF8());
  223309. }
  223310. delete intern;
  223311. }
  223312. }
  223313. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223314. {
  223315. close();
  223316. NamedPipeInternal* const intern = new NamedPipeInternal();
  223317. internal = intern;
  223318. intern->createdPipe = createPipe;
  223319. intern->blocked = false;
  223320. intern->stopReadOperation = false;
  223321. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223322. siginterrupt (SIGPIPE, 1);
  223323. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223324. intern->pipeInName = pipePath + "_in";
  223325. intern->pipeOutName = pipePath + "_out";
  223326. intern->pipeIn = -1;
  223327. intern->pipeOut = -1;
  223328. if (createPipe)
  223329. {
  223330. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223331. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223332. {
  223333. delete intern;
  223334. internal = 0;
  223335. return false;
  223336. }
  223337. }
  223338. return true;
  223339. }
  223340. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223341. {
  223342. int bytesRead = -1;
  223343. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223344. if (intern != 0)
  223345. {
  223346. intern->blocked = true;
  223347. if (intern->pipeIn == -1)
  223348. {
  223349. if (intern->createdPipe)
  223350. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223351. else
  223352. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223353. if (intern->pipeIn == -1)
  223354. {
  223355. intern->blocked = false;
  223356. return -1;
  223357. }
  223358. }
  223359. bytesRead = 0;
  223360. char* p = (char*) destBuffer;
  223361. while (bytesRead < maxBytesToRead)
  223362. {
  223363. const int bytesThisTime = maxBytesToRead - bytesRead;
  223364. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223365. if (numRead <= 0 || intern->stopReadOperation)
  223366. {
  223367. bytesRead = -1;
  223368. break;
  223369. }
  223370. bytesRead += numRead;
  223371. p += bytesRead;
  223372. }
  223373. intern->blocked = false;
  223374. }
  223375. return bytesRead;
  223376. }
  223377. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223378. {
  223379. int bytesWritten = -1;
  223380. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223381. if (intern != 0)
  223382. {
  223383. if (intern->pipeOut == -1)
  223384. {
  223385. if (intern->createdPipe)
  223386. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223387. else
  223388. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223389. if (intern->pipeOut == -1)
  223390. {
  223391. return -1;
  223392. }
  223393. }
  223394. const char* p = (const char*) sourceBuffer;
  223395. bytesWritten = 0;
  223396. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223397. while (bytesWritten < numBytesToWrite
  223398. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223399. {
  223400. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223401. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223402. if (numWritten <= 0)
  223403. {
  223404. bytesWritten = -1;
  223405. break;
  223406. }
  223407. bytesWritten += numWritten;
  223408. p += bytesWritten;
  223409. }
  223410. }
  223411. return bytesWritten;
  223412. }
  223413. #endif
  223414. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223415. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223416. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223417. // compiled on its own).
  223418. #if JUCE_INCLUDED_FILE
  223419. /*
  223420. Note that a lot of methods that you'd expect to find in this file actually
  223421. live in juce_posix_SharedCode.h!
  223422. */
  223423. void JUCE_API juce_threadEntryPoint (void*);
  223424. void* threadEntryProc (void* userData)
  223425. {
  223426. const ScopedAutoReleasePool pool;
  223427. juce_threadEntryPoint (userData);
  223428. return 0;
  223429. }
  223430. void* juce_createThread (void* userData)
  223431. {
  223432. pthread_t handle = 0;
  223433. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223434. {
  223435. pthread_detach (handle);
  223436. return (void*) handle;
  223437. }
  223438. return 0;
  223439. }
  223440. void juce_killThread (void* handle)
  223441. {
  223442. if (handle != 0)
  223443. pthread_cancel ((pthread_t) handle);
  223444. }
  223445. void juce_setCurrentThreadName (const String& /*name*/)
  223446. {
  223447. }
  223448. bool juce_setThreadPriority (void* handle, int priority)
  223449. {
  223450. if (handle == 0)
  223451. handle = (void*) pthread_self();
  223452. struct sched_param param;
  223453. int policy;
  223454. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223455. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223456. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223457. }
  223458. Thread::ThreadID Thread::getCurrentThreadId()
  223459. {
  223460. return static_cast <ThreadID> (pthread_self());
  223461. }
  223462. void Thread::yield()
  223463. {
  223464. sched_yield();
  223465. }
  223466. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223467. {
  223468. // xxx
  223469. jassertfalse;
  223470. }
  223471. bool Process::isForegroundProcess()
  223472. {
  223473. #if JUCE_MAC
  223474. return [NSApp isActive];
  223475. #else
  223476. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223477. #endif
  223478. }
  223479. void Process::raisePrivilege()
  223480. {
  223481. jassertfalse;
  223482. }
  223483. void Process::lowerPrivilege()
  223484. {
  223485. jassertfalse;
  223486. }
  223487. void Process::terminate()
  223488. {
  223489. exit (0);
  223490. }
  223491. void Process::setPriority (ProcessPriority)
  223492. {
  223493. // xxx
  223494. }
  223495. #endif
  223496. /*** End of inlined file: juce_mac_Threads.mm ***/
  223497. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223498. /*
  223499. This file contains posix routines that are common to both the Linux and Mac builds.
  223500. It gets included directly in the cpp files for these platforms.
  223501. */
  223502. CriticalSection::CriticalSection() throw()
  223503. {
  223504. pthread_mutexattr_t atts;
  223505. pthread_mutexattr_init (&atts);
  223506. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223507. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223508. pthread_mutex_init (&internal, &atts);
  223509. }
  223510. CriticalSection::~CriticalSection() throw()
  223511. {
  223512. pthread_mutex_destroy (&internal);
  223513. }
  223514. void CriticalSection::enter() const throw()
  223515. {
  223516. pthread_mutex_lock (&internal);
  223517. }
  223518. bool CriticalSection::tryEnter() const throw()
  223519. {
  223520. return pthread_mutex_trylock (&internal) == 0;
  223521. }
  223522. void CriticalSection::exit() const throw()
  223523. {
  223524. pthread_mutex_unlock (&internal);
  223525. }
  223526. class WaitableEventImpl
  223527. {
  223528. public:
  223529. WaitableEventImpl (const bool manualReset_)
  223530. : triggered (false),
  223531. manualReset (manualReset_)
  223532. {
  223533. pthread_cond_init (&condition, 0);
  223534. pthread_mutexattr_t atts;
  223535. pthread_mutexattr_init (&atts);
  223536. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223537. pthread_mutex_init (&mutex, &atts);
  223538. }
  223539. ~WaitableEventImpl()
  223540. {
  223541. pthread_cond_destroy (&condition);
  223542. pthread_mutex_destroy (&mutex);
  223543. }
  223544. bool wait (const int timeOutMillisecs) throw()
  223545. {
  223546. pthread_mutex_lock (&mutex);
  223547. if (! triggered)
  223548. {
  223549. if (timeOutMillisecs < 0)
  223550. {
  223551. do
  223552. {
  223553. pthread_cond_wait (&condition, &mutex);
  223554. }
  223555. while (! triggered);
  223556. }
  223557. else
  223558. {
  223559. struct timeval now;
  223560. gettimeofday (&now, 0);
  223561. struct timespec time;
  223562. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223563. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223564. if (time.tv_nsec >= 1000000000)
  223565. {
  223566. time.tv_nsec -= 1000000000;
  223567. time.tv_sec++;
  223568. }
  223569. do
  223570. {
  223571. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223572. {
  223573. pthread_mutex_unlock (&mutex);
  223574. return false;
  223575. }
  223576. }
  223577. while (! triggered);
  223578. }
  223579. }
  223580. if (! manualReset)
  223581. triggered = false;
  223582. pthread_mutex_unlock (&mutex);
  223583. return true;
  223584. }
  223585. void signal() throw()
  223586. {
  223587. pthread_mutex_lock (&mutex);
  223588. triggered = true;
  223589. pthread_cond_broadcast (&condition);
  223590. pthread_mutex_unlock (&mutex);
  223591. }
  223592. void reset() throw()
  223593. {
  223594. pthread_mutex_lock (&mutex);
  223595. triggered = false;
  223596. pthread_mutex_unlock (&mutex);
  223597. }
  223598. private:
  223599. pthread_cond_t condition;
  223600. pthread_mutex_t mutex;
  223601. bool triggered;
  223602. const bool manualReset;
  223603. WaitableEventImpl (const WaitableEventImpl&);
  223604. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223605. };
  223606. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223607. : internal (new WaitableEventImpl (manualReset))
  223608. {
  223609. }
  223610. WaitableEvent::~WaitableEvent() throw()
  223611. {
  223612. delete static_cast <WaitableEventImpl*> (internal);
  223613. }
  223614. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223615. {
  223616. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223617. }
  223618. void WaitableEvent::signal() const throw()
  223619. {
  223620. static_cast <WaitableEventImpl*> (internal)->signal();
  223621. }
  223622. void WaitableEvent::reset() const throw()
  223623. {
  223624. static_cast <WaitableEventImpl*> (internal)->reset();
  223625. }
  223626. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223627. {
  223628. struct timespec time;
  223629. time.tv_sec = millisecs / 1000;
  223630. time.tv_nsec = (millisecs % 1000) * 1000000;
  223631. nanosleep (&time, 0);
  223632. }
  223633. const juce_wchar File::separator = '/';
  223634. const String File::separatorString ("/");
  223635. const File File::getCurrentWorkingDirectory()
  223636. {
  223637. HeapBlock<char> heapBuffer;
  223638. char localBuffer [1024];
  223639. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223640. int bufferSize = 4096;
  223641. while (cwd == 0 && errno == ERANGE)
  223642. {
  223643. heapBuffer.malloc (bufferSize);
  223644. cwd = getcwd (heapBuffer, bufferSize - 1);
  223645. bufferSize += 1024;
  223646. }
  223647. return File (String::fromUTF8 (cwd));
  223648. }
  223649. bool File::setAsCurrentWorkingDirectory() const
  223650. {
  223651. return chdir (getFullPathName().toUTF8()) == 0;
  223652. }
  223653. static bool juce_stat (const String& fileName, struct stat& info)
  223654. {
  223655. return fileName.isNotEmpty()
  223656. && (stat (fileName.toUTF8(), &info) == 0);
  223657. }
  223658. bool File::isDirectory() const
  223659. {
  223660. struct stat info;
  223661. return fullPath.isEmpty()
  223662. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223663. }
  223664. bool File::exists() const
  223665. {
  223666. return fullPath.isNotEmpty()
  223667. && access (fullPath.toUTF8(), F_OK) == 0;
  223668. }
  223669. bool File::existsAsFile() const
  223670. {
  223671. return exists() && ! isDirectory();
  223672. }
  223673. int64 File::getSize() const
  223674. {
  223675. struct stat info;
  223676. return juce_stat (fullPath, info) ? info.st_size : 0;
  223677. }
  223678. bool File::hasWriteAccess() const
  223679. {
  223680. if (exists())
  223681. return access (fullPath.toUTF8(), W_OK) == 0;
  223682. if ((! isDirectory()) && fullPath.containsChar (separator))
  223683. return getParentDirectory().hasWriteAccess();
  223684. return false;
  223685. }
  223686. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223687. {
  223688. struct stat info;
  223689. const int res = stat (fullPath.toUTF8(), &info);
  223690. if (res != 0)
  223691. return false;
  223692. info.st_mode &= 0777; // Just permissions
  223693. if (shouldBeReadOnly)
  223694. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223695. else
  223696. // Give everybody write permission?
  223697. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223698. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223699. }
  223700. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223701. {
  223702. modificationTime = 0;
  223703. accessTime = 0;
  223704. creationTime = 0;
  223705. struct stat info;
  223706. const int res = stat (fullPath.toUTF8(), &info);
  223707. if (res == 0)
  223708. {
  223709. modificationTime = (int64) info.st_mtime * 1000;
  223710. accessTime = (int64) info.st_atime * 1000;
  223711. creationTime = (int64) info.st_ctime * 1000;
  223712. }
  223713. }
  223714. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223715. {
  223716. struct utimbuf times;
  223717. times.actime = (time_t) (accessTime / 1000);
  223718. times.modtime = (time_t) (modificationTime / 1000);
  223719. return utime (fullPath.toUTF8(), &times) == 0;
  223720. }
  223721. bool File::deleteFile() const
  223722. {
  223723. if (! exists())
  223724. return true;
  223725. else if (isDirectory())
  223726. return rmdir (fullPath.toUTF8()) == 0;
  223727. else
  223728. return remove (fullPath.toUTF8()) == 0;
  223729. }
  223730. bool File::moveInternal (const File& dest) const
  223731. {
  223732. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223733. return true;
  223734. if (hasWriteAccess() && copyInternal (dest))
  223735. {
  223736. if (deleteFile())
  223737. return true;
  223738. dest.deleteFile();
  223739. }
  223740. return false;
  223741. }
  223742. void File::createDirectoryInternal (const String& fileName) const
  223743. {
  223744. mkdir (fileName.toUTF8(), 0777);
  223745. }
  223746. void* juce_fileOpen (const File& file, bool forWriting)
  223747. {
  223748. int flags = O_RDONLY;
  223749. if (forWriting)
  223750. {
  223751. if (file.exists())
  223752. {
  223753. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223754. if (f != -1)
  223755. lseek (f, 0, SEEK_END);
  223756. return (void*) f;
  223757. }
  223758. else
  223759. {
  223760. flags = O_RDWR + O_CREAT;
  223761. }
  223762. }
  223763. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223764. }
  223765. void juce_fileClose (void* handle)
  223766. {
  223767. if (handle != 0)
  223768. close ((int) (pointer_sized_int) handle);
  223769. }
  223770. int juce_fileRead (void* handle, void* buffer, int size)
  223771. {
  223772. if (handle != 0)
  223773. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223774. return 0;
  223775. }
  223776. int juce_fileWrite (void* handle, const void* buffer, int size)
  223777. {
  223778. if (handle != 0)
  223779. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223780. return 0;
  223781. }
  223782. int64 juce_fileSetPosition (void* handle, int64 pos)
  223783. {
  223784. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223785. return pos;
  223786. return -1;
  223787. }
  223788. int64 FileOutputStream::getPositionInternal() const
  223789. {
  223790. if (fileHandle != 0)
  223791. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223792. return -1;
  223793. }
  223794. void FileOutputStream::flushInternal()
  223795. {
  223796. if (fileHandle != 0)
  223797. fsync ((int) (pointer_sized_int) fileHandle);
  223798. }
  223799. const File juce_getExecutableFile()
  223800. {
  223801. Dl_info exeInfo;
  223802. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223803. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223804. }
  223805. // if this file doesn't exist, find a parent of it that does..
  223806. static bool juce_doStatFS (File f, struct statfs& result)
  223807. {
  223808. for (int i = 5; --i >= 0;)
  223809. {
  223810. if (f.exists())
  223811. break;
  223812. f = f.getParentDirectory();
  223813. }
  223814. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  223815. }
  223816. int64 File::getBytesFreeOnVolume() const
  223817. {
  223818. struct statfs buf;
  223819. if (juce_doStatFS (*this, buf))
  223820. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  223821. return 0;
  223822. }
  223823. int64 File::getVolumeTotalSize() const
  223824. {
  223825. struct statfs buf;
  223826. if (juce_doStatFS (*this, buf))
  223827. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  223828. return 0;
  223829. }
  223830. const String File::getVolumeLabel() const
  223831. {
  223832. #if JUCE_MAC
  223833. struct VolAttrBuf
  223834. {
  223835. u_int32_t length;
  223836. attrreference_t mountPointRef;
  223837. char mountPointSpace [MAXPATHLEN];
  223838. } attrBuf;
  223839. struct attrlist attrList;
  223840. zerostruct (attrList);
  223841. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  223842. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  223843. File f (*this);
  223844. for (;;)
  223845. {
  223846. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  223847. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  223848. (int) attrBuf.mountPointRef.attr_length);
  223849. const File parent (f.getParentDirectory());
  223850. if (f == parent)
  223851. break;
  223852. f = parent;
  223853. }
  223854. #endif
  223855. return String::empty;
  223856. }
  223857. int File::getVolumeSerialNumber() const
  223858. {
  223859. return 0; // xxx
  223860. }
  223861. void juce_runSystemCommand (const String& command)
  223862. {
  223863. int result = system (command.toUTF8());
  223864. (void) result;
  223865. }
  223866. const String juce_getOutputFromCommand (const String& command)
  223867. {
  223868. // slight bodge here, as we just pipe the output into a temp file and read it...
  223869. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  223870. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  223871. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  223872. String result (tempFile.loadFileAsString());
  223873. tempFile.deleteFile();
  223874. return result;
  223875. }
  223876. class InterProcessLock::Pimpl
  223877. {
  223878. public:
  223879. Pimpl (const String& name, const int timeOutMillisecs)
  223880. : handle (0), refCount (1)
  223881. {
  223882. #if JUCE_MAC
  223883. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  223884. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  223885. #else
  223886. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  223887. #endif
  223888. temp.create();
  223889. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  223890. if (handle != 0)
  223891. {
  223892. struct flock fl;
  223893. zerostruct (fl);
  223894. fl.l_whence = SEEK_SET;
  223895. fl.l_type = F_WRLCK;
  223896. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  223897. for (;;)
  223898. {
  223899. const int result = fcntl (handle, F_SETLK, &fl);
  223900. if (result >= 0)
  223901. return;
  223902. if (errno != EINTR)
  223903. {
  223904. if (timeOutMillisecs == 0
  223905. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  223906. break;
  223907. Thread::sleep (10);
  223908. }
  223909. }
  223910. }
  223911. closeFile();
  223912. }
  223913. ~Pimpl()
  223914. {
  223915. closeFile();
  223916. }
  223917. void closeFile()
  223918. {
  223919. if (handle != 0)
  223920. {
  223921. struct flock fl;
  223922. zerostruct (fl);
  223923. fl.l_whence = SEEK_SET;
  223924. fl.l_type = F_UNLCK;
  223925. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  223926. {}
  223927. close (handle);
  223928. handle = 0;
  223929. }
  223930. }
  223931. int handle, refCount;
  223932. };
  223933. InterProcessLock::InterProcessLock (const String& name_)
  223934. : name (name_)
  223935. {
  223936. }
  223937. InterProcessLock::~InterProcessLock()
  223938. {
  223939. }
  223940. bool InterProcessLock::enter (const int timeOutMillisecs)
  223941. {
  223942. const ScopedLock sl (lock);
  223943. if (pimpl == 0)
  223944. {
  223945. pimpl = new Pimpl (name, timeOutMillisecs);
  223946. if (pimpl->handle == 0)
  223947. pimpl = 0;
  223948. }
  223949. else
  223950. {
  223951. pimpl->refCount++;
  223952. }
  223953. return pimpl != 0;
  223954. }
  223955. void InterProcessLock::exit()
  223956. {
  223957. const ScopedLock sl (lock);
  223958. // Trying to release the lock too many times!
  223959. jassert (pimpl != 0);
  223960. if (pimpl != 0 && --(pimpl->refCount) == 0)
  223961. pimpl = 0;
  223962. }
  223963. /*** End of inlined file: juce_posix_SharedCode.h ***/
  223964. /*** Start of inlined file: juce_mac_Files.mm ***/
  223965. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223966. // compiled on its own).
  223967. #if JUCE_INCLUDED_FILE
  223968. /*
  223969. Note that a lot of methods that you'd expect to find in this file actually
  223970. live in juce_posix_SharedCode.h!
  223971. */
  223972. bool File::copyInternal (const File& dest) const
  223973. {
  223974. const ScopedAutoReleasePool pool;
  223975. NSFileManager* fm = [NSFileManager defaultManager];
  223976. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  223977. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223978. && [fm copyItemAtPath: juceStringToNS (fullPath)
  223979. toPath: juceStringToNS (dest.getFullPathName())
  223980. error: nil];
  223981. #else
  223982. && [fm copyPath: juceStringToNS (fullPath)
  223983. toPath: juceStringToNS (dest.getFullPathName())
  223984. handler: nil];
  223985. #endif
  223986. }
  223987. void File::findFileSystemRoots (Array<File>& destArray)
  223988. {
  223989. destArray.add (File ("/"));
  223990. }
  223991. static bool isFileOnDriveType (const File& f, const char* const* types)
  223992. {
  223993. struct statfs buf;
  223994. if (juce_doStatFS (f, buf))
  223995. {
  223996. const String type (buf.f_fstypename);
  223997. while (*types != 0)
  223998. if (type.equalsIgnoreCase (*types++))
  223999. return true;
  224000. }
  224001. return false;
  224002. }
  224003. bool File::isOnCDRomDrive() const
  224004. {
  224005. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224006. return isFileOnDriveType (*this, cdTypes);
  224007. }
  224008. bool File::isOnHardDisk() const
  224009. {
  224010. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224011. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  224012. }
  224013. bool File::isOnRemovableDrive() const
  224014. {
  224015. #if JUCE_IPHONE
  224016. return false; // xxx is this possible?
  224017. #else
  224018. const ScopedAutoReleasePool pool;
  224019. BOOL removable = false;
  224020. [[NSWorkspace sharedWorkspace]
  224021. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224022. isRemovable: &removable
  224023. isWritable: nil
  224024. isUnmountable: nil
  224025. description: nil
  224026. type: nil];
  224027. return removable;
  224028. #endif
  224029. }
  224030. static bool juce_isHiddenFile (const String& path)
  224031. {
  224032. #if JUCE_IPHONE
  224033. return File (path).getFileName().startsWithChar ('.');
  224034. #else
  224035. FSRef ref;
  224036. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  224037. return false;
  224038. FSCatalogInfo info;
  224039. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  224040. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  224041. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224042. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224043. #endif
  224044. }
  224045. bool File::isHidden() const
  224046. {
  224047. return juce_isHiddenFile (getFullPathName());
  224048. }
  224049. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224050. const File File::getSpecialLocation (const SpecialLocationType type)
  224051. {
  224052. const ScopedAutoReleasePool pool;
  224053. String resultPath;
  224054. switch (type)
  224055. {
  224056. case userHomeDirectory:
  224057. resultPath = nsStringToJuce (NSHomeDirectory());
  224058. break;
  224059. case userDocumentsDirectory:
  224060. resultPath = "~/Documents";
  224061. break;
  224062. case userDesktopDirectory:
  224063. resultPath = "~/Desktop";
  224064. break;
  224065. case userApplicationDataDirectory:
  224066. resultPath = "~/Library";
  224067. break;
  224068. case commonApplicationDataDirectory:
  224069. resultPath = "/Library";
  224070. break;
  224071. case globalApplicationsDirectory:
  224072. resultPath = "/Applications";
  224073. break;
  224074. case userMusicDirectory:
  224075. resultPath = "~/Music";
  224076. break;
  224077. case userMoviesDirectory:
  224078. resultPath = "~/Movies";
  224079. break;
  224080. case tempDirectory:
  224081. {
  224082. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224083. tmp.createDirectory();
  224084. return tmp.getFullPathName();
  224085. }
  224086. case invokedExecutableFile:
  224087. if (juce_Argv0 != 0)
  224088. return File (String::fromUTF8 (juce_Argv0));
  224089. // deliberate fall-through...
  224090. case currentExecutableFile:
  224091. return juce_getExecutableFile();
  224092. case currentApplicationFile:
  224093. {
  224094. const File exe (juce_getExecutableFile());
  224095. const File parent (exe.getParentDirectory());
  224096. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224097. ? parent.getParentDirectory().getParentDirectory()
  224098. : exe;
  224099. }
  224100. default:
  224101. jassertfalse; // unknown type?
  224102. break;
  224103. }
  224104. if (resultPath.isNotEmpty())
  224105. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224106. return File::nonexistent;
  224107. }
  224108. const String File::getVersion() const
  224109. {
  224110. const ScopedAutoReleasePool pool;
  224111. String result;
  224112. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224113. if (bundle != 0)
  224114. {
  224115. NSDictionary* info = [bundle infoDictionary];
  224116. if (info != 0)
  224117. {
  224118. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224119. if (name != nil)
  224120. result = nsStringToJuce (name);
  224121. }
  224122. }
  224123. return result;
  224124. }
  224125. const File File::getLinkedTarget() const
  224126. {
  224127. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224128. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224129. #else
  224130. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224131. #endif
  224132. if (dest != nil)
  224133. return File (nsStringToJuce (dest));
  224134. return *this;
  224135. }
  224136. bool File::moveToTrash() const
  224137. {
  224138. if (! exists())
  224139. return true;
  224140. #if JUCE_IPHONE
  224141. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224142. #else
  224143. const ScopedAutoReleasePool pool;
  224144. NSString* p = juceStringToNS (getFullPathName());
  224145. return [[NSWorkspace sharedWorkspace]
  224146. performFileOperation: NSWorkspaceRecycleOperation
  224147. source: [p stringByDeletingLastPathComponent]
  224148. destination: @""
  224149. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224150. tag: nil ];
  224151. #endif
  224152. }
  224153. class DirectoryIterator::NativeIterator::Pimpl
  224154. {
  224155. public:
  224156. Pimpl (const File& directory, const String& wildCard_)
  224157. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224158. wildCard (wildCard_),
  224159. enumerator (0)
  224160. {
  224161. ScopedAutoReleasePool pool;
  224162. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224163. wildcardUTF8 = wildCard.toUTF8();
  224164. }
  224165. ~Pimpl()
  224166. {
  224167. [enumerator release];
  224168. }
  224169. bool next (String& filenameFound,
  224170. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224171. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224172. {
  224173. ScopedAutoReleasePool pool;
  224174. for (;;)
  224175. {
  224176. NSString* file;
  224177. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224178. return false;
  224179. [enumerator skipDescendents];
  224180. filenameFound = nsStringToJuce (file);
  224181. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224182. continue;
  224183. const String path (parentDir + filenameFound);
  224184. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224185. {
  224186. struct stat info;
  224187. const bool statOk = juce_stat (path, info);
  224188. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224189. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224190. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  224191. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  224192. }
  224193. if (isHidden != 0)
  224194. *isHidden = juce_isHiddenFile (path);
  224195. if (isReadOnly != 0)
  224196. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224197. return true;
  224198. }
  224199. }
  224200. private:
  224201. String parentDir, wildCard;
  224202. const char* wildcardUTF8;
  224203. NSDirectoryEnumerator* enumerator;
  224204. Pimpl (const Pimpl&);
  224205. Pimpl& operator= (const Pimpl&);
  224206. };
  224207. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224208. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224209. {
  224210. }
  224211. DirectoryIterator::NativeIterator::~NativeIterator()
  224212. {
  224213. }
  224214. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224215. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224216. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224217. {
  224218. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224219. }
  224220. bool juce_launchExecutable (const String& pathAndArguments)
  224221. {
  224222. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224223. const int cpid = fork();
  224224. if (cpid == 0)
  224225. {
  224226. // Child process
  224227. if (execve (argv[0], (char**) argv, 0) < 0)
  224228. exit (0);
  224229. }
  224230. else
  224231. {
  224232. if (cpid < 0)
  224233. return false;
  224234. }
  224235. return true;
  224236. }
  224237. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224238. {
  224239. #if JUCE_IPHONE
  224240. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224241. #else
  224242. const ScopedAutoReleasePool pool;
  224243. if (parameters.isEmpty())
  224244. {
  224245. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224246. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224247. }
  224248. bool ok = false;
  224249. FSRef ref;
  224250. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224251. {
  224252. if (PlatformUtilities::isBundle (fileName))
  224253. {
  224254. NSMutableArray* urls = [NSMutableArray array];
  224255. StringArray docs;
  224256. docs.addTokens (parameters, true);
  224257. for (int i = 0; i < docs.size(); ++i)
  224258. [urls addObject: juceStringToNS (docs[i])];
  224259. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224260. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224261. options: 0
  224262. additionalEventParamDescriptor: nil
  224263. launchIdentifiers: nil];
  224264. }
  224265. else
  224266. {
  224267. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224268. }
  224269. }
  224270. return ok;
  224271. #endif
  224272. }
  224273. void File::revealToUser() const
  224274. {
  224275. #if ! JUCE_IPHONE
  224276. if (exists())
  224277. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224278. else if (getParentDirectory().exists())
  224279. getParentDirectory().revealToUser();
  224280. #endif
  224281. }
  224282. #if ! JUCE_IPHONE
  224283. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224284. {
  224285. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224286. }
  224287. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224288. {
  224289. char path [2048];
  224290. zerostruct (path);
  224291. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224292. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224293. return String::empty;
  224294. }
  224295. #endif
  224296. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224297. {
  224298. const ScopedAutoReleasePool pool;
  224299. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224300. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224301. #else
  224302. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224303. #endif
  224304. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224305. return [fileDict fileHFSTypeCode];
  224306. }
  224307. bool PlatformUtilities::isBundle (const String& filename)
  224308. {
  224309. #if JUCE_IPHONE
  224310. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224311. #else
  224312. const ScopedAutoReleasePool pool;
  224313. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224314. #endif
  224315. }
  224316. #endif
  224317. /*** End of inlined file: juce_mac_Files.mm ***/
  224318. #if JUCE_IPHONE
  224319. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224320. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224321. // compiled on its own).
  224322. #if JUCE_INCLUDED_FILE
  224323. static JUCEApplication* juce_intialisingApp;
  224324. END_JUCE_NAMESPACE
  224325. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224326. {
  224327. }
  224328. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224329. - (void) applicationWillResignActive: (UIApplication*) application;
  224330. @end
  224331. @implementation JuceAppStartupDelegate
  224332. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224333. {
  224334. String dummy;
  224335. if (! juce_intialisingApp->initialiseApp (dummy))
  224336. exit (0);
  224337. }
  224338. - (void) applicationWillResignActive: (UIApplication*) application
  224339. {
  224340. JUCEApplication::shutdownAppAndClearUp();
  224341. }
  224342. @end
  224343. BEGIN_JUCE_NAMESPACE
  224344. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  224345. {
  224346. juce_intialisingApp = app;
  224347. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224348. }
  224349. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224350. {
  224351. pool = [[NSAutoreleasePool alloc] init];
  224352. }
  224353. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224354. {
  224355. [((NSAutoreleasePool*) pool) release];
  224356. }
  224357. void PlatformUtilities::beep()
  224358. {
  224359. //xxx
  224360. //AudioServicesPlaySystemSound ();
  224361. }
  224362. void PlatformUtilities::addItemToDock (const File& file)
  224363. {
  224364. }
  224365. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224366. END_JUCE_NAMESPACE
  224367. @interface JuceAlertBoxDelegate : NSObject
  224368. {
  224369. @public
  224370. bool clickedOk;
  224371. }
  224372. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224373. @end
  224374. @implementation JuceAlertBoxDelegate
  224375. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224376. {
  224377. clickedOk = (buttonIndex == 0);
  224378. alertView.hidden = true;
  224379. }
  224380. @end
  224381. BEGIN_JUCE_NAMESPACE
  224382. // (This function is used directly by other bits of code)
  224383. bool juce_iPhoneShowModalAlert (const String& title,
  224384. const String& bodyText,
  224385. NSString* okButtonText,
  224386. NSString* cancelButtonText)
  224387. {
  224388. const ScopedAutoReleasePool pool;
  224389. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224390. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224391. message: juceStringToNS (bodyText)
  224392. delegate: callback
  224393. cancelButtonTitle: okButtonText
  224394. otherButtonTitles: cancelButtonText, nil];
  224395. [alert retain];
  224396. [alert show];
  224397. while (! alert.hidden && alert.superview != nil)
  224398. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224399. const bool result = callback->clickedOk;
  224400. [alert release];
  224401. [callback release];
  224402. return result;
  224403. }
  224404. bool AlertWindow::showNativeDialogBox (const String& title,
  224405. const String& bodyText,
  224406. bool isOkCancel)
  224407. {
  224408. return juce_iPhoneShowModalAlert (title, bodyText,
  224409. @"OK",
  224410. isOkCancel ? @"Cancel" : nil);
  224411. }
  224412. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224413. {
  224414. jassertfalse; // no such thing on the iphone!
  224415. return false;
  224416. }
  224417. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224418. {
  224419. jassertfalse; // no such thing on the iphone!
  224420. return false;
  224421. }
  224422. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224423. {
  224424. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224425. }
  224426. bool Desktop::isScreenSaverEnabled()
  224427. {
  224428. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224429. }
  224430. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224431. {
  224432. const ScopedAutoReleasePool pool;
  224433. monitorCoords.clear();
  224434. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224435. : [[UIScreen mainScreen] bounds];
  224436. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224437. (int) r.origin.y,
  224438. (int) r.size.width,
  224439. (int) r.size.height));
  224440. }
  224441. #endif
  224442. #endif
  224443. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224444. #else
  224445. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224446. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224447. // compiled on its own).
  224448. #if JUCE_INCLUDED_FILE
  224449. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224450. {
  224451. pool = [[NSAutoreleasePool alloc] init];
  224452. }
  224453. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224454. {
  224455. [((NSAutoreleasePool*) pool) release];
  224456. }
  224457. void PlatformUtilities::beep()
  224458. {
  224459. NSBeep();
  224460. }
  224461. void PlatformUtilities::addItemToDock (const File& file)
  224462. {
  224463. // check that it's not already there...
  224464. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224465. .containsIgnoreCase (file.getFullPathName()))
  224466. {
  224467. 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>"
  224468. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224469. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224470. }
  224471. }
  224472. int PlatformUtilities::getOSXMinorVersionNumber()
  224473. {
  224474. SInt32 versionMinor = 0;
  224475. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224476. (void) err;
  224477. jassert (err == noErr);
  224478. return (int) versionMinor;
  224479. }
  224480. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224481. bool AlertWindow::showNativeDialogBox (const String& title,
  224482. const String& bodyText,
  224483. bool isOkCancel)
  224484. {
  224485. const ScopedAutoReleasePool pool;
  224486. return NSRunAlertPanel (juceStringToNS (title),
  224487. juceStringToNS (bodyText),
  224488. @"Ok",
  224489. isOkCancel ? @"Cancel" : nil,
  224490. nil) == NSAlertDefaultReturn;
  224491. }
  224492. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224493. {
  224494. if (files.size() == 0)
  224495. return false;
  224496. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224497. if (draggingSource == 0)
  224498. {
  224499. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224500. return false;
  224501. }
  224502. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224503. if (sourceComp == 0)
  224504. {
  224505. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224506. return false;
  224507. }
  224508. const ScopedAutoReleasePool pool;
  224509. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224510. if (view == 0)
  224511. return false;
  224512. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224513. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224514. owner: nil];
  224515. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224516. for (int i = 0; i < files.size(); ++i)
  224517. [filesArray addObject: juceStringToNS (files[i])];
  224518. [pboard setPropertyList: filesArray
  224519. forType: NSFilenamesPboardType];
  224520. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224521. fromView: nil];
  224522. dragPosition.x -= 16;
  224523. dragPosition.y -= 16;
  224524. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224525. at: dragPosition
  224526. offset: NSMakeSize (0, 0)
  224527. event: [[view window] currentEvent]
  224528. pasteboard: pboard
  224529. source: view
  224530. slideBack: YES];
  224531. return true;
  224532. }
  224533. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224534. {
  224535. jassertfalse; // not implemented!
  224536. return false;
  224537. }
  224538. bool Desktop::canUseSemiTransparentWindows() throw()
  224539. {
  224540. return true;
  224541. }
  224542. const Point<int> Desktop::getMousePosition()
  224543. {
  224544. const ScopedAutoReleasePool pool;
  224545. const NSPoint p ([NSEvent mouseLocation]);
  224546. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224547. }
  224548. void Desktop::setMousePosition (const Point<int>& newPosition)
  224549. {
  224550. // this rubbish needs to be done around the warp call, to avoid causing a
  224551. // bizarre glitch..
  224552. CGAssociateMouseAndMouseCursorPosition (false);
  224553. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224554. CGAssociateMouseAndMouseCursorPosition (true);
  224555. }
  224556. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224557. class ScreenSaverDefeater : public Timer,
  224558. public DeletedAtShutdown
  224559. {
  224560. public:
  224561. ScreenSaverDefeater()
  224562. {
  224563. startTimer (10000);
  224564. timerCallback();
  224565. }
  224566. ~ScreenSaverDefeater() {}
  224567. void timerCallback()
  224568. {
  224569. if (Process::isForegroundProcess())
  224570. UpdateSystemActivity (UsrActivity);
  224571. }
  224572. };
  224573. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224574. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224575. {
  224576. if (isEnabled)
  224577. deleteAndZero (screenSaverDefeater);
  224578. else if (screenSaverDefeater == 0)
  224579. screenSaverDefeater = new ScreenSaverDefeater();
  224580. }
  224581. bool Desktop::isScreenSaverEnabled()
  224582. {
  224583. return screenSaverDefeater == 0;
  224584. }
  224585. #else
  224586. static IOPMAssertionID screenSaverDisablerID = 0;
  224587. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224588. {
  224589. if (isEnabled)
  224590. {
  224591. if (screenSaverDisablerID != 0)
  224592. {
  224593. IOPMAssertionRelease (screenSaverDisablerID);
  224594. screenSaverDisablerID = 0;
  224595. }
  224596. }
  224597. else
  224598. {
  224599. if (screenSaverDisablerID == 0)
  224600. {
  224601. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224602. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224603. CFSTR ("Juce"), &screenSaverDisablerID);
  224604. #else
  224605. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224606. &screenSaverDisablerID);
  224607. #endif
  224608. }
  224609. }
  224610. }
  224611. bool Desktop::isScreenSaverEnabled()
  224612. {
  224613. return screenSaverDisablerID == 0;
  224614. }
  224615. #endif
  224616. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224617. {
  224618. const ScopedAutoReleasePool pool;
  224619. monitorCoords.clear();
  224620. NSArray* screens = [NSScreen screens];
  224621. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224622. for (unsigned int i = 0; i < [screens count]; ++i)
  224623. {
  224624. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224625. NSRect r = clipToWorkArea ? [s visibleFrame]
  224626. : [s frame];
  224627. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224628. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224629. (int) r.size.width,
  224630. (int) r.size.height));
  224631. }
  224632. jassert (monitorCoords.size() > 0);
  224633. }
  224634. #endif
  224635. #endif
  224636. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224637. #endif
  224638. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224639. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224640. // compiled on its own).
  224641. #if JUCE_INCLUDED_FILE
  224642. void Logger::outputDebugString (const String& text)
  224643. {
  224644. std::cerr << text << std::endl;
  224645. }
  224646. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224647. {
  224648. static char testResult = 0;
  224649. if (testResult == 0)
  224650. {
  224651. struct kinfo_proc info;
  224652. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224653. size_t sz = sizeof (info);
  224654. sysctl (m, 4, &info, &sz, 0, 0);
  224655. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224656. }
  224657. return testResult > 0;
  224658. }
  224659. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224660. {
  224661. return juce_isRunningUnderDebugger();
  224662. }
  224663. #endif
  224664. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224665. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224666. #if JUCE_IPHONE
  224667. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224668. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224669. // compiled on its own).
  224670. #if JUCE_INCLUDED_FILE
  224671. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224672. #define SUPPORT_10_4_FONTS 1
  224673. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224674. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224675. #define SUPPORT_ONLY_10_4_FONTS 1
  224676. #endif
  224677. END_JUCE_NAMESPACE
  224678. @interface NSFont (PrivateHack)
  224679. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224680. @end
  224681. BEGIN_JUCE_NAMESPACE
  224682. #endif
  224683. class MacTypeface : public Typeface
  224684. {
  224685. public:
  224686. MacTypeface (const Font& font)
  224687. : Typeface (font.getTypefaceName())
  224688. {
  224689. const ScopedAutoReleasePool pool;
  224690. renderingTransform = CGAffineTransformIdentity;
  224691. bool needsItalicTransform = false;
  224692. #if JUCE_IPHONE
  224693. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224694. if (font.isItalic() || font.isBold())
  224695. {
  224696. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224697. for (NSString* i in familyFonts)
  224698. {
  224699. const String fn (nsStringToJuce (i));
  224700. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224701. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224702. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224703. || afterDash.containsIgnoreCase ("italic")
  224704. || fn.endsWithIgnoreCase ("oblique")
  224705. || fn.endsWithIgnoreCase ("italic");
  224706. if (probablyBold == font.isBold()
  224707. && probablyItalic == font.isItalic())
  224708. {
  224709. fontName = i;
  224710. needsItalicTransform = false;
  224711. break;
  224712. }
  224713. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224714. {
  224715. fontName = i;
  224716. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224717. }
  224718. }
  224719. if (needsItalicTransform)
  224720. renderingTransform.c = 0.15f;
  224721. }
  224722. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224723. const int ascender = abs (CGFontGetAscent (fontRef));
  224724. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224725. ascent = ascender / totalHeight;
  224726. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224727. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224728. #else
  224729. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224730. if (font.isItalic())
  224731. {
  224732. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224733. toHaveTrait: NSItalicFontMask];
  224734. if (newFont == nsFont)
  224735. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224736. nsFont = newFont;
  224737. }
  224738. if (font.isBold())
  224739. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224740. [nsFont retain];
  224741. ascent = std::abs ((float) [nsFont ascender]);
  224742. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224743. ascent /= totalSize;
  224744. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224745. if (needsItalicTransform)
  224746. {
  224747. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224748. renderingTransform.c = 0.15f;
  224749. }
  224750. #if SUPPORT_ONLY_10_4_FONTS
  224751. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224752. if (atsFont == 0)
  224753. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224754. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224755. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224756. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224757. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224758. #else
  224759. #if SUPPORT_10_4_FONTS
  224760. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224761. {
  224762. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224763. if (atsFont == 0)
  224764. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224765. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224766. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224767. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224768. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224769. }
  224770. else
  224771. #endif
  224772. {
  224773. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224774. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224775. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224776. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224777. }
  224778. #endif
  224779. #endif
  224780. }
  224781. ~MacTypeface()
  224782. {
  224783. #if ! JUCE_IPHONE
  224784. [nsFont release];
  224785. #endif
  224786. if (fontRef != 0)
  224787. CGFontRelease (fontRef);
  224788. }
  224789. float getAscent() const
  224790. {
  224791. return ascent;
  224792. }
  224793. float getDescent() const
  224794. {
  224795. return 1.0f - ascent;
  224796. }
  224797. float getStringWidth (const String& text)
  224798. {
  224799. if (fontRef == 0 || text.isEmpty())
  224800. return 0;
  224801. const int length = text.length();
  224802. HeapBlock <CGGlyph> glyphs;
  224803. createGlyphsForString (text, length, glyphs);
  224804. float x = 0;
  224805. #if SUPPORT_ONLY_10_4_FONTS
  224806. HeapBlock <NSSize> advances (length);
  224807. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224808. for (int i = 0; i < length; ++i)
  224809. x += advances[i].width;
  224810. #else
  224811. #if SUPPORT_10_4_FONTS
  224812. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224813. {
  224814. HeapBlock <NSSize> advances (length);
  224815. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  224816. for (int i = 0; i < length; ++i)
  224817. x += advances[i].width;
  224818. }
  224819. else
  224820. #endif
  224821. {
  224822. HeapBlock <int> advances (length);
  224823. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224824. for (int i = 0; i < length; ++i)
  224825. x += advances[i];
  224826. }
  224827. #endif
  224828. return x * unitsToHeightScaleFactor;
  224829. }
  224830. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  224831. {
  224832. xOffsets.add (0);
  224833. if (fontRef == 0 || text.isEmpty())
  224834. return;
  224835. const int length = text.length();
  224836. HeapBlock <CGGlyph> glyphs;
  224837. createGlyphsForString (text, length, glyphs);
  224838. #if SUPPORT_ONLY_10_4_FONTS
  224839. HeapBlock <NSSize> advances (length);
  224840. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224841. int x = 0;
  224842. for (int i = 0; i < length; ++i)
  224843. {
  224844. x += advances[i].width;
  224845. xOffsets.add (x * unitsToHeightScaleFactor);
  224846. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  224847. }
  224848. #else
  224849. #if SUPPORT_10_4_FONTS
  224850. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224851. {
  224852. HeapBlock <NSSize> advances (length);
  224853. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224854. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  224855. float x = 0;
  224856. for (int i = 0; i < length; ++i)
  224857. {
  224858. x += advances[i].width;
  224859. xOffsets.add (x * unitsToHeightScaleFactor);
  224860. resultGlyphs.add (nsGlyphs[i]);
  224861. }
  224862. }
  224863. else
  224864. #endif
  224865. {
  224866. HeapBlock <int> advances (length);
  224867. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224868. {
  224869. int x = 0;
  224870. for (int i = 0; i < length; ++i)
  224871. {
  224872. x += advances [i];
  224873. xOffsets.add (x * unitsToHeightScaleFactor);
  224874. resultGlyphs.add (glyphs[i]);
  224875. }
  224876. }
  224877. }
  224878. #endif
  224879. }
  224880. bool getOutlineForGlyph (int glyphNumber, Path& path)
  224881. {
  224882. #if JUCE_IPHONE
  224883. return false;
  224884. #else
  224885. if (nsFont == 0)
  224886. return false;
  224887. // we might need to apply a transform to the path, so it mustn't have anything else in it
  224888. jassert (path.isEmpty());
  224889. const ScopedAutoReleasePool pool;
  224890. NSBezierPath* bez = [NSBezierPath bezierPath];
  224891. [bez moveToPoint: NSMakePoint (0, 0)];
  224892. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  224893. inFont: nsFont];
  224894. for (int i = 0; i < [bez elementCount]; ++i)
  224895. {
  224896. NSPoint p[3];
  224897. switch ([bez elementAtIndex: i associatedPoints: p])
  224898. {
  224899. case NSMoveToBezierPathElement:
  224900. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  224901. break;
  224902. case NSLineToBezierPathElement:
  224903. path.lineTo ((float) p[0].x, (float) -p[0].y);
  224904. break;
  224905. case NSCurveToBezierPathElement:
  224906. 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);
  224907. break;
  224908. case NSClosePathBezierPathElement:
  224909. path.closeSubPath();
  224910. break;
  224911. default:
  224912. jassertfalse;
  224913. break;
  224914. }
  224915. }
  224916. path.applyTransform (pathTransform);
  224917. return true;
  224918. #endif
  224919. }
  224920. juce_UseDebuggingNewOperator
  224921. CGFontRef fontRef;
  224922. float fontHeightToCGSizeFactor;
  224923. CGAffineTransform renderingTransform;
  224924. private:
  224925. float ascent, unitsToHeightScaleFactor;
  224926. #if JUCE_IPHONE
  224927. #else
  224928. NSFont* nsFont;
  224929. AffineTransform pathTransform;
  224930. #endif
  224931. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  224932. {
  224933. #if SUPPORT_10_4_FONTS
  224934. #if ! SUPPORT_ONLY_10_4_FONTS
  224935. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224936. #endif
  224937. {
  224938. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  224939. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224940. for (int i = 0; i < length; ++i)
  224941. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  224942. return;
  224943. }
  224944. #endif
  224945. #if ! SUPPORT_ONLY_10_4_FONTS
  224946. if (charToGlyphMapper == 0)
  224947. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  224948. glyphs.malloc (length);
  224949. for (int i = 0; i < length; ++i)
  224950. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  224951. #endif
  224952. }
  224953. #if ! SUPPORT_ONLY_10_4_FONTS
  224954. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  224955. class CharToGlyphMapper
  224956. {
  224957. public:
  224958. CharToGlyphMapper (CGFontRef fontRef)
  224959. : segCount (0), endCode (0), startCode (0), idDelta (0),
  224960. idRangeOffset (0), glyphIndexes (0)
  224961. {
  224962. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  224963. if (cmapTable != 0)
  224964. {
  224965. const int numSubtables = getValue16 (cmapTable, 2);
  224966. for (int i = 0; i < numSubtables; ++i)
  224967. {
  224968. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  224969. {
  224970. const int offset = getValue32 (cmapTable, i * 8 + 8);
  224971. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  224972. {
  224973. const int length = getValue16 (cmapTable, offset + 2);
  224974. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  224975. segCount = segCountX2 / 2;
  224976. const int endCodeOffset = offset + 14;
  224977. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  224978. const int idDeltaOffset = startCodeOffset + segCountX2;
  224979. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  224980. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  224981. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  224982. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  224983. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  224984. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  224985. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  224986. }
  224987. break;
  224988. }
  224989. }
  224990. CFRelease (cmapTable);
  224991. }
  224992. }
  224993. ~CharToGlyphMapper()
  224994. {
  224995. if (endCode != 0)
  224996. {
  224997. CFRelease (endCode);
  224998. CFRelease (startCode);
  224999. CFRelease (idDelta);
  225000. CFRelease (idRangeOffset);
  225001. CFRelease (glyphIndexes);
  225002. }
  225003. }
  225004. int getGlyphForCharacter (const juce_wchar c) const
  225005. {
  225006. for (int i = 0; i < segCount; ++i)
  225007. {
  225008. if (getValue16 (endCode, i * 2) >= c)
  225009. {
  225010. const int start = getValue16 (startCode, i * 2);
  225011. if (start > c)
  225012. break;
  225013. const int delta = getValue16 (idDelta, i * 2);
  225014. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225015. if (rangeOffset == 0)
  225016. return delta + c;
  225017. else
  225018. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225019. }
  225020. }
  225021. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225022. return jmax (-1, c - 29);
  225023. }
  225024. private:
  225025. int segCount;
  225026. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225027. static uint16 getValue16 (CFDataRef data, const int index)
  225028. {
  225029. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225030. }
  225031. static uint32 getValue32 (CFDataRef data, const int index)
  225032. {
  225033. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225034. }
  225035. };
  225036. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225037. #endif
  225038. MacTypeface (const MacTypeface&);
  225039. MacTypeface& operator= (const MacTypeface&);
  225040. };
  225041. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225042. {
  225043. return new MacTypeface (font);
  225044. }
  225045. const StringArray Font::findAllTypefaceNames()
  225046. {
  225047. StringArray names;
  225048. const ScopedAutoReleasePool pool;
  225049. #if JUCE_IPHONE
  225050. NSArray* fonts = [UIFont familyNames];
  225051. #else
  225052. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225053. #endif
  225054. for (unsigned int i = 0; i < [fonts count]; ++i)
  225055. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225056. names.sort (true);
  225057. return names;
  225058. }
  225059. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  225060. {
  225061. #if JUCE_IPHONE
  225062. defaultSans = "Helvetica";
  225063. defaultSerif = "Times New Roman";
  225064. defaultFixed = "Courier New";
  225065. #else
  225066. defaultSans = "Lucida Grande";
  225067. defaultSerif = "Times New Roman";
  225068. defaultFixed = "Monaco";
  225069. #endif
  225070. }
  225071. #endif
  225072. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225073. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225074. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225075. // compiled on its own).
  225076. #if JUCE_INCLUDED_FILE
  225077. class CoreGraphicsImage : public Image::SharedImage
  225078. {
  225079. public:
  225080. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225081. : Image::SharedImage (format_, width_, height_)
  225082. {
  225083. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225084. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225085. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225086. imageData = imageDataAllocated;
  225087. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225088. : CGColorSpaceCreateDeviceRGB();
  225089. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225090. colourSpace, getCGImageFlags (format_));
  225091. CGColorSpaceRelease (colourSpace);
  225092. }
  225093. ~CoreGraphicsImage()
  225094. {
  225095. CGContextRelease (context);
  225096. }
  225097. Image::ImageType getType() const { return Image::NativeImage; }
  225098. LowLevelGraphicsContext* createLowLevelContext();
  225099. SharedImage* clone()
  225100. {
  225101. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225102. memcpy (im->imageData, imageData, lineStride * height);
  225103. return im;
  225104. }
  225105. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  225106. {
  225107. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225108. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225109. {
  225110. return CGBitmapContextCreateImage (nativeImage->context);
  225111. }
  225112. else
  225113. {
  225114. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  225115. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225116. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225117. 8, srcData.pixelStride * 8, srcData.lineStride,
  225118. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225119. 0, true, kCGRenderingIntentDefault);
  225120. CGDataProviderRelease (provider);
  225121. return imageRef;
  225122. }
  225123. }
  225124. #if JUCE_MAC
  225125. static NSImage* createNSImage (const Image& image)
  225126. {
  225127. const ScopedAutoReleasePool pool;
  225128. NSImage* im = [[NSImage alloc] init];
  225129. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225130. [im lockFocus];
  225131. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225132. CGImageRef imageRef = createImage (image, false, colourSpace);
  225133. CGColorSpaceRelease (colourSpace);
  225134. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225135. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225136. CGImageRelease (imageRef);
  225137. [im unlockFocus];
  225138. return im;
  225139. }
  225140. #endif
  225141. CGContextRef context;
  225142. HeapBlock<uint8> imageDataAllocated;
  225143. private:
  225144. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225145. {
  225146. #if JUCE_BIG_ENDIAN
  225147. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225148. #else
  225149. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225150. #endif
  225151. }
  225152. };
  225153. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225154. {
  225155. #if USE_COREGRAPHICS_RENDERING
  225156. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225157. #else
  225158. return createSoftwareImage (format, width, height, clearImage);
  225159. #endif
  225160. }
  225161. class CoreGraphicsContext : public LowLevelGraphicsContext
  225162. {
  225163. public:
  225164. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225165. : context (context_),
  225166. flipHeight (flipHeight_),
  225167. state (new SavedState()),
  225168. numGradientLookupEntries (0),
  225169. lastClipRectIsValid (false)
  225170. {
  225171. CGContextRetain (context);
  225172. CGContextSaveGState(context);
  225173. CGContextSetShouldSmoothFonts (context, true);
  225174. CGContextSetShouldAntialias (context, true);
  225175. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225176. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225177. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225178. gradientCallbacks.version = 0;
  225179. gradientCallbacks.evaluate = gradientCallback;
  225180. gradientCallbacks.releaseInfo = 0;
  225181. setFont (Font());
  225182. }
  225183. ~CoreGraphicsContext()
  225184. {
  225185. CGContextRestoreGState (context);
  225186. CGContextRelease (context);
  225187. CGColorSpaceRelease (rgbColourSpace);
  225188. CGColorSpaceRelease (greyColourSpace);
  225189. }
  225190. bool isVectorDevice() const { return false; }
  225191. void setOrigin (int x, int y)
  225192. {
  225193. CGContextTranslateCTM (context, x, -y);
  225194. if (lastClipRectIsValid)
  225195. lastClipRect.translate (-x, -y);
  225196. }
  225197. bool clipToRectangle (const Rectangle<int>& r)
  225198. {
  225199. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225200. if (lastClipRectIsValid)
  225201. {
  225202. lastClipRect = lastClipRect.getIntersection (r);
  225203. return ! lastClipRect.isEmpty();
  225204. }
  225205. return ! isClipEmpty();
  225206. }
  225207. bool clipToRectangleList (const RectangleList& clipRegion)
  225208. {
  225209. if (clipRegion.isEmpty())
  225210. {
  225211. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225212. lastClipRectIsValid = true;
  225213. lastClipRect = Rectangle<int>();
  225214. return false;
  225215. }
  225216. else
  225217. {
  225218. const int numRects = clipRegion.getNumRectangles();
  225219. HeapBlock <CGRect> rects (numRects);
  225220. for (int i = 0; i < numRects; ++i)
  225221. {
  225222. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225223. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225224. }
  225225. CGContextClipToRects (context, rects, numRects);
  225226. lastClipRectIsValid = false;
  225227. return ! isClipEmpty();
  225228. }
  225229. }
  225230. void excludeClipRectangle (const Rectangle<int>& r)
  225231. {
  225232. RectangleList remaining (getClipBounds());
  225233. remaining.subtract (r);
  225234. clipToRectangleList (remaining);
  225235. lastClipRectIsValid = false;
  225236. }
  225237. void clipToPath (const Path& path, const AffineTransform& transform)
  225238. {
  225239. createPath (path, transform);
  225240. CGContextClip (context);
  225241. lastClipRectIsValid = false;
  225242. }
  225243. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  225244. {
  225245. if (! transform.isSingularity())
  225246. {
  225247. Image singleChannelImage (sourceImage);
  225248. if (sourceImage.getFormat() != Image::SingleChannel)
  225249. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225250. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225251. if (srcClip != sourceImage.getBounds())
  225252. {
  225253. CGImageRef fullImage = image;
  225254. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225255. srcClip.getWidth(), srcClip.getHeight()));
  225256. CGImageRelease (fullImage);
  225257. }
  225258. flip();
  225259. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225260. applyTransform (t);
  225261. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225262. CGContextClipToMask (context, r, image);
  225263. applyTransform (t.inverted());
  225264. flip();
  225265. CGImageRelease (image);
  225266. lastClipRectIsValid = false;
  225267. }
  225268. }
  225269. bool clipRegionIntersects (const Rectangle<int>& r)
  225270. {
  225271. return getClipBounds().intersects (r);
  225272. }
  225273. const Rectangle<int> getClipBounds() const
  225274. {
  225275. if (! lastClipRectIsValid)
  225276. {
  225277. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225278. lastClipRectIsValid = true;
  225279. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225280. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225281. roundToInt (bounds.size.width),
  225282. roundToInt (bounds.size.height));
  225283. }
  225284. return lastClipRect;
  225285. }
  225286. bool isClipEmpty() const
  225287. {
  225288. return getClipBounds().isEmpty();
  225289. }
  225290. void saveState()
  225291. {
  225292. CGContextSaveGState (context);
  225293. stateStack.add (new SavedState (*state));
  225294. }
  225295. void restoreState()
  225296. {
  225297. CGContextRestoreGState (context);
  225298. SavedState* const top = stateStack.getLast();
  225299. if (top != 0)
  225300. {
  225301. state = top;
  225302. stateStack.removeLast (1, false);
  225303. lastClipRectIsValid = false;
  225304. }
  225305. else
  225306. {
  225307. jassertfalse; // trying to pop with an empty stack!
  225308. }
  225309. }
  225310. void setFill (const FillType& fillType)
  225311. {
  225312. state->fillType = fillType;
  225313. if (fillType.isColour())
  225314. {
  225315. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225316. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225317. CGContextSetAlpha (context, 1.0f);
  225318. }
  225319. }
  225320. void setOpacity (float newOpacity)
  225321. {
  225322. state->fillType.setOpacity (newOpacity);
  225323. setFill (state->fillType);
  225324. }
  225325. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225326. {
  225327. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225328. ? kCGInterpolationLow
  225329. : kCGInterpolationHigh);
  225330. }
  225331. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225332. {
  225333. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225334. if (replaceExistingContents)
  225335. {
  225336. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225337. CGContextClearRect (context, cgRect);
  225338. #else
  225339. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225340. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225341. CGContextClearRect (context, cgRect);
  225342. else
  225343. #endif
  225344. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225345. #endif
  225346. fillRect (r, false);
  225347. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225348. }
  225349. else
  225350. {
  225351. if (state->fillType.isColour())
  225352. {
  225353. CGContextFillRect (context, cgRect);
  225354. }
  225355. else if (state->fillType.isGradient())
  225356. {
  225357. CGContextSaveGState (context);
  225358. CGContextClipToRect (context, cgRect);
  225359. drawGradient();
  225360. CGContextRestoreGState (context);
  225361. }
  225362. else
  225363. {
  225364. CGContextSaveGState (context);
  225365. CGContextClipToRect (context, cgRect);
  225366. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225367. CGContextRestoreGState (context);
  225368. }
  225369. }
  225370. }
  225371. void fillPath (const Path& path, const AffineTransform& transform)
  225372. {
  225373. CGContextSaveGState (context);
  225374. if (state->fillType.isColour())
  225375. {
  225376. flip();
  225377. applyTransform (transform);
  225378. createPath (path);
  225379. if (path.isUsingNonZeroWinding())
  225380. CGContextFillPath (context);
  225381. else
  225382. CGContextEOFillPath (context);
  225383. }
  225384. else
  225385. {
  225386. createPath (path, transform);
  225387. if (path.isUsingNonZeroWinding())
  225388. CGContextClip (context);
  225389. else
  225390. CGContextEOClip (context);
  225391. if (state->fillType.isGradient())
  225392. drawGradient();
  225393. else
  225394. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225395. }
  225396. CGContextRestoreGState (context);
  225397. }
  225398. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  225399. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225400. {
  225401. jassert (sourceImage.getBounds().contains (srcClip));
  225402. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225403. CGImageRef image = fullImage;
  225404. if (srcClip != sourceImage.getBounds())
  225405. {
  225406. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225407. srcClip.getWidth(), srcClip.getHeight()));
  225408. CGImageRelease (fullImage);
  225409. }
  225410. CGContextSaveGState (context);
  225411. CGContextSetAlpha (context, state->fillType.getOpacity());
  225412. flip();
  225413. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225414. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225415. if (fillEntireClipAsTiles)
  225416. {
  225417. #if JUCE_IPHONE
  225418. CGContextDrawTiledImage (context, imageRect, image);
  225419. #else
  225420. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225421. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225422. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225423. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225424. CGContextDrawTiledImage (context, imageRect, image);
  225425. else
  225426. #endif
  225427. {
  225428. // Fallback to manually doing a tiled fill on 10.4
  225429. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225430. const int iw = srcClip.getWidth();
  225431. const int ih = srcClip.getHeight();
  225432. int x = 0, y = 0;
  225433. while (x > clip.origin.x) x -= iw;
  225434. while (y > clip.origin.y) y -= ih;
  225435. const int right = (int) (clip.origin.x + clip.size.width);
  225436. const int bottom = (int) (clip.origin.y + clip.size.height);
  225437. while (y < bottom)
  225438. {
  225439. for (int x2 = x; x2 < right; x2 += iw)
  225440. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225441. y += ih;
  225442. }
  225443. }
  225444. #endif
  225445. }
  225446. else
  225447. {
  225448. CGContextDrawImage (context, imageRect, image);
  225449. }
  225450. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225451. CGContextRestoreGState (context);
  225452. }
  225453. void drawLine (const Line<float>& line)
  225454. {
  225455. CGContextSetLineCap (context, kCGLineCapSquare);
  225456. CGContextSetLineWidth (context, 1.0f);
  225457. CGContextSetRGBStrokeColor (context,
  225458. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225459. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225460. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225461. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225462. CGContextStrokeLineSegments (context, cgLine, 1);
  225463. }
  225464. void drawVerticalLine (const int x, float top, float bottom)
  225465. {
  225466. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225467. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225468. #else
  225469. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225470. // the x co-ord slightly to trick it..
  225471. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225472. #endif
  225473. }
  225474. void drawHorizontalLine (const int y, float left, float right)
  225475. {
  225476. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225477. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225478. #else
  225479. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225480. // the x co-ord slightly to trick it..
  225481. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225482. #endif
  225483. }
  225484. void setFont (const Font& newFont)
  225485. {
  225486. if (state->font != newFont)
  225487. {
  225488. state->fontRef = 0;
  225489. state->font = newFont;
  225490. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225491. if (mf != 0)
  225492. {
  225493. state->fontRef = mf->fontRef;
  225494. CGContextSetFont (context, state->fontRef);
  225495. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225496. state->fontTransform = mf->renderingTransform;
  225497. state->fontTransform.a *= state->font.getHorizontalScale();
  225498. CGContextSetTextMatrix (context, state->fontTransform);
  225499. }
  225500. }
  225501. }
  225502. const Font getFont()
  225503. {
  225504. return state->font;
  225505. }
  225506. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225507. {
  225508. if (state->fontRef != 0 && state->fillType.isColour())
  225509. {
  225510. if (transform.isOnlyTranslation())
  225511. {
  225512. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225513. CGGlyph g = glyphNumber;
  225514. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225515. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225516. }
  225517. else
  225518. {
  225519. CGContextSaveGState (context);
  225520. flip();
  225521. applyTransform (transform);
  225522. CGAffineTransform t = state->fontTransform;
  225523. t.d = -t.d;
  225524. CGContextSetTextMatrix (context, t);
  225525. CGGlyph g = glyphNumber;
  225526. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225527. CGContextRestoreGState (context);
  225528. }
  225529. }
  225530. else
  225531. {
  225532. Path p;
  225533. Font& f = state->font;
  225534. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225535. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225536. .followedBy (transform));
  225537. }
  225538. }
  225539. private:
  225540. CGContextRef context;
  225541. const CGFloat flipHeight;
  225542. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225543. CGFunctionCallbacks gradientCallbacks;
  225544. mutable Rectangle<int> lastClipRect;
  225545. mutable bool lastClipRectIsValid;
  225546. struct SavedState
  225547. {
  225548. SavedState()
  225549. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225550. {
  225551. }
  225552. SavedState (const SavedState& other)
  225553. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225554. fontTransform (other.fontTransform)
  225555. {
  225556. }
  225557. ~SavedState()
  225558. {
  225559. }
  225560. FillType fillType;
  225561. Font font;
  225562. CGFontRef fontRef;
  225563. CGAffineTransform fontTransform;
  225564. };
  225565. ScopedPointer <SavedState> state;
  225566. OwnedArray <SavedState> stateStack;
  225567. HeapBlock <PixelARGB> gradientLookupTable;
  225568. int numGradientLookupEntries;
  225569. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225570. {
  225571. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225572. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225573. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225574. colour.unpremultiply();
  225575. outData[0] = colour.getRed() / 255.0f;
  225576. outData[1] = colour.getGreen() / 255.0f;
  225577. outData[2] = colour.getBlue() / 255.0f;
  225578. outData[3] = colour.getAlpha() / 255.0f;
  225579. }
  225580. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225581. {
  225582. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225583. --numGradientLookupEntries;
  225584. CGShadingRef result = 0;
  225585. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225586. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225587. if (gradient.isRadial)
  225588. {
  225589. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225590. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225591. function, true, true);
  225592. }
  225593. else
  225594. {
  225595. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225596. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225597. function, true, true);
  225598. }
  225599. CGFunctionRelease (function);
  225600. return result;
  225601. }
  225602. void drawGradient()
  225603. {
  225604. flip();
  225605. applyTransform (state->fillType.transform);
  225606. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225607. // you draw a gradient with high quality interp enabled).
  225608. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225609. CGContextSetAlpha (context, state->fillType.getOpacity());
  225610. CGContextDrawShading (context, shading);
  225611. CGShadingRelease (shading);
  225612. }
  225613. void createPath (const Path& path) const
  225614. {
  225615. CGContextBeginPath (context);
  225616. Path::Iterator i (path);
  225617. while (i.next())
  225618. {
  225619. switch (i.elementType)
  225620. {
  225621. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225622. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225623. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225624. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225625. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225626. default: jassertfalse; break;
  225627. }
  225628. }
  225629. }
  225630. void createPath (const Path& path, const AffineTransform& transform) const
  225631. {
  225632. CGContextBeginPath (context);
  225633. Path::Iterator i (path);
  225634. while (i.next())
  225635. {
  225636. switch (i.elementType)
  225637. {
  225638. case Path::Iterator::startNewSubPath:
  225639. transform.transformPoint (i.x1, i.y1);
  225640. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225641. break;
  225642. case Path::Iterator::lineTo:
  225643. transform.transformPoint (i.x1, i.y1);
  225644. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225645. break;
  225646. case Path::Iterator::quadraticTo:
  225647. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  225648. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225649. break;
  225650. case Path::Iterator::cubicTo:
  225651. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  225652. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225653. break;
  225654. case Path::Iterator::closePath:
  225655. CGContextClosePath (context); break;
  225656. default:
  225657. jassertfalse;
  225658. break;
  225659. }
  225660. }
  225661. }
  225662. void flip() const
  225663. {
  225664. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225665. }
  225666. void applyTransform (const AffineTransform& transform) const
  225667. {
  225668. CGAffineTransform t;
  225669. t.a = transform.mat00;
  225670. t.b = transform.mat10;
  225671. t.c = transform.mat01;
  225672. t.d = transform.mat11;
  225673. t.tx = transform.mat02;
  225674. t.ty = transform.mat12;
  225675. CGContextConcatCTM (context, t);
  225676. }
  225677. CoreGraphicsContext (const CoreGraphicsContext&);
  225678. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225679. };
  225680. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225681. {
  225682. return new CoreGraphicsContext (context, height);
  225683. }
  225684. #endif
  225685. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225686. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225687. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225688. // compiled on its own).
  225689. #if JUCE_INCLUDED_FILE
  225690. class UIViewComponentPeer;
  225691. END_JUCE_NAMESPACE
  225692. #define JuceUIView MakeObjCClassName(JuceUIView)
  225693. @interface JuceUIView : UIView <UITextFieldDelegate>
  225694. {
  225695. @public
  225696. UIViewComponentPeer* owner;
  225697. UITextField *hiddenTextField;
  225698. }
  225699. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225700. - (void) dealloc;
  225701. - (void) drawRect: (CGRect) r;
  225702. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225703. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225704. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225705. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225706. - (BOOL) becomeFirstResponder;
  225707. - (BOOL) resignFirstResponder;
  225708. - (BOOL) canBecomeFirstResponder;
  225709. - (void) asyncRepaint: (id) rect;
  225710. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225711. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225712. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225713. @end
  225714. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225715. @interface JuceUIWindow : UIWindow
  225716. {
  225717. @private
  225718. UIViewComponentPeer* owner;
  225719. bool isZooming;
  225720. }
  225721. - (void) setOwner: (UIViewComponentPeer*) owner;
  225722. - (void) becomeKeyWindow;
  225723. @end
  225724. BEGIN_JUCE_NAMESPACE
  225725. class UIViewComponentPeer : public ComponentPeer,
  225726. public FocusChangeListener
  225727. {
  225728. public:
  225729. UIViewComponentPeer (Component* const component,
  225730. const int windowStyleFlags,
  225731. UIView* viewToAttachTo);
  225732. ~UIViewComponentPeer();
  225733. void* getNativeHandle() const;
  225734. void setVisible (bool shouldBeVisible);
  225735. void setTitle (const String& title);
  225736. void setPosition (int x, int y);
  225737. void setSize (int w, int h);
  225738. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225739. const Rectangle<int> getBounds() const;
  225740. const Rectangle<int> getBounds (const bool global) const;
  225741. const Point<int> getScreenPosition() const;
  225742. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225743. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225744. void setMinimised (bool shouldBeMinimised);
  225745. bool isMinimised() const;
  225746. void setFullScreen (bool shouldBeFullScreen);
  225747. bool isFullScreen() const;
  225748. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225749. const BorderSize getFrameSize() const;
  225750. bool setAlwaysOnTop (bool alwaysOnTop);
  225751. void toFront (bool makeActiveWindow);
  225752. void toBehind (ComponentPeer* other);
  225753. void setIcon (const Image& newIcon);
  225754. virtual void drawRect (CGRect r);
  225755. virtual bool canBecomeKeyWindow();
  225756. virtual bool windowShouldClose();
  225757. virtual void redirectMovedOrResized();
  225758. virtual CGRect constrainRect (CGRect r);
  225759. virtual void viewFocusGain();
  225760. virtual void viewFocusLoss();
  225761. bool isFocused() const;
  225762. void grabFocus();
  225763. void textInputRequired (const Point<int>& position);
  225764. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225765. virtual BOOL textFieldShouldClear();
  225766. virtual BOOL textFieldShouldReturn();
  225767. void updateHiddenTextContent (TextInputTarget* target);
  225768. void globalFocusChanged (Component*);
  225769. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225770. void repaint (const Rectangle<int>& area);
  225771. void performAnyPendingRepaintsNow();
  225772. juce_UseDebuggingNewOperator
  225773. UIWindow* window;
  225774. JuceUIView* view;
  225775. bool isSharedWindow, fullScreen, insideDrawRect;
  225776. static ModifierKeys currentModifiers;
  225777. static int64 getMouseTime (UIEvent* e)
  225778. {
  225779. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225780. + (int64) ([e timestamp] * 1000.0);
  225781. }
  225782. Array <UITouch*> currentTouches;
  225783. };
  225784. END_JUCE_NAMESPACE
  225785. @implementation JuceUIView
  225786. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225787. withFrame: (CGRect) frame
  225788. {
  225789. [super initWithFrame: frame];
  225790. owner = owner_;
  225791. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225792. [self addSubview: hiddenTextField];
  225793. hiddenTextField.delegate = self;
  225794. return self;
  225795. }
  225796. - (void) dealloc
  225797. {
  225798. [hiddenTextField removeFromSuperview];
  225799. [hiddenTextField release];
  225800. [super dealloc];
  225801. }
  225802. - (void) drawRect: (CGRect) r
  225803. {
  225804. if (owner != 0)
  225805. owner->drawRect (r);
  225806. }
  225807. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225808. {
  225809. return false;
  225810. }
  225811. ModifierKeys UIViewComponentPeer::currentModifiers;
  225812. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225813. {
  225814. return UIViewComponentPeer::currentModifiers;
  225815. }
  225816. void ModifierKeys::updateCurrentModifiers() throw()
  225817. {
  225818. currentModifiers = UIViewComponentPeer::currentModifiers;
  225819. }
  225820. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225821. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225822. {
  225823. if (owner != 0)
  225824. owner->handleTouches (event, true, false, false);
  225825. }
  225826. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  225827. {
  225828. if (owner != 0)
  225829. owner->handleTouches (event, false, false, false);
  225830. }
  225831. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  225832. {
  225833. if (owner != 0)
  225834. owner->handleTouches (event, false, true, false);
  225835. }
  225836. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  225837. {
  225838. if (owner != 0)
  225839. owner->handleTouches (event, false, true, true);
  225840. [self touchesEnded: touches withEvent: event];
  225841. }
  225842. - (BOOL) becomeFirstResponder
  225843. {
  225844. if (owner != 0)
  225845. owner->viewFocusGain();
  225846. return true;
  225847. }
  225848. - (BOOL) resignFirstResponder
  225849. {
  225850. if (owner != 0)
  225851. owner->viewFocusLoss();
  225852. return true;
  225853. }
  225854. - (BOOL) canBecomeFirstResponder
  225855. {
  225856. return owner != 0 && owner->canBecomeKeyWindow();
  225857. }
  225858. - (void) asyncRepaint: (id) rect
  225859. {
  225860. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  225861. [self setNeedsDisplayInRect: *r];
  225862. }
  225863. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  225864. {
  225865. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  225866. nsStringToJuce (text));
  225867. }
  225868. - (BOOL) textFieldShouldClear: (UITextField*) textField
  225869. {
  225870. return owner->textFieldShouldClear();
  225871. }
  225872. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  225873. {
  225874. return owner->textFieldShouldReturn();
  225875. }
  225876. @end
  225877. @implementation JuceUIWindow
  225878. - (void) setOwner: (UIViewComponentPeer*) owner_
  225879. {
  225880. owner = owner_;
  225881. isZooming = false;
  225882. }
  225883. - (void) becomeKeyWindow
  225884. {
  225885. [super becomeKeyWindow];
  225886. if (owner != 0)
  225887. owner->grabFocus();
  225888. }
  225889. @end
  225890. BEGIN_JUCE_NAMESPACE
  225891. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  225892. const int windowStyleFlags,
  225893. UIView* viewToAttachTo)
  225894. : ComponentPeer (component, windowStyleFlags),
  225895. window (0),
  225896. view (0),
  225897. isSharedWindow (viewToAttachTo != 0),
  225898. fullScreen (false),
  225899. insideDrawRect (false)
  225900. {
  225901. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  225902. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  225903. if (isSharedWindow)
  225904. {
  225905. window = [viewToAttachTo window];
  225906. [viewToAttachTo addSubview: view];
  225907. setVisible (component->isVisible());
  225908. }
  225909. else
  225910. {
  225911. r.origin.x = (float) component->getX();
  225912. r.origin.y = (float) component->getY();
  225913. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  225914. window = [[JuceUIWindow alloc] init];
  225915. window.frame = r;
  225916. window.opaque = component->isOpaque();
  225917. view.opaque = component->isOpaque();
  225918. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225919. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225920. [((JuceUIWindow*) window) setOwner: this];
  225921. if (component->isAlwaysOnTop())
  225922. window.windowLevel = UIWindowLevelAlert;
  225923. [window addSubview: view];
  225924. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225925. view.hidden = ! component->isVisible();
  225926. window.hidden = ! component->isVisible();
  225927. view.multipleTouchEnabled = YES;
  225928. }
  225929. setTitle (component->getName());
  225930. Desktop::getInstance().addFocusChangeListener (this);
  225931. }
  225932. UIViewComponentPeer::~UIViewComponentPeer()
  225933. {
  225934. Desktop::getInstance().removeFocusChangeListener (this);
  225935. view->owner = 0;
  225936. [view removeFromSuperview];
  225937. [view release];
  225938. if (! isSharedWindow)
  225939. {
  225940. [((JuceUIWindow*) window) setOwner: 0];
  225941. [window release];
  225942. }
  225943. }
  225944. void* UIViewComponentPeer::getNativeHandle() const
  225945. {
  225946. return view;
  225947. }
  225948. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  225949. {
  225950. view.hidden = ! shouldBeVisible;
  225951. if (! isSharedWindow)
  225952. window.hidden = ! shouldBeVisible;
  225953. }
  225954. void UIViewComponentPeer::setTitle (const String& title)
  225955. {
  225956. // xxx is this possible?
  225957. }
  225958. void UIViewComponentPeer::setPosition (int x, int y)
  225959. {
  225960. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  225961. }
  225962. void UIViewComponentPeer::setSize (int w, int h)
  225963. {
  225964. setBounds (component->getX(), component->getY(), w, h, false);
  225965. }
  225966. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  225967. {
  225968. fullScreen = isNowFullScreen;
  225969. w = jmax (0, w);
  225970. h = jmax (0, h);
  225971. CGRect r;
  225972. r.origin.x = (float) x;
  225973. r.origin.y = (float) y;
  225974. r.size.width = (float) w;
  225975. r.size.height = (float) h;
  225976. if (isSharedWindow)
  225977. {
  225978. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225979. if ([view frame].size.width != r.size.width
  225980. || [view frame].size.height != r.size.height)
  225981. [view setNeedsDisplay];
  225982. view.frame = r;
  225983. }
  225984. else
  225985. {
  225986. window.frame = r;
  225987. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225988. }
  225989. }
  225990. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  225991. {
  225992. CGRect r = [view frame];
  225993. if (global && [view window] != 0)
  225994. {
  225995. r = [view convertRect: r toView: nil];
  225996. CGRect wr = [[view window] frame];
  225997. r.origin.x += wr.origin.x;
  225998. r.origin.y += wr.origin.y;
  225999. }
  226000. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  226001. (int) r.size.width, (int) r.size.height);
  226002. }
  226003. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226004. {
  226005. return getBounds (! isSharedWindow);
  226006. }
  226007. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226008. {
  226009. return getBounds (true).getPosition();
  226010. }
  226011. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  226012. {
  226013. return relativePosition + getScreenPosition();
  226014. }
  226015. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  226016. {
  226017. return screenPosition - getScreenPosition();
  226018. }
  226019. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226020. {
  226021. if (constrainer != 0)
  226022. {
  226023. CGRect current = [window frame];
  226024. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226025. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226026. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  226027. (int) r.size.width, (int) r.size.height);
  226028. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  226029. (int) current.size.width, (int) current.size.height);
  226030. constrainer->checkBounds (pos, original,
  226031. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226032. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226033. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226034. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226035. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226036. r.origin.x = pos.getX();
  226037. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226038. r.size.width = pos.getWidth();
  226039. r.size.height = pos.getHeight();
  226040. }
  226041. return r;
  226042. }
  226043. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226044. {
  226045. // xxx
  226046. }
  226047. bool UIViewComponentPeer::isMinimised() const
  226048. {
  226049. return false;
  226050. }
  226051. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226052. {
  226053. if (! isSharedWindow)
  226054. {
  226055. Rectangle<int> r (lastNonFullscreenBounds);
  226056. setMinimised (false);
  226057. if (fullScreen != shouldBeFullScreen)
  226058. {
  226059. if (shouldBeFullScreen)
  226060. r = Desktop::getInstance().getMainMonitorArea();
  226061. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226062. if (r != getComponent()->getBounds() && ! r.isEmpty())
  226063. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226064. }
  226065. }
  226066. }
  226067. bool UIViewComponentPeer::isFullScreen() const
  226068. {
  226069. return fullScreen;
  226070. }
  226071. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226072. {
  226073. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  226074. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  226075. return false;
  226076. CGPoint p;
  226077. p.x = (float) position.getX();
  226078. p.y = (float) position.getY();
  226079. UIView* v = [view hitTest: p withEvent: nil];
  226080. if (trueIfInAChildWindow)
  226081. return v != nil;
  226082. return v == view;
  226083. }
  226084. const BorderSize UIViewComponentPeer::getFrameSize() const
  226085. {
  226086. BorderSize b;
  226087. if (! isSharedWindow)
  226088. {
  226089. CGRect v = [view convertRect: [view frame] toView: nil];
  226090. CGRect w = [window frame];
  226091. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  226092. b.setBottom ((int) v.origin.y);
  226093. b.setLeft ((int) v.origin.x);
  226094. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  226095. }
  226096. return b;
  226097. }
  226098. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226099. {
  226100. if (! isSharedWindow)
  226101. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226102. return true;
  226103. }
  226104. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226105. {
  226106. if (isSharedWindow)
  226107. [[view superview] bringSubviewToFront: view];
  226108. if (window != 0 && component->isVisible())
  226109. [window makeKeyAndVisible];
  226110. }
  226111. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226112. {
  226113. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226114. jassert (otherPeer != 0); // wrong type of window?
  226115. if (otherPeer != 0)
  226116. {
  226117. if (isSharedWindow)
  226118. {
  226119. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226120. }
  226121. else
  226122. {
  226123. jassertfalse; // don't know how to do this
  226124. }
  226125. }
  226126. }
  226127. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226128. {
  226129. // to do..
  226130. }
  226131. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226132. {
  226133. NSArray* touches = [[event touchesForView: view] allObjects];
  226134. for (unsigned int i = 0; i < [touches count]; ++i)
  226135. {
  226136. UITouch* touch = [touches objectAtIndex: i];
  226137. CGPoint p = [touch locationInView: view];
  226138. const Point<int> pos ((int) p.x, (int) p.y);
  226139. juce_lastMousePos = pos + getScreenPosition();
  226140. const int64 time = getMouseTime (event);
  226141. int touchIndex = currentTouches.indexOf (touch);
  226142. if (touchIndex < 0)
  226143. {
  226144. touchIndex = currentTouches.size();
  226145. currentTouches.add (touch);
  226146. }
  226147. if (isDown)
  226148. {
  226149. currentModifiers = currentModifiers.withoutMouseButtons();
  226150. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226151. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226152. }
  226153. else if (isUp)
  226154. {
  226155. currentModifiers = currentModifiers.withoutMouseButtons();
  226156. currentTouches.remove (touchIndex);
  226157. }
  226158. if (isCancel)
  226159. currentTouches.clear();
  226160. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226161. }
  226162. }
  226163. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226164. void UIViewComponentPeer::viewFocusGain()
  226165. {
  226166. if (currentlyFocusedPeer != this)
  226167. {
  226168. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226169. currentlyFocusedPeer->handleFocusLoss();
  226170. currentlyFocusedPeer = this;
  226171. handleFocusGain();
  226172. }
  226173. }
  226174. void UIViewComponentPeer::viewFocusLoss()
  226175. {
  226176. if (currentlyFocusedPeer == this)
  226177. {
  226178. currentlyFocusedPeer = 0;
  226179. handleFocusLoss();
  226180. }
  226181. }
  226182. void juce_HandleProcessFocusChange()
  226183. {
  226184. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226185. {
  226186. if (Process::isForegroundProcess())
  226187. {
  226188. currentlyFocusedPeer->handleFocusGain();
  226189. ComponentPeer::bringModalComponentToFront();
  226190. }
  226191. else
  226192. {
  226193. currentlyFocusedPeer->handleFocusLoss();
  226194. // turn kiosk mode off if we lose focus..
  226195. Desktop::getInstance().setKioskModeComponent (0);
  226196. }
  226197. }
  226198. }
  226199. bool UIViewComponentPeer::isFocused() const
  226200. {
  226201. return isSharedWindow ? this == currentlyFocusedPeer
  226202. : (window != 0 && [window isKeyWindow]);
  226203. }
  226204. void UIViewComponentPeer::grabFocus()
  226205. {
  226206. if (window != 0)
  226207. {
  226208. [window makeKeyWindow];
  226209. viewFocusGain();
  226210. }
  226211. }
  226212. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226213. {
  226214. }
  226215. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226216. {
  226217. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226218. }
  226219. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  226220. {
  226221. TextInputTarget* const target = findCurrentTextInputTarget();
  226222. if (target != 0)
  226223. {
  226224. const Range<int> currentSelection (target->getHighlightedRegion());
  226225. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226226. if (currentSelection.isEmpty())
  226227. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226228. target->insertTextAtCaret (text);
  226229. updateHiddenTextContent (target);
  226230. }
  226231. return NO;
  226232. }
  226233. BOOL UIViewComponentPeer::textFieldShouldClear()
  226234. {
  226235. TextInputTarget* const target = findCurrentTextInputTarget();
  226236. if (target != 0)
  226237. {
  226238. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  226239. target->insertTextAtCaret (String::empty);
  226240. updateHiddenTextContent (target);
  226241. }
  226242. return YES;
  226243. }
  226244. BOOL UIViewComponentPeer::textFieldShouldReturn()
  226245. {
  226246. TextInputTarget* const target = findCurrentTextInputTarget();
  226247. if (target != 0)
  226248. {
  226249. target->insertTextAtCaret ("\n");
  226250. updateHiddenTextContent (target);
  226251. }
  226252. return YES;
  226253. }
  226254. void UIViewComponentPeer::globalFocusChanged (Component*)
  226255. {
  226256. TextInputTarget* const target = findCurrentTextInputTarget();
  226257. if (target != 0)
  226258. {
  226259. Component* comp = dynamic_cast<Component*> (target);
  226260. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226261. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226262. updateHiddenTextContent (target);
  226263. [view->hiddenTextField becomeFirstResponder];
  226264. }
  226265. else
  226266. {
  226267. [view->hiddenTextField resignFirstResponder];
  226268. }
  226269. }
  226270. void UIViewComponentPeer::drawRect (CGRect r)
  226271. {
  226272. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226273. return;
  226274. CGContextRef cg = UIGraphicsGetCurrentContext();
  226275. if (! component->isOpaque())
  226276. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226277. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226278. CoreGraphicsContext g (cg, view.bounds.size.height);
  226279. insideDrawRect = true;
  226280. handlePaint (g);
  226281. insideDrawRect = false;
  226282. }
  226283. bool UIViewComponentPeer::canBecomeKeyWindow()
  226284. {
  226285. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226286. }
  226287. bool UIViewComponentPeer::windowShouldClose()
  226288. {
  226289. if (! isValidPeer (this))
  226290. return YES;
  226291. handleUserClosingWindow();
  226292. return NO;
  226293. }
  226294. void UIViewComponentPeer::redirectMovedOrResized()
  226295. {
  226296. handleMovedOrResized();
  226297. }
  226298. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226299. {
  226300. }
  226301. class AsyncRepaintMessage : public CallbackMessage
  226302. {
  226303. public:
  226304. UIViewComponentPeer* const peer;
  226305. const Rectangle<int> rect;
  226306. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226307. : peer (peer_), rect (rect_)
  226308. {
  226309. }
  226310. void messageCallback()
  226311. {
  226312. if (ComponentPeer::isValidPeer (peer))
  226313. peer->repaint (rect);
  226314. }
  226315. };
  226316. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226317. {
  226318. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226319. {
  226320. (new AsyncRepaintMessage (this, area))->post();
  226321. }
  226322. else
  226323. {
  226324. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226325. (float) area.getWidth(), (float) area.getHeight())];
  226326. }
  226327. }
  226328. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226329. {
  226330. }
  226331. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226332. {
  226333. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226334. }
  226335. const Image juce_createIconForFile (const File& file)
  226336. {
  226337. return Image();
  226338. }
  226339. void Desktop::createMouseInputSources()
  226340. {
  226341. for (int i = 0; i < 10; ++i)
  226342. mouseSources.add (new MouseInputSource (i, false));
  226343. }
  226344. bool Desktop::canUseSemiTransparentWindows() throw()
  226345. {
  226346. return true;
  226347. }
  226348. const Point<int> Desktop::getMousePosition()
  226349. {
  226350. return juce_lastMousePos;
  226351. }
  226352. void Desktop::setMousePosition (const Point<int>&)
  226353. {
  226354. }
  226355. const int KeyPress::spaceKey = ' ';
  226356. const int KeyPress::returnKey = 0x0d;
  226357. const int KeyPress::escapeKey = 0x1b;
  226358. const int KeyPress::backspaceKey = 0x7f;
  226359. const int KeyPress::leftKey = 0x1000;
  226360. const int KeyPress::rightKey = 0x1001;
  226361. const int KeyPress::upKey = 0x1002;
  226362. const int KeyPress::downKey = 0x1003;
  226363. const int KeyPress::pageUpKey = 0x1004;
  226364. const int KeyPress::pageDownKey = 0x1005;
  226365. const int KeyPress::endKey = 0x1006;
  226366. const int KeyPress::homeKey = 0x1007;
  226367. const int KeyPress::deleteKey = 0x1008;
  226368. const int KeyPress::insertKey = -1;
  226369. const int KeyPress::tabKey = 9;
  226370. const int KeyPress::F1Key = 0x2001;
  226371. const int KeyPress::F2Key = 0x2002;
  226372. const int KeyPress::F3Key = 0x2003;
  226373. const int KeyPress::F4Key = 0x2004;
  226374. const int KeyPress::F5Key = 0x2005;
  226375. const int KeyPress::F6Key = 0x2006;
  226376. const int KeyPress::F7Key = 0x2007;
  226377. const int KeyPress::F8Key = 0x2008;
  226378. const int KeyPress::F9Key = 0x2009;
  226379. const int KeyPress::F10Key = 0x200a;
  226380. const int KeyPress::F11Key = 0x200b;
  226381. const int KeyPress::F12Key = 0x200c;
  226382. const int KeyPress::F13Key = 0x200d;
  226383. const int KeyPress::F14Key = 0x200e;
  226384. const int KeyPress::F15Key = 0x200f;
  226385. const int KeyPress::F16Key = 0x2010;
  226386. const int KeyPress::numberPad0 = 0x30020;
  226387. const int KeyPress::numberPad1 = 0x30021;
  226388. const int KeyPress::numberPad2 = 0x30022;
  226389. const int KeyPress::numberPad3 = 0x30023;
  226390. const int KeyPress::numberPad4 = 0x30024;
  226391. const int KeyPress::numberPad5 = 0x30025;
  226392. const int KeyPress::numberPad6 = 0x30026;
  226393. const int KeyPress::numberPad7 = 0x30027;
  226394. const int KeyPress::numberPad8 = 0x30028;
  226395. const int KeyPress::numberPad9 = 0x30029;
  226396. const int KeyPress::numberPadAdd = 0x3002a;
  226397. const int KeyPress::numberPadSubtract = 0x3002b;
  226398. const int KeyPress::numberPadMultiply = 0x3002c;
  226399. const int KeyPress::numberPadDivide = 0x3002d;
  226400. const int KeyPress::numberPadSeparator = 0x3002e;
  226401. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226402. const int KeyPress::numberPadEquals = 0x30030;
  226403. const int KeyPress::numberPadDelete = 0x30031;
  226404. const int KeyPress::playKey = 0x30000;
  226405. const int KeyPress::stopKey = 0x30001;
  226406. const int KeyPress::fastForwardKey = 0x30002;
  226407. const int KeyPress::rewindKey = 0x30003;
  226408. #endif
  226409. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226410. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226411. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226412. // compiled on its own).
  226413. #if JUCE_INCLUDED_FILE
  226414. struct CallbackMessagePayload
  226415. {
  226416. MessageCallbackFunction* function;
  226417. void* parameter;
  226418. void* volatile result;
  226419. bool volatile hasBeenExecuted;
  226420. };
  226421. END_JUCE_NAMESPACE
  226422. @interface JuceCustomMessageHandler : NSObject
  226423. {
  226424. }
  226425. - (void) performCallback: (id) info;
  226426. @end
  226427. @implementation JuceCustomMessageHandler
  226428. - (void) performCallback: (id) info
  226429. {
  226430. if ([info isKindOfClass: [NSData class]])
  226431. {
  226432. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226433. if (pl != 0)
  226434. {
  226435. pl->result = (*pl->function) (pl->parameter);
  226436. pl->hasBeenExecuted = true;
  226437. }
  226438. }
  226439. else
  226440. {
  226441. jassertfalse; // should never get here!
  226442. }
  226443. }
  226444. @end
  226445. BEGIN_JUCE_NAMESPACE
  226446. void MessageManager::runDispatchLoop()
  226447. {
  226448. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226449. runDispatchLoopUntil (-1);
  226450. }
  226451. void MessageManager::stopDispatchLoop()
  226452. {
  226453. exit (0); // iPhone apps get no mercy..
  226454. }
  226455. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226456. {
  226457. const ScopedAutoReleasePool pool;
  226458. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226459. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226460. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226461. while (! quitMessagePosted)
  226462. {
  226463. const ScopedAutoReleasePool pool;
  226464. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226465. beforeDate: endDate];
  226466. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226467. break;
  226468. }
  226469. return ! quitMessagePosted;
  226470. }
  226471. static CFRunLoopRef runLoop = 0;
  226472. static CFRunLoopSourceRef runLoopSource = 0;
  226473. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  226474. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226475. static void runLoopSourceCallback (void*)
  226476. {
  226477. if (pendingMessages != 0)
  226478. {
  226479. int numDispatched = 0;
  226480. do
  226481. {
  226482. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  226483. if (nextMessage == 0)
  226484. return;
  226485. const ScopedAutoReleasePool pool;
  226486. MessageManager::getInstance()->deliverMessage (nextMessage);
  226487. } while (++numDispatched <= 4);
  226488. CFRunLoopSourceSignal (runLoopSource);
  226489. CFRunLoopWakeUp (runLoop);
  226490. }
  226491. }
  226492. void MessageManager::doPlatformSpecificInitialisation()
  226493. {
  226494. pendingMessages = new OwnedArray <Message, CriticalSection>();
  226495. runLoop = CFRunLoopGetCurrent();
  226496. CFRunLoopSourceContext sourceContext;
  226497. zerostruct (sourceContext);
  226498. sourceContext.perform = runLoopSourceCallback;
  226499. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226500. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226501. if (juceCustomMessageHandler == 0)
  226502. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226503. }
  226504. void MessageManager::doPlatformSpecificShutdown()
  226505. {
  226506. CFRunLoopSourceInvalidate (runLoopSource);
  226507. CFRelease (runLoopSource);
  226508. runLoopSource = 0;
  226509. deleteAndZero (pendingMessages);
  226510. if (juceCustomMessageHandler != 0)
  226511. {
  226512. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226513. [juceCustomMessageHandler release];
  226514. juceCustomMessageHandler = 0;
  226515. }
  226516. }
  226517. bool juce_postMessageToSystemQueue (Message* message)
  226518. {
  226519. if (pendingMessages != 0)
  226520. {
  226521. pendingMessages->add (message);
  226522. CFRunLoopSourceSignal (runLoopSource);
  226523. CFRunLoopWakeUp (runLoop);
  226524. }
  226525. return true;
  226526. }
  226527. void MessageManager::broadcastMessage (const String& value) throw()
  226528. {
  226529. }
  226530. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226531. void* data)
  226532. {
  226533. if (isThisTheMessageThread())
  226534. {
  226535. return (*callback) (data);
  226536. }
  226537. else
  226538. {
  226539. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226540. // deadlock because the message manager is blocked from running, so can never
  226541. // call your function..
  226542. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226543. const ScopedAutoReleasePool pool;
  226544. CallbackMessagePayload cmp;
  226545. cmp.function = callback;
  226546. cmp.parameter = data;
  226547. cmp.result = 0;
  226548. cmp.hasBeenExecuted = false;
  226549. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226550. withObject: [NSData dataWithBytesNoCopy: &cmp
  226551. length: sizeof (cmp)
  226552. freeWhenDone: NO]
  226553. waitUntilDone: YES];
  226554. return cmp.result;
  226555. }
  226556. }
  226557. #endif
  226558. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226559. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226560. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226561. // compiled on its own).
  226562. #if JUCE_INCLUDED_FILE
  226563. #if JUCE_MAC
  226564. END_JUCE_NAMESPACE
  226565. using namespace JUCE_NAMESPACE;
  226566. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226567. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226568. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226569. #else
  226570. @interface JuceFileChooserDelegate : NSObject
  226571. #endif
  226572. {
  226573. StringArray* filters;
  226574. }
  226575. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226576. - (void) dealloc;
  226577. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226578. @end
  226579. @implementation JuceFileChooserDelegate
  226580. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226581. {
  226582. [super init];
  226583. filters = filters_;
  226584. return self;
  226585. }
  226586. - (void) dealloc
  226587. {
  226588. delete filters;
  226589. [super dealloc];
  226590. }
  226591. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226592. {
  226593. (void) sender;
  226594. const File f (nsStringToJuce (filename));
  226595. for (int i = filters->size(); --i >= 0;)
  226596. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226597. return true;
  226598. return f.isDirectory();
  226599. }
  226600. @end
  226601. BEGIN_JUCE_NAMESPACE
  226602. void FileChooser::showPlatformDialog (Array<File>& results,
  226603. const String& title,
  226604. const File& currentFileOrDirectory,
  226605. const String& filter,
  226606. bool selectsDirectory,
  226607. bool selectsFiles,
  226608. bool isSaveDialogue,
  226609. bool warnAboutOverwritingExistingFiles,
  226610. bool selectMultipleFiles,
  226611. FilePreviewComponent* extraInfoComponent)
  226612. {
  226613. const ScopedAutoReleasePool pool;
  226614. StringArray* filters = new StringArray();
  226615. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226616. filters->trim();
  226617. filters->removeEmptyStrings();
  226618. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226619. [delegate autorelease];
  226620. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226621. : [NSOpenPanel openPanel];
  226622. [panel setTitle: juceStringToNS (title)];
  226623. if (! isSaveDialogue)
  226624. {
  226625. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226626. [openPanel setCanChooseDirectories: selectsDirectory];
  226627. [openPanel setCanChooseFiles: selectsFiles];
  226628. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226629. }
  226630. [panel setDelegate: delegate];
  226631. if (isSaveDialogue || selectsDirectory)
  226632. [panel setCanCreateDirectories: YES];
  226633. String directory, filename;
  226634. if (currentFileOrDirectory.isDirectory())
  226635. {
  226636. directory = currentFileOrDirectory.getFullPathName();
  226637. }
  226638. else
  226639. {
  226640. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226641. filename = currentFileOrDirectory.getFileName();
  226642. }
  226643. if ([panel runModalForDirectory: juceStringToNS (directory)
  226644. file: juceStringToNS (filename)]
  226645. == NSOKButton)
  226646. {
  226647. if (isSaveDialogue)
  226648. {
  226649. results.add (File (nsStringToJuce ([panel filename])));
  226650. }
  226651. else
  226652. {
  226653. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226654. NSArray* urls = [openPanel filenames];
  226655. for (unsigned int i = 0; i < [urls count]; ++i)
  226656. {
  226657. NSString* f = [urls objectAtIndex: i];
  226658. results.add (File (nsStringToJuce (f)));
  226659. }
  226660. }
  226661. }
  226662. [panel setDelegate: nil];
  226663. }
  226664. #else
  226665. void FileChooser::showPlatformDialog (Array<File>& results,
  226666. const String& title,
  226667. const File& currentFileOrDirectory,
  226668. const String& filter,
  226669. bool selectsDirectory,
  226670. bool selectsFiles,
  226671. bool isSaveDialogue,
  226672. bool warnAboutOverwritingExistingFiles,
  226673. bool selectMultipleFiles,
  226674. FilePreviewComponent* extraInfoComponent)
  226675. {
  226676. const ScopedAutoReleasePool pool;
  226677. jassertfalse; //xxx to do
  226678. }
  226679. #endif
  226680. #endif
  226681. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226682. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226683. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226684. // compiled on its own).
  226685. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226686. #if JUCE_MAC
  226687. END_JUCE_NAMESPACE
  226688. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226689. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226690. {
  226691. CriticalSection* contextLock;
  226692. bool needsUpdate;
  226693. }
  226694. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226695. - (bool) makeActive;
  226696. - (void) makeInactive;
  226697. - (void) reshape;
  226698. @end
  226699. @implementation ThreadSafeNSOpenGLView
  226700. - (id) initWithFrame: (NSRect) frameRect
  226701. pixelFormat: (NSOpenGLPixelFormat*) format
  226702. {
  226703. contextLock = new CriticalSection();
  226704. self = [super initWithFrame: frameRect pixelFormat: format];
  226705. if (self != nil)
  226706. [[NSNotificationCenter defaultCenter] addObserver: self
  226707. selector: @selector (_surfaceNeedsUpdate:)
  226708. name: NSViewGlobalFrameDidChangeNotification
  226709. object: self];
  226710. return self;
  226711. }
  226712. - (void) dealloc
  226713. {
  226714. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226715. delete contextLock;
  226716. [super dealloc];
  226717. }
  226718. - (bool) makeActive
  226719. {
  226720. const ScopedLock sl (*contextLock);
  226721. if ([self openGLContext] == 0)
  226722. return false;
  226723. [[self openGLContext] makeCurrentContext];
  226724. if (needsUpdate)
  226725. {
  226726. [super update];
  226727. needsUpdate = false;
  226728. }
  226729. return true;
  226730. }
  226731. - (void) makeInactive
  226732. {
  226733. const ScopedLock sl (*contextLock);
  226734. [NSOpenGLContext clearCurrentContext];
  226735. }
  226736. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226737. {
  226738. const ScopedLock sl (*contextLock);
  226739. needsUpdate = true;
  226740. }
  226741. - (void) update
  226742. {
  226743. const ScopedLock sl (*contextLock);
  226744. needsUpdate = true;
  226745. }
  226746. - (void) reshape
  226747. {
  226748. const ScopedLock sl (*contextLock);
  226749. needsUpdate = true;
  226750. }
  226751. @end
  226752. BEGIN_JUCE_NAMESPACE
  226753. class WindowedGLContext : public OpenGLContext
  226754. {
  226755. public:
  226756. WindowedGLContext (Component* const component,
  226757. const OpenGLPixelFormat& pixelFormat_,
  226758. NSOpenGLContext* sharedContext)
  226759. : renderContext (0),
  226760. pixelFormat (pixelFormat_)
  226761. {
  226762. jassert (component != 0);
  226763. NSOpenGLPixelFormatAttribute attribs [64];
  226764. int n = 0;
  226765. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226766. attribs[n++] = NSOpenGLPFAAccelerated;
  226767. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226768. attribs[n++] = NSOpenGLPFAColorSize;
  226769. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226770. pixelFormat.greenBits,
  226771. pixelFormat.blueBits);
  226772. attribs[n++] = NSOpenGLPFAAlphaSize;
  226773. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226774. attribs[n++] = NSOpenGLPFADepthSize;
  226775. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226776. attribs[n++] = NSOpenGLPFAStencilSize;
  226777. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226778. attribs[n++] = NSOpenGLPFAAccumSize;
  226779. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226780. pixelFormat.accumulationBufferGreenBits,
  226781. pixelFormat.accumulationBufferBlueBits,
  226782. pixelFormat.accumulationBufferAlphaBits);
  226783. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226784. attribs[n++] = NSOpenGLPFASampleBuffers;
  226785. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226786. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226787. attribs[n++] = NSOpenGLPFANoRecovery;
  226788. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226789. NSOpenGLPixelFormat* format
  226790. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226791. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226792. pixelFormat: format];
  226793. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226794. shareContext: sharedContext] autorelease];
  226795. const GLint swapInterval = 1;
  226796. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226797. [view setOpenGLContext: renderContext];
  226798. [renderContext setView: view];
  226799. [format release];
  226800. viewHolder = new NSViewComponentInternal (view, component);
  226801. }
  226802. ~WindowedGLContext()
  226803. {
  226804. makeInactive();
  226805. [renderContext clearDrawable];
  226806. viewHolder = 0;
  226807. }
  226808. bool makeActive() const throw()
  226809. {
  226810. jassert (renderContext != 0);
  226811. [view makeActive];
  226812. return isActive();
  226813. }
  226814. bool makeInactive() const throw()
  226815. {
  226816. [view makeInactive];
  226817. return true;
  226818. }
  226819. bool isActive() const throw()
  226820. {
  226821. return [NSOpenGLContext currentContext] == renderContext;
  226822. }
  226823. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226824. void* getRawContext() const throw() { return renderContext; }
  226825. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226826. {
  226827. }
  226828. void swapBuffers()
  226829. {
  226830. [renderContext flushBuffer];
  226831. }
  226832. bool setSwapInterval (const int numFramesPerSwap)
  226833. {
  226834. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226835. forParameter: NSOpenGLCPSwapInterval];
  226836. return true;
  226837. }
  226838. int getSwapInterval() const
  226839. {
  226840. GLint numFrames = 0;
  226841. [renderContext getValues: &numFrames
  226842. forParameter: NSOpenGLCPSwapInterval];
  226843. return numFrames;
  226844. }
  226845. void repaint()
  226846. {
  226847. // we need to invalidate the juce view that holds this gl view, to make it
  226848. // cause a repaint callback
  226849. NSView* v = (NSView*) viewHolder->view;
  226850. NSRect r = [v frame];
  226851. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226852. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226853. // repaint message, thus never causing our paint() callback, and never repainting
  226854. // the comp. So invalidating just a little bit around the edge helps..
  226855. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226856. }
  226857. void* getNativeWindowHandle() const { return viewHolder->view; }
  226858. juce_UseDebuggingNewOperator
  226859. NSOpenGLContext* renderContext;
  226860. ThreadSafeNSOpenGLView* view;
  226861. private:
  226862. OpenGLPixelFormat pixelFormat;
  226863. ScopedPointer <NSViewComponentInternal> viewHolder;
  226864. WindowedGLContext (const WindowedGLContext&);
  226865. WindowedGLContext& operator= (const WindowedGLContext&);
  226866. };
  226867. OpenGLContext* OpenGLComponent::createContext()
  226868. {
  226869. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  226870. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  226871. return (c->renderContext != 0) ? c.release() : 0;
  226872. }
  226873. void* OpenGLComponent::getNativeWindowHandle() const
  226874. {
  226875. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  226876. : 0;
  226877. }
  226878. void juce_glViewport (const int w, const int h)
  226879. {
  226880. glViewport (0, 0, w, h);
  226881. }
  226882. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226883. OwnedArray <OpenGLPixelFormat>& results)
  226884. {
  226885. /* GLint attribs [64];
  226886. int n = 0;
  226887. attribs[n++] = AGL_RGBA;
  226888. attribs[n++] = AGL_DOUBLEBUFFER;
  226889. attribs[n++] = AGL_ACCELERATED;
  226890. attribs[n++] = AGL_NO_RECOVERY;
  226891. attribs[n++] = AGL_NONE;
  226892. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  226893. while (p != 0)
  226894. {
  226895. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  226896. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  226897. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  226898. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  226899. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  226900. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  226901. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  226902. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  226903. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  226904. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  226905. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  226906. results.add (pf);
  226907. p = aglNextPixelFormat (p);
  226908. }*/
  226909. //jassertfalse //xxx can't see how you do this in cocoa!
  226910. }
  226911. #else
  226912. END_JUCE_NAMESPACE
  226913. @interface JuceGLView : UIView
  226914. {
  226915. }
  226916. + (Class) layerClass;
  226917. @end
  226918. @implementation JuceGLView
  226919. + (Class) layerClass
  226920. {
  226921. return [CAEAGLLayer class];
  226922. }
  226923. @end
  226924. BEGIN_JUCE_NAMESPACE
  226925. class GLESContext : public OpenGLContext
  226926. {
  226927. public:
  226928. GLESContext (UIViewComponentPeer* peer,
  226929. Component* const component_,
  226930. const OpenGLPixelFormat& pixelFormat_,
  226931. const GLESContext* const sharedContext,
  226932. NSUInteger apiType)
  226933. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  226934. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  226935. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  226936. {
  226937. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  226938. view.opaque = YES;
  226939. view.hidden = NO;
  226940. view.backgroundColor = [UIColor blackColor];
  226941. view.userInteractionEnabled = NO;
  226942. glLayer = (CAEAGLLayer*) [view layer];
  226943. [peer->view addSubview: view];
  226944. if (sharedContext != 0)
  226945. context = [[EAGLContext alloc] initWithAPI: apiType
  226946. sharegroup: [sharedContext->context sharegroup]];
  226947. else
  226948. context = [[EAGLContext alloc] initWithAPI: apiType];
  226949. createGLBuffers();
  226950. }
  226951. ~GLESContext()
  226952. {
  226953. makeInactive();
  226954. [context release];
  226955. [view removeFromSuperview];
  226956. [view release];
  226957. freeGLBuffers();
  226958. }
  226959. bool makeActive() const throw()
  226960. {
  226961. jassert (context != 0);
  226962. [EAGLContext setCurrentContext: context];
  226963. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226964. return true;
  226965. }
  226966. void swapBuffers()
  226967. {
  226968. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226969. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  226970. }
  226971. bool makeInactive() const throw()
  226972. {
  226973. return [EAGLContext setCurrentContext: nil];
  226974. }
  226975. bool isActive() const throw()
  226976. {
  226977. return [EAGLContext currentContext] == context;
  226978. }
  226979. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226980. void* getRawContext() const throw() { return glLayer; }
  226981. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226982. {
  226983. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  226984. if (lastWidth != w || lastHeight != h)
  226985. {
  226986. lastWidth = w;
  226987. lastHeight = h;
  226988. freeGLBuffers();
  226989. createGLBuffers();
  226990. }
  226991. }
  226992. bool setSwapInterval (const int numFramesPerSwap)
  226993. {
  226994. numFrames = numFramesPerSwap;
  226995. return true;
  226996. }
  226997. int getSwapInterval() const
  226998. {
  226999. return numFrames;
  227000. }
  227001. void repaint()
  227002. {
  227003. }
  227004. void createGLBuffers()
  227005. {
  227006. makeActive();
  227007. glGenFramebuffersOES (1, &frameBufferHandle);
  227008. glGenRenderbuffersOES (1, &colorBufferHandle);
  227009. glGenRenderbuffersOES (1, &depthBufferHandle);
  227010. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227011. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227012. GLint width, height;
  227013. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227014. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227015. if (useDepthBuffer)
  227016. {
  227017. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227018. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227019. }
  227020. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227021. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227022. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227023. if (useDepthBuffer)
  227024. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227025. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227026. }
  227027. void freeGLBuffers()
  227028. {
  227029. if (frameBufferHandle != 0)
  227030. {
  227031. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227032. frameBufferHandle = 0;
  227033. }
  227034. if (colorBufferHandle != 0)
  227035. {
  227036. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227037. colorBufferHandle = 0;
  227038. }
  227039. if (depthBufferHandle != 0)
  227040. {
  227041. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227042. depthBufferHandle = 0;
  227043. }
  227044. }
  227045. juce_UseDebuggingNewOperator
  227046. private:
  227047. Component::SafePointer<Component> component;
  227048. OpenGLPixelFormat pixelFormat;
  227049. JuceGLView* view;
  227050. CAEAGLLayer* glLayer;
  227051. EAGLContext* context;
  227052. bool useDepthBuffer;
  227053. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227054. int numFrames;
  227055. int lastWidth, lastHeight;
  227056. GLESContext (const GLESContext&);
  227057. GLESContext& operator= (const GLESContext&);
  227058. };
  227059. OpenGLContext* OpenGLComponent::createContext()
  227060. {
  227061. ScopedAutoReleasePool pool;
  227062. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227063. if (peer != 0)
  227064. return new GLESContext (peer, this, preferredPixelFormat,
  227065. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227066. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227067. return 0;
  227068. }
  227069. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227070. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227071. {
  227072. }
  227073. void juce_glViewport (const int w, const int h)
  227074. {
  227075. glViewport (0, 0, w, h);
  227076. }
  227077. #endif
  227078. #endif
  227079. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227080. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227081. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227082. // compiled on its own).
  227083. #if JUCE_INCLUDED_FILE
  227084. #if JUCE_MAC
  227085. namespace MouseCursorHelpers
  227086. {
  227087. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227088. {
  227089. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227090. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227091. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227092. [im release];
  227093. return c;
  227094. }
  227095. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227096. {
  227097. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227098. BufferedInputStream buf (&fileStream, 4096, false);
  227099. PNGImageFormat pngFormat;
  227100. Image im (pngFormat.decodeImage (buf));
  227101. if (im.isValid())
  227102. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227103. jassertfalse;
  227104. return 0;
  227105. }
  227106. }
  227107. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227108. {
  227109. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227110. }
  227111. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227112. {
  227113. const ScopedAutoReleasePool pool;
  227114. NSCursor* c = 0;
  227115. switch (type)
  227116. {
  227117. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227118. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227119. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227120. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227121. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227122. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227123. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227124. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227125. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227126. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227127. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227128. case UpDownResizeCursor:
  227129. case TopEdgeResizeCursor:
  227130. case BottomEdgeResizeCursor:
  227131. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227132. case TopLeftCornerResizeCursor:
  227133. case BottomRightCornerResizeCursor:
  227134. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227135. case TopRightCornerResizeCursor:
  227136. case BottomLeftCornerResizeCursor:
  227137. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227138. case UpDownLeftRightResizeCursor:
  227139. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227140. default:
  227141. jassertfalse;
  227142. break;
  227143. }
  227144. [c retain];
  227145. return c;
  227146. }
  227147. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227148. {
  227149. [((NSCursor*) cursorHandle) release];
  227150. }
  227151. void MouseCursor::showInAllWindows() const
  227152. {
  227153. showInWindow (0);
  227154. }
  227155. void MouseCursor::showInWindow (ComponentPeer*) const
  227156. {
  227157. [((NSCursor*) getHandle()) set];
  227158. }
  227159. #else
  227160. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227161. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227162. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227163. void MouseCursor::showInAllWindows() const {}
  227164. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227165. #endif
  227166. #endif
  227167. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227168. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227169. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227170. // compiled on its own).
  227171. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227172. #if JUCE_MAC
  227173. END_JUCE_NAMESPACE
  227174. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227175. @interface DownloadClickDetector : NSObject
  227176. {
  227177. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227178. }
  227179. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227180. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227181. request: (NSURLRequest*) request
  227182. frame: (WebFrame*) frame
  227183. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227184. @end
  227185. @implementation DownloadClickDetector
  227186. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227187. {
  227188. [super init];
  227189. ownerComponent = ownerComponent_;
  227190. return self;
  227191. }
  227192. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227193. request: (NSURLRequest*) request
  227194. frame: (WebFrame*) frame
  227195. decisionListener: (id <WebPolicyDecisionListener>) listener
  227196. {
  227197. (void) sender;
  227198. (void) request;
  227199. (void) frame;
  227200. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227201. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227202. [listener use];
  227203. else
  227204. [listener ignore];
  227205. }
  227206. @end
  227207. BEGIN_JUCE_NAMESPACE
  227208. class WebBrowserComponentInternal : public NSViewComponent
  227209. {
  227210. public:
  227211. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227212. {
  227213. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227214. frameName: @""
  227215. groupName: @""];
  227216. setView (webView);
  227217. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227218. [webView setPolicyDelegate: clickListener];
  227219. }
  227220. ~WebBrowserComponentInternal()
  227221. {
  227222. [webView setPolicyDelegate: nil];
  227223. [clickListener release];
  227224. setView (0);
  227225. }
  227226. void goToURL (const String& url,
  227227. const StringArray* headers,
  227228. const MemoryBlock* postData)
  227229. {
  227230. NSMutableURLRequest* r
  227231. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227232. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227233. timeoutInterval: 30.0];
  227234. if (postData != 0 && postData->getSize() > 0)
  227235. {
  227236. [r setHTTPMethod: @"POST"];
  227237. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227238. length: postData->getSize()]];
  227239. }
  227240. if (headers != 0)
  227241. {
  227242. for (int i = 0; i < headers->size(); ++i)
  227243. {
  227244. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227245. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227246. [r setValue: juceStringToNS (headerValue)
  227247. forHTTPHeaderField: juceStringToNS (headerName)];
  227248. }
  227249. }
  227250. stop();
  227251. [[webView mainFrame] loadRequest: r];
  227252. }
  227253. void goBack()
  227254. {
  227255. [webView goBack];
  227256. }
  227257. void goForward()
  227258. {
  227259. [webView goForward];
  227260. }
  227261. void stop()
  227262. {
  227263. [webView stopLoading: nil];
  227264. }
  227265. void refresh()
  227266. {
  227267. [webView reload: nil];
  227268. }
  227269. private:
  227270. WebView* webView;
  227271. DownloadClickDetector* clickListener;
  227272. };
  227273. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227274. : browser (0),
  227275. blankPageShown (false),
  227276. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227277. {
  227278. setOpaque (true);
  227279. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227280. }
  227281. WebBrowserComponent::~WebBrowserComponent()
  227282. {
  227283. deleteAndZero (browser);
  227284. }
  227285. void WebBrowserComponent::goToURL (const String& url,
  227286. const StringArray* headers,
  227287. const MemoryBlock* postData)
  227288. {
  227289. lastURL = url;
  227290. lastHeaders.clear();
  227291. if (headers != 0)
  227292. lastHeaders = *headers;
  227293. lastPostData.setSize (0);
  227294. if (postData != 0)
  227295. lastPostData = *postData;
  227296. blankPageShown = false;
  227297. browser->goToURL (url, headers, postData);
  227298. }
  227299. void WebBrowserComponent::stop()
  227300. {
  227301. browser->stop();
  227302. }
  227303. void WebBrowserComponent::goBack()
  227304. {
  227305. lastURL = String::empty;
  227306. blankPageShown = false;
  227307. browser->goBack();
  227308. }
  227309. void WebBrowserComponent::goForward()
  227310. {
  227311. lastURL = String::empty;
  227312. browser->goForward();
  227313. }
  227314. void WebBrowserComponent::refresh()
  227315. {
  227316. browser->refresh();
  227317. }
  227318. void WebBrowserComponent::paint (Graphics&)
  227319. {
  227320. }
  227321. void WebBrowserComponent::checkWindowAssociation()
  227322. {
  227323. if (isShowing())
  227324. {
  227325. if (blankPageShown)
  227326. goBack();
  227327. }
  227328. else
  227329. {
  227330. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227331. {
  227332. // when the component becomes invisible, some stuff like flash
  227333. // carries on playing audio, so we need to force it onto a blank
  227334. // page to avoid this, (and send it back when it's made visible again).
  227335. blankPageShown = true;
  227336. browser->goToURL ("about:blank", 0, 0);
  227337. }
  227338. }
  227339. }
  227340. void WebBrowserComponent::reloadLastURL()
  227341. {
  227342. if (lastURL.isNotEmpty())
  227343. {
  227344. goToURL (lastURL, &lastHeaders, &lastPostData);
  227345. lastURL = String::empty;
  227346. }
  227347. }
  227348. void WebBrowserComponent::parentHierarchyChanged()
  227349. {
  227350. checkWindowAssociation();
  227351. }
  227352. void WebBrowserComponent::resized()
  227353. {
  227354. browser->setSize (getWidth(), getHeight());
  227355. }
  227356. void WebBrowserComponent::visibilityChanged()
  227357. {
  227358. checkWindowAssociation();
  227359. }
  227360. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227361. {
  227362. return true;
  227363. }
  227364. #else
  227365. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227366. {
  227367. }
  227368. WebBrowserComponent::~WebBrowserComponent()
  227369. {
  227370. }
  227371. void WebBrowserComponent::goToURL (const String& url,
  227372. const StringArray* headers,
  227373. const MemoryBlock* postData)
  227374. {
  227375. }
  227376. void WebBrowserComponent::stop()
  227377. {
  227378. }
  227379. void WebBrowserComponent::goBack()
  227380. {
  227381. }
  227382. void WebBrowserComponent::goForward()
  227383. {
  227384. }
  227385. void WebBrowserComponent::refresh()
  227386. {
  227387. }
  227388. void WebBrowserComponent::paint (Graphics& g)
  227389. {
  227390. }
  227391. void WebBrowserComponent::checkWindowAssociation()
  227392. {
  227393. }
  227394. void WebBrowserComponent::reloadLastURL()
  227395. {
  227396. }
  227397. void WebBrowserComponent::parentHierarchyChanged()
  227398. {
  227399. }
  227400. void WebBrowserComponent::resized()
  227401. {
  227402. }
  227403. void WebBrowserComponent::visibilityChanged()
  227404. {
  227405. }
  227406. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227407. {
  227408. return true;
  227409. }
  227410. #endif
  227411. #endif
  227412. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227413. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227414. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227415. // compiled on its own).
  227416. #if JUCE_INCLUDED_FILE
  227417. class IPhoneAudioIODevice : public AudioIODevice
  227418. {
  227419. public:
  227420. IPhoneAudioIODevice (const String& deviceName)
  227421. : AudioIODevice (deviceName, "Audio"),
  227422. audioUnit (0),
  227423. isRunning (false),
  227424. callback (0),
  227425. actualBufferSize (0),
  227426. floatData (1, 2)
  227427. {
  227428. numInputChannels = 2;
  227429. numOutputChannels = 2;
  227430. preferredBufferSize = 0;
  227431. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227432. updateDeviceInfo();
  227433. }
  227434. ~IPhoneAudioIODevice()
  227435. {
  227436. close();
  227437. }
  227438. const StringArray getOutputChannelNames()
  227439. {
  227440. StringArray s;
  227441. s.add ("Left");
  227442. s.add ("Right");
  227443. return s;
  227444. }
  227445. const StringArray getInputChannelNames()
  227446. {
  227447. StringArray s;
  227448. if (audioInputIsAvailable)
  227449. {
  227450. s.add ("Left");
  227451. s.add ("Right");
  227452. }
  227453. return s;
  227454. }
  227455. int getNumSampleRates()
  227456. {
  227457. return 1;
  227458. }
  227459. double getSampleRate (int index)
  227460. {
  227461. return sampleRate;
  227462. }
  227463. int getNumBufferSizesAvailable()
  227464. {
  227465. return 1;
  227466. }
  227467. int getBufferSizeSamples (int index)
  227468. {
  227469. return getDefaultBufferSize();
  227470. }
  227471. int getDefaultBufferSize()
  227472. {
  227473. return 1024;
  227474. }
  227475. const String open (const BigInteger& inputChannels,
  227476. const BigInteger& outputChannels,
  227477. double sampleRate,
  227478. int bufferSize)
  227479. {
  227480. close();
  227481. lastError = String::empty;
  227482. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227483. // xxx set up channel mapping
  227484. activeOutputChans = outputChannels;
  227485. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227486. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227487. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227488. activeInputChans = inputChannels;
  227489. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227490. numInputChannels = activeInputChans.countNumberOfSetBits();
  227491. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227492. AudioSessionSetActive (true);
  227493. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  227494. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227495. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227496. fixAudioRouteIfSetToReceiver();
  227497. updateDeviceInfo();
  227498. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227499. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227500. actualBufferSize = preferredBufferSize;
  227501. prepareFloatBuffers();
  227502. isRunning = true;
  227503. propertyChanged (0, 0, 0); // creates and starts the AU
  227504. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227505. return lastError;
  227506. }
  227507. void close()
  227508. {
  227509. if (isRunning)
  227510. {
  227511. isRunning = false;
  227512. AudioSessionSetActive (false);
  227513. if (audioUnit != 0)
  227514. {
  227515. AudioComponentInstanceDispose (audioUnit);
  227516. audioUnit = 0;
  227517. }
  227518. }
  227519. }
  227520. bool isOpen()
  227521. {
  227522. return isRunning;
  227523. }
  227524. int getCurrentBufferSizeSamples()
  227525. {
  227526. return actualBufferSize;
  227527. }
  227528. double getCurrentSampleRate()
  227529. {
  227530. return sampleRate;
  227531. }
  227532. int getCurrentBitDepth()
  227533. {
  227534. return 16;
  227535. }
  227536. const BigInteger getActiveOutputChannels() const
  227537. {
  227538. return activeOutputChans;
  227539. }
  227540. const BigInteger getActiveInputChannels() const
  227541. {
  227542. return activeInputChans;
  227543. }
  227544. int getOutputLatencyInSamples()
  227545. {
  227546. return 0; //xxx
  227547. }
  227548. int getInputLatencyInSamples()
  227549. {
  227550. return 0; //xxx
  227551. }
  227552. void start (AudioIODeviceCallback* callback_)
  227553. {
  227554. if (isRunning && callback != callback_)
  227555. {
  227556. if (callback_ != 0)
  227557. callback_->audioDeviceAboutToStart (this);
  227558. const ScopedLock sl (callbackLock);
  227559. callback = callback_;
  227560. }
  227561. }
  227562. void stop()
  227563. {
  227564. if (isRunning)
  227565. {
  227566. AudioIODeviceCallback* lastCallback;
  227567. {
  227568. const ScopedLock sl (callbackLock);
  227569. lastCallback = callback;
  227570. callback = 0;
  227571. }
  227572. if (lastCallback != 0)
  227573. lastCallback->audioDeviceStopped();
  227574. }
  227575. }
  227576. bool isPlaying()
  227577. {
  227578. return isRunning && callback != 0;
  227579. }
  227580. const String getLastError()
  227581. {
  227582. return lastError;
  227583. }
  227584. private:
  227585. CriticalSection callbackLock;
  227586. Float64 sampleRate;
  227587. int numInputChannels, numOutputChannels;
  227588. int preferredBufferSize;
  227589. int actualBufferSize;
  227590. bool isRunning;
  227591. String lastError;
  227592. AudioStreamBasicDescription format;
  227593. AudioUnit audioUnit;
  227594. UInt32 audioInputIsAvailable;
  227595. AudioIODeviceCallback* callback;
  227596. BigInteger activeOutputChans, activeInputChans;
  227597. AudioSampleBuffer floatData;
  227598. float* inputChannels[3];
  227599. float* outputChannels[3];
  227600. bool monoInputChannelNumber, monoOutputChannelNumber;
  227601. void prepareFloatBuffers()
  227602. {
  227603. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227604. zerostruct (inputChannels);
  227605. zerostruct (outputChannels);
  227606. for (int i = 0; i < numInputChannels; ++i)
  227607. inputChannels[i] = floatData.getSampleData (i);
  227608. for (int i = 0; i < numOutputChannels; ++i)
  227609. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227610. }
  227611. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227612. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227613. {
  227614. OSStatus err = noErr;
  227615. if (audioInputIsAvailable)
  227616. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227617. const ScopedLock sl (callbackLock);
  227618. if (callback != 0)
  227619. {
  227620. if (audioInputIsAvailable && numInputChannels > 0)
  227621. {
  227622. short* shortData = (short*) ioData->mBuffers[0].mData;
  227623. if (numInputChannels >= 2)
  227624. {
  227625. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227626. {
  227627. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227628. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227629. }
  227630. }
  227631. else
  227632. {
  227633. if (monoInputChannelNumber > 0)
  227634. ++shortData;
  227635. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227636. {
  227637. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227638. ++shortData;
  227639. }
  227640. }
  227641. }
  227642. else
  227643. {
  227644. for (int i = numInputChannels; --i >= 0;)
  227645. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227646. }
  227647. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227648. outputChannels, numOutputChannels,
  227649. (int) inNumberFrames);
  227650. short* shortData = (short*) ioData->mBuffers[0].mData;
  227651. int n = 0;
  227652. if (numOutputChannels >= 2)
  227653. {
  227654. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227655. {
  227656. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227657. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227658. }
  227659. }
  227660. else if (numOutputChannels == 1)
  227661. {
  227662. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227663. {
  227664. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227665. shortData [n++] = s;
  227666. shortData [n++] = s;
  227667. }
  227668. }
  227669. else
  227670. {
  227671. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227672. }
  227673. }
  227674. else
  227675. {
  227676. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227677. }
  227678. return err;
  227679. }
  227680. void updateDeviceInfo()
  227681. {
  227682. UInt32 size = sizeof (sampleRate);
  227683. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227684. size = sizeof (audioInputIsAvailable);
  227685. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227686. }
  227687. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227688. {
  227689. if (! isRunning)
  227690. return;
  227691. if (inPropertyValue != 0)
  227692. {
  227693. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227694. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227695. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227696. SInt32 routeChangeReason;
  227697. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227698. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227699. fixAudioRouteIfSetToReceiver();
  227700. }
  227701. updateDeviceInfo();
  227702. createAudioUnit();
  227703. AudioSessionSetActive (true);
  227704. if (audioUnit != 0)
  227705. {
  227706. UInt32 formatSize = sizeof (format);
  227707. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227708. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227709. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227710. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227711. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227712. AudioOutputUnitStart (audioUnit);
  227713. }
  227714. }
  227715. void interruptionListener (UInt32 inInterruption)
  227716. {
  227717. /*if (inInterruption == kAudioSessionBeginInterruption)
  227718. {
  227719. isRunning = false;
  227720. AudioOutputUnitStop (audioUnit);
  227721. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227722. "This could have been interrupted by another application or by unplugging a headset",
  227723. @"Resume",
  227724. @"Cancel"))
  227725. {
  227726. isRunning = true;
  227727. propertyChanged (0, 0, 0);
  227728. }
  227729. }*/
  227730. if (inInterruption == kAudioSessionEndInterruption)
  227731. {
  227732. isRunning = true;
  227733. AudioSessionSetActive (true);
  227734. AudioOutputUnitStart (audioUnit);
  227735. }
  227736. }
  227737. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227738. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227739. {
  227740. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227741. }
  227742. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227743. {
  227744. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227745. }
  227746. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227747. {
  227748. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227749. }
  227750. void resetFormat (const int numChannels)
  227751. {
  227752. memset (&format, 0, sizeof (format));
  227753. format.mFormatID = kAudioFormatLinearPCM;
  227754. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227755. format.mBitsPerChannel = 8 * sizeof (short);
  227756. format.mChannelsPerFrame = 2;
  227757. format.mFramesPerPacket = 1;
  227758. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227759. }
  227760. bool createAudioUnit()
  227761. {
  227762. if (audioUnit != 0)
  227763. {
  227764. AudioComponentInstanceDispose (audioUnit);
  227765. audioUnit = 0;
  227766. }
  227767. resetFormat (2);
  227768. AudioComponentDescription desc;
  227769. desc.componentType = kAudioUnitType_Output;
  227770. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227771. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227772. desc.componentFlags = 0;
  227773. desc.componentFlagsMask = 0;
  227774. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227775. AudioComponentInstanceNew (comp, &audioUnit);
  227776. if (audioUnit == 0)
  227777. return false;
  227778. const UInt32 one = 1;
  227779. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227780. AudioChannelLayout layout;
  227781. layout.mChannelBitmap = 0;
  227782. layout.mNumberChannelDescriptions = 0;
  227783. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227784. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227785. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227786. AURenderCallbackStruct inputProc;
  227787. inputProc.inputProc = processStatic;
  227788. inputProc.inputProcRefCon = this;
  227789. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227790. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227791. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227792. AudioUnitInitialize (audioUnit);
  227793. return true;
  227794. }
  227795. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227796. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227797. static void fixAudioRouteIfSetToReceiver()
  227798. {
  227799. CFStringRef audioRoute = 0;
  227800. UInt32 propertySize = sizeof (audioRoute);
  227801. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227802. {
  227803. NSString* route = (NSString*) audioRoute;
  227804. //DBG ("audio route: " + nsStringToJuce (route));
  227805. if ([route hasPrefix: @"Receiver"])
  227806. {
  227807. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227808. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227809. }
  227810. CFRelease (audioRoute);
  227811. }
  227812. }
  227813. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  227814. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  227815. };
  227816. class IPhoneAudioIODeviceType : public AudioIODeviceType
  227817. {
  227818. public:
  227819. IPhoneAudioIODeviceType()
  227820. : AudioIODeviceType ("iPhone Audio")
  227821. {
  227822. }
  227823. ~IPhoneAudioIODeviceType()
  227824. {
  227825. }
  227826. void scanForDevices()
  227827. {
  227828. }
  227829. const StringArray getDeviceNames (bool wantInputNames) const
  227830. {
  227831. StringArray s;
  227832. s.add ("iPhone Audio");
  227833. return s;
  227834. }
  227835. int getDefaultDeviceIndex (bool forInput) const
  227836. {
  227837. return 0;
  227838. }
  227839. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  227840. {
  227841. return device != 0 ? 0 : -1;
  227842. }
  227843. bool hasSeparateInputsAndOutputs() const { return false; }
  227844. AudioIODevice* createDevice (const String& outputDeviceName,
  227845. const String& inputDeviceName)
  227846. {
  227847. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  227848. {
  227849. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  227850. : inputDeviceName);
  227851. }
  227852. return 0;
  227853. }
  227854. juce_UseDebuggingNewOperator
  227855. private:
  227856. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  227857. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  227858. };
  227859. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  227860. {
  227861. return new IPhoneAudioIODeviceType();
  227862. }
  227863. #endif
  227864. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  227865. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  227866. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227867. // compiled on its own).
  227868. #if JUCE_INCLUDED_FILE
  227869. #if JUCE_MAC
  227870. #undef log
  227871. #define log(a) Logger::writeToLog(a)
  227872. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  227873. {
  227874. if (err == noErr)
  227875. return true;
  227876. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  227877. jassertfalse;
  227878. return false;
  227879. }
  227880. #undef OK
  227881. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  227882. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  227883. {
  227884. String result;
  227885. CFStringRef str = 0;
  227886. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  227887. if (str != 0)
  227888. {
  227889. result = PlatformUtilities::cfStringToJuceString (str);
  227890. CFRelease (str);
  227891. str = 0;
  227892. }
  227893. MIDIEntityRef entity = 0;
  227894. MIDIEndpointGetEntity (endpoint, &entity);
  227895. if (entity == 0)
  227896. return result; // probably virtual
  227897. if (result.isEmpty())
  227898. {
  227899. // endpoint name has zero length - try the entity
  227900. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  227901. if (str != 0)
  227902. {
  227903. result += PlatformUtilities::cfStringToJuceString (str);
  227904. CFRelease (str);
  227905. str = 0;
  227906. }
  227907. }
  227908. // now consider the device's name
  227909. MIDIDeviceRef device = 0;
  227910. MIDIEntityGetDevice (entity, &device);
  227911. if (device == 0)
  227912. return result;
  227913. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  227914. if (str != 0)
  227915. {
  227916. const String s (PlatformUtilities::cfStringToJuceString (str));
  227917. CFRelease (str);
  227918. // if an external device has only one entity, throw away
  227919. // the endpoint name and just use the device name
  227920. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  227921. {
  227922. result = s;
  227923. }
  227924. else if (! result.startsWithIgnoreCase (s))
  227925. {
  227926. // prepend the device name to the entity name
  227927. result = (s + " " + result).trimEnd();
  227928. }
  227929. }
  227930. return result;
  227931. }
  227932. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  227933. {
  227934. String result;
  227935. // Does the endpoint have connections?
  227936. CFDataRef connections = 0;
  227937. int numConnections = 0;
  227938. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  227939. if (connections != 0)
  227940. {
  227941. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  227942. if (numConnections > 0)
  227943. {
  227944. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  227945. for (int i = 0; i < numConnections; ++i, ++pid)
  227946. {
  227947. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  227948. MIDIObjectRef connObject;
  227949. MIDIObjectType connObjectType;
  227950. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  227951. if (err == noErr)
  227952. {
  227953. String s;
  227954. if (connObjectType == kMIDIObjectType_ExternalSource
  227955. || connObjectType == kMIDIObjectType_ExternalDestination)
  227956. {
  227957. // Connected to an external device's endpoint (10.3 and later).
  227958. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  227959. }
  227960. else
  227961. {
  227962. // Connected to an external device (10.2) (or something else, catch-all)
  227963. CFStringRef str = 0;
  227964. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  227965. if (str != 0)
  227966. {
  227967. s = PlatformUtilities::cfStringToJuceString (str);
  227968. CFRelease (str);
  227969. }
  227970. }
  227971. if (s.isNotEmpty())
  227972. {
  227973. if (result.isNotEmpty())
  227974. result += ", ";
  227975. result += s;
  227976. }
  227977. }
  227978. }
  227979. }
  227980. CFRelease (connections);
  227981. }
  227982. if (result.isNotEmpty())
  227983. return result;
  227984. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  227985. return getEndpointName (endpoint, false);
  227986. }
  227987. const StringArray MidiOutput::getDevices()
  227988. {
  227989. StringArray s;
  227990. const ItemCount num = MIDIGetNumberOfDestinations();
  227991. for (ItemCount i = 0; i < num; ++i)
  227992. {
  227993. MIDIEndpointRef dest = MIDIGetDestination (i);
  227994. if (dest != 0)
  227995. {
  227996. String name (getConnectedEndpointName (dest));
  227997. if (name.isEmpty())
  227998. name = "<error>";
  227999. s.add (name);
  228000. }
  228001. else
  228002. {
  228003. s.add ("<error>");
  228004. }
  228005. }
  228006. return s;
  228007. }
  228008. int MidiOutput::getDefaultDeviceIndex()
  228009. {
  228010. return 0;
  228011. }
  228012. static MIDIClientRef globalMidiClient;
  228013. static bool hasGlobalClientBeenCreated = false;
  228014. static bool makeSureClientExists()
  228015. {
  228016. if (! hasGlobalClientBeenCreated)
  228017. {
  228018. String name ("JUCE");
  228019. if (JUCEApplication::getInstance() != 0)
  228020. name = JUCEApplication::getInstance()->getApplicationName();
  228021. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228022. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228023. CFRelease (appName);
  228024. }
  228025. return hasGlobalClientBeenCreated;
  228026. }
  228027. class MidiPortAndEndpoint
  228028. {
  228029. public:
  228030. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228031. : port (port_), endPoint (endPoint_)
  228032. {
  228033. }
  228034. ~MidiPortAndEndpoint()
  228035. {
  228036. if (port != 0)
  228037. MIDIPortDispose (port);
  228038. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228039. MIDIEndpointDispose (endPoint);
  228040. }
  228041. MIDIPortRef port;
  228042. MIDIEndpointRef endPoint;
  228043. };
  228044. MidiOutput* MidiOutput::openDevice (int index)
  228045. {
  228046. MidiOutput* mo = 0;
  228047. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  228048. {
  228049. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228050. CFStringRef pname;
  228051. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228052. {
  228053. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  228054. if (makeSureClientExists())
  228055. {
  228056. MIDIPortRef port;
  228057. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  228058. {
  228059. mo = new MidiOutput();
  228060. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  228061. }
  228062. }
  228063. CFRelease (pname);
  228064. }
  228065. }
  228066. return mo;
  228067. }
  228068. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228069. {
  228070. MidiOutput* mo = 0;
  228071. if (makeSureClientExists())
  228072. {
  228073. MIDIEndpointRef endPoint;
  228074. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228075. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  228076. {
  228077. mo = new MidiOutput();
  228078. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  228079. }
  228080. CFRelease (name);
  228081. }
  228082. return mo;
  228083. }
  228084. MidiOutput::~MidiOutput()
  228085. {
  228086. delete (MidiPortAndEndpoint*) internal;
  228087. }
  228088. void MidiOutput::reset()
  228089. {
  228090. }
  228091. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228092. {
  228093. return false;
  228094. }
  228095. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228096. {
  228097. }
  228098. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228099. {
  228100. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  228101. if (message.isSysEx())
  228102. {
  228103. const int maxPacketSize = 256;
  228104. int pos = 0, bytesLeft = message.getRawDataSize();
  228105. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228106. HeapBlock <MIDIPacketList> packets;
  228107. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  228108. packets->numPackets = numPackets;
  228109. MIDIPacket* p = packets->packet;
  228110. for (int i = 0; i < numPackets; ++i)
  228111. {
  228112. p->timeStamp = 0;
  228113. p->length = jmin (maxPacketSize, bytesLeft);
  228114. memcpy (p->data, message.getRawData() + pos, p->length);
  228115. pos += p->length;
  228116. bytesLeft -= p->length;
  228117. p = MIDIPacketNext (p);
  228118. }
  228119. if (mpe->port != 0)
  228120. MIDISend (mpe->port, mpe->endPoint, packets);
  228121. else
  228122. MIDIReceived (mpe->endPoint, packets);
  228123. }
  228124. else
  228125. {
  228126. MIDIPacketList packets;
  228127. packets.numPackets = 1;
  228128. packets.packet[0].timeStamp = 0;
  228129. packets.packet[0].length = message.getRawDataSize();
  228130. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228131. if (mpe->port != 0)
  228132. MIDISend (mpe->port, mpe->endPoint, &packets);
  228133. else
  228134. MIDIReceived (mpe->endPoint, &packets);
  228135. }
  228136. }
  228137. const StringArray MidiInput::getDevices()
  228138. {
  228139. StringArray s;
  228140. const ItemCount num = MIDIGetNumberOfSources();
  228141. for (ItemCount i = 0; i < num; ++i)
  228142. {
  228143. MIDIEndpointRef source = MIDIGetSource (i);
  228144. if (source != 0)
  228145. {
  228146. String name (getConnectedEndpointName (source));
  228147. if (name.isEmpty())
  228148. name = "<error>";
  228149. s.add (name);
  228150. }
  228151. else
  228152. {
  228153. s.add ("<error>");
  228154. }
  228155. }
  228156. return s;
  228157. }
  228158. int MidiInput::getDefaultDeviceIndex()
  228159. {
  228160. return 0;
  228161. }
  228162. struct MidiPortAndCallback
  228163. {
  228164. MidiInput* input;
  228165. MidiPortAndEndpoint* portAndEndpoint;
  228166. MidiInputCallback* callback;
  228167. MemoryBlock pendingData;
  228168. int pendingBytes;
  228169. double pendingDataTime;
  228170. bool active;
  228171. void processSysex (const uint8*& d, int& size, const double time)
  228172. {
  228173. if (*d == 0xf0)
  228174. {
  228175. pendingBytes = 0;
  228176. pendingDataTime = time;
  228177. }
  228178. pendingData.ensureSize (pendingBytes + size, false);
  228179. uint8* totalMessage = (uint8*) pendingData.getData();
  228180. uint8* dest = totalMessage + pendingBytes;
  228181. while (size > 0)
  228182. {
  228183. if (pendingBytes > 0 && *d >= 0x80)
  228184. {
  228185. if (*d >= 0xfa || *d == 0xf8)
  228186. {
  228187. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228188. ++d;
  228189. --size;
  228190. }
  228191. else
  228192. {
  228193. if (*d == 0xf7)
  228194. {
  228195. *dest++ = *d++;
  228196. pendingBytes++;
  228197. --size;
  228198. }
  228199. break;
  228200. }
  228201. }
  228202. else
  228203. {
  228204. *dest++ = *d++;
  228205. pendingBytes++;
  228206. --size;
  228207. }
  228208. }
  228209. if (totalMessage [pendingBytes - 1] == 0xf7)
  228210. {
  228211. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228212. pendingBytes = 0;
  228213. }
  228214. else
  228215. {
  228216. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228217. }
  228218. }
  228219. };
  228220. namespace CoreMidiCallbacks
  228221. {
  228222. static CriticalSection callbackLock;
  228223. static Array<void*> activeCallbacks;
  228224. }
  228225. static void midiInputProc (const MIDIPacketList* pktlist,
  228226. void* readProcRefCon,
  228227. void* /*srcConnRefCon*/)
  228228. {
  228229. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228230. const double originalTime = time;
  228231. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228232. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228233. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228234. {
  228235. const MIDIPacket* packet = &pktlist->packet[0];
  228236. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228237. {
  228238. const uint8* d = (const uint8*) (packet->data);
  228239. int size = packet->length;
  228240. while (size > 0)
  228241. {
  228242. time = originalTime;
  228243. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228244. {
  228245. mpc->processSysex (d, size, time);
  228246. }
  228247. else
  228248. {
  228249. int used = 0;
  228250. const MidiMessage m (d, size, used, 0, time);
  228251. if (used <= 0)
  228252. {
  228253. jassertfalse; // malformed midi message
  228254. break;
  228255. }
  228256. else
  228257. {
  228258. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228259. }
  228260. size -= used;
  228261. d += used;
  228262. }
  228263. }
  228264. packet = MIDIPacketNext (packet);
  228265. }
  228266. }
  228267. }
  228268. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228269. {
  228270. MidiInput* mi = 0;
  228271. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228272. {
  228273. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228274. if (endPoint != 0)
  228275. {
  228276. CFStringRef pname;
  228277. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228278. {
  228279. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228280. if (makeSureClientExists())
  228281. {
  228282. MIDIPortRef port;
  228283. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228284. mpc->active = false;
  228285. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228286. {
  228287. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228288. {
  228289. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228290. mpc->callback = callback;
  228291. mpc->pendingBytes = 0;
  228292. mpc->pendingData.ensureSize (128);
  228293. mi = new MidiInput (getDevices() [index]);
  228294. mpc->input = mi;
  228295. mi->internal = mpc;
  228296. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228297. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228298. }
  228299. else
  228300. {
  228301. OK (MIDIPortDispose (port));
  228302. }
  228303. }
  228304. }
  228305. }
  228306. CFRelease (pname);
  228307. }
  228308. }
  228309. return mi;
  228310. }
  228311. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228312. {
  228313. MidiInput* mi = 0;
  228314. if (makeSureClientExists())
  228315. {
  228316. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228317. mpc->active = false;
  228318. MIDIEndpointRef endPoint;
  228319. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228320. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228321. {
  228322. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228323. mpc->callback = callback;
  228324. mpc->pendingBytes = 0;
  228325. mpc->pendingData.ensureSize (128);
  228326. mi = new MidiInput (deviceName);
  228327. mpc->input = mi;
  228328. mi->internal = mpc;
  228329. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228330. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228331. }
  228332. CFRelease (name);
  228333. }
  228334. return mi;
  228335. }
  228336. MidiInput::MidiInput (const String& name_)
  228337. : name (name_)
  228338. {
  228339. }
  228340. MidiInput::~MidiInput()
  228341. {
  228342. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228343. mpc->active = false;
  228344. {
  228345. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228346. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228347. }
  228348. if (mpc->portAndEndpoint->port != 0)
  228349. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228350. delete mpc->portAndEndpoint;
  228351. delete mpc;
  228352. }
  228353. void MidiInput::start()
  228354. {
  228355. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228356. ((MidiPortAndCallback*) internal)->active = true;
  228357. }
  228358. void MidiInput::stop()
  228359. {
  228360. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228361. ((MidiPortAndCallback*) internal)->active = false;
  228362. }
  228363. #undef log
  228364. #else
  228365. MidiOutput::~MidiOutput()
  228366. {
  228367. }
  228368. void MidiOutput::reset()
  228369. {
  228370. }
  228371. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228372. {
  228373. return false;
  228374. }
  228375. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228376. {
  228377. }
  228378. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228379. {
  228380. }
  228381. const StringArray MidiOutput::getDevices()
  228382. {
  228383. return StringArray();
  228384. }
  228385. MidiOutput* MidiOutput::openDevice (int index)
  228386. {
  228387. return 0;
  228388. }
  228389. const StringArray MidiInput::getDevices()
  228390. {
  228391. return StringArray();
  228392. }
  228393. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228394. {
  228395. return 0;
  228396. }
  228397. #endif
  228398. #endif
  228399. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228400. #else
  228401. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228402. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228403. // compiled on its own).
  228404. #if JUCE_INCLUDED_FILE
  228405. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228406. #define SUPPORT_10_4_FONTS 1
  228407. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228408. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228409. #define SUPPORT_ONLY_10_4_FONTS 1
  228410. #endif
  228411. END_JUCE_NAMESPACE
  228412. @interface NSFont (PrivateHack)
  228413. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228414. @end
  228415. BEGIN_JUCE_NAMESPACE
  228416. #endif
  228417. class MacTypeface : public Typeface
  228418. {
  228419. public:
  228420. MacTypeface (const Font& font)
  228421. : Typeface (font.getTypefaceName())
  228422. {
  228423. const ScopedAutoReleasePool pool;
  228424. renderingTransform = CGAffineTransformIdentity;
  228425. bool needsItalicTransform = false;
  228426. #if JUCE_IPHONE
  228427. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228428. if (font.isItalic() || font.isBold())
  228429. {
  228430. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228431. for (NSString* i in familyFonts)
  228432. {
  228433. const String fn (nsStringToJuce (i));
  228434. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228435. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228436. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228437. || afterDash.containsIgnoreCase ("italic")
  228438. || fn.endsWithIgnoreCase ("oblique")
  228439. || fn.endsWithIgnoreCase ("italic");
  228440. if (probablyBold == font.isBold()
  228441. && probablyItalic == font.isItalic())
  228442. {
  228443. fontName = i;
  228444. needsItalicTransform = false;
  228445. break;
  228446. }
  228447. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228448. {
  228449. fontName = i;
  228450. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228451. }
  228452. }
  228453. if (needsItalicTransform)
  228454. renderingTransform.c = 0.15f;
  228455. }
  228456. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228457. const int ascender = abs (CGFontGetAscent (fontRef));
  228458. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228459. ascent = ascender / totalHeight;
  228460. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228461. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228462. #else
  228463. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228464. if (font.isItalic())
  228465. {
  228466. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228467. toHaveTrait: NSItalicFontMask];
  228468. if (newFont == nsFont)
  228469. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228470. nsFont = newFont;
  228471. }
  228472. if (font.isBold())
  228473. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228474. [nsFont retain];
  228475. ascent = std::abs ((float) [nsFont ascender]);
  228476. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228477. ascent /= totalSize;
  228478. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228479. if (needsItalicTransform)
  228480. {
  228481. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228482. renderingTransform.c = 0.15f;
  228483. }
  228484. #if SUPPORT_ONLY_10_4_FONTS
  228485. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228486. if (atsFont == 0)
  228487. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228488. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228489. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228490. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228491. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228492. #else
  228493. #if SUPPORT_10_4_FONTS
  228494. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228495. {
  228496. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228497. if (atsFont == 0)
  228498. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228499. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228500. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228501. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228502. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228503. }
  228504. else
  228505. #endif
  228506. {
  228507. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228508. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228509. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228510. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228511. }
  228512. #endif
  228513. #endif
  228514. }
  228515. ~MacTypeface()
  228516. {
  228517. #if ! JUCE_IPHONE
  228518. [nsFont release];
  228519. #endif
  228520. if (fontRef != 0)
  228521. CGFontRelease (fontRef);
  228522. }
  228523. float getAscent() const
  228524. {
  228525. return ascent;
  228526. }
  228527. float getDescent() const
  228528. {
  228529. return 1.0f - ascent;
  228530. }
  228531. float getStringWidth (const String& text)
  228532. {
  228533. if (fontRef == 0 || text.isEmpty())
  228534. return 0;
  228535. const int length = text.length();
  228536. HeapBlock <CGGlyph> glyphs;
  228537. createGlyphsForString (text, length, glyphs);
  228538. float x = 0;
  228539. #if SUPPORT_ONLY_10_4_FONTS
  228540. HeapBlock <NSSize> advances (length);
  228541. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228542. for (int i = 0; i < length; ++i)
  228543. x += advances[i].width;
  228544. #else
  228545. #if SUPPORT_10_4_FONTS
  228546. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228547. {
  228548. HeapBlock <NSSize> advances (length);
  228549. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228550. for (int i = 0; i < length; ++i)
  228551. x += advances[i].width;
  228552. }
  228553. else
  228554. #endif
  228555. {
  228556. HeapBlock <int> advances (length);
  228557. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228558. for (int i = 0; i < length; ++i)
  228559. x += advances[i];
  228560. }
  228561. #endif
  228562. return x * unitsToHeightScaleFactor;
  228563. }
  228564. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228565. {
  228566. xOffsets.add (0);
  228567. if (fontRef == 0 || text.isEmpty())
  228568. return;
  228569. const int length = text.length();
  228570. HeapBlock <CGGlyph> glyphs;
  228571. createGlyphsForString (text, length, glyphs);
  228572. #if SUPPORT_ONLY_10_4_FONTS
  228573. HeapBlock <NSSize> advances (length);
  228574. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228575. int x = 0;
  228576. for (int i = 0; i < length; ++i)
  228577. {
  228578. x += advances[i].width;
  228579. xOffsets.add (x * unitsToHeightScaleFactor);
  228580. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228581. }
  228582. #else
  228583. #if SUPPORT_10_4_FONTS
  228584. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228585. {
  228586. HeapBlock <NSSize> advances (length);
  228587. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228588. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228589. float x = 0;
  228590. for (int i = 0; i < length; ++i)
  228591. {
  228592. x += advances[i].width;
  228593. xOffsets.add (x * unitsToHeightScaleFactor);
  228594. resultGlyphs.add (nsGlyphs[i]);
  228595. }
  228596. }
  228597. else
  228598. #endif
  228599. {
  228600. HeapBlock <int> advances (length);
  228601. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228602. {
  228603. int x = 0;
  228604. for (int i = 0; i < length; ++i)
  228605. {
  228606. x += advances [i];
  228607. xOffsets.add (x * unitsToHeightScaleFactor);
  228608. resultGlyphs.add (glyphs[i]);
  228609. }
  228610. }
  228611. }
  228612. #endif
  228613. }
  228614. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228615. {
  228616. #if JUCE_IPHONE
  228617. return false;
  228618. #else
  228619. if (nsFont == 0)
  228620. return false;
  228621. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228622. jassert (path.isEmpty());
  228623. const ScopedAutoReleasePool pool;
  228624. NSBezierPath* bez = [NSBezierPath bezierPath];
  228625. [bez moveToPoint: NSMakePoint (0, 0)];
  228626. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228627. inFont: nsFont];
  228628. for (int i = 0; i < [bez elementCount]; ++i)
  228629. {
  228630. NSPoint p[3];
  228631. switch ([bez elementAtIndex: i associatedPoints: p])
  228632. {
  228633. case NSMoveToBezierPathElement:
  228634. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228635. break;
  228636. case NSLineToBezierPathElement:
  228637. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228638. break;
  228639. case NSCurveToBezierPathElement:
  228640. 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);
  228641. break;
  228642. case NSClosePathBezierPathElement:
  228643. path.closeSubPath();
  228644. break;
  228645. default:
  228646. jassertfalse;
  228647. break;
  228648. }
  228649. }
  228650. path.applyTransform (pathTransform);
  228651. return true;
  228652. #endif
  228653. }
  228654. juce_UseDebuggingNewOperator
  228655. CGFontRef fontRef;
  228656. float fontHeightToCGSizeFactor;
  228657. CGAffineTransform renderingTransform;
  228658. private:
  228659. float ascent, unitsToHeightScaleFactor;
  228660. #if JUCE_IPHONE
  228661. #else
  228662. NSFont* nsFont;
  228663. AffineTransform pathTransform;
  228664. #endif
  228665. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228666. {
  228667. #if SUPPORT_10_4_FONTS
  228668. #if ! SUPPORT_ONLY_10_4_FONTS
  228669. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228670. #endif
  228671. {
  228672. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228673. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228674. for (int i = 0; i < length; ++i)
  228675. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228676. return;
  228677. }
  228678. #endif
  228679. #if ! SUPPORT_ONLY_10_4_FONTS
  228680. if (charToGlyphMapper == 0)
  228681. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228682. glyphs.malloc (length);
  228683. for (int i = 0; i < length; ++i)
  228684. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228685. #endif
  228686. }
  228687. #if ! SUPPORT_ONLY_10_4_FONTS
  228688. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228689. class CharToGlyphMapper
  228690. {
  228691. public:
  228692. CharToGlyphMapper (CGFontRef fontRef)
  228693. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228694. idRangeOffset (0), glyphIndexes (0)
  228695. {
  228696. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228697. if (cmapTable != 0)
  228698. {
  228699. const int numSubtables = getValue16 (cmapTable, 2);
  228700. for (int i = 0; i < numSubtables; ++i)
  228701. {
  228702. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228703. {
  228704. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228705. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228706. {
  228707. const int length = getValue16 (cmapTable, offset + 2);
  228708. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228709. segCount = segCountX2 / 2;
  228710. const int endCodeOffset = offset + 14;
  228711. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228712. const int idDeltaOffset = startCodeOffset + segCountX2;
  228713. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228714. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228715. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228716. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228717. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228718. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228719. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228720. }
  228721. break;
  228722. }
  228723. }
  228724. CFRelease (cmapTable);
  228725. }
  228726. }
  228727. ~CharToGlyphMapper()
  228728. {
  228729. if (endCode != 0)
  228730. {
  228731. CFRelease (endCode);
  228732. CFRelease (startCode);
  228733. CFRelease (idDelta);
  228734. CFRelease (idRangeOffset);
  228735. CFRelease (glyphIndexes);
  228736. }
  228737. }
  228738. int getGlyphForCharacter (const juce_wchar c) const
  228739. {
  228740. for (int i = 0; i < segCount; ++i)
  228741. {
  228742. if (getValue16 (endCode, i * 2) >= c)
  228743. {
  228744. const int start = getValue16 (startCode, i * 2);
  228745. if (start > c)
  228746. break;
  228747. const int delta = getValue16 (idDelta, i * 2);
  228748. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228749. if (rangeOffset == 0)
  228750. return delta + c;
  228751. else
  228752. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228753. }
  228754. }
  228755. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228756. return jmax (-1, c - 29);
  228757. }
  228758. private:
  228759. int segCount;
  228760. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228761. static uint16 getValue16 (CFDataRef data, const int index)
  228762. {
  228763. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228764. }
  228765. static uint32 getValue32 (CFDataRef data, const int index)
  228766. {
  228767. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228768. }
  228769. };
  228770. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228771. #endif
  228772. MacTypeface (const MacTypeface&);
  228773. MacTypeface& operator= (const MacTypeface&);
  228774. };
  228775. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228776. {
  228777. return new MacTypeface (font);
  228778. }
  228779. const StringArray Font::findAllTypefaceNames()
  228780. {
  228781. StringArray names;
  228782. const ScopedAutoReleasePool pool;
  228783. #if JUCE_IPHONE
  228784. NSArray* fonts = [UIFont familyNames];
  228785. #else
  228786. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228787. #endif
  228788. for (unsigned int i = 0; i < [fonts count]; ++i)
  228789. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228790. names.sort (true);
  228791. return names;
  228792. }
  228793. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228794. {
  228795. #if JUCE_IPHONE
  228796. defaultSans = "Helvetica";
  228797. defaultSerif = "Times New Roman";
  228798. defaultFixed = "Courier New";
  228799. #else
  228800. defaultSans = "Lucida Grande";
  228801. defaultSerif = "Times New Roman";
  228802. defaultFixed = "Monaco";
  228803. #endif
  228804. }
  228805. #endif
  228806. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228807. // (must go before juce_mac_CoreGraphicsContext.mm)
  228808. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228809. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228810. // compiled on its own).
  228811. #if JUCE_INCLUDED_FILE
  228812. class CoreGraphicsImage : public Image::SharedImage
  228813. {
  228814. public:
  228815. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  228816. : Image::SharedImage (format_, width_, height_)
  228817. {
  228818. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  228819. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  228820. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  228821. imageData = imageDataAllocated;
  228822. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  228823. : CGColorSpaceCreateDeviceRGB();
  228824. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  228825. colourSpace, getCGImageFlags (format_));
  228826. CGColorSpaceRelease (colourSpace);
  228827. }
  228828. ~CoreGraphicsImage()
  228829. {
  228830. CGContextRelease (context);
  228831. }
  228832. Image::ImageType getType() const { return Image::NativeImage; }
  228833. LowLevelGraphicsContext* createLowLevelContext();
  228834. SharedImage* clone()
  228835. {
  228836. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  228837. memcpy (im->imageData, imageData, lineStride * height);
  228838. return im;
  228839. }
  228840. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  228841. {
  228842. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  228843. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  228844. {
  228845. return CGBitmapContextCreateImage (nativeImage->context);
  228846. }
  228847. else
  228848. {
  228849. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  228850. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  228851. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  228852. 8, srcData.pixelStride * 8, srcData.lineStride,
  228853. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  228854. 0, true, kCGRenderingIntentDefault);
  228855. CGDataProviderRelease (provider);
  228856. return imageRef;
  228857. }
  228858. }
  228859. #if JUCE_MAC
  228860. static NSImage* createNSImage (const Image& image)
  228861. {
  228862. const ScopedAutoReleasePool pool;
  228863. NSImage* im = [[NSImage alloc] init];
  228864. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  228865. [im lockFocus];
  228866. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228867. CGImageRef imageRef = createImage (image, false, colourSpace);
  228868. CGColorSpaceRelease (colourSpace);
  228869. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228870. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  228871. CGImageRelease (imageRef);
  228872. [im unlockFocus];
  228873. return im;
  228874. }
  228875. #endif
  228876. CGContextRef context;
  228877. HeapBlock<uint8> imageDataAllocated;
  228878. private:
  228879. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  228880. {
  228881. #if JUCE_BIG_ENDIAN
  228882. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  228883. #else
  228884. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  228885. #endif
  228886. }
  228887. };
  228888. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  228889. {
  228890. #if USE_COREGRAPHICS_RENDERING
  228891. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  228892. #else
  228893. return createSoftwareImage (format, width, height, clearImage);
  228894. #endif
  228895. }
  228896. class CoreGraphicsContext : public LowLevelGraphicsContext
  228897. {
  228898. public:
  228899. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  228900. : context (context_),
  228901. flipHeight (flipHeight_),
  228902. state (new SavedState()),
  228903. numGradientLookupEntries (0),
  228904. lastClipRectIsValid (false)
  228905. {
  228906. CGContextRetain (context);
  228907. CGContextSaveGState(context);
  228908. CGContextSetShouldSmoothFonts (context, true);
  228909. CGContextSetShouldAntialias (context, true);
  228910. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228911. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  228912. greyColourSpace = CGColorSpaceCreateDeviceGray();
  228913. gradientCallbacks.version = 0;
  228914. gradientCallbacks.evaluate = gradientCallback;
  228915. gradientCallbacks.releaseInfo = 0;
  228916. setFont (Font());
  228917. }
  228918. ~CoreGraphicsContext()
  228919. {
  228920. CGContextRestoreGState (context);
  228921. CGContextRelease (context);
  228922. CGColorSpaceRelease (rgbColourSpace);
  228923. CGColorSpaceRelease (greyColourSpace);
  228924. }
  228925. bool isVectorDevice() const { return false; }
  228926. void setOrigin (int x, int y)
  228927. {
  228928. CGContextTranslateCTM (context, x, -y);
  228929. if (lastClipRectIsValid)
  228930. lastClipRect.translate (-x, -y);
  228931. }
  228932. bool clipToRectangle (const Rectangle<int>& r)
  228933. {
  228934. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  228935. if (lastClipRectIsValid)
  228936. {
  228937. lastClipRect = lastClipRect.getIntersection (r);
  228938. return ! lastClipRect.isEmpty();
  228939. }
  228940. return ! isClipEmpty();
  228941. }
  228942. bool clipToRectangleList (const RectangleList& clipRegion)
  228943. {
  228944. if (clipRegion.isEmpty())
  228945. {
  228946. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  228947. lastClipRectIsValid = true;
  228948. lastClipRect = Rectangle<int>();
  228949. return false;
  228950. }
  228951. else
  228952. {
  228953. const int numRects = clipRegion.getNumRectangles();
  228954. HeapBlock <CGRect> rects (numRects);
  228955. for (int i = 0; i < numRects; ++i)
  228956. {
  228957. const Rectangle<int>& r = clipRegion.getRectangle(i);
  228958. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228959. }
  228960. CGContextClipToRects (context, rects, numRects);
  228961. lastClipRectIsValid = false;
  228962. return ! isClipEmpty();
  228963. }
  228964. }
  228965. void excludeClipRectangle (const Rectangle<int>& r)
  228966. {
  228967. RectangleList remaining (getClipBounds());
  228968. remaining.subtract (r);
  228969. clipToRectangleList (remaining);
  228970. lastClipRectIsValid = false;
  228971. }
  228972. void clipToPath (const Path& path, const AffineTransform& transform)
  228973. {
  228974. createPath (path, transform);
  228975. CGContextClip (context);
  228976. lastClipRectIsValid = false;
  228977. }
  228978. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  228979. {
  228980. if (! transform.isSingularity())
  228981. {
  228982. Image singleChannelImage (sourceImage);
  228983. if (sourceImage.getFormat() != Image::SingleChannel)
  228984. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  228985. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  228986. if (srcClip != sourceImage.getBounds())
  228987. {
  228988. CGImageRef fullImage = image;
  228989. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228990. srcClip.getWidth(), srcClip.getHeight()));
  228991. CGImageRelease (fullImage);
  228992. }
  228993. flip();
  228994. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228995. applyTransform (t);
  228996. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228997. CGContextClipToMask (context, r, image);
  228998. applyTransform (t.inverted());
  228999. flip();
  229000. CGImageRelease (image);
  229001. lastClipRectIsValid = false;
  229002. }
  229003. }
  229004. bool clipRegionIntersects (const Rectangle<int>& r)
  229005. {
  229006. return getClipBounds().intersects (r);
  229007. }
  229008. const Rectangle<int> getClipBounds() const
  229009. {
  229010. if (! lastClipRectIsValid)
  229011. {
  229012. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229013. lastClipRectIsValid = true;
  229014. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229015. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229016. roundToInt (bounds.size.width),
  229017. roundToInt (bounds.size.height));
  229018. }
  229019. return lastClipRect;
  229020. }
  229021. bool isClipEmpty() const
  229022. {
  229023. return getClipBounds().isEmpty();
  229024. }
  229025. void saveState()
  229026. {
  229027. CGContextSaveGState (context);
  229028. stateStack.add (new SavedState (*state));
  229029. }
  229030. void restoreState()
  229031. {
  229032. CGContextRestoreGState (context);
  229033. SavedState* const top = stateStack.getLast();
  229034. if (top != 0)
  229035. {
  229036. state = top;
  229037. stateStack.removeLast (1, false);
  229038. lastClipRectIsValid = false;
  229039. }
  229040. else
  229041. {
  229042. jassertfalse; // trying to pop with an empty stack!
  229043. }
  229044. }
  229045. void setFill (const FillType& fillType)
  229046. {
  229047. state->fillType = fillType;
  229048. if (fillType.isColour())
  229049. {
  229050. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229051. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229052. CGContextSetAlpha (context, 1.0f);
  229053. }
  229054. }
  229055. void setOpacity (float newOpacity)
  229056. {
  229057. state->fillType.setOpacity (newOpacity);
  229058. setFill (state->fillType);
  229059. }
  229060. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229061. {
  229062. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229063. ? kCGInterpolationLow
  229064. : kCGInterpolationHigh);
  229065. }
  229066. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229067. {
  229068. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229069. if (replaceExistingContents)
  229070. {
  229071. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229072. CGContextClearRect (context, cgRect);
  229073. #else
  229074. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229075. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229076. CGContextClearRect (context, cgRect);
  229077. else
  229078. #endif
  229079. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229080. #endif
  229081. fillRect (r, false);
  229082. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229083. }
  229084. else
  229085. {
  229086. if (state->fillType.isColour())
  229087. {
  229088. CGContextFillRect (context, cgRect);
  229089. }
  229090. else if (state->fillType.isGradient())
  229091. {
  229092. CGContextSaveGState (context);
  229093. CGContextClipToRect (context, cgRect);
  229094. drawGradient();
  229095. CGContextRestoreGState (context);
  229096. }
  229097. else
  229098. {
  229099. CGContextSaveGState (context);
  229100. CGContextClipToRect (context, cgRect);
  229101. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  229102. CGContextRestoreGState (context);
  229103. }
  229104. }
  229105. }
  229106. void fillPath (const Path& path, const AffineTransform& transform)
  229107. {
  229108. CGContextSaveGState (context);
  229109. if (state->fillType.isColour())
  229110. {
  229111. flip();
  229112. applyTransform (transform);
  229113. createPath (path);
  229114. if (path.isUsingNonZeroWinding())
  229115. CGContextFillPath (context);
  229116. else
  229117. CGContextEOFillPath (context);
  229118. }
  229119. else
  229120. {
  229121. createPath (path, transform);
  229122. if (path.isUsingNonZeroWinding())
  229123. CGContextClip (context);
  229124. else
  229125. CGContextEOClip (context);
  229126. if (state->fillType.isGradient())
  229127. drawGradient();
  229128. else
  229129. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  229130. }
  229131. CGContextRestoreGState (context);
  229132. }
  229133. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  229134. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229135. {
  229136. jassert (sourceImage.getBounds().contains (srcClip));
  229137. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  229138. CGImageRef image = fullImage;
  229139. if (srcClip != sourceImage.getBounds())
  229140. {
  229141. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  229142. srcClip.getWidth(), srcClip.getHeight()));
  229143. CGImageRelease (fullImage);
  229144. }
  229145. CGContextSaveGState (context);
  229146. CGContextSetAlpha (context, state->fillType.getOpacity());
  229147. flip();
  229148. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  229149. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  229150. if (fillEntireClipAsTiles)
  229151. {
  229152. #if JUCE_IPHONE
  229153. CGContextDrawTiledImage (context, imageRect, image);
  229154. #else
  229155. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229156. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229157. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229158. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229159. CGContextDrawTiledImage (context, imageRect, image);
  229160. else
  229161. #endif
  229162. {
  229163. // Fallback to manually doing a tiled fill on 10.4
  229164. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229165. const int iw = srcClip.getWidth();
  229166. const int ih = srcClip.getHeight();
  229167. int x = 0, y = 0;
  229168. while (x > clip.origin.x) x -= iw;
  229169. while (y > clip.origin.y) y -= ih;
  229170. const int right = (int) (clip.origin.x + clip.size.width);
  229171. const int bottom = (int) (clip.origin.y + clip.size.height);
  229172. while (y < bottom)
  229173. {
  229174. for (int x2 = x; x2 < right; x2 += iw)
  229175. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229176. y += ih;
  229177. }
  229178. }
  229179. #endif
  229180. }
  229181. else
  229182. {
  229183. CGContextDrawImage (context, imageRect, image);
  229184. }
  229185. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229186. CGContextRestoreGState (context);
  229187. }
  229188. void drawLine (const Line<float>& line)
  229189. {
  229190. CGContextSetLineCap (context, kCGLineCapSquare);
  229191. CGContextSetLineWidth (context, 1.0f);
  229192. CGContextSetRGBStrokeColor (context,
  229193. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229194. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229195. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229196. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229197. CGContextStrokeLineSegments (context, cgLine, 1);
  229198. }
  229199. void drawVerticalLine (const int x, float top, float bottom)
  229200. {
  229201. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229202. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229203. #else
  229204. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229205. // the x co-ord slightly to trick it..
  229206. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229207. #endif
  229208. }
  229209. void drawHorizontalLine (const int y, float left, float right)
  229210. {
  229211. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229212. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229213. #else
  229214. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229215. // the x co-ord slightly to trick it..
  229216. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229217. #endif
  229218. }
  229219. void setFont (const Font& newFont)
  229220. {
  229221. if (state->font != newFont)
  229222. {
  229223. state->fontRef = 0;
  229224. state->font = newFont;
  229225. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229226. if (mf != 0)
  229227. {
  229228. state->fontRef = mf->fontRef;
  229229. CGContextSetFont (context, state->fontRef);
  229230. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229231. state->fontTransform = mf->renderingTransform;
  229232. state->fontTransform.a *= state->font.getHorizontalScale();
  229233. CGContextSetTextMatrix (context, state->fontTransform);
  229234. }
  229235. }
  229236. }
  229237. const Font getFont()
  229238. {
  229239. return state->font;
  229240. }
  229241. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229242. {
  229243. if (state->fontRef != 0 && state->fillType.isColour())
  229244. {
  229245. if (transform.isOnlyTranslation())
  229246. {
  229247. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229248. CGGlyph g = glyphNumber;
  229249. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229250. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229251. }
  229252. else
  229253. {
  229254. CGContextSaveGState (context);
  229255. flip();
  229256. applyTransform (transform);
  229257. CGAffineTransform t = state->fontTransform;
  229258. t.d = -t.d;
  229259. CGContextSetTextMatrix (context, t);
  229260. CGGlyph g = glyphNumber;
  229261. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229262. CGContextRestoreGState (context);
  229263. }
  229264. }
  229265. else
  229266. {
  229267. Path p;
  229268. Font& f = state->font;
  229269. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229270. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229271. .followedBy (transform));
  229272. }
  229273. }
  229274. private:
  229275. CGContextRef context;
  229276. const CGFloat flipHeight;
  229277. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229278. CGFunctionCallbacks gradientCallbacks;
  229279. mutable Rectangle<int> lastClipRect;
  229280. mutable bool lastClipRectIsValid;
  229281. struct SavedState
  229282. {
  229283. SavedState()
  229284. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229285. {
  229286. }
  229287. SavedState (const SavedState& other)
  229288. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229289. fontTransform (other.fontTransform)
  229290. {
  229291. }
  229292. ~SavedState()
  229293. {
  229294. }
  229295. FillType fillType;
  229296. Font font;
  229297. CGFontRef fontRef;
  229298. CGAffineTransform fontTransform;
  229299. };
  229300. ScopedPointer <SavedState> state;
  229301. OwnedArray <SavedState> stateStack;
  229302. HeapBlock <PixelARGB> gradientLookupTable;
  229303. int numGradientLookupEntries;
  229304. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229305. {
  229306. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229307. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229308. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229309. colour.unpremultiply();
  229310. outData[0] = colour.getRed() / 255.0f;
  229311. outData[1] = colour.getGreen() / 255.0f;
  229312. outData[2] = colour.getBlue() / 255.0f;
  229313. outData[3] = colour.getAlpha() / 255.0f;
  229314. }
  229315. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229316. {
  229317. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229318. --numGradientLookupEntries;
  229319. CGShadingRef result = 0;
  229320. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229321. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229322. if (gradient.isRadial)
  229323. {
  229324. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229325. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229326. function, true, true);
  229327. }
  229328. else
  229329. {
  229330. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229331. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229332. function, true, true);
  229333. }
  229334. CGFunctionRelease (function);
  229335. return result;
  229336. }
  229337. void drawGradient()
  229338. {
  229339. flip();
  229340. applyTransform (state->fillType.transform);
  229341. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229342. // you draw a gradient with high quality interp enabled).
  229343. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229344. CGContextSetAlpha (context, state->fillType.getOpacity());
  229345. CGContextDrawShading (context, shading);
  229346. CGShadingRelease (shading);
  229347. }
  229348. void createPath (const Path& path) const
  229349. {
  229350. CGContextBeginPath (context);
  229351. Path::Iterator i (path);
  229352. while (i.next())
  229353. {
  229354. switch (i.elementType)
  229355. {
  229356. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229357. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229358. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229359. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229360. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229361. default: jassertfalse; break;
  229362. }
  229363. }
  229364. }
  229365. void createPath (const Path& path, const AffineTransform& transform) const
  229366. {
  229367. CGContextBeginPath (context);
  229368. Path::Iterator i (path);
  229369. while (i.next())
  229370. {
  229371. switch (i.elementType)
  229372. {
  229373. case Path::Iterator::startNewSubPath:
  229374. transform.transformPoint (i.x1, i.y1);
  229375. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229376. break;
  229377. case Path::Iterator::lineTo:
  229378. transform.transformPoint (i.x1, i.y1);
  229379. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229380. break;
  229381. case Path::Iterator::quadraticTo:
  229382. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  229383. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229384. break;
  229385. case Path::Iterator::cubicTo:
  229386. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  229387. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229388. break;
  229389. case Path::Iterator::closePath:
  229390. CGContextClosePath (context); break;
  229391. default:
  229392. jassertfalse;
  229393. break;
  229394. }
  229395. }
  229396. }
  229397. void flip() const
  229398. {
  229399. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229400. }
  229401. void applyTransform (const AffineTransform& transform) const
  229402. {
  229403. CGAffineTransform t;
  229404. t.a = transform.mat00;
  229405. t.b = transform.mat10;
  229406. t.c = transform.mat01;
  229407. t.d = transform.mat11;
  229408. t.tx = transform.mat02;
  229409. t.ty = transform.mat12;
  229410. CGContextConcatCTM (context, t);
  229411. }
  229412. CoreGraphicsContext (const CoreGraphicsContext&);
  229413. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229414. };
  229415. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229416. {
  229417. return new CoreGraphicsContext (context, height);
  229418. }
  229419. #endif
  229420. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229421. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229422. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229423. // compiled on its own).
  229424. #if JUCE_INCLUDED_FILE
  229425. class NSViewComponentPeer;
  229426. END_JUCE_NAMESPACE
  229427. @interface NSEvent (JuceDeviceDelta)
  229428. - (float) deviceDeltaX;
  229429. - (float) deviceDeltaY;
  229430. @end
  229431. #define JuceNSView MakeObjCClassName(JuceNSView)
  229432. @interface JuceNSView : NSView<NSTextInput>
  229433. {
  229434. @public
  229435. NSViewComponentPeer* owner;
  229436. NSNotificationCenter* notificationCenter;
  229437. String* stringBeingComposed;
  229438. bool textWasInserted;
  229439. }
  229440. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229441. - (void) dealloc;
  229442. - (BOOL) isOpaque;
  229443. - (void) drawRect: (NSRect) r;
  229444. - (void) mouseDown: (NSEvent*) ev;
  229445. - (void) asyncMouseDown: (NSEvent*) ev;
  229446. - (void) mouseUp: (NSEvent*) ev;
  229447. - (void) asyncMouseUp: (NSEvent*) ev;
  229448. - (void) mouseDragged: (NSEvent*) ev;
  229449. - (void) mouseMoved: (NSEvent*) ev;
  229450. - (void) mouseEntered: (NSEvent*) ev;
  229451. - (void) mouseExited: (NSEvent*) ev;
  229452. - (void) rightMouseDown: (NSEvent*) ev;
  229453. - (void) rightMouseDragged: (NSEvent*) ev;
  229454. - (void) rightMouseUp: (NSEvent*) ev;
  229455. - (void) otherMouseDown: (NSEvent*) ev;
  229456. - (void) otherMouseDragged: (NSEvent*) ev;
  229457. - (void) otherMouseUp: (NSEvent*) ev;
  229458. - (void) scrollWheel: (NSEvent*) ev;
  229459. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229460. - (void) frameChanged: (NSNotification*) n;
  229461. - (void) viewDidMoveToWindow;
  229462. - (void) keyDown: (NSEvent*) ev;
  229463. - (void) keyUp: (NSEvent*) ev;
  229464. // NSTextInput Methods
  229465. - (void) insertText: (id) aString;
  229466. - (void) doCommandBySelector: (SEL) aSelector;
  229467. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229468. - (void) unmarkText;
  229469. - (BOOL) hasMarkedText;
  229470. - (long) conversationIdentifier;
  229471. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229472. - (NSRange) markedRange;
  229473. - (NSRange) selectedRange;
  229474. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229475. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  229476. - (NSArray*) validAttributesForMarkedText;
  229477. - (void) flagsChanged: (NSEvent*) ev;
  229478. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229479. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229480. #endif
  229481. - (BOOL) becomeFirstResponder;
  229482. - (BOOL) resignFirstResponder;
  229483. - (BOOL) acceptsFirstResponder;
  229484. - (void) asyncRepaint: (id) rect;
  229485. - (NSArray*) getSupportedDragTypes;
  229486. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229487. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229488. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229489. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229490. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229491. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229492. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229493. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229494. @end
  229495. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229496. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229497. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229498. #else
  229499. @interface JuceNSWindow : NSWindow
  229500. #endif
  229501. {
  229502. @private
  229503. NSViewComponentPeer* owner;
  229504. bool isZooming;
  229505. }
  229506. - (void) setOwner: (NSViewComponentPeer*) owner;
  229507. - (BOOL) canBecomeKeyWindow;
  229508. - (void) becomeKeyWindow;
  229509. - (BOOL) windowShouldClose: (id) window;
  229510. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229511. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229512. - (void) zoom: (id) sender;
  229513. @end
  229514. BEGIN_JUCE_NAMESPACE
  229515. class NSViewComponentPeer : public ComponentPeer
  229516. {
  229517. public:
  229518. NSViewComponentPeer (Component* const component,
  229519. const int windowStyleFlags,
  229520. NSView* viewToAttachTo);
  229521. ~NSViewComponentPeer();
  229522. void* getNativeHandle() const;
  229523. void setVisible (bool shouldBeVisible);
  229524. void setTitle (const String& title);
  229525. void setPosition (int x, int y);
  229526. void setSize (int w, int h);
  229527. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229528. const Rectangle<int> getBounds (const bool global) const;
  229529. const Rectangle<int> getBounds() const;
  229530. const Point<int> getScreenPosition() const;
  229531. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229532. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229533. void setMinimised (bool shouldBeMinimised);
  229534. bool isMinimised() const;
  229535. void setFullScreen (bool shouldBeFullScreen);
  229536. bool isFullScreen() const;
  229537. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229538. const BorderSize getFrameSize() const;
  229539. bool setAlwaysOnTop (bool alwaysOnTop);
  229540. void toFront (bool makeActiveWindow);
  229541. void toBehind (ComponentPeer* other);
  229542. void setIcon (const Image& newIcon);
  229543. const StringArray getAvailableRenderingEngines() throw();
  229544. int getCurrentRenderingEngine() throw();
  229545. void setCurrentRenderingEngine (int index) throw();
  229546. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229547. for example having more than one juce plugin loaded into a host, then when a
  229548. method is called, the actual code that runs might actually be in a different module
  229549. than the one you expect... So any calls to library functions or statics that are
  229550. made inside obj-c methods will probably end up getting executed in a different DLL's
  229551. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229552. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229553. virtual methods of an object that's known to live inside the right module's space.
  229554. */
  229555. virtual void redirectMouseDown (NSEvent* ev);
  229556. virtual void redirectMouseUp (NSEvent* ev);
  229557. virtual void redirectMouseDrag (NSEvent* ev);
  229558. virtual void redirectMouseMove (NSEvent* ev);
  229559. virtual void redirectMouseEnter (NSEvent* ev);
  229560. virtual void redirectMouseExit (NSEvent* ev);
  229561. virtual void redirectMouseWheel (NSEvent* ev);
  229562. void sendMouseEvent (NSEvent* ev);
  229563. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229564. virtual bool redirectKeyDown (NSEvent* ev);
  229565. virtual bool redirectKeyUp (NSEvent* ev);
  229566. virtual void redirectModKeyChange (NSEvent* ev);
  229567. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229568. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229569. #endif
  229570. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229571. virtual bool isOpaque();
  229572. virtual void drawRect (NSRect r);
  229573. virtual bool canBecomeKeyWindow();
  229574. virtual bool windowShouldClose();
  229575. virtual void redirectMovedOrResized();
  229576. virtual void viewMovedToWindow();
  229577. virtual NSRect constrainRect (NSRect r);
  229578. static void showArrowCursorIfNeeded();
  229579. static void updateModifiers (NSEvent* e);
  229580. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229581. static int getKeyCodeFromEvent (NSEvent* ev)
  229582. {
  229583. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229584. int keyCode = unmodified[0];
  229585. if (keyCode == 0x19) // (backwards-tab)
  229586. keyCode = '\t';
  229587. else if (keyCode == 0x03) // (enter)
  229588. keyCode = '\r';
  229589. return keyCode;
  229590. }
  229591. static int64 getMouseTime (NSEvent* e)
  229592. {
  229593. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229594. + (int64) ([e timestamp] * 1000.0);
  229595. }
  229596. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229597. {
  229598. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229599. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229600. }
  229601. static int getModifierForButtonNumber (const NSInteger num)
  229602. {
  229603. return num == 0 ? ModifierKeys::leftButtonModifier
  229604. : (num == 1 ? ModifierKeys::rightButtonModifier
  229605. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229606. }
  229607. virtual void viewFocusGain();
  229608. virtual void viewFocusLoss();
  229609. bool isFocused() const;
  229610. void grabFocus();
  229611. void textInputRequired (const Point<int>& position);
  229612. void repaint (const Rectangle<int>& area);
  229613. void performAnyPendingRepaintsNow();
  229614. juce_UseDebuggingNewOperator
  229615. NSWindow* window;
  229616. JuceNSView* view;
  229617. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229618. static ModifierKeys currentModifiers;
  229619. static ComponentPeer* currentlyFocusedPeer;
  229620. static Array<int> keysCurrentlyDown;
  229621. };
  229622. END_JUCE_NAMESPACE
  229623. @implementation JuceNSView
  229624. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229625. withFrame: (NSRect) frame
  229626. {
  229627. [super initWithFrame: frame];
  229628. owner = owner_;
  229629. stringBeingComposed = 0;
  229630. textWasInserted = false;
  229631. notificationCenter = [NSNotificationCenter defaultCenter];
  229632. [notificationCenter addObserver: self
  229633. selector: @selector (frameChanged:)
  229634. name: NSViewFrameDidChangeNotification
  229635. object: self];
  229636. if (! owner_->isSharedWindow)
  229637. {
  229638. [notificationCenter addObserver: self
  229639. selector: @selector (frameChanged:)
  229640. name: NSWindowDidMoveNotification
  229641. object: owner_->window];
  229642. }
  229643. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229644. return self;
  229645. }
  229646. - (void) dealloc
  229647. {
  229648. [notificationCenter removeObserver: self];
  229649. delete stringBeingComposed;
  229650. [super dealloc];
  229651. }
  229652. - (void) drawRect: (NSRect) r
  229653. {
  229654. if (owner != 0)
  229655. owner->drawRect (r);
  229656. }
  229657. - (BOOL) isOpaque
  229658. {
  229659. return owner == 0 || owner->isOpaque();
  229660. }
  229661. - (void) mouseDown: (NSEvent*) ev
  229662. {
  229663. // In some host situations, the host will stop modal loops from working
  229664. // correctly if they're called from a mouse event, so we'll trigger
  229665. // the event asynchronously..
  229666. if (JUCEApplication::getInstance() == 0)
  229667. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229668. withObject: ev
  229669. waitUntilDone: NO];
  229670. else
  229671. [self asyncMouseDown: ev];
  229672. }
  229673. - (void) asyncMouseDown: (NSEvent*) ev
  229674. {
  229675. if (owner != 0)
  229676. owner->redirectMouseDown (ev);
  229677. }
  229678. - (void) mouseUp: (NSEvent*) ev
  229679. {
  229680. // In some host situations, the host will stop modal loops from working
  229681. // correctly if they're called from a mouse event, so we'll trigger
  229682. // the event asynchronously..
  229683. if (JUCEApplication::getInstance() == 0)
  229684. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229685. withObject: ev
  229686. waitUntilDone: NO];
  229687. else
  229688. [self asyncMouseUp: ev];
  229689. }
  229690. - (void) asyncMouseUp: (NSEvent*) ev
  229691. {
  229692. if (owner != 0)
  229693. owner->redirectMouseUp (ev);
  229694. }
  229695. - (void) mouseDragged: (NSEvent*) ev
  229696. {
  229697. if (owner != 0)
  229698. owner->redirectMouseDrag (ev);
  229699. }
  229700. - (void) mouseMoved: (NSEvent*) ev
  229701. {
  229702. if (owner != 0)
  229703. owner->redirectMouseMove (ev);
  229704. }
  229705. - (void) mouseEntered: (NSEvent*) ev
  229706. {
  229707. if (owner != 0)
  229708. owner->redirectMouseEnter (ev);
  229709. }
  229710. - (void) mouseExited: (NSEvent*) ev
  229711. {
  229712. if (owner != 0)
  229713. owner->redirectMouseExit (ev);
  229714. }
  229715. - (void) rightMouseDown: (NSEvent*) ev
  229716. {
  229717. [self mouseDown: ev];
  229718. }
  229719. - (void) rightMouseDragged: (NSEvent*) ev
  229720. {
  229721. [self mouseDragged: ev];
  229722. }
  229723. - (void) rightMouseUp: (NSEvent*) ev
  229724. {
  229725. [self mouseUp: ev];
  229726. }
  229727. - (void) otherMouseDown: (NSEvent*) ev
  229728. {
  229729. [self mouseDown: ev];
  229730. }
  229731. - (void) otherMouseDragged: (NSEvent*) ev
  229732. {
  229733. [self mouseDragged: ev];
  229734. }
  229735. - (void) otherMouseUp: (NSEvent*) ev
  229736. {
  229737. [self mouseUp: ev];
  229738. }
  229739. - (void) scrollWheel: (NSEvent*) ev
  229740. {
  229741. if (owner != 0)
  229742. owner->redirectMouseWheel (ev);
  229743. }
  229744. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229745. {
  229746. (void) ev;
  229747. return YES;
  229748. }
  229749. - (void) frameChanged: (NSNotification*) n
  229750. {
  229751. (void) n;
  229752. if (owner != 0)
  229753. owner->redirectMovedOrResized();
  229754. }
  229755. - (void) viewDidMoveToWindow
  229756. {
  229757. if (owner != 0)
  229758. owner->viewMovedToWindow();
  229759. }
  229760. - (void) asyncRepaint: (id) rect
  229761. {
  229762. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229763. [self setNeedsDisplayInRect: *r];
  229764. }
  229765. - (void) keyDown: (NSEvent*) ev
  229766. {
  229767. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229768. textWasInserted = false;
  229769. if (target != 0)
  229770. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229771. else
  229772. deleteAndZero (stringBeingComposed);
  229773. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229774. [super keyDown: ev];
  229775. }
  229776. - (void) keyUp: (NSEvent*) ev
  229777. {
  229778. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229779. [super keyUp: ev];
  229780. }
  229781. - (void) insertText: (id) aString
  229782. {
  229783. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229784. if ([aString length] > 0)
  229785. {
  229786. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229787. if (target != 0)
  229788. {
  229789. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  229790. textWasInserted = true;
  229791. }
  229792. }
  229793. deleteAndZero (stringBeingComposed);
  229794. }
  229795. - (void) doCommandBySelector: (SEL) aSelector
  229796. {
  229797. (void) aSelector;
  229798. }
  229799. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229800. {
  229801. (void) selectionRange;
  229802. if (stringBeingComposed == 0)
  229803. stringBeingComposed = new String();
  229804. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229805. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229806. if (target != 0)
  229807. {
  229808. const Range<int> currentHighlight (target->getHighlightedRegion());
  229809. target->insertTextAtCaret (*stringBeingComposed);
  229810. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229811. textWasInserted = true;
  229812. }
  229813. }
  229814. - (void) unmarkText
  229815. {
  229816. if (stringBeingComposed != 0)
  229817. {
  229818. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229819. if (target != 0)
  229820. {
  229821. target->insertTextAtCaret (*stringBeingComposed);
  229822. textWasInserted = true;
  229823. }
  229824. }
  229825. deleteAndZero (stringBeingComposed);
  229826. }
  229827. - (BOOL) hasMarkedText
  229828. {
  229829. return stringBeingComposed != 0;
  229830. }
  229831. - (long) conversationIdentifier
  229832. {
  229833. return (long) (pointer_sized_int) self;
  229834. }
  229835. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  229836. {
  229837. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229838. if (target != 0)
  229839. {
  229840. const Range<int> r ((int) theRange.location,
  229841. (int) (theRange.location + theRange.length));
  229842. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  229843. }
  229844. return nil;
  229845. }
  229846. - (NSRange) markedRange
  229847. {
  229848. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  229849. : NSMakeRange (NSNotFound, 0);
  229850. }
  229851. - (NSRange) selectedRange
  229852. {
  229853. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229854. if (target != 0)
  229855. {
  229856. const Range<int> highlight (target->getHighlightedRegion());
  229857. if (! highlight.isEmpty())
  229858. return NSMakeRange (highlight.getStart(), highlight.getLength());
  229859. }
  229860. return NSMakeRange (NSNotFound, 0);
  229861. }
  229862. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  229863. {
  229864. (void) theRange;
  229865. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  229866. if (comp == 0)
  229867. return NSMakeRect (0, 0, 0, 0);
  229868. const Rectangle<int> bounds (comp->getScreenBounds());
  229869. return NSMakeRect (bounds.getX(),
  229870. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  229871. bounds.getWidth(),
  229872. bounds.getHeight());
  229873. }
  229874. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  229875. {
  229876. (void) thePoint;
  229877. return NSNotFound;
  229878. }
  229879. - (NSArray*) validAttributesForMarkedText
  229880. {
  229881. return [NSArray array];
  229882. }
  229883. - (void) flagsChanged: (NSEvent*) ev
  229884. {
  229885. if (owner != 0)
  229886. owner->redirectModKeyChange (ev);
  229887. }
  229888. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229889. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  229890. {
  229891. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  229892. return true;
  229893. return [super performKeyEquivalent: ev];
  229894. }
  229895. #endif
  229896. - (BOOL) becomeFirstResponder
  229897. {
  229898. if (owner != 0)
  229899. owner->viewFocusGain();
  229900. return true;
  229901. }
  229902. - (BOOL) resignFirstResponder
  229903. {
  229904. if (owner != 0)
  229905. owner->viewFocusLoss();
  229906. return true;
  229907. }
  229908. - (BOOL) acceptsFirstResponder
  229909. {
  229910. return owner != 0 && owner->canBecomeKeyWindow();
  229911. }
  229912. - (NSArray*) getSupportedDragTypes
  229913. {
  229914. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  229915. }
  229916. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  229917. {
  229918. return owner != 0 && owner->sendDragCallback (type, sender);
  229919. }
  229920. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  229921. {
  229922. if ([self sendDragCallback: 0 sender: sender])
  229923. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229924. else
  229925. return NSDragOperationNone;
  229926. }
  229927. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  229928. {
  229929. if ([self sendDragCallback: 0 sender: sender])
  229930. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229931. else
  229932. return NSDragOperationNone;
  229933. }
  229934. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  229935. {
  229936. [self sendDragCallback: 1 sender: sender];
  229937. }
  229938. - (void) draggingExited: (id <NSDraggingInfo>) sender
  229939. {
  229940. [self sendDragCallback: 1 sender: sender];
  229941. }
  229942. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  229943. {
  229944. (void) sender;
  229945. return YES;
  229946. }
  229947. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  229948. {
  229949. return [self sendDragCallback: 2 sender: sender];
  229950. }
  229951. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  229952. {
  229953. (void) sender;
  229954. }
  229955. @end
  229956. @implementation JuceNSWindow
  229957. - (void) setOwner: (NSViewComponentPeer*) owner_
  229958. {
  229959. owner = owner_;
  229960. isZooming = false;
  229961. }
  229962. - (BOOL) canBecomeKeyWindow
  229963. {
  229964. return owner != 0 && owner->canBecomeKeyWindow();
  229965. }
  229966. - (void) becomeKeyWindow
  229967. {
  229968. [super becomeKeyWindow];
  229969. if (owner != 0)
  229970. owner->grabFocus();
  229971. }
  229972. - (BOOL) windowShouldClose: (id) window
  229973. {
  229974. (void) window;
  229975. return owner == 0 || owner->windowShouldClose();
  229976. }
  229977. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  229978. {
  229979. (void) screen;
  229980. if (owner != 0)
  229981. frameRect = owner->constrainRect (frameRect);
  229982. return frameRect;
  229983. }
  229984. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  229985. {
  229986. (void) window;
  229987. if (isZooming)
  229988. return proposedFrameSize;
  229989. NSRect frameRect = [self frame];
  229990. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  229991. frameRect.size = proposedFrameSize;
  229992. if (owner != 0)
  229993. frameRect = owner->constrainRect (frameRect);
  229994. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229995. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229996. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229997. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229998. return frameRect.size;
  229999. }
  230000. - (void) zoom: (id) sender
  230001. {
  230002. isZooming = true;
  230003. [super zoom: sender];
  230004. isZooming = false;
  230005. }
  230006. - (void) windowWillMove: (NSNotification*) notification
  230007. {
  230008. (void) notification;
  230009. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230010. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230011. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230012. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230013. }
  230014. @end
  230015. BEGIN_JUCE_NAMESPACE
  230016. ModifierKeys NSViewComponentPeer::currentModifiers;
  230017. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230018. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230019. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230020. {
  230021. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230022. return true;
  230023. if (keyCode >= 'A' && keyCode <= 'Z'
  230024. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230025. return true;
  230026. if (keyCode >= 'a' && keyCode <= 'z'
  230027. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230028. return true;
  230029. return false;
  230030. }
  230031. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230032. {
  230033. int m = 0;
  230034. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230035. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230036. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230037. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230038. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230039. }
  230040. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230041. {
  230042. updateModifiers (ev);
  230043. int keyCode = getKeyCodeFromEvent (ev);
  230044. if (keyCode != 0)
  230045. {
  230046. if (isKeyDown)
  230047. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230048. else
  230049. keysCurrentlyDown.removeValue (keyCode);
  230050. }
  230051. }
  230052. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230053. {
  230054. return NSViewComponentPeer::currentModifiers;
  230055. }
  230056. void ModifierKeys::updateCurrentModifiers() throw()
  230057. {
  230058. currentModifiers = NSViewComponentPeer::currentModifiers;
  230059. }
  230060. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230061. const int windowStyleFlags,
  230062. NSView* viewToAttachTo)
  230063. : ComponentPeer (component_, windowStyleFlags),
  230064. window (0),
  230065. view (0),
  230066. isSharedWindow (viewToAttachTo != 0),
  230067. fullScreen (false),
  230068. insideDrawRect (false),
  230069. #if USE_COREGRAPHICS_RENDERING
  230070. usingCoreGraphics (true),
  230071. #else
  230072. usingCoreGraphics (false),
  230073. #endif
  230074. recursiveToFrontCall (false)
  230075. {
  230076. NSRect r;
  230077. r.origin.x = 0;
  230078. r.origin.y = 0;
  230079. r.size.width = (float) component->getWidth();
  230080. r.size.height = (float) component->getHeight();
  230081. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230082. [view setPostsFrameChangedNotifications: YES];
  230083. if (isSharedWindow)
  230084. {
  230085. window = [viewToAttachTo window];
  230086. [viewToAttachTo addSubview: view];
  230087. setVisible (component->isVisible());
  230088. }
  230089. else
  230090. {
  230091. r.origin.x = (float) component->getX();
  230092. r.origin.y = (float) component->getY();
  230093. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230094. unsigned int style = 0;
  230095. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230096. style = NSBorderlessWindowMask;
  230097. else
  230098. style = NSTitledWindowMask;
  230099. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230100. style |= NSMiniaturizableWindowMask;
  230101. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230102. style |= NSClosableWindowMask;
  230103. if ((windowStyleFlags & windowIsResizable) != 0)
  230104. style |= NSResizableWindowMask;
  230105. window = [[JuceNSWindow alloc] initWithContentRect: r
  230106. styleMask: style
  230107. backing: NSBackingStoreBuffered
  230108. defer: YES];
  230109. [((JuceNSWindow*) window) setOwner: this];
  230110. [window orderOut: nil];
  230111. [window setDelegate: (JuceNSWindow*) window];
  230112. [window setOpaque: component->isOpaque()];
  230113. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230114. if (component->isAlwaysOnTop())
  230115. [window setLevel: NSFloatingWindowLevel];
  230116. [window setContentView: view];
  230117. [window setAutodisplay: YES];
  230118. [window setAcceptsMouseMovedEvents: YES];
  230119. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230120. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230121. [window setReleasedWhenClosed: YES];
  230122. [window retain];
  230123. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230124. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230125. }
  230126. setTitle (component->getName());
  230127. }
  230128. NSViewComponentPeer::~NSViewComponentPeer()
  230129. {
  230130. view->owner = 0;
  230131. [view removeFromSuperview];
  230132. [view release];
  230133. if (! isSharedWindow)
  230134. {
  230135. [((JuceNSWindow*) window) setOwner: 0];
  230136. [window close];
  230137. [window release];
  230138. }
  230139. }
  230140. void* NSViewComponentPeer::getNativeHandle() const
  230141. {
  230142. return view;
  230143. }
  230144. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230145. {
  230146. if (isSharedWindow)
  230147. {
  230148. [view setHidden: ! shouldBeVisible];
  230149. }
  230150. else
  230151. {
  230152. if (shouldBeVisible)
  230153. {
  230154. [window orderFront: nil];
  230155. handleBroughtToFront();
  230156. }
  230157. else
  230158. {
  230159. [window orderOut: nil];
  230160. }
  230161. }
  230162. }
  230163. void NSViewComponentPeer::setTitle (const String& title)
  230164. {
  230165. const ScopedAutoReleasePool pool;
  230166. if (! isSharedWindow)
  230167. [window setTitle: juceStringToNS (title)];
  230168. }
  230169. void NSViewComponentPeer::setPosition (int x, int y)
  230170. {
  230171. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230172. }
  230173. void NSViewComponentPeer::setSize (int w, int h)
  230174. {
  230175. setBounds (component->getX(), component->getY(), w, h, false);
  230176. }
  230177. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230178. {
  230179. fullScreen = isNowFullScreen;
  230180. w = jmax (0, w);
  230181. h = jmax (0, h);
  230182. NSRect r;
  230183. r.origin.x = (float) x;
  230184. r.origin.y = (float) y;
  230185. r.size.width = (float) w;
  230186. r.size.height = (float) h;
  230187. if (isSharedWindow)
  230188. {
  230189. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230190. if ([view frame].size.width != r.size.width
  230191. || [view frame].size.height != r.size.height)
  230192. [view setNeedsDisplay: true];
  230193. [view setFrame: r];
  230194. }
  230195. else
  230196. {
  230197. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230198. [window setFrame: [window frameRectForContentRect: r]
  230199. display: true];
  230200. }
  230201. }
  230202. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230203. {
  230204. NSRect r = [view frame];
  230205. if (global && [view window] != 0)
  230206. {
  230207. r = [view convertRect: r toView: nil];
  230208. NSRect wr = [[view window] frame];
  230209. r.origin.x += wr.origin.x;
  230210. r.origin.y += wr.origin.y;
  230211. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230212. }
  230213. else
  230214. {
  230215. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230216. }
  230217. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230218. }
  230219. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230220. {
  230221. return getBounds (! isSharedWindow);
  230222. }
  230223. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230224. {
  230225. return getBounds (true).getPosition();
  230226. }
  230227. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230228. {
  230229. return relativePosition + getScreenPosition();
  230230. }
  230231. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230232. {
  230233. return screenPosition - getScreenPosition();
  230234. }
  230235. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230236. {
  230237. if (constrainer != 0)
  230238. {
  230239. NSRect current = [window frame];
  230240. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230241. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230242. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230243. (int) r.size.width, (int) r.size.height);
  230244. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230245. (int) current.size.width, (int) current.size.height);
  230246. constrainer->checkBounds (pos, original,
  230247. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230248. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230249. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230250. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230251. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230252. r.origin.x = pos.getX();
  230253. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230254. r.size.width = pos.getWidth();
  230255. r.size.height = pos.getHeight();
  230256. }
  230257. return r;
  230258. }
  230259. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230260. {
  230261. if (! isSharedWindow)
  230262. {
  230263. if (shouldBeMinimised)
  230264. [window miniaturize: nil];
  230265. else
  230266. [window deminiaturize: nil];
  230267. }
  230268. }
  230269. bool NSViewComponentPeer::isMinimised() const
  230270. {
  230271. return window != 0 && [window isMiniaturized];
  230272. }
  230273. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230274. {
  230275. if (! isSharedWindow)
  230276. {
  230277. Rectangle<int> r (lastNonFullscreenBounds);
  230278. setMinimised (false);
  230279. if (fullScreen != shouldBeFullScreen)
  230280. {
  230281. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230282. {
  230283. fullScreen = true;
  230284. [window performZoom: nil];
  230285. }
  230286. else
  230287. {
  230288. if (shouldBeFullScreen)
  230289. r = Desktop::getInstance().getMainMonitorArea();
  230290. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230291. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230292. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230293. }
  230294. }
  230295. }
  230296. }
  230297. bool NSViewComponentPeer::isFullScreen() const
  230298. {
  230299. return fullScreen;
  230300. }
  230301. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230302. {
  230303. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230304. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230305. return false;
  230306. NSPoint p;
  230307. p.x = (float) position.getX();
  230308. p.y = (float) position.getY();
  230309. NSView* v = [view hitTest: p];
  230310. if (trueIfInAChildWindow)
  230311. return v != nil;
  230312. return v == view;
  230313. }
  230314. const BorderSize NSViewComponentPeer::getFrameSize() const
  230315. {
  230316. BorderSize b;
  230317. if (! isSharedWindow)
  230318. {
  230319. NSRect v = [view convertRect: [view frame] toView: nil];
  230320. NSRect w = [window frame];
  230321. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230322. b.setBottom ((int) v.origin.y);
  230323. b.setLeft ((int) v.origin.x);
  230324. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230325. }
  230326. return b;
  230327. }
  230328. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230329. {
  230330. if (! isSharedWindow)
  230331. {
  230332. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230333. : NSNormalWindowLevel];
  230334. }
  230335. return true;
  230336. }
  230337. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230338. {
  230339. if (isSharedWindow)
  230340. {
  230341. [[view superview] addSubview: view
  230342. positioned: NSWindowAbove
  230343. relativeTo: nil];
  230344. }
  230345. if (window != 0 && component->isVisible())
  230346. {
  230347. if (makeActiveWindow)
  230348. [window makeKeyAndOrderFront: nil];
  230349. else
  230350. [window orderFront: nil];
  230351. if (! recursiveToFrontCall)
  230352. {
  230353. recursiveToFrontCall = true;
  230354. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230355. handleBroughtToFront();
  230356. recursiveToFrontCall = false;
  230357. }
  230358. }
  230359. }
  230360. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230361. {
  230362. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230363. jassert (otherPeer != 0); // wrong type of window?
  230364. if (otherPeer != 0)
  230365. {
  230366. if (isSharedWindow)
  230367. {
  230368. [[view superview] addSubview: view
  230369. positioned: NSWindowBelow
  230370. relativeTo: otherPeer->view];
  230371. }
  230372. else
  230373. {
  230374. [window orderWindow: NSWindowBelow
  230375. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230376. : nil ];
  230377. }
  230378. }
  230379. }
  230380. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230381. {
  230382. // to do..
  230383. }
  230384. void NSViewComponentPeer::viewFocusGain()
  230385. {
  230386. if (currentlyFocusedPeer != this)
  230387. {
  230388. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230389. currentlyFocusedPeer->handleFocusLoss();
  230390. currentlyFocusedPeer = this;
  230391. handleFocusGain();
  230392. }
  230393. }
  230394. void NSViewComponentPeer::viewFocusLoss()
  230395. {
  230396. if (currentlyFocusedPeer == this)
  230397. {
  230398. currentlyFocusedPeer = 0;
  230399. handleFocusLoss();
  230400. }
  230401. }
  230402. void juce_HandleProcessFocusChange()
  230403. {
  230404. NSViewComponentPeer::keysCurrentlyDown.clear();
  230405. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230406. {
  230407. if (Process::isForegroundProcess())
  230408. {
  230409. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230410. ComponentPeer::bringModalComponentToFront();
  230411. }
  230412. else
  230413. {
  230414. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230415. // turn kiosk mode off if we lose focus..
  230416. Desktop::getInstance().setKioskModeComponent (0);
  230417. }
  230418. }
  230419. }
  230420. bool NSViewComponentPeer::isFocused() const
  230421. {
  230422. return isSharedWindow ? this == currentlyFocusedPeer
  230423. : (window != 0 && [window isKeyWindow]);
  230424. }
  230425. void NSViewComponentPeer::grabFocus()
  230426. {
  230427. if (window != 0)
  230428. {
  230429. [window makeKeyWindow];
  230430. [window makeFirstResponder: view];
  230431. viewFocusGain();
  230432. }
  230433. }
  230434. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230435. {
  230436. }
  230437. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230438. {
  230439. String unicode (nsStringToJuce ([ev characters]));
  230440. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230441. int keyCode = getKeyCodeFromEvent (ev);
  230442. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230443. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230444. if (unicode.isNotEmpty() || keyCode != 0)
  230445. {
  230446. if (isKeyDown)
  230447. {
  230448. bool used = false;
  230449. while (unicode.length() > 0)
  230450. {
  230451. juce_wchar textCharacter = unicode[0];
  230452. unicode = unicode.substring (1);
  230453. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230454. textCharacter = 0;
  230455. used = handleKeyUpOrDown (true) || used;
  230456. used = handleKeyPress (keyCode, textCharacter) || used;
  230457. }
  230458. return used;
  230459. }
  230460. else
  230461. {
  230462. if (handleKeyUpOrDown (false))
  230463. return true;
  230464. }
  230465. }
  230466. return false;
  230467. }
  230468. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230469. {
  230470. updateKeysDown (ev, true);
  230471. bool used = handleKeyEvent (ev, true);
  230472. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230473. {
  230474. // for command keys, the key-up event is thrown away, so simulate one..
  230475. updateKeysDown (ev, false);
  230476. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230477. }
  230478. // (If we're running modally, don't allow unused keystrokes to be passed
  230479. // along to other blocked views..)
  230480. if (Component::getCurrentlyModalComponent() != 0)
  230481. used = true;
  230482. return used;
  230483. }
  230484. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230485. {
  230486. updateKeysDown (ev, false);
  230487. return handleKeyEvent (ev, false)
  230488. || Component::getCurrentlyModalComponent() != 0;
  230489. }
  230490. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230491. {
  230492. keysCurrentlyDown.clear();
  230493. handleKeyUpOrDown (true);
  230494. updateModifiers (ev);
  230495. handleModifierKeysChange();
  230496. }
  230497. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230498. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230499. {
  230500. if ([ev type] == NSKeyDown)
  230501. return redirectKeyDown (ev);
  230502. else if ([ev type] == NSKeyUp)
  230503. return redirectKeyUp (ev);
  230504. return false;
  230505. }
  230506. #endif
  230507. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230508. {
  230509. updateModifiers (ev);
  230510. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230511. }
  230512. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230513. {
  230514. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230515. sendMouseEvent (ev);
  230516. }
  230517. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230518. {
  230519. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230520. sendMouseEvent (ev);
  230521. showArrowCursorIfNeeded();
  230522. }
  230523. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230524. {
  230525. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230526. sendMouseEvent (ev);
  230527. }
  230528. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230529. {
  230530. currentModifiers = currentModifiers.withoutMouseButtons();
  230531. sendMouseEvent (ev);
  230532. showArrowCursorIfNeeded();
  230533. }
  230534. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230535. {
  230536. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230537. currentModifiers = currentModifiers.withoutMouseButtons();
  230538. sendMouseEvent (ev);
  230539. }
  230540. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230541. {
  230542. currentModifiers = currentModifiers.withoutMouseButtons();
  230543. sendMouseEvent (ev);
  230544. }
  230545. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230546. {
  230547. updateModifiers (ev);
  230548. float x = 0, y = 0;
  230549. @try
  230550. {
  230551. x = [ev deviceDeltaX] * 0.5f;
  230552. y = [ev deviceDeltaY] * 0.5f;
  230553. }
  230554. @catch (...)
  230555. {
  230556. x = [ev deltaX] * 10.0f;
  230557. y = [ev deltaY] * 10.0f;
  230558. }
  230559. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  230560. }
  230561. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230562. {
  230563. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230564. if (mouse.getComponentUnderMouse() == 0
  230565. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230566. {
  230567. [[NSCursor arrowCursor] set];
  230568. }
  230569. }
  230570. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230571. {
  230572. NSString* bestType
  230573. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230574. if (bestType == nil)
  230575. return false;
  230576. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230577. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230578. StringArray files;
  230579. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230580. if (list == nil)
  230581. return false;
  230582. if ([list isKindOfClass: [NSArray class]])
  230583. {
  230584. NSArray* items = (NSArray*) list;
  230585. for (unsigned int i = 0; i < [items count]; ++i)
  230586. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230587. }
  230588. if (files.size() == 0)
  230589. return false;
  230590. if (type == 0)
  230591. handleFileDragMove (files, pos);
  230592. else if (type == 1)
  230593. handleFileDragExit (files);
  230594. else if (type == 2)
  230595. handleFileDragDrop (files, pos);
  230596. return true;
  230597. }
  230598. bool NSViewComponentPeer::isOpaque()
  230599. {
  230600. return component == 0 || component->isOpaque();
  230601. }
  230602. void NSViewComponentPeer::drawRect (NSRect r)
  230603. {
  230604. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230605. return;
  230606. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230607. if (! component->isOpaque())
  230608. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230609. #if USE_COREGRAPHICS_RENDERING
  230610. if (usingCoreGraphics)
  230611. {
  230612. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230613. insideDrawRect = true;
  230614. handlePaint (context);
  230615. insideDrawRect = false;
  230616. }
  230617. else
  230618. #endif
  230619. {
  230620. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230621. (int) (r.size.width + 0.5f),
  230622. (int) (r.size.height + 0.5f),
  230623. ! getComponent()->isOpaque());
  230624. const int xOffset = -roundToInt (r.origin.x);
  230625. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230626. const NSRect* rects = 0;
  230627. NSInteger numRects = 0;
  230628. [view getRectsBeingDrawn: &rects count: &numRects];
  230629. const Rectangle<int> clipBounds (temp.getBounds());
  230630. RectangleList clip;
  230631. for (int i = 0; i < numRects; ++i)
  230632. {
  230633. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230634. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230635. roundToInt (rects[i].size.width),
  230636. roundToInt (rects[i].size.height))));
  230637. }
  230638. if (! clip.isEmpty())
  230639. {
  230640. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230641. insideDrawRect = true;
  230642. handlePaint (context);
  230643. insideDrawRect = false;
  230644. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230645. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230646. CGColorSpaceRelease (colourSpace);
  230647. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230648. CGImageRelease (image);
  230649. }
  230650. }
  230651. }
  230652. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230653. {
  230654. StringArray s;
  230655. s.add ("Software Renderer");
  230656. #if USE_COREGRAPHICS_RENDERING
  230657. s.add ("CoreGraphics Renderer");
  230658. #endif
  230659. return s;
  230660. }
  230661. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230662. {
  230663. return usingCoreGraphics ? 1 : 0;
  230664. }
  230665. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230666. {
  230667. #if USE_COREGRAPHICS_RENDERING
  230668. if (usingCoreGraphics != (index > 0))
  230669. {
  230670. usingCoreGraphics = index > 0;
  230671. [view setNeedsDisplay: true];
  230672. }
  230673. #endif
  230674. }
  230675. bool NSViewComponentPeer::canBecomeKeyWindow()
  230676. {
  230677. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230678. }
  230679. bool NSViewComponentPeer::windowShouldClose()
  230680. {
  230681. if (! isValidPeer (this))
  230682. return YES;
  230683. handleUserClosingWindow();
  230684. return NO;
  230685. }
  230686. void NSViewComponentPeer::redirectMovedOrResized()
  230687. {
  230688. handleMovedOrResized();
  230689. }
  230690. void NSViewComponentPeer::viewMovedToWindow()
  230691. {
  230692. if (isSharedWindow)
  230693. window = [view window];
  230694. }
  230695. void Desktop::createMouseInputSources()
  230696. {
  230697. mouseSources.add (new MouseInputSource (0, true));
  230698. }
  230699. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230700. {
  230701. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230702. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230703. // is apparently still available in 64-bit apps..
  230704. if (enableOrDisable)
  230705. {
  230706. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230707. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230708. }
  230709. else
  230710. {
  230711. SetSystemUIMode (kUIModeNormal, 0);
  230712. }
  230713. }
  230714. class AsyncRepaintMessage : public CallbackMessage
  230715. {
  230716. public:
  230717. NSViewComponentPeer* const peer;
  230718. const Rectangle<int> rect;
  230719. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230720. : peer (peer_), rect (rect_)
  230721. {
  230722. }
  230723. void messageCallback()
  230724. {
  230725. if (ComponentPeer::isValidPeer (peer))
  230726. peer->repaint (rect);
  230727. }
  230728. };
  230729. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230730. {
  230731. if (insideDrawRect)
  230732. {
  230733. (new AsyncRepaintMessage (this, area))->post();
  230734. }
  230735. else
  230736. {
  230737. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230738. (float) area.getWidth(), (float) area.getHeight())];
  230739. }
  230740. }
  230741. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230742. {
  230743. [view displayIfNeeded];
  230744. }
  230745. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230746. {
  230747. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230748. }
  230749. const Image juce_createIconForFile (const File& file)
  230750. {
  230751. const ScopedAutoReleasePool pool;
  230752. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230753. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230754. [NSGraphicsContext saveGraphicsState];
  230755. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230756. [image drawAtPoint: NSMakePoint (0, 0)
  230757. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230758. operation: NSCompositeSourceOver fraction: 1.0f];
  230759. [[NSGraphicsContext currentContext] flushGraphics];
  230760. [NSGraphicsContext restoreGraphicsState];
  230761. return Image (result);
  230762. }
  230763. const int KeyPress::spaceKey = ' ';
  230764. const int KeyPress::returnKey = 0x0d;
  230765. const int KeyPress::escapeKey = 0x1b;
  230766. const int KeyPress::backspaceKey = 0x7f;
  230767. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230768. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230769. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230770. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230771. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230772. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230773. const int KeyPress::endKey = NSEndFunctionKey;
  230774. const int KeyPress::homeKey = NSHomeFunctionKey;
  230775. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230776. const int KeyPress::insertKey = -1;
  230777. const int KeyPress::tabKey = 9;
  230778. const int KeyPress::F1Key = NSF1FunctionKey;
  230779. const int KeyPress::F2Key = NSF2FunctionKey;
  230780. const int KeyPress::F3Key = NSF3FunctionKey;
  230781. const int KeyPress::F4Key = NSF4FunctionKey;
  230782. const int KeyPress::F5Key = NSF5FunctionKey;
  230783. const int KeyPress::F6Key = NSF6FunctionKey;
  230784. const int KeyPress::F7Key = NSF7FunctionKey;
  230785. const int KeyPress::F8Key = NSF8FunctionKey;
  230786. const int KeyPress::F9Key = NSF9FunctionKey;
  230787. const int KeyPress::F10Key = NSF10FunctionKey;
  230788. const int KeyPress::F11Key = NSF1FunctionKey;
  230789. const int KeyPress::F12Key = NSF12FunctionKey;
  230790. const int KeyPress::F13Key = NSF13FunctionKey;
  230791. const int KeyPress::F14Key = NSF14FunctionKey;
  230792. const int KeyPress::F15Key = NSF15FunctionKey;
  230793. const int KeyPress::F16Key = NSF16FunctionKey;
  230794. const int KeyPress::numberPad0 = 0x30020;
  230795. const int KeyPress::numberPad1 = 0x30021;
  230796. const int KeyPress::numberPad2 = 0x30022;
  230797. const int KeyPress::numberPad3 = 0x30023;
  230798. const int KeyPress::numberPad4 = 0x30024;
  230799. const int KeyPress::numberPad5 = 0x30025;
  230800. const int KeyPress::numberPad6 = 0x30026;
  230801. const int KeyPress::numberPad7 = 0x30027;
  230802. const int KeyPress::numberPad8 = 0x30028;
  230803. const int KeyPress::numberPad9 = 0x30029;
  230804. const int KeyPress::numberPadAdd = 0x3002a;
  230805. const int KeyPress::numberPadSubtract = 0x3002b;
  230806. const int KeyPress::numberPadMultiply = 0x3002c;
  230807. const int KeyPress::numberPadDivide = 0x3002d;
  230808. const int KeyPress::numberPadSeparator = 0x3002e;
  230809. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230810. const int KeyPress::numberPadEquals = 0x30030;
  230811. const int KeyPress::numberPadDelete = 0x30031;
  230812. const int KeyPress::playKey = 0x30000;
  230813. const int KeyPress::stopKey = 0x30001;
  230814. const int KeyPress::fastForwardKey = 0x30002;
  230815. const int KeyPress::rewindKey = 0x30003;
  230816. #endif
  230817. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230818. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230819. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230820. // compiled on its own).
  230821. #if JUCE_INCLUDED_FILE
  230822. #if JUCE_MAC
  230823. namespace MouseCursorHelpers
  230824. {
  230825. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  230826. {
  230827. NSImage* im = CoreGraphicsImage::createNSImage (image);
  230828. NSCursor* c = [[NSCursor alloc] initWithImage: im
  230829. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  230830. [im release];
  230831. return c;
  230832. }
  230833. static void* fromWebKitFile (const char* filename, float hx, float hy)
  230834. {
  230835. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  230836. BufferedInputStream buf (&fileStream, 4096, false);
  230837. PNGImageFormat pngFormat;
  230838. Image im (pngFormat.decodeImage (buf));
  230839. if (im.isValid())
  230840. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  230841. jassertfalse;
  230842. return 0;
  230843. }
  230844. }
  230845. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  230846. {
  230847. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  230848. }
  230849. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  230850. {
  230851. const ScopedAutoReleasePool pool;
  230852. NSCursor* c = 0;
  230853. switch (type)
  230854. {
  230855. case NormalCursor: c = [NSCursor arrowCursor]; break;
  230856. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  230857. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  230858. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  230859. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  230860. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  230861. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  230862. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  230863. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  230864. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  230865. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  230866. case UpDownResizeCursor:
  230867. case TopEdgeResizeCursor:
  230868. case BottomEdgeResizeCursor:
  230869. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  230870. case TopLeftCornerResizeCursor:
  230871. case BottomRightCornerResizeCursor:
  230872. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  230873. case TopRightCornerResizeCursor:
  230874. case BottomLeftCornerResizeCursor:
  230875. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  230876. case UpDownLeftRightResizeCursor:
  230877. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  230878. default:
  230879. jassertfalse;
  230880. break;
  230881. }
  230882. [c retain];
  230883. return c;
  230884. }
  230885. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  230886. {
  230887. [((NSCursor*) cursorHandle) release];
  230888. }
  230889. void MouseCursor::showInAllWindows() const
  230890. {
  230891. showInWindow (0);
  230892. }
  230893. void MouseCursor::showInWindow (ComponentPeer*) const
  230894. {
  230895. [((NSCursor*) getHandle()) set];
  230896. }
  230897. #else
  230898. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  230899. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  230900. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  230901. void MouseCursor::showInAllWindows() const {}
  230902. void MouseCursor::showInWindow (ComponentPeer*) const {}
  230903. #endif
  230904. #endif
  230905. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  230906. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  230907. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230908. // compiled on its own).
  230909. #if JUCE_INCLUDED_FILE
  230910. class NSViewComponentInternal : public ComponentMovementWatcher
  230911. {
  230912. Component* const owner;
  230913. NSViewComponentPeer* currentPeer;
  230914. bool wasShowing;
  230915. public:
  230916. NSView* const view;
  230917. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  230918. : ComponentMovementWatcher (owner_),
  230919. owner (owner_),
  230920. currentPeer (0),
  230921. wasShowing (false),
  230922. view (view_)
  230923. {
  230924. [view_ retain];
  230925. if (owner_->isShowing())
  230926. componentPeerChanged();
  230927. }
  230928. ~NSViewComponentInternal()
  230929. {
  230930. [view removeFromSuperview];
  230931. [view release];
  230932. }
  230933. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  230934. {
  230935. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  230936. // The ComponentMovementWatcher version of this method avoids calling
  230937. // us when the top-level comp is resized, but for an NSView we need to know this
  230938. // because with inverted co-ords, we need to update the position even if the
  230939. // top-left pos hasn't changed
  230940. if (comp.isOnDesktop() && wasResized)
  230941. componentMovedOrResized (wasMoved, wasResized);
  230942. }
  230943. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  230944. {
  230945. Component* const topComp = owner->getTopLevelComponent();
  230946. if (topComp->getPeer() != 0)
  230947. {
  230948. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  230949. NSRect r;
  230950. r.origin.x = (float) pos.getX();
  230951. r.origin.y = (float) pos.getY();
  230952. r.size.width = (float) owner->getWidth();
  230953. r.size.height = (float) owner->getHeight();
  230954. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230955. [view setFrame: r];
  230956. }
  230957. }
  230958. void componentPeerChanged()
  230959. {
  230960. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  230961. if (currentPeer != peer)
  230962. {
  230963. [view removeFromSuperview];
  230964. currentPeer = peer;
  230965. if (peer != 0)
  230966. {
  230967. [peer->view addSubview: view];
  230968. componentMovedOrResized (false, false);
  230969. }
  230970. }
  230971. [view setHidden: ! owner->isShowing()];
  230972. }
  230973. void componentVisibilityChanged (Component&)
  230974. {
  230975. componentPeerChanged();
  230976. }
  230977. juce_UseDebuggingNewOperator
  230978. private:
  230979. NSViewComponentInternal (const NSViewComponentInternal&);
  230980. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  230981. };
  230982. NSViewComponent::NSViewComponent()
  230983. {
  230984. }
  230985. NSViewComponent::~NSViewComponent()
  230986. {
  230987. }
  230988. void NSViewComponent::setView (void* view)
  230989. {
  230990. if (view != getView())
  230991. {
  230992. if (view != 0)
  230993. info = new NSViewComponentInternal ((NSView*) view, this);
  230994. else
  230995. info = 0;
  230996. }
  230997. }
  230998. void* NSViewComponent::getView() const
  230999. {
  231000. return info == 0 ? 0 : info->view;
  231001. }
  231002. void NSViewComponent::paint (Graphics&)
  231003. {
  231004. }
  231005. #endif
  231006. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231007. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231008. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231009. // compiled on its own).
  231010. #if JUCE_INCLUDED_FILE
  231011. AppleRemoteDevice::AppleRemoteDevice()
  231012. : device (0),
  231013. queue (0),
  231014. remoteId (0)
  231015. {
  231016. }
  231017. AppleRemoteDevice::~AppleRemoteDevice()
  231018. {
  231019. stop();
  231020. }
  231021. static io_object_t getAppleRemoteDevice()
  231022. {
  231023. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231024. io_iterator_t iter = 0;
  231025. io_object_t iod = 0;
  231026. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231027. && iter != 0)
  231028. {
  231029. iod = IOIteratorNext (iter);
  231030. }
  231031. IOObjectRelease (iter);
  231032. return iod;
  231033. }
  231034. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  231035. {
  231036. jassert (*device == 0);
  231037. io_name_t classname;
  231038. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231039. {
  231040. IOCFPlugInInterface** cfPlugInInterface = 0;
  231041. SInt32 score = 0;
  231042. if (IOCreatePlugInInterfaceForService (iod,
  231043. kIOHIDDeviceUserClientTypeID,
  231044. kIOCFPlugInInterfaceID,
  231045. &cfPlugInInterface,
  231046. &score) == kIOReturnSuccess)
  231047. {
  231048. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231049. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231050. device);
  231051. (void) hr;
  231052. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231053. }
  231054. }
  231055. return *device != 0;
  231056. }
  231057. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231058. {
  231059. if (queue != 0)
  231060. return true;
  231061. stop();
  231062. bool result = false;
  231063. io_object_t iod = getAppleRemoteDevice();
  231064. if (iod != 0)
  231065. {
  231066. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231067. result = true;
  231068. else
  231069. stop();
  231070. IOObjectRelease (iod);
  231071. }
  231072. return result;
  231073. }
  231074. void AppleRemoteDevice::stop()
  231075. {
  231076. if (queue != 0)
  231077. {
  231078. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231079. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231080. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231081. queue = 0;
  231082. }
  231083. if (device != 0)
  231084. {
  231085. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231086. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231087. device = 0;
  231088. }
  231089. }
  231090. bool AppleRemoteDevice::isActive() const
  231091. {
  231092. return queue != 0;
  231093. }
  231094. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231095. {
  231096. if (result == kIOReturnSuccess)
  231097. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231098. }
  231099. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231100. {
  231101. Array <int> cookies;
  231102. CFArrayRef elements;
  231103. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231104. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231105. return false;
  231106. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231107. {
  231108. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231109. // get the cookie
  231110. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231111. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231112. continue;
  231113. long number;
  231114. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231115. continue;
  231116. cookies.add ((int) number);
  231117. }
  231118. CFRelease (elements);
  231119. if ((*(IOHIDDeviceInterface**) device)
  231120. ->open ((IOHIDDeviceInterface**) device,
  231121. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  231122. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  231123. {
  231124. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231125. if (queue != 0)
  231126. {
  231127. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231128. for (int i = 0; i < cookies.size(); ++i)
  231129. {
  231130. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231131. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231132. }
  231133. CFRunLoopSourceRef eventSource;
  231134. if ((*(IOHIDQueueInterface**) queue)
  231135. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231136. {
  231137. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231138. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231139. {
  231140. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231141. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231142. return true;
  231143. }
  231144. }
  231145. }
  231146. }
  231147. return false;
  231148. }
  231149. void AppleRemoteDevice::handleCallbackInternal()
  231150. {
  231151. int totalValues = 0;
  231152. AbsoluteTime nullTime = { 0, 0 };
  231153. char cookies [12];
  231154. int numCookies = 0;
  231155. while (numCookies < numElementsInArray (cookies))
  231156. {
  231157. IOHIDEventStruct e;
  231158. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231159. break;
  231160. if ((int) e.elementCookie == 19)
  231161. {
  231162. remoteId = e.value;
  231163. buttonPressed (switched, false);
  231164. }
  231165. else
  231166. {
  231167. totalValues += e.value;
  231168. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231169. }
  231170. }
  231171. cookies [numCookies++] = 0;
  231172. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231173. static const char buttonPatterns[] =
  231174. {
  231175. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231176. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231177. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231178. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231179. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231180. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231181. 0x1f, 0x12, 0x04, 0x02, 0,
  231182. 0x1f, 0x12, 0x03, 0x02, 0,
  231183. 0x1f, 0x12, 0x1f, 0x12, 0,
  231184. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  231185. 19, 0
  231186. };
  231187. int buttonNum = (int) menuButton;
  231188. int i = 0;
  231189. while (i < numElementsInArray (buttonPatterns))
  231190. {
  231191. if (strcmp (cookies, buttonPatterns + i) == 0)
  231192. {
  231193. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  231194. break;
  231195. }
  231196. i += (int) strlen (buttonPatterns + i) + 1;
  231197. ++buttonNum;
  231198. }
  231199. }
  231200. #endif
  231201. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231202. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231203. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231204. // compiled on its own).
  231205. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231206. #if JUCE_MAC
  231207. END_JUCE_NAMESPACE
  231208. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231209. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231210. {
  231211. CriticalSection* contextLock;
  231212. bool needsUpdate;
  231213. }
  231214. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231215. - (bool) makeActive;
  231216. - (void) makeInactive;
  231217. - (void) reshape;
  231218. @end
  231219. @implementation ThreadSafeNSOpenGLView
  231220. - (id) initWithFrame: (NSRect) frameRect
  231221. pixelFormat: (NSOpenGLPixelFormat*) format
  231222. {
  231223. contextLock = new CriticalSection();
  231224. self = [super initWithFrame: frameRect pixelFormat: format];
  231225. if (self != nil)
  231226. [[NSNotificationCenter defaultCenter] addObserver: self
  231227. selector: @selector (_surfaceNeedsUpdate:)
  231228. name: NSViewGlobalFrameDidChangeNotification
  231229. object: self];
  231230. return self;
  231231. }
  231232. - (void) dealloc
  231233. {
  231234. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231235. delete contextLock;
  231236. [super dealloc];
  231237. }
  231238. - (bool) makeActive
  231239. {
  231240. const ScopedLock sl (*contextLock);
  231241. if ([self openGLContext] == 0)
  231242. return false;
  231243. [[self openGLContext] makeCurrentContext];
  231244. if (needsUpdate)
  231245. {
  231246. [super update];
  231247. needsUpdate = false;
  231248. }
  231249. return true;
  231250. }
  231251. - (void) makeInactive
  231252. {
  231253. const ScopedLock sl (*contextLock);
  231254. [NSOpenGLContext clearCurrentContext];
  231255. }
  231256. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231257. {
  231258. const ScopedLock sl (*contextLock);
  231259. needsUpdate = true;
  231260. }
  231261. - (void) update
  231262. {
  231263. const ScopedLock sl (*contextLock);
  231264. needsUpdate = true;
  231265. }
  231266. - (void) reshape
  231267. {
  231268. const ScopedLock sl (*contextLock);
  231269. needsUpdate = true;
  231270. }
  231271. @end
  231272. BEGIN_JUCE_NAMESPACE
  231273. class WindowedGLContext : public OpenGLContext
  231274. {
  231275. public:
  231276. WindowedGLContext (Component* const component,
  231277. const OpenGLPixelFormat& pixelFormat_,
  231278. NSOpenGLContext* sharedContext)
  231279. : renderContext (0),
  231280. pixelFormat (pixelFormat_)
  231281. {
  231282. jassert (component != 0);
  231283. NSOpenGLPixelFormatAttribute attribs [64];
  231284. int n = 0;
  231285. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231286. attribs[n++] = NSOpenGLPFAAccelerated;
  231287. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231288. attribs[n++] = NSOpenGLPFAColorSize;
  231289. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231290. pixelFormat.greenBits,
  231291. pixelFormat.blueBits);
  231292. attribs[n++] = NSOpenGLPFAAlphaSize;
  231293. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231294. attribs[n++] = NSOpenGLPFADepthSize;
  231295. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231296. attribs[n++] = NSOpenGLPFAStencilSize;
  231297. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231298. attribs[n++] = NSOpenGLPFAAccumSize;
  231299. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231300. pixelFormat.accumulationBufferGreenBits,
  231301. pixelFormat.accumulationBufferBlueBits,
  231302. pixelFormat.accumulationBufferAlphaBits);
  231303. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231304. attribs[n++] = NSOpenGLPFASampleBuffers;
  231305. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231306. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231307. attribs[n++] = NSOpenGLPFANoRecovery;
  231308. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231309. NSOpenGLPixelFormat* format
  231310. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231311. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231312. pixelFormat: format];
  231313. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231314. shareContext: sharedContext] autorelease];
  231315. const GLint swapInterval = 1;
  231316. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231317. [view setOpenGLContext: renderContext];
  231318. [renderContext setView: view];
  231319. [format release];
  231320. viewHolder = new NSViewComponentInternal (view, component);
  231321. }
  231322. ~WindowedGLContext()
  231323. {
  231324. makeInactive();
  231325. [renderContext clearDrawable];
  231326. viewHolder = 0;
  231327. }
  231328. bool makeActive() const throw()
  231329. {
  231330. jassert (renderContext != 0);
  231331. [view makeActive];
  231332. return isActive();
  231333. }
  231334. bool makeInactive() const throw()
  231335. {
  231336. [view makeInactive];
  231337. return true;
  231338. }
  231339. bool isActive() const throw()
  231340. {
  231341. return [NSOpenGLContext currentContext] == renderContext;
  231342. }
  231343. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231344. void* getRawContext() const throw() { return renderContext; }
  231345. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231346. {
  231347. }
  231348. void swapBuffers()
  231349. {
  231350. [renderContext flushBuffer];
  231351. }
  231352. bool setSwapInterval (const int numFramesPerSwap)
  231353. {
  231354. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231355. forParameter: NSOpenGLCPSwapInterval];
  231356. return true;
  231357. }
  231358. int getSwapInterval() const
  231359. {
  231360. GLint numFrames = 0;
  231361. [renderContext getValues: &numFrames
  231362. forParameter: NSOpenGLCPSwapInterval];
  231363. return numFrames;
  231364. }
  231365. void repaint()
  231366. {
  231367. // we need to invalidate the juce view that holds this gl view, to make it
  231368. // cause a repaint callback
  231369. NSView* v = (NSView*) viewHolder->view;
  231370. NSRect r = [v frame];
  231371. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231372. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231373. // repaint message, thus never causing our paint() callback, and never repainting
  231374. // the comp. So invalidating just a little bit around the edge helps..
  231375. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231376. }
  231377. void* getNativeWindowHandle() const { return viewHolder->view; }
  231378. juce_UseDebuggingNewOperator
  231379. NSOpenGLContext* renderContext;
  231380. ThreadSafeNSOpenGLView* view;
  231381. private:
  231382. OpenGLPixelFormat pixelFormat;
  231383. ScopedPointer <NSViewComponentInternal> viewHolder;
  231384. WindowedGLContext (const WindowedGLContext&);
  231385. WindowedGLContext& operator= (const WindowedGLContext&);
  231386. };
  231387. OpenGLContext* OpenGLComponent::createContext()
  231388. {
  231389. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231390. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231391. return (c->renderContext != 0) ? c.release() : 0;
  231392. }
  231393. void* OpenGLComponent::getNativeWindowHandle() const
  231394. {
  231395. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231396. : 0;
  231397. }
  231398. void juce_glViewport (const int w, const int h)
  231399. {
  231400. glViewport (0, 0, w, h);
  231401. }
  231402. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231403. OwnedArray <OpenGLPixelFormat>& results)
  231404. {
  231405. /* GLint attribs [64];
  231406. int n = 0;
  231407. attribs[n++] = AGL_RGBA;
  231408. attribs[n++] = AGL_DOUBLEBUFFER;
  231409. attribs[n++] = AGL_ACCELERATED;
  231410. attribs[n++] = AGL_NO_RECOVERY;
  231411. attribs[n++] = AGL_NONE;
  231412. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231413. while (p != 0)
  231414. {
  231415. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231416. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231417. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231418. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231419. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231420. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231421. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231422. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231423. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231424. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231425. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231426. results.add (pf);
  231427. p = aglNextPixelFormat (p);
  231428. }*/
  231429. //jassertfalse //xxx can't see how you do this in cocoa!
  231430. }
  231431. #else
  231432. END_JUCE_NAMESPACE
  231433. @interface JuceGLView : UIView
  231434. {
  231435. }
  231436. + (Class) layerClass;
  231437. @end
  231438. @implementation JuceGLView
  231439. + (Class) layerClass
  231440. {
  231441. return [CAEAGLLayer class];
  231442. }
  231443. @end
  231444. BEGIN_JUCE_NAMESPACE
  231445. class GLESContext : public OpenGLContext
  231446. {
  231447. public:
  231448. GLESContext (UIViewComponentPeer* peer,
  231449. Component* const component_,
  231450. const OpenGLPixelFormat& pixelFormat_,
  231451. const GLESContext* const sharedContext,
  231452. NSUInteger apiType)
  231453. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231454. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231455. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231456. {
  231457. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231458. view.opaque = YES;
  231459. view.hidden = NO;
  231460. view.backgroundColor = [UIColor blackColor];
  231461. view.userInteractionEnabled = NO;
  231462. glLayer = (CAEAGLLayer*) [view layer];
  231463. [peer->view addSubview: view];
  231464. if (sharedContext != 0)
  231465. context = [[EAGLContext alloc] initWithAPI: apiType
  231466. sharegroup: [sharedContext->context sharegroup]];
  231467. else
  231468. context = [[EAGLContext alloc] initWithAPI: apiType];
  231469. createGLBuffers();
  231470. }
  231471. ~GLESContext()
  231472. {
  231473. makeInactive();
  231474. [context release];
  231475. [view removeFromSuperview];
  231476. [view release];
  231477. freeGLBuffers();
  231478. }
  231479. bool makeActive() const throw()
  231480. {
  231481. jassert (context != 0);
  231482. [EAGLContext setCurrentContext: context];
  231483. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231484. return true;
  231485. }
  231486. void swapBuffers()
  231487. {
  231488. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231489. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231490. }
  231491. bool makeInactive() const throw()
  231492. {
  231493. return [EAGLContext setCurrentContext: nil];
  231494. }
  231495. bool isActive() const throw()
  231496. {
  231497. return [EAGLContext currentContext] == context;
  231498. }
  231499. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231500. void* getRawContext() const throw() { return glLayer; }
  231501. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231502. {
  231503. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231504. if (lastWidth != w || lastHeight != h)
  231505. {
  231506. lastWidth = w;
  231507. lastHeight = h;
  231508. freeGLBuffers();
  231509. createGLBuffers();
  231510. }
  231511. }
  231512. bool setSwapInterval (const int numFramesPerSwap)
  231513. {
  231514. numFrames = numFramesPerSwap;
  231515. return true;
  231516. }
  231517. int getSwapInterval() const
  231518. {
  231519. return numFrames;
  231520. }
  231521. void repaint()
  231522. {
  231523. }
  231524. void createGLBuffers()
  231525. {
  231526. makeActive();
  231527. glGenFramebuffersOES (1, &frameBufferHandle);
  231528. glGenRenderbuffersOES (1, &colorBufferHandle);
  231529. glGenRenderbuffersOES (1, &depthBufferHandle);
  231530. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231531. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231532. GLint width, height;
  231533. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231534. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231535. if (useDepthBuffer)
  231536. {
  231537. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231538. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231539. }
  231540. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231541. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231542. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231543. if (useDepthBuffer)
  231544. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231545. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231546. }
  231547. void freeGLBuffers()
  231548. {
  231549. if (frameBufferHandle != 0)
  231550. {
  231551. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231552. frameBufferHandle = 0;
  231553. }
  231554. if (colorBufferHandle != 0)
  231555. {
  231556. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231557. colorBufferHandle = 0;
  231558. }
  231559. if (depthBufferHandle != 0)
  231560. {
  231561. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231562. depthBufferHandle = 0;
  231563. }
  231564. }
  231565. juce_UseDebuggingNewOperator
  231566. private:
  231567. Component::SafePointer<Component> component;
  231568. OpenGLPixelFormat pixelFormat;
  231569. JuceGLView* view;
  231570. CAEAGLLayer* glLayer;
  231571. EAGLContext* context;
  231572. bool useDepthBuffer;
  231573. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231574. int numFrames;
  231575. int lastWidth, lastHeight;
  231576. GLESContext (const GLESContext&);
  231577. GLESContext& operator= (const GLESContext&);
  231578. };
  231579. OpenGLContext* OpenGLComponent::createContext()
  231580. {
  231581. ScopedAutoReleasePool pool;
  231582. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231583. if (peer != 0)
  231584. return new GLESContext (peer, this, preferredPixelFormat,
  231585. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231586. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231587. return 0;
  231588. }
  231589. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231590. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231591. {
  231592. }
  231593. void juce_glViewport (const int w, const int h)
  231594. {
  231595. glViewport (0, 0, w, h);
  231596. }
  231597. #endif
  231598. #endif
  231599. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231600. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231601. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231602. // compiled on its own).
  231603. #if JUCE_INCLUDED_FILE
  231604. class JuceMainMenuHandler;
  231605. END_JUCE_NAMESPACE
  231606. using namespace JUCE_NAMESPACE;
  231607. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231608. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231609. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231610. #else
  231611. @interface JuceMenuCallback : NSObject
  231612. #endif
  231613. {
  231614. JuceMainMenuHandler* owner;
  231615. }
  231616. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231617. - (void) dealloc;
  231618. - (void) menuItemInvoked: (id) menu;
  231619. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231620. @end
  231621. BEGIN_JUCE_NAMESPACE
  231622. class JuceMainMenuHandler : private MenuBarModelListener,
  231623. private DeletedAtShutdown
  231624. {
  231625. public:
  231626. static JuceMainMenuHandler* instance;
  231627. JuceMainMenuHandler()
  231628. : currentModel (0),
  231629. lastUpdateTime (0)
  231630. {
  231631. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231632. }
  231633. ~JuceMainMenuHandler()
  231634. {
  231635. setMenu (0);
  231636. jassert (instance == this);
  231637. instance = 0;
  231638. [callback release];
  231639. }
  231640. void setMenu (MenuBarModel* const newMenuBarModel)
  231641. {
  231642. if (currentModel != newMenuBarModel)
  231643. {
  231644. if (currentModel != 0)
  231645. currentModel->removeListener (this);
  231646. currentModel = newMenuBarModel;
  231647. if (currentModel != 0)
  231648. currentModel->addListener (this);
  231649. menuBarItemsChanged (0);
  231650. }
  231651. }
  231652. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231653. const String& name, const int menuId, const int tag)
  231654. {
  231655. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231656. action: nil
  231657. keyEquivalent: @""];
  231658. [item setTag: tag];
  231659. NSMenu* sub = createMenu (child, name, menuId, tag);
  231660. [parent setSubmenu: sub forItem: item];
  231661. [sub setAutoenablesItems: false];
  231662. [sub release];
  231663. }
  231664. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231665. const String& name, const int menuId, const int tag)
  231666. {
  231667. [parentItem setTag: tag];
  231668. NSMenu* menu = [parentItem submenu];
  231669. [menu setTitle: juceStringToNS (name)];
  231670. while ([menu numberOfItems] > 0)
  231671. [menu removeItemAtIndex: 0];
  231672. PopupMenu::MenuItemIterator iter (menuToCopy);
  231673. while (iter.next())
  231674. addMenuItem (iter, menu, menuId, tag);
  231675. [menu setAutoenablesItems: false];
  231676. [menu update];
  231677. }
  231678. void menuBarItemsChanged (MenuBarModel*)
  231679. {
  231680. lastUpdateTime = Time::getMillisecondCounter();
  231681. StringArray menuNames;
  231682. if (currentModel != 0)
  231683. menuNames = currentModel->getMenuBarNames();
  231684. NSMenu* menuBar = [NSApp mainMenu];
  231685. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231686. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231687. int menuId = 1;
  231688. for (int i = 0; i < menuNames.size(); ++i)
  231689. {
  231690. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231691. if (i >= [menuBar numberOfItems] - 1)
  231692. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231693. else
  231694. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231695. }
  231696. }
  231697. static void flashMenuBar (NSMenu* menu)
  231698. {
  231699. if ([[menu title] isEqualToString: @"Apple"])
  231700. return;
  231701. [menu retain];
  231702. const unichar f35Key = NSF35FunctionKey;
  231703. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231704. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231705. action: nil
  231706. keyEquivalent: f35String];
  231707. [item setTarget: nil];
  231708. [menu insertItem: item atIndex: [menu numberOfItems]];
  231709. [item release];
  231710. if ([menu indexOfItem: item] >= 0)
  231711. {
  231712. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231713. location: NSZeroPoint
  231714. modifierFlags: NSCommandKeyMask
  231715. timestamp: 0
  231716. windowNumber: 0
  231717. context: [NSGraphicsContext currentContext]
  231718. characters: f35String
  231719. charactersIgnoringModifiers: f35String
  231720. isARepeat: NO
  231721. keyCode: 0];
  231722. [menu performKeyEquivalent: f35Event];
  231723. if ([menu indexOfItem: item] >= 0)
  231724. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231725. }
  231726. [menu release];
  231727. }
  231728. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231729. {
  231730. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231731. {
  231732. NSMenuItem* m = [menu itemAtIndex: i];
  231733. if ([m tag] == info.commandID)
  231734. return m;
  231735. if ([m submenu] != 0)
  231736. {
  231737. NSMenuItem* found = findMenuItem ([m submenu], info);
  231738. if (found != 0)
  231739. return found;
  231740. }
  231741. }
  231742. return 0;
  231743. }
  231744. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231745. {
  231746. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231747. if (item != 0)
  231748. flashMenuBar ([item menu]);
  231749. }
  231750. void updateMenus()
  231751. {
  231752. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231753. menuBarItemsChanged (0);
  231754. }
  231755. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231756. {
  231757. if (currentModel != 0)
  231758. {
  231759. if (commandManager != 0)
  231760. {
  231761. ApplicationCommandTarget::InvocationInfo info (commandId);
  231762. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231763. commandManager->invoke (info, true);
  231764. }
  231765. currentModel->menuItemSelected (commandId, topLevelIndex);
  231766. }
  231767. }
  231768. MenuBarModel* currentModel;
  231769. uint32 lastUpdateTime;
  231770. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231771. const int topLevelMenuId, const int topLevelIndex)
  231772. {
  231773. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231774. if (text == 0)
  231775. text = @"";
  231776. if (iter.isSeparator)
  231777. {
  231778. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231779. }
  231780. else if (iter.isSectionHeader)
  231781. {
  231782. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231783. action: nil
  231784. keyEquivalent: @""];
  231785. [item setEnabled: false];
  231786. }
  231787. else if (iter.subMenu != 0)
  231788. {
  231789. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231790. action: nil
  231791. keyEquivalent: @""];
  231792. [item setTag: iter.itemId];
  231793. [item setEnabled: iter.isEnabled];
  231794. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231795. [sub setDelegate: nil];
  231796. [menuToAddTo setSubmenu: sub forItem: item];
  231797. [sub release];
  231798. }
  231799. else
  231800. {
  231801. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231802. action: @selector (menuItemInvoked:)
  231803. keyEquivalent: @""];
  231804. [item setTag: iter.itemId];
  231805. [item setEnabled: iter.isEnabled];
  231806. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231807. [item setTarget: (id) callback];
  231808. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231809. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231810. [item setRepresentedObject: info];
  231811. if (iter.commandManager != 0)
  231812. {
  231813. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  231814. ->getKeyPressesAssignedToCommand (iter.itemId));
  231815. if (keyPresses.size() > 0)
  231816. {
  231817. const KeyPress& kp = keyPresses.getReference(0);
  231818. if (kp.getKeyCode() != KeyPress::backspaceKey
  231819. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  231820. // every time you press the key while editing text)
  231821. {
  231822. juce_wchar key = kp.getTextCharacter();
  231823. if (kp.getKeyCode() == KeyPress::backspaceKey)
  231824. key = NSBackspaceCharacter;
  231825. else if (kp.getKeyCode() == KeyPress::deleteKey)
  231826. key = NSDeleteCharacter;
  231827. else if (key == 0)
  231828. key = (juce_wchar) kp.getKeyCode();
  231829. unsigned int mods = 0;
  231830. if (kp.getModifiers().isShiftDown())
  231831. mods |= NSShiftKeyMask;
  231832. if (kp.getModifiers().isCtrlDown())
  231833. mods |= NSControlKeyMask;
  231834. if (kp.getModifiers().isAltDown())
  231835. mods |= NSAlternateKeyMask;
  231836. if (kp.getModifiers().isCommandDown())
  231837. mods |= NSCommandKeyMask;
  231838. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  231839. [item setKeyEquivalentModifierMask: mods];
  231840. }
  231841. }
  231842. }
  231843. }
  231844. }
  231845. JuceMenuCallback* callback;
  231846. private:
  231847. NSMenu* createMenu (const PopupMenu menu,
  231848. const String& menuName,
  231849. const int topLevelMenuId,
  231850. const int topLevelIndex)
  231851. {
  231852. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  231853. [m setAutoenablesItems: false];
  231854. [m setDelegate: callback];
  231855. PopupMenu::MenuItemIterator iter (menu);
  231856. while (iter.next())
  231857. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  231858. [m update];
  231859. return m;
  231860. }
  231861. };
  231862. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  231863. END_JUCE_NAMESPACE
  231864. @implementation JuceMenuCallback
  231865. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  231866. {
  231867. [super init];
  231868. owner = owner_;
  231869. return self;
  231870. }
  231871. - (void) dealloc
  231872. {
  231873. [super dealloc];
  231874. }
  231875. - (void) menuItemInvoked: (id) menu
  231876. {
  231877. NSMenuItem* item = (NSMenuItem*) menu;
  231878. if ([[item representedObject] isKindOfClass: [NSArray class]])
  231879. {
  231880. // 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
  231881. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  231882. // into the focused component and let it trigger the menu item indirectly.
  231883. NSEvent* e = [NSApp currentEvent];
  231884. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  231885. {
  231886. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  231887. {
  231888. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  231889. if (peer != 0)
  231890. {
  231891. if ([e type] == NSKeyDown)
  231892. peer->redirectKeyDown (e);
  231893. else
  231894. peer->redirectKeyUp (e);
  231895. return;
  231896. }
  231897. }
  231898. }
  231899. NSArray* info = (NSArray*) [item representedObject];
  231900. owner->invoke ((int) [item tag],
  231901. (ApplicationCommandManager*) (pointer_sized_int)
  231902. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  231903. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  231904. }
  231905. }
  231906. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231907. {
  231908. (void) menu;
  231909. if (JuceMainMenuHandler::instance != 0)
  231910. JuceMainMenuHandler::instance->updateMenus();
  231911. }
  231912. @end
  231913. BEGIN_JUCE_NAMESPACE
  231914. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  231915. const PopupMenu* extraItems)
  231916. {
  231917. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  231918. {
  231919. PopupMenu::MenuItemIterator iter (*extraItems);
  231920. while (iter.next())
  231921. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  231922. [menu addItem: [NSMenuItem separatorItem]];
  231923. }
  231924. NSMenuItem* item;
  231925. // Services...
  231926. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  231927. action: nil keyEquivalent: @""];
  231928. [menu addItem: item];
  231929. [item release];
  231930. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  231931. [menu setSubmenu: servicesMenu forItem: item];
  231932. [NSApp setServicesMenu: servicesMenu];
  231933. [servicesMenu release];
  231934. [menu addItem: [NSMenuItem separatorItem]];
  231935. // Hide + Show stuff...
  231936. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  231937. action: @selector (hide:) keyEquivalent: @"h"];
  231938. [item setTarget: NSApp];
  231939. [menu addItem: item];
  231940. [item release];
  231941. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  231942. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  231943. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  231944. [item setTarget: NSApp];
  231945. [menu addItem: item];
  231946. [item release];
  231947. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  231948. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  231949. [item setTarget: NSApp];
  231950. [menu addItem: item];
  231951. [item release];
  231952. [menu addItem: [NSMenuItem separatorItem]];
  231953. // Quit item....
  231954. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  231955. action: @selector (terminate:) keyEquivalent: @"q"];
  231956. [item setTarget: NSApp];
  231957. [menu addItem: item];
  231958. [item release];
  231959. return menu;
  231960. }
  231961. // Since our app has no NIB, this initialises a standard app menu...
  231962. static void rebuildMainMenu (const PopupMenu* extraItems)
  231963. {
  231964. // this can't be used in a plugin!
  231965. jassert (JUCEApplication::getInstance() != 0);
  231966. if (JUCEApplication::getInstance() != 0)
  231967. {
  231968. const ScopedAutoReleasePool pool;
  231969. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  231970. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  231971. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  231972. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  231973. [mainMenu setSubmenu: appMenu forItem: item];
  231974. [NSApp setMainMenu: mainMenu];
  231975. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  231976. [appMenu release];
  231977. [mainMenu release];
  231978. }
  231979. }
  231980. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  231981. const PopupMenu* extraAppleMenuItems)
  231982. {
  231983. if (getMacMainMenu() != newMenuBarModel)
  231984. {
  231985. const ScopedAutoReleasePool pool;
  231986. if (newMenuBarModel == 0)
  231987. {
  231988. delete JuceMainMenuHandler::instance;
  231989. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  231990. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  231991. extraAppleMenuItems = 0;
  231992. }
  231993. else
  231994. {
  231995. if (JuceMainMenuHandler::instance == 0)
  231996. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  231997. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  231998. }
  231999. }
  232000. rebuildMainMenu (extraAppleMenuItems);
  232001. if (newMenuBarModel != 0)
  232002. newMenuBarModel->menuItemsChanged();
  232003. }
  232004. MenuBarModel* MenuBarModel::getMacMainMenu()
  232005. {
  232006. return JuceMainMenuHandler::instance != 0
  232007. ? JuceMainMenuHandler::instance->currentModel : 0;
  232008. }
  232009. void initialiseMainMenu()
  232010. {
  232011. if (JUCEApplication::getInstance() != 0) // only needed in an app
  232012. rebuildMainMenu (0);
  232013. }
  232014. #endif
  232015. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232016. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232017. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232018. // compiled on its own).
  232019. #if JUCE_INCLUDED_FILE
  232020. #if JUCE_MAC
  232021. END_JUCE_NAMESPACE
  232022. using namespace JUCE_NAMESPACE;
  232023. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232024. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232025. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232026. #else
  232027. @interface JuceFileChooserDelegate : NSObject
  232028. #endif
  232029. {
  232030. StringArray* filters;
  232031. }
  232032. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232033. - (void) dealloc;
  232034. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232035. @end
  232036. @implementation JuceFileChooserDelegate
  232037. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232038. {
  232039. [super init];
  232040. filters = filters_;
  232041. return self;
  232042. }
  232043. - (void) dealloc
  232044. {
  232045. delete filters;
  232046. [super dealloc];
  232047. }
  232048. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232049. {
  232050. (void) sender;
  232051. const File f (nsStringToJuce (filename));
  232052. for (int i = filters->size(); --i >= 0;)
  232053. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232054. return true;
  232055. return f.isDirectory();
  232056. }
  232057. @end
  232058. BEGIN_JUCE_NAMESPACE
  232059. void FileChooser::showPlatformDialog (Array<File>& results,
  232060. const String& title,
  232061. const File& currentFileOrDirectory,
  232062. const String& filter,
  232063. bool selectsDirectory,
  232064. bool selectsFiles,
  232065. bool isSaveDialogue,
  232066. bool warnAboutOverwritingExistingFiles,
  232067. bool selectMultipleFiles,
  232068. FilePreviewComponent* extraInfoComponent)
  232069. {
  232070. const ScopedAutoReleasePool pool;
  232071. StringArray* filters = new StringArray();
  232072. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232073. filters->trim();
  232074. filters->removeEmptyStrings();
  232075. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232076. [delegate autorelease];
  232077. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232078. : [NSOpenPanel openPanel];
  232079. [panel setTitle: juceStringToNS (title)];
  232080. if (! isSaveDialogue)
  232081. {
  232082. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232083. [openPanel setCanChooseDirectories: selectsDirectory];
  232084. [openPanel setCanChooseFiles: selectsFiles];
  232085. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232086. }
  232087. [panel setDelegate: delegate];
  232088. if (isSaveDialogue || selectsDirectory)
  232089. [panel setCanCreateDirectories: YES];
  232090. String directory, filename;
  232091. if (currentFileOrDirectory.isDirectory())
  232092. {
  232093. directory = currentFileOrDirectory.getFullPathName();
  232094. }
  232095. else
  232096. {
  232097. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232098. filename = currentFileOrDirectory.getFileName();
  232099. }
  232100. if ([panel runModalForDirectory: juceStringToNS (directory)
  232101. file: juceStringToNS (filename)]
  232102. == NSOKButton)
  232103. {
  232104. if (isSaveDialogue)
  232105. {
  232106. results.add (File (nsStringToJuce ([panel filename])));
  232107. }
  232108. else
  232109. {
  232110. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232111. NSArray* urls = [openPanel filenames];
  232112. for (unsigned int i = 0; i < [urls count]; ++i)
  232113. {
  232114. NSString* f = [urls objectAtIndex: i];
  232115. results.add (File (nsStringToJuce (f)));
  232116. }
  232117. }
  232118. }
  232119. [panel setDelegate: nil];
  232120. }
  232121. #else
  232122. void FileChooser::showPlatformDialog (Array<File>& results,
  232123. const String& title,
  232124. const File& currentFileOrDirectory,
  232125. const String& filter,
  232126. bool selectsDirectory,
  232127. bool selectsFiles,
  232128. bool isSaveDialogue,
  232129. bool warnAboutOverwritingExistingFiles,
  232130. bool selectMultipleFiles,
  232131. FilePreviewComponent* extraInfoComponent)
  232132. {
  232133. const ScopedAutoReleasePool pool;
  232134. jassertfalse; //xxx to do
  232135. }
  232136. #endif
  232137. #endif
  232138. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232139. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232140. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232141. // compiled on its own).
  232142. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232143. END_JUCE_NAMESPACE
  232144. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232145. @interface NonInterceptingQTMovieView : QTMovieView
  232146. {
  232147. }
  232148. - (id) initWithFrame: (NSRect) frame;
  232149. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232150. - (NSView*) hitTest: (NSPoint) p;
  232151. @end
  232152. @implementation NonInterceptingQTMovieView
  232153. - (id) initWithFrame: (NSRect) frame
  232154. {
  232155. self = [super initWithFrame: frame];
  232156. [self setNextResponder: [self superview]];
  232157. return self;
  232158. }
  232159. - (void) dealloc
  232160. {
  232161. [super dealloc];
  232162. }
  232163. - (NSView*) hitTest: (NSPoint) point
  232164. {
  232165. return [self isControllerVisible] ? [super hitTest: point] : nil;
  232166. }
  232167. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  232168. {
  232169. return YES;
  232170. }
  232171. @end
  232172. BEGIN_JUCE_NAMESPACE
  232173. #define theMovie (static_cast <QTMovie*> (movie))
  232174. QuickTimeMovieComponent::QuickTimeMovieComponent()
  232175. : movie (0)
  232176. {
  232177. setOpaque (true);
  232178. setVisible (true);
  232179. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  232180. setView (view);
  232181. [view release];
  232182. }
  232183. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  232184. {
  232185. closeMovie();
  232186. setView (0);
  232187. }
  232188. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  232189. {
  232190. return true;
  232191. }
  232192. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  232193. {
  232194. // unfortunately, QTMovie objects can only be created on the main thread..
  232195. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232196. QTMovie* movie = 0;
  232197. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232198. if (fin != 0)
  232199. {
  232200. movieFile = fin->getFile();
  232201. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232202. error: nil];
  232203. }
  232204. else
  232205. {
  232206. MemoryBlock temp;
  232207. movieStream->readIntoMemoryBlock (temp);
  232208. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232209. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232210. {
  232211. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232212. length: temp.getSize()]
  232213. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232214. MIMEType: @""]
  232215. error: nil];
  232216. if (movie != 0)
  232217. break;
  232218. }
  232219. }
  232220. return movie;
  232221. }
  232222. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232223. const bool isControllerVisible_)
  232224. {
  232225. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232226. }
  232227. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232228. const bool controllerVisible_)
  232229. {
  232230. closeMovie();
  232231. if (getPeer() == 0)
  232232. {
  232233. // To open a movie, this component must be visible inside a functioning window, so that
  232234. // the QT control can be assigned to the window.
  232235. jassertfalse;
  232236. return false;
  232237. }
  232238. movie = openMovieFromStream (movieStream, movieFile);
  232239. [theMovie retain];
  232240. QTMovieView* view = (QTMovieView*) getView();
  232241. [view setMovie: theMovie];
  232242. [view setControllerVisible: controllerVisible_];
  232243. setLooping (looping);
  232244. return movie != nil;
  232245. }
  232246. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232247. const bool isControllerVisible_)
  232248. {
  232249. // unfortunately, QTMovie objects can only be created on the main thread..
  232250. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232251. closeMovie();
  232252. if (getPeer() == 0)
  232253. {
  232254. // To open a movie, this component must be visible inside a functioning window, so that
  232255. // the QT control can be assigned to the window.
  232256. jassertfalse;
  232257. return false;
  232258. }
  232259. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232260. NSError* err;
  232261. if ([QTMovie canInitWithURL: url])
  232262. movie = [QTMovie movieWithURL: url error: &err];
  232263. [theMovie retain];
  232264. QTMovieView* view = (QTMovieView*) getView();
  232265. [view setMovie: theMovie];
  232266. [view setControllerVisible: controllerVisible];
  232267. setLooping (looping);
  232268. return movie != nil;
  232269. }
  232270. void QuickTimeMovieComponent::closeMovie()
  232271. {
  232272. stop();
  232273. QTMovieView* view = (QTMovieView*) getView();
  232274. [view setMovie: nil];
  232275. [theMovie release];
  232276. movie = 0;
  232277. movieFile = File::nonexistent;
  232278. }
  232279. bool QuickTimeMovieComponent::isMovieOpen() const
  232280. {
  232281. return movie != nil;
  232282. }
  232283. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232284. {
  232285. return movieFile;
  232286. }
  232287. void QuickTimeMovieComponent::play()
  232288. {
  232289. [theMovie play];
  232290. }
  232291. void QuickTimeMovieComponent::stop()
  232292. {
  232293. [theMovie stop];
  232294. }
  232295. bool QuickTimeMovieComponent::isPlaying() const
  232296. {
  232297. return movie != 0 && [theMovie rate] != 0;
  232298. }
  232299. void QuickTimeMovieComponent::setPosition (const double seconds)
  232300. {
  232301. if (movie != 0)
  232302. {
  232303. QTTime t;
  232304. t.timeValue = (uint64) (100000.0 * seconds);
  232305. t.timeScale = 100000;
  232306. t.flags = 0;
  232307. [theMovie setCurrentTime: t];
  232308. }
  232309. }
  232310. double QuickTimeMovieComponent::getPosition() const
  232311. {
  232312. if (movie == 0)
  232313. return 0.0;
  232314. QTTime t = [theMovie currentTime];
  232315. return t.timeValue / (double) t.timeScale;
  232316. }
  232317. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232318. {
  232319. [theMovie setRate: newSpeed];
  232320. }
  232321. double QuickTimeMovieComponent::getMovieDuration() const
  232322. {
  232323. if (movie == 0)
  232324. return 0.0;
  232325. QTTime t = [theMovie duration];
  232326. return t.timeValue / (double) t.timeScale;
  232327. }
  232328. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232329. {
  232330. looping = shouldLoop;
  232331. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232332. forKey: QTMovieLoopsAttribute];
  232333. }
  232334. bool QuickTimeMovieComponent::isLooping() const
  232335. {
  232336. return looping;
  232337. }
  232338. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232339. {
  232340. [theMovie setVolume: newVolume];
  232341. }
  232342. float QuickTimeMovieComponent::getMovieVolume() const
  232343. {
  232344. return movie != 0 ? [theMovie volume] : 0.0f;
  232345. }
  232346. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232347. {
  232348. width = 0;
  232349. height = 0;
  232350. if (movie != 0)
  232351. {
  232352. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232353. width = (int) s.width;
  232354. height = (int) s.height;
  232355. }
  232356. }
  232357. void QuickTimeMovieComponent::paint (Graphics& g)
  232358. {
  232359. if (movie == 0)
  232360. g.fillAll (Colours::black);
  232361. }
  232362. bool QuickTimeMovieComponent::isControllerVisible() const
  232363. {
  232364. return controllerVisible;
  232365. }
  232366. void QuickTimeMovieComponent::goToStart()
  232367. {
  232368. setPosition (0.0);
  232369. }
  232370. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232371. const RectanglePlacement& placement)
  232372. {
  232373. int normalWidth, normalHeight;
  232374. getMovieNormalSize (normalWidth, normalHeight);
  232375. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232376. {
  232377. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232378. placement.applyTo (x, y, w, h,
  232379. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232380. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232381. if (w > 0 && h > 0)
  232382. {
  232383. setBounds (roundToInt (x), roundToInt (y),
  232384. roundToInt (w), roundToInt (h));
  232385. }
  232386. }
  232387. else
  232388. {
  232389. setBounds (spaceToFitWithin);
  232390. }
  232391. }
  232392. #if ! (JUCE_MAC && JUCE_64BIT)
  232393. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232394. {
  232395. if (movieStream == 0)
  232396. return false;
  232397. File file;
  232398. QTMovie* movie = openMovieFromStream (movieStream, file);
  232399. if (movie != nil)
  232400. result = [movie quickTimeMovie];
  232401. return movie != nil;
  232402. }
  232403. #endif
  232404. #endif
  232405. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232406. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232407. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232408. // compiled on its own).
  232409. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232410. const int kilobytesPerSecond1x = 176;
  232411. END_JUCE_NAMESPACE
  232412. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232413. @interface OpenDiskDevice : NSObject
  232414. {
  232415. @public
  232416. DRDevice* device;
  232417. NSMutableArray* tracks;
  232418. bool underrunProtection;
  232419. }
  232420. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232421. - (void) dealloc;
  232422. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232423. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232424. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232425. @end
  232426. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232427. @interface AudioTrackProducer : NSObject
  232428. {
  232429. JUCE_NAMESPACE::AudioSource* source;
  232430. int readPosition, lengthInFrames;
  232431. }
  232432. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232433. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232434. - (void) dealloc;
  232435. - (void) setupTrackProperties: (DRTrack*) track;
  232436. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232437. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232438. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232439. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232440. toMedia:(NSDictionary*)mediaInfo;
  232441. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232442. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232443. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232444. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232445. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232446. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232447. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232448. ioFlags:(uint32_t*)flags;
  232449. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232450. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232451. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232452. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232453. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232454. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232455. ioFlags:(uint32_t*)flags;
  232456. @end
  232457. @implementation OpenDiskDevice
  232458. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232459. {
  232460. [super init];
  232461. device = device_;
  232462. tracks = [[NSMutableArray alloc] init];
  232463. underrunProtection = true;
  232464. return self;
  232465. }
  232466. - (void) dealloc
  232467. {
  232468. [tracks release];
  232469. [super dealloc];
  232470. }
  232471. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232472. {
  232473. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232474. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232475. [p setupTrackProperties: t];
  232476. [tracks addObject: t];
  232477. [t release];
  232478. [p release];
  232479. }
  232480. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232481. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232482. {
  232483. DRBurn* burn = [DRBurn burnForDevice: device];
  232484. if (! [device acquireExclusiveAccess])
  232485. {
  232486. *error = "Couldn't open or write to the CD device";
  232487. return;
  232488. }
  232489. [device acquireMediaReservation];
  232490. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232491. [d autorelease];
  232492. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232493. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232494. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232495. if (burnSpeed > 0)
  232496. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232497. if (! underrunProtection)
  232498. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232499. [burn setProperties: d];
  232500. [burn writeLayout: tracks];
  232501. for (;;)
  232502. {
  232503. JUCE_NAMESPACE::Thread::sleep (300);
  232504. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232505. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232506. {
  232507. [burn abort];
  232508. *error = "User cancelled the write operation";
  232509. break;
  232510. }
  232511. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232512. {
  232513. *error = "Write operation failed";
  232514. break;
  232515. }
  232516. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232517. {
  232518. break;
  232519. }
  232520. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232521. objectForKey: DRErrorStatusErrorStringKey];
  232522. if ([err length] > 0)
  232523. {
  232524. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232525. break;
  232526. }
  232527. }
  232528. [device releaseMediaReservation];
  232529. [device releaseExclusiveAccess];
  232530. }
  232531. @end
  232532. @implementation AudioTrackProducer
  232533. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232534. {
  232535. lengthInFrames = lengthInFrames_;
  232536. readPosition = 0;
  232537. return self;
  232538. }
  232539. - (void) setupTrackProperties: (DRTrack*) track
  232540. {
  232541. NSMutableDictionary* p = [[track properties] mutableCopy];
  232542. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232543. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232544. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232545. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232546. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232547. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232548. [track setProperties: p];
  232549. [p release];
  232550. }
  232551. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232552. {
  232553. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232554. if (s != nil)
  232555. s->source = source_;
  232556. return s;
  232557. }
  232558. - (void) dealloc
  232559. {
  232560. if (source != 0)
  232561. {
  232562. source->releaseResources();
  232563. delete source;
  232564. }
  232565. [super dealloc];
  232566. }
  232567. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232568. {
  232569. }
  232570. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232571. {
  232572. return true;
  232573. }
  232574. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232575. {
  232576. return lengthInFrames;
  232577. }
  232578. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232579. toMedia: (NSDictionary*) mediaInfo
  232580. {
  232581. if (source != 0)
  232582. source->prepareToPlay (44100 / 75, 44100);
  232583. readPosition = 0;
  232584. return true;
  232585. }
  232586. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232587. {
  232588. if (source != 0)
  232589. source->prepareToPlay (44100 / 75, 44100);
  232590. return true;
  232591. }
  232592. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232593. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232594. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232595. {
  232596. if (source != 0)
  232597. {
  232598. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232599. if (numSamples > 0)
  232600. {
  232601. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232602. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232603. info.buffer = &tempBuffer;
  232604. info.startSample = 0;
  232605. info.numSamples = numSamples;
  232606. source->getNextAudioBlock (info);
  232607. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232608. buffer, numSamples, 4);
  232609. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232610. buffer + 2, numSamples, 4);
  232611. readPosition += numSamples;
  232612. }
  232613. return numSamples * 4;
  232614. }
  232615. return 0;
  232616. }
  232617. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232618. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232619. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232620. ioFlags: (uint32_t*) flags
  232621. {
  232622. zeromem (buffer, bufferLength);
  232623. return bufferLength;
  232624. }
  232625. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232626. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232627. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232628. {
  232629. return true;
  232630. }
  232631. @end
  232632. BEGIN_JUCE_NAMESPACE
  232633. class AudioCDBurner::Pimpl : public Timer
  232634. {
  232635. public:
  232636. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232637. : device (0), owner (owner_)
  232638. {
  232639. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232640. if (dev != 0)
  232641. {
  232642. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232643. lastState = getDiskState();
  232644. startTimer (1000);
  232645. }
  232646. }
  232647. ~Pimpl()
  232648. {
  232649. stopTimer();
  232650. [device release];
  232651. }
  232652. void timerCallback()
  232653. {
  232654. const DiskState state = getDiskState();
  232655. if (state != lastState)
  232656. {
  232657. lastState = state;
  232658. owner.sendChangeMessage (&owner);
  232659. }
  232660. }
  232661. DiskState getDiskState() const
  232662. {
  232663. if ([device->device isValid])
  232664. {
  232665. NSDictionary* status = [device->device status];
  232666. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232667. if ([state isEqualTo: DRDeviceMediaStateNone])
  232668. {
  232669. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232670. return trayOpen;
  232671. return noDisc;
  232672. }
  232673. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232674. {
  232675. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232676. return writableDiskPresent;
  232677. else
  232678. return readOnlyDiskPresent;
  232679. }
  232680. }
  232681. return unknown;
  232682. }
  232683. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232684. const Array<int> getAvailableWriteSpeeds() const
  232685. {
  232686. Array<int> results;
  232687. if ([device->device isValid])
  232688. {
  232689. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232690. for (unsigned int i = 0; i < [speeds count]; ++i)
  232691. {
  232692. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232693. results.add (kbPerSec / kilobytesPerSecond1x);
  232694. }
  232695. }
  232696. return results;
  232697. }
  232698. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232699. {
  232700. if ([device->device isValid])
  232701. {
  232702. device->underrunProtection = shouldBeEnabled;
  232703. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232704. }
  232705. return false;
  232706. }
  232707. int getNumAvailableAudioBlocks() const
  232708. {
  232709. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232710. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232711. }
  232712. OpenDiskDevice* device;
  232713. private:
  232714. DiskState lastState;
  232715. AudioCDBurner& owner;
  232716. };
  232717. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232718. {
  232719. pimpl = new Pimpl (*this, deviceIndex);
  232720. }
  232721. AudioCDBurner::~AudioCDBurner()
  232722. {
  232723. }
  232724. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232725. {
  232726. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232727. if (b->pimpl->device == 0)
  232728. b = 0;
  232729. return b.release();
  232730. }
  232731. static NSArray* findDiskBurnerDevices()
  232732. {
  232733. NSMutableArray* results = [NSMutableArray array];
  232734. NSArray* devs = [DRDevice devices];
  232735. if (devs != 0)
  232736. {
  232737. int num = [devs count];
  232738. int i;
  232739. for (i = 0; i < num; ++i)
  232740. {
  232741. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232742. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232743. if (name != nil)
  232744. [results addObject: name];
  232745. }
  232746. }
  232747. return results;
  232748. }
  232749. const StringArray AudioCDBurner::findAvailableDevices()
  232750. {
  232751. NSArray* names = findDiskBurnerDevices();
  232752. StringArray s;
  232753. for (unsigned int i = 0; i < [names count]; ++i)
  232754. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232755. return s;
  232756. }
  232757. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232758. {
  232759. return pimpl->getDiskState();
  232760. }
  232761. bool AudioCDBurner::isDiskPresent() const
  232762. {
  232763. return getDiskState() == writableDiskPresent;
  232764. }
  232765. bool AudioCDBurner::openTray()
  232766. {
  232767. return pimpl->openTray();
  232768. }
  232769. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232770. {
  232771. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232772. DiskState oldState = getDiskState();
  232773. DiskState newState = oldState;
  232774. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232775. {
  232776. newState = getDiskState();
  232777. Thread::sleep (100);
  232778. }
  232779. return newState;
  232780. }
  232781. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232782. {
  232783. return pimpl->getAvailableWriteSpeeds();
  232784. }
  232785. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232786. {
  232787. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232788. }
  232789. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232790. {
  232791. return pimpl->getNumAvailableAudioBlocks();
  232792. }
  232793. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232794. {
  232795. if ([pimpl->device->device isValid])
  232796. {
  232797. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232798. return true;
  232799. }
  232800. return false;
  232801. }
  232802. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232803. bool ejectDiscAfterwards,
  232804. bool performFakeBurnForTesting,
  232805. int writeSpeed)
  232806. {
  232807. String error ("Couldn't open or write to the CD device");
  232808. if ([pimpl->device->device isValid])
  232809. {
  232810. error = String::empty;
  232811. [pimpl->device burn: listener
  232812. errorString: &error
  232813. ejectAfterwards: ejectDiscAfterwards
  232814. isFake: performFakeBurnForTesting
  232815. speed: writeSpeed];
  232816. }
  232817. return error;
  232818. }
  232819. #endif
  232820. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232821. void AudioCDReader::ejectDisk()
  232822. {
  232823. const ScopedAutoReleasePool p;
  232824. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  232825. }
  232826. #endif
  232827. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  232828. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  232829. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232830. // compiled on its own).
  232831. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232832. static void juce_findCDs (Array<File>& cds)
  232833. {
  232834. File volumes ("/Volumes");
  232835. volumes.findChildFiles (cds, File::findDirectories, false);
  232836. for (int i = cds.size(); --i >= 0;)
  232837. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  232838. cds.remove (i);
  232839. }
  232840. const StringArray AudioCDReader::getAvailableCDNames()
  232841. {
  232842. Array<File> cds;
  232843. juce_findCDs (cds);
  232844. StringArray names;
  232845. for (int i = 0; i < cds.size(); ++i)
  232846. names.add (cds.getReference(i).getFileName());
  232847. return names;
  232848. }
  232849. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  232850. {
  232851. Array<File> cds;
  232852. juce_findCDs (cds);
  232853. if (cds[index].exists())
  232854. return new AudioCDReader (cds[index]);
  232855. return 0;
  232856. }
  232857. AudioCDReader::AudioCDReader (const File& volume)
  232858. : AudioFormatReader (0, "CD Audio"),
  232859. volumeDir (volume),
  232860. currentReaderTrack (-1),
  232861. reader (0)
  232862. {
  232863. sampleRate = 44100.0;
  232864. bitsPerSample = 16;
  232865. numChannels = 2;
  232866. usesFloatingPointData = false;
  232867. refreshTrackLengths();
  232868. }
  232869. AudioCDReader::~AudioCDReader()
  232870. {
  232871. }
  232872. static int juce_getCDTrackNumber (const File& file)
  232873. {
  232874. return file.getFileName()
  232875. .initialSectionContainingOnly ("0123456789")
  232876. .getIntValue();
  232877. }
  232878. int AudioCDReader::compareElements (const File& first, const File& second)
  232879. {
  232880. const int firstTrack = juce_getCDTrackNumber (first);
  232881. const int secondTrack = juce_getCDTrackNumber (second);
  232882. jassert (firstTrack > 0 && secondTrack > 0);
  232883. return firstTrack - secondTrack;
  232884. }
  232885. void AudioCDReader::refreshTrackLengths()
  232886. {
  232887. tracks.clear();
  232888. trackStartSamples.clear();
  232889. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  232890. tracks.sort (*this);
  232891. AiffAudioFormat format;
  232892. int sample = 0;
  232893. for (int i = 0; i < tracks.size(); ++i)
  232894. {
  232895. trackStartSamples.add (sample);
  232896. FileInputStream* const in = tracks.getReference(i).createInputStream();
  232897. if (in != 0)
  232898. {
  232899. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  232900. if (r != 0)
  232901. sample += (int) r->lengthInSamples;
  232902. }
  232903. }
  232904. trackStartSamples.add (sample);
  232905. lengthInSamples = sample;
  232906. }
  232907. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  232908. int64 startSampleInFile, int numSamples)
  232909. {
  232910. while (numSamples > 0)
  232911. {
  232912. int track = -1;
  232913. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  232914. {
  232915. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  232916. {
  232917. track = i;
  232918. break;
  232919. }
  232920. }
  232921. if (track < 0)
  232922. return false;
  232923. if (track != currentReaderTrack)
  232924. {
  232925. reader = 0;
  232926. FileInputStream* const in = tracks [track].createInputStream();
  232927. if (in != 0)
  232928. {
  232929. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  232930. AiffAudioFormat format;
  232931. reader = format.createReaderFor (bin, true);
  232932. if (reader == 0)
  232933. currentReaderTrack = -1;
  232934. else
  232935. currentReaderTrack = track;
  232936. }
  232937. }
  232938. if (reader == 0)
  232939. return false;
  232940. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  232941. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  232942. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  232943. numSamples -= numAvailable;
  232944. startSampleInFile += numAvailable;
  232945. }
  232946. return true;
  232947. }
  232948. bool AudioCDReader::isCDStillPresent() const
  232949. {
  232950. return volumeDir.exists();
  232951. }
  232952. int AudioCDReader::getNumTracks() const
  232953. {
  232954. return tracks.size();
  232955. }
  232956. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  232957. {
  232958. return trackStartSamples [trackNum];
  232959. }
  232960. bool AudioCDReader::isTrackAudio (int trackNum) const
  232961. {
  232962. return tracks [trackNum] != File::nonexistent;
  232963. }
  232964. void AudioCDReader::enableIndexScanning (bool b)
  232965. {
  232966. // any way to do this on a Mac??
  232967. }
  232968. int AudioCDReader::getLastIndex() const
  232969. {
  232970. return 0;
  232971. }
  232972. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  232973. {
  232974. return Array <int>();
  232975. }
  232976. int AudioCDReader::getCDDBId()
  232977. {
  232978. return 0; //xxx
  232979. }
  232980. #endif
  232981. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  232982. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  232983. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232984. // compiled on its own).
  232985. #if JUCE_INCLUDED_FILE
  232986. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  232987. for example having more than one juce plugin loaded into a host, then when a
  232988. method is called, the actual code that runs might actually be in a different module
  232989. than the one you expect... So any calls to library functions or statics that are
  232990. made inside obj-c methods will probably end up getting executed in a different DLL's
  232991. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  232992. To work around this insanity, I'm only allowing obj-c methods to make calls to
  232993. virtual methods of an object that's known to live inside the right module's space.
  232994. */
  232995. class AppDelegateRedirector
  232996. {
  232997. public:
  232998. AppDelegateRedirector()
  232999. {
  233000. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  233001. runLoop = CFRunLoopGetMain();
  233002. #else
  233003. runLoop = CFRunLoopGetCurrent();
  233004. #endif
  233005. CFRunLoopSourceContext sourceContext;
  233006. zerostruct (sourceContext);
  233007. sourceContext.info = this;
  233008. sourceContext.perform = runLoopSourceCallback;
  233009. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  233010. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233011. }
  233012. virtual ~AppDelegateRedirector()
  233013. {
  233014. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233015. CFRunLoopSourceInvalidate (runLoopSource);
  233016. CFRelease (runLoopSource);
  233017. }
  233018. virtual NSApplicationTerminateReply shouldTerminate()
  233019. {
  233020. if (JUCEApplication::getInstance() != 0)
  233021. {
  233022. JUCEApplication::getInstance()->systemRequestedQuit();
  233023. return NSTerminateCancel;
  233024. }
  233025. return NSTerminateNow;
  233026. }
  233027. virtual BOOL openFile (const NSString* filename)
  233028. {
  233029. if (JUCEApplication::getInstance() != 0)
  233030. {
  233031. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  233032. return YES;
  233033. }
  233034. return NO;
  233035. }
  233036. virtual void openFiles (NSArray* filenames)
  233037. {
  233038. StringArray files;
  233039. for (unsigned int i = 0; i < [filenames count]; ++i)
  233040. {
  233041. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  233042. if (filename.containsChar (' '))
  233043. filename = filename.quoted('"');
  233044. files.add (filename);
  233045. }
  233046. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233047. {
  233048. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233049. }
  233050. }
  233051. virtual void focusChanged()
  233052. {
  233053. juce_HandleProcessFocusChange();
  233054. }
  233055. struct CallbackMessagePayload
  233056. {
  233057. MessageCallbackFunction* function;
  233058. void* parameter;
  233059. void* volatile result;
  233060. bool volatile hasBeenExecuted;
  233061. };
  233062. virtual void performCallback (CallbackMessagePayload* pl)
  233063. {
  233064. pl->result = (*pl->function) (pl->parameter);
  233065. pl->hasBeenExecuted = true;
  233066. }
  233067. virtual void deleteSelf()
  233068. {
  233069. delete this;
  233070. }
  233071. void postMessage (Message* const m)
  233072. {
  233073. messages.add (m);
  233074. CFRunLoopSourceSignal (runLoopSource);
  233075. CFRunLoopWakeUp (runLoop);
  233076. }
  233077. private:
  233078. CFRunLoopRef runLoop;
  233079. CFRunLoopSourceRef runLoopSource;
  233080. OwnedArray <Message, CriticalSection> messages;
  233081. void runLoopCallback()
  233082. {
  233083. int numDispatched = 0;
  233084. do
  233085. {
  233086. Message* const nextMessage = messages.removeAndReturn (0);
  233087. if (nextMessage == 0)
  233088. return;
  233089. const ScopedAutoReleasePool pool;
  233090. MessageManager::getInstance()->deliverMessage (nextMessage);
  233091. } while (++numDispatched <= 4);
  233092. CFRunLoopSourceSignal (runLoopSource);
  233093. CFRunLoopWakeUp (runLoop);
  233094. }
  233095. static void runLoopSourceCallback (void* info)
  233096. {
  233097. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  233098. }
  233099. };
  233100. END_JUCE_NAMESPACE
  233101. using namespace JUCE_NAMESPACE;
  233102. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  233103. @interface JuceAppDelegate : NSObject
  233104. {
  233105. @private
  233106. id oldDelegate;
  233107. @public
  233108. AppDelegateRedirector* redirector;
  233109. }
  233110. - (JuceAppDelegate*) init;
  233111. - (void) dealloc;
  233112. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  233113. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  233114. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  233115. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  233116. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  233117. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  233118. - (void) performCallback: (id) info;
  233119. - (void) dummyMethod;
  233120. @end
  233121. @implementation JuceAppDelegate
  233122. - (JuceAppDelegate*) init
  233123. {
  233124. [super init];
  233125. redirector = new AppDelegateRedirector();
  233126. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  233127. if (JUCEApplication::getInstance() != 0)
  233128. {
  233129. oldDelegate = [NSApp delegate];
  233130. [NSApp setDelegate: self];
  233131. }
  233132. else
  233133. {
  233134. oldDelegate = 0;
  233135. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233136. name: NSApplicationDidResignActiveNotification object: NSApp];
  233137. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233138. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233139. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233140. name: NSApplicationWillUnhideNotification object: NSApp];
  233141. }
  233142. return self;
  233143. }
  233144. - (void) dealloc
  233145. {
  233146. if (oldDelegate != 0)
  233147. [NSApp setDelegate: oldDelegate];
  233148. redirector->deleteSelf();
  233149. [super dealloc];
  233150. }
  233151. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233152. {
  233153. (void) app;
  233154. return redirector->shouldTerminate();
  233155. }
  233156. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  233157. {
  233158. (void) app;
  233159. return redirector->openFile (filename);
  233160. }
  233161. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  233162. {
  233163. (void) sender;
  233164. return redirector->openFiles (filenames);
  233165. }
  233166. - (void) applicationDidBecomeActive: (NSNotification*) notification
  233167. {
  233168. (void) notification;
  233169. redirector->focusChanged();
  233170. }
  233171. - (void) applicationDidResignActive: (NSNotification*) notification
  233172. {
  233173. (void) notification;
  233174. redirector->focusChanged();
  233175. }
  233176. - (void) applicationWillUnhide: (NSNotification*) notification
  233177. {
  233178. (void) notification;
  233179. redirector->focusChanged();
  233180. }
  233181. - (void) performCallback: (id) info
  233182. {
  233183. if ([info isKindOfClass: [NSData class]])
  233184. {
  233185. AppDelegateRedirector::CallbackMessagePayload* pl
  233186. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  233187. if (pl != 0)
  233188. redirector->performCallback (pl);
  233189. }
  233190. else
  233191. {
  233192. jassertfalse; // should never get here!
  233193. }
  233194. }
  233195. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233196. @end
  233197. BEGIN_JUCE_NAMESPACE
  233198. static JuceAppDelegate* juceAppDelegate = 0;
  233199. void MessageManager::runDispatchLoop()
  233200. {
  233201. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233202. {
  233203. const ScopedAutoReleasePool pool;
  233204. // must only be called by the message thread!
  233205. jassert (isThisTheMessageThread());
  233206. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233207. @try
  233208. {
  233209. [NSApp run];
  233210. }
  233211. @catch (NSException* e)
  233212. {
  233213. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233214. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233215. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233216. }
  233217. @finally
  233218. {
  233219. }
  233220. #else
  233221. [NSApp run];
  233222. #endif
  233223. }
  233224. }
  233225. void MessageManager::stopDispatchLoop()
  233226. {
  233227. quitMessagePosted = true;
  233228. [NSApp stop: nil];
  233229. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233230. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233231. }
  233232. static bool isEventBlockedByModalComps (NSEvent* e)
  233233. {
  233234. if (Component::getNumCurrentlyModalComponents() == 0)
  233235. return false;
  233236. NSWindow* const w = [e window];
  233237. if (w == 0 || [w worksWhenModal])
  233238. return false;
  233239. bool isKey = false, isInputAttempt = false;
  233240. switch ([e type])
  233241. {
  233242. case NSKeyDown:
  233243. case NSKeyUp:
  233244. isKey = isInputAttempt = true;
  233245. break;
  233246. case NSLeftMouseDown:
  233247. case NSRightMouseDown:
  233248. case NSOtherMouseDown:
  233249. isInputAttempt = true;
  233250. break;
  233251. case NSLeftMouseDragged:
  233252. case NSRightMouseDragged:
  233253. case NSLeftMouseUp:
  233254. case NSRightMouseUp:
  233255. case NSOtherMouseUp:
  233256. case NSOtherMouseDragged:
  233257. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233258. return false;
  233259. break;
  233260. case NSMouseMoved:
  233261. case NSMouseEntered:
  233262. case NSMouseExited:
  233263. case NSCursorUpdate:
  233264. case NSScrollWheel:
  233265. case NSTabletPoint:
  233266. case NSTabletProximity:
  233267. break;
  233268. default:
  233269. return false;
  233270. }
  233271. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233272. {
  233273. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233274. NSView* const compView = (NSView*) peer->getNativeHandle();
  233275. if ([compView window] == w)
  233276. {
  233277. if (isKey)
  233278. {
  233279. if (compView == [w firstResponder])
  233280. return false;
  233281. }
  233282. else
  233283. {
  233284. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233285. [compView bounds]))
  233286. return false;
  233287. }
  233288. }
  233289. }
  233290. if (isInputAttempt)
  233291. {
  233292. if (! [NSApp isActive])
  233293. [NSApp activateIgnoringOtherApps: YES];
  233294. Component* const modal = Component::getCurrentlyModalComponent (0);
  233295. if (modal != 0)
  233296. modal->inputAttemptWhenModal();
  233297. }
  233298. return true;
  233299. }
  233300. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233301. {
  233302. const ScopedAutoReleasePool pool;
  233303. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233304. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233305. while (! quitMessagePosted)
  233306. {
  233307. const ScopedAutoReleasePool pool2;
  233308. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233309. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233310. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233311. inMode: NSDefaultRunLoopMode
  233312. dequeue: YES];
  233313. if (e != 0 && ! isEventBlockedByModalComps (e))
  233314. [NSApp sendEvent: e];
  233315. if (Time::getMillisecondCounter() >= endTime)
  233316. break;
  233317. }
  233318. return ! quitMessagePosted;
  233319. }
  233320. void MessageManager::doPlatformSpecificInitialisation()
  233321. {
  233322. if (juceAppDelegate == 0)
  233323. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233324. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233325. // correctly (needed prior to 10.5)
  233326. if (! [NSThread isMultiThreaded])
  233327. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233328. toTarget: juceAppDelegate
  233329. withObject: nil];
  233330. initialiseMainMenu();
  233331. }
  233332. void MessageManager::doPlatformSpecificShutdown()
  233333. {
  233334. if (juceAppDelegate != 0)
  233335. {
  233336. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233337. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233338. [juceAppDelegate release];
  233339. juceAppDelegate = 0;
  233340. }
  233341. }
  233342. bool juce_postMessageToSystemQueue (Message* message)
  233343. {
  233344. juceAppDelegate->redirector->postMessage (message);
  233345. return true;
  233346. }
  233347. void MessageManager::broadcastMessage (const String& value) throw()
  233348. {
  233349. }
  233350. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  233351. void* data)
  233352. {
  233353. if (isThisTheMessageThread())
  233354. {
  233355. return (*callback) (data);
  233356. }
  233357. else
  233358. {
  233359. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233360. // deadlock because the message manager is blocked from running, so can never
  233361. // call your function..
  233362. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233363. const ScopedAutoReleasePool pool;
  233364. AppDelegateRedirector::CallbackMessagePayload cmp;
  233365. cmp.function = callback;
  233366. cmp.parameter = data;
  233367. cmp.result = 0;
  233368. cmp.hasBeenExecuted = false;
  233369. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233370. withObject: [NSData dataWithBytesNoCopy: &cmp
  233371. length: sizeof (cmp)
  233372. freeWhenDone: NO]
  233373. waitUntilDone: YES];
  233374. return cmp.result;
  233375. }
  233376. }
  233377. #endif
  233378. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233379. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233380. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233381. // compiled on its own).
  233382. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233383. #if JUCE_MAC
  233384. END_JUCE_NAMESPACE
  233385. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233386. @interface DownloadClickDetector : NSObject
  233387. {
  233388. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233389. }
  233390. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233391. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233392. request: (NSURLRequest*) request
  233393. frame: (WebFrame*) frame
  233394. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233395. @end
  233396. @implementation DownloadClickDetector
  233397. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233398. {
  233399. [super init];
  233400. ownerComponent = ownerComponent_;
  233401. return self;
  233402. }
  233403. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233404. request: (NSURLRequest*) request
  233405. frame: (WebFrame*) frame
  233406. decisionListener: (id <WebPolicyDecisionListener>) listener
  233407. {
  233408. (void) sender;
  233409. (void) request;
  233410. (void) frame;
  233411. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233412. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233413. [listener use];
  233414. else
  233415. [listener ignore];
  233416. }
  233417. @end
  233418. BEGIN_JUCE_NAMESPACE
  233419. class WebBrowserComponentInternal : public NSViewComponent
  233420. {
  233421. public:
  233422. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233423. {
  233424. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233425. frameName: @""
  233426. groupName: @""];
  233427. setView (webView);
  233428. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233429. [webView setPolicyDelegate: clickListener];
  233430. }
  233431. ~WebBrowserComponentInternal()
  233432. {
  233433. [webView setPolicyDelegate: nil];
  233434. [clickListener release];
  233435. setView (0);
  233436. }
  233437. void goToURL (const String& url,
  233438. const StringArray* headers,
  233439. const MemoryBlock* postData)
  233440. {
  233441. NSMutableURLRequest* r
  233442. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233443. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233444. timeoutInterval: 30.0];
  233445. if (postData != 0 && postData->getSize() > 0)
  233446. {
  233447. [r setHTTPMethod: @"POST"];
  233448. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233449. length: postData->getSize()]];
  233450. }
  233451. if (headers != 0)
  233452. {
  233453. for (int i = 0; i < headers->size(); ++i)
  233454. {
  233455. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233456. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233457. [r setValue: juceStringToNS (headerValue)
  233458. forHTTPHeaderField: juceStringToNS (headerName)];
  233459. }
  233460. }
  233461. stop();
  233462. [[webView mainFrame] loadRequest: r];
  233463. }
  233464. void goBack()
  233465. {
  233466. [webView goBack];
  233467. }
  233468. void goForward()
  233469. {
  233470. [webView goForward];
  233471. }
  233472. void stop()
  233473. {
  233474. [webView stopLoading: nil];
  233475. }
  233476. void refresh()
  233477. {
  233478. [webView reload: nil];
  233479. }
  233480. private:
  233481. WebView* webView;
  233482. DownloadClickDetector* clickListener;
  233483. };
  233484. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233485. : browser (0),
  233486. blankPageShown (false),
  233487. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233488. {
  233489. setOpaque (true);
  233490. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233491. }
  233492. WebBrowserComponent::~WebBrowserComponent()
  233493. {
  233494. deleteAndZero (browser);
  233495. }
  233496. void WebBrowserComponent::goToURL (const String& url,
  233497. const StringArray* headers,
  233498. const MemoryBlock* postData)
  233499. {
  233500. lastURL = url;
  233501. lastHeaders.clear();
  233502. if (headers != 0)
  233503. lastHeaders = *headers;
  233504. lastPostData.setSize (0);
  233505. if (postData != 0)
  233506. lastPostData = *postData;
  233507. blankPageShown = false;
  233508. browser->goToURL (url, headers, postData);
  233509. }
  233510. void WebBrowserComponent::stop()
  233511. {
  233512. browser->stop();
  233513. }
  233514. void WebBrowserComponent::goBack()
  233515. {
  233516. lastURL = String::empty;
  233517. blankPageShown = false;
  233518. browser->goBack();
  233519. }
  233520. void WebBrowserComponent::goForward()
  233521. {
  233522. lastURL = String::empty;
  233523. browser->goForward();
  233524. }
  233525. void WebBrowserComponent::refresh()
  233526. {
  233527. browser->refresh();
  233528. }
  233529. void WebBrowserComponent::paint (Graphics&)
  233530. {
  233531. }
  233532. void WebBrowserComponent::checkWindowAssociation()
  233533. {
  233534. if (isShowing())
  233535. {
  233536. if (blankPageShown)
  233537. goBack();
  233538. }
  233539. else
  233540. {
  233541. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233542. {
  233543. // when the component becomes invisible, some stuff like flash
  233544. // carries on playing audio, so we need to force it onto a blank
  233545. // page to avoid this, (and send it back when it's made visible again).
  233546. blankPageShown = true;
  233547. browser->goToURL ("about:blank", 0, 0);
  233548. }
  233549. }
  233550. }
  233551. void WebBrowserComponent::reloadLastURL()
  233552. {
  233553. if (lastURL.isNotEmpty())
  233554. {
  233555. goToURL (lastURL, &lastHeaders, &lastPostData);
  233556. lastURL = String::empty;
  233557. }
  233558. }
  233559. void WebBrowserComponent::parentHierarchyChanged()
  233560. {
  233561. checkWindowAssociation();
  233562. }
  233563. void WebBrowserComponent::resized()
  233564. {
  233565. browser->setSize (getWidth(), getHeight());
  233566. }
  233567. void WebBrowserComponent::visibilityChanged()
  233568. {
  233569. checkWindowAssociation();
  233570. }
  233571. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233572. {
  233573. return true;
  233574. }
  233575. #else
  233576. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233577. {
  233578. }
  233579. WebBrowserComponent::~WebBrowserComponent()
  233580. {
  233581. }
  233582. void WebBrowserComponent::goToURL (const String& url,
  233583. const StringArray* headers,
  233584. const MemoryBlock* postData)
  233585. {
  233586. }
  233587. void WebBrowserComponent::stop()
  233588. {
  233589. }
  233590. void WebBrowserComponent::goBack()
  233591. {
  233592. }
  233593. void WebBrowserComponent::goForward()
  233594. {
  233595. }
  233596. void WebBrowserComponent::refresh()
  233597. {
  233598. }
  233599. void WebBrowserComponent::paint (Graphics& g)
  233600. {
  233601. }
  233602. void WebBrowserComponent::checkWindowAssociation()
  233603. {
  233604. }
  233605. void WebBrowserComponent::reloadLastURL()
  233606. {
  233607. }
  233608. void WebBrowserComponent::parentHierarchyChanged()
  233609. {
  233610. }
  233611. void WebBrowserComponent::resized()
  233612. {
  233613. }
  233614. void WebBrowserComponent::visibilityChanged()
  233615. {
  233616. }
  233617. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233618. {
  233619. return true;
  233620. }
  233621. #endif
  233622. #endif
  233623. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233624. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233625. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233626. // compiled on its own).
  233627. #if JUCE_INCLUDED_FILE
  233628. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233629. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233630. #endif
  233631. #undef log
  233632. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233633. #define log(a) Logger::writeToLog (a)
  233634. #else
  233635. #define log(a)
  233636. #endif
  233637. #undef OK
  233638. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233639. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233640. {
  233641. if (err == noErr)
  233642. return true;
  233643. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233644. jassertfalse;
  233645. return false;
  233646. }
  233647. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233648. #else
  233649. #define OK(a) (a == noErr)
  233650. #endif
  233651. class CoreAudioInternal : public Timer
  233652. {
  233653. public:
  233654. CoreAudioInternal (AudioDeviceID id)
  233655. : inputLatency (0),
  233656. outputLatency (0),
  233657. callback (0),
  233658. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233659. audioProcID (0),
  233660. #endif
  233661. isSlaveDevice (false),
  233662. deviceID (id),
  233663. started (false),
  233664. sampleRate (0),
  233665. bufferSize (512),
  233666. numInputChans (0),
  233667. numOutputChans (0),
  233668. callbacksAllowed (true),
  233669. numInputChannelInfos (0),
  233670. numOutputChannelInfos (0)
  233671. {
  233672. jassert (deviceID != 0);
  233673. updateDetailsFromDevice();
  233674. AudioObjectPropertyAddress pa;
  233675. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233676. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233677. pa.mElement = kAudioObjectPropertyElementWildcard;
  233678. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233679. }
  233680. ~CoreAudioInternal()
  233681. {
  233682. AudioObjectPropertyAddress pa;
  233683. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233684. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233685. pa.mElement = kAudioObjectPropertyElementWildcard;
  233686. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233687. stop (false);
  233688. }
  233689. void allocateTempBuffers()
  233690. {
  233691. const int tempBufSize = bufferSize + 4;
  233692. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233693. tempInputBuffers.calloc (numInputChans + 2);
  233694. tempOutputBuffers.calloc (numOutputChans + 2);
  233695. int i, count = 0;
  233696. for (i = 0; i < numInputChans; ++i)
  233697. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233698. for (i = 0; i < numOutputChans; ++i)
  233699. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233700. }
  233701. // returns the number of actual available channels
  233702. void fillInChannelInfo (const bool input)
  233703. {
  233704. int chanNum = 0;
  233705. UInt32 size;
  233706. AudioObjectPropertyAddress pa;
  233707. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233708. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233709. pa.mElement = kAudioObjectPropertyElementMaster;
  233710. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233711. {
  233712. HeapBlock <AudioBufferList> bufList;
  233713. bufList.calloc (size, 1);
  233714. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233715. {
  233716. const int numStreams = bufList->mNumberBuffers;
  233717. for (int i = 0; i < numStreams; ++i)
  233718. {
  233719. const AudioBuffer& b = bufList->mBuffers[i];
  233720. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233721. {
  233722. String name;
  233723. {
  233724. char channelName [256];
  233725. zerostruct (channelName);
  233726. UInt32 nameSize = sizeof (channelName);
  233727. UInt32 channelNum = chanNum + 1;
  233728. pa.mSelector = kAudioDevicePropertyChannelName;
  233729. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233730. name = String::fromUTF8 (channelName, nameSize);
  233731. }
  233732. if (input)
  233733. {
  233734. if (activeInputChans[chanNum])
  233735. {
  233736. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233737. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233738. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233739. ++numInputChannelInfos;
  233740. }
  233741. if (name.isEmpty())
  233742. name << "Input " << (chanNum + 1);
  233743. inChanNames.add (name);
  233744. }
  233745. else
  233746. {
  233747. if (activeOutputChans[chanNum])
  233748. {
  233749. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233750. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233751. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233752. ++numOutputChannelInfos;
  233753. }
  233754. if (name.isEmpty())
  233755. name << "Output " << (chanNum + 1);
  233756. outChanNames.add (name);
  233757. }
  233758. ++chanNum;
  233759. }
  233760. }
  233761. }
  233762. }
  233763. }
  233764. void updateDetailsFromDevice()
  233765. {
  233766. stopTimer();
  233767. if (deviceID == 0)
  233768. return;
  233769. const ScopedLock sl (callbackLock);
  233770. Float64 sr;
  233771. UInt32 size = sizeof (Float64);
  233772. AudioObjectPropertyAddress pa;
  233773. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233774. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233775. pa.mElement = kAudioObjectPropertyElementMaster;
  233776. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233777. sampleRate = sr;
  233778. UInt32 framesPerBuf;
  233779. size = sizeof (framesPerBuf);
  233780. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233781. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233782. {
  233783. bufferSize = framesPerBuf;
  233784. allocateTempBuffers();
  233785. }
  233786. bufferSizes.clear();
  233787. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233788. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233789. {
  233790. HeapBlock <AudioValueRange> ranges;
  233791. ranges.calloc (size, 1);
  233792. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233793. {
  233794. bufferSizes.add ((int) ranges[0].mMinimum);
  233795. for (int i = 32; i < 2048; i += 32)
  233796. {
  233797. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233798. {
  233799. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233800. {
  233801. bufferSizes.addIfNotAlreadyThere (i);
  233802. break;
  233803. }
  233804. }
  233805. }
  233806. if (bufferSize > 0)
  233807. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233808. }
  233809. }
  233810. if (bufferSizes.size() == 0 && bufferSize > 0)
  233811. bufferSizes.add (bufferSize);
  233812. sampleRates.clear();
  233813. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233814. String rates;
  233815. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  233816. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233817. {
  233818. HeapBlock <AudioValueRange> ranges;
  233819. ranges.calloc (size, 1);
  233820. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233821. {
  233822. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  233823. {
  233824. bool ok = false;
  233825. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233826. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  233827. ok = true;
  233828. if (ok)
  233829. {
  233830. sampleRates.add (possibleRates[i]);
  233831. rates << possibleRates[i] << ' ';
  233832. }
  233833. }
  233834. }
  233835. }
  233836. if (sampleRates.size() == 0 && sampleRate > 0)
  233837. {
  233838. sampleRates.add (sampleRate);
  233839. rates << sampleRate;
  233840. }
  233841. log ("sr: " + rates);
  233842. inputLatency = 0;
  233843. outputLatency = 0;
  233844. UInt32 lat;
  233845. size = sizeof (lat);
  233846. pa.mSelector = kAudioDevicePropertyLatency;
  233847. pa.mScope = kAudioDevicePropertyScopeInput;
  233848. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  233849. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233850. inputLatency = (int) lat;
  233851. pa.mScope = kAudioDevicePropertyScopeOutput;
  233852. size = sizeof (lat);
  233853. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233854. outputLatency = (int) lat;
  233855. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  233856. inChanNames.clear();
  233857. outChanNames.clear();
  233858. inputChannelInfo.calloc (numInputChans + 2);
  233859. numInputChannelInfos = 0;
  233860. outputChannelInfo.calloc (numOutputChans + 2);
  233861. numOutputChannelInfos = 0;
  233862. fillInChannelInfo (true);
  233863. fillInChannelInfo (false);
  233864. }
  233865. const StringArray getSources (bool input)
  233866. {
  233867. StringArray s;
  233868. HeapBlock <OSType> types;
  233869. const int num = getAllDataSourcesForDevice (deviceID, types);
  233870. for (int i = 0; i < num; ++i)
  233871. {
  233872. AudioValueTranslation avt;
  233873. char buffer[256];
  233874. avt.mInputData = &(types[i]);
  233875. avt.mInputDataSize = sizeof (UInt32);
  233876. avt.mOutputData = buffer;
  233877. avt.mOutputDataSize = 256;
  233878. UInt32 transSize = sizeof (avt);
  233879. AudioObjectPropertyAddress pa;
  233880. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  233881. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233882. pa.mElement = kAudioObjectPropertyElementMaster;
  233883. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  233884. {
  233885. DBG (buffer);
  233886. s.add (buffer);
  233887. }
  233888. }
  233889. return s;
  233890. }
  233891. int getCurrentSourceIndex (bool input) const
  233892. {
  233893. OSType currentSourceID = 0;
  233894. UInt32 size = sizeof (currentSourceID);
  233895. int result = -1;
  233896. AudioObjectPropertyAddress pa;
  233897. pa.mSelector = kAudioDevicePropertyDataSource;
  233898. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233899. pa.mElement = kAudioObjectPropertyElementMaster;
  233900. if (deviceID != 0)
  233901. {
  233902. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  233903. {
  233904. HeapBlock <OSType> types;
  233905. const int num = getAllDataSourcesForDevice (deviceID, types);
  233906. for (int i = 0; i < num; ++i)
  233907. {
  233908. if (types[num] == currentSourceID)
  233909. {
  233910. result = i;
  233911. break;
  233912. }
  233913. }
  233914. }
  233915. }
  233916. return result;
  233917. }
  233918. void setCurrentSourceIndex (int index, bool input)
  233919. {
  233920. if (deviceID != 0)
  233921. {
  233922. HeapBlock <OSType> types;
  233923. const int num = getAllDataSourcesForDevice (deviceID, types);
  233924. if (((unsigned int) index) < (unsigned int) num)
  233925. {
  233926. AudioObjectPropertyAddress pa;
  233927. pa.mSelector = kAudioDevicePropertyDataSource;
  233928. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233929. pa.mElement = kAudioObjectPropertyElementMaster;
  233930. OSType typeId = types[index];
  233931. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  233932. }
  233933. }
  233934. }
  233935. const String reopen (const BigInteger& inputChannels,
  233936. const BigInteger& outputChannels,
  233937. double newSampleRate,
  233938. int bufferSizeSamples)
  233939. {
  233940. String error;
  233941. log ("CoreAudio reopen");
  233942. callbacksAllowed = false;
  233943. stopTimer();
  233944. stop (false);
  233945. activeInputChans = inputChannels;
  233946. activeInputChans.setRange (inChanNames.size(),
  233947. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  233948. false);
  233949. activeOutputChans = outputChannels;
  233950. activeOutputChans.setRange (outChanNames.size(),
  233951. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  233952. false);
  233953. numInputChans = activeInputChans.countNumberOfSetBits();
  233954. numOutputChans = activeOutputChans.countNumberOfSetBits();
  233955. // set sample rate
  233956. AudioObjectPropertyAddress pa;
  233957. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233958. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233959. pa.mElement = kAudioObjectPropertyElementMaster;
  233960. Float64 sr = newSampleRate;
  233961. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  233962. {
  233963. error = "Couldn't change sample rate";
  233964. }
  233965. else
  233966. {
  233967. // change buffer size
  233968. UInt32 framesPerBuf = bufferSizeSamples;
  233969. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233970. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  233971. {
  233972. error = "Couldn't change buffer size";
  233973. }
  233974. else
  233975. {
  233976. // Annoyingly, after changing the rate and buffer size, some devices fail to
  233977. // correctly report their new settings until some random time in the future, so
  233978. // after calling updateDetailsFromDevice, we need to manually bodge these values
  233979. // to make sure we're using the correct numbers..
  233980. updateDetailsFromDevice();
  233981. sampleRate = newSampleRate;
  233982. bufferSize = bufferSizeSamples;
  233983. if (sampleRates.size() == 0)
  233984. error = "Device has no available sample-rates";
  233985. else if (bufferSizes.size() == 0)
  233986. error = "Device has no available buffer-sizes";
  233987. else if (inputDevice != 0)
  233988. error = inputDevice->reopen (inputChannels,
  233989. outputChannels,
  233990. newSampleRate,
  233991. bufferSizeSamples);
  233992. }
  233993. }
  233994. callbacksAllowed = true;
  233995. return error;
  233996. }
  233997. bool start (AudioIODeviceCallback* cb)
  233998. {
  233999. if (! started)
  234000. {
  234001. callback = 0;
  234002. if (deviceID != 0)
  234003. {
  234004. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234005. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234006. #else
  234007. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234008. #endif
  234009. {
  234010. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234011. {
  234012. started = true;
  234013. }
  234014. else
  234015. {
  234016. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234017. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234018. #else
  234019. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234020. audioProcID = 0;
  234021. #endif
  234022. }
  234023. }
  234024. }
  234025. }
  234026. if (started)
  234027. {
  234028. const ScopedLock sl (callbackLock);
  234029. callback = cb;
  234030. }
  234031. if (inputDevice != 0)
  234032. return started && inputDevice->start (cb);
  234033. else
  234034. return started;
  234035. }
  234036. void stop (bool leaveInterruptRunning)
  234037. {
  234038. {
  234039. const ScopedLock sl (callbackLock);
  234040. callback = 0;
  234041. }
  234042. if (started
  234043. && (deviceID != 0)
  234044. && ! leaveInterruptRunning)
  234045. {
  234046. OK (AudioDeviceStop (deviceID, audioIOProc));
  234047. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234048. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234049. #else
  234050. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234051. audioProcID = 0;
  234052. #endif
  234053. started = false;
  234054. { const ScopedLock sl (callbackLock); }
  234055. // wait until it's definately stopped calling back..
  234056. for (int i = 40; --i >= 0;)
  234057. {
  234058. Thread::sleep (50);
  234059. UInt32 running = 0;
  234060. UInt32 size = sizeof (running);
  234061. AudioObjectPropertyAddress pa;
  234062. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234063. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234064. pa.mElement = kAudioObjectPropertyElementMaster;
  234065. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234066. if (running == 0)
  234067. break;
  234068. }
  234069. const ScopedLock sl (callbackLock);
  234070. }
  234071. if (inputDevice != 0)
  234072. inputDevice->stop (leaveInterruptRunning);
  234073. }
  234074. double getSampleRate() const
  234075. {
  234076. return sampleRate;
  234077. }
  234078. int getBufferSize() const
  234079. {
  234080. return bufferSize;
  234081. }
  234082. void audioCallback (const AudioBufferList* inInputData,
  234083. AudioBufferList* outOutputData)
  234084. {
  234085. int i;
  234086. const ScopedLock sl (callbackLock);
  234087. if (callback != 0)
  234088. {
  234089. if (inputDevice == 0)
  234090. {
  234091. for (i = numInputChans; --i >= 0;)
  234092. {
  234093. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  234094. float* dest = tempInputBuffers [i];
  234095. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  234096. + info.dataOffsetSamples;
  234097. const int stride = info.dataStrideSamples;
  234098. if (stride != 0) // if this is zero, info is invalid
  234099. {
  234100. for (int j = bufferSize; --j >= 0;)
  234101. {
  234102. *dest++ = *src;
  234103. src += stride;
  234104. }
  234105. }
  234106. }
  234107. }
  234108. if (! isSlaveDevice)
  234109. {
  234110. if (inputDevice == 0)
  234111. {
  234112. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  234113. numInputChans,
  234114. tempOutputBuffers,
  234115. numOutputChans,
  234116. bufferSize);
  234117. }
  234118. else
  234119. {
  234120. jassert (inputDevice->bufferSize == bufferSize);
  234121. // Sometimes the two linked devices seem to get their callbacks in
  234122. // parallel, so we need to lock both devices to stop the input data being
  234123. // changed while inside our callback..
  234124. const ScopedLock sl2 (inputDevice->callbackLock);
  234125. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  234126. inputDevice->numInputChans,
  234127. tempOutputBuffers,
  234128. numOutputChans,
  234129. bufferSize);
  234130. }
  234131. for (i = numOutputChans; --i >= 0;)
  234132. {
  234133. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234134. const float* src = tempOutputBuffers [i];
  234135. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234136. + info.dataOffsetSamples;
  234137. const int stride = info.dataStrideSamples;
  234138. if (stride != 0) // if this is zero, info is invalid
  234139. {
  234140. for (int j = bufferSize; --j >= 0;)
  234141. {
  234142. *dest = *src++;
  234143. dest += stride;
  234144. }
  234145. }
  234146. }
  234147. }
  234148. }
  234149. else
  234150. {
  234151. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  234152. {
  234153. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234154. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234155. + info.dataOffsetSamples;
  234156. const int stride = info.dataStrideSamples;
  234157. if (stride != 0) // if this is zero, info is invalid
  234158. {
  234159. for (int j = bufferSize; --j >= 0;)
  234160. {
  234161. *dest = 0.0f;
  234162. dest += stride;
  234163. }
  234164. }
  234165. }
  234166. }
  234167. }
  234168. // called by callbacks
  234169. void deviceDetailsChanged()
  234170. {
  234171. if (callbacksAllowed)
  234172. startTimer (100);
  234173. }
  234174. void timerCallback()
  234175. {
  234176. stopTimer();
  234177. log ("CoreAudio device changed callback");
  234178. const double oldSampleRate = sampleRate;
  234179. const int oldBufferSize = bufferSize;
  234180. updateDetailsFromDevice();
  234181. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  234182. {
  234183. callbacksAllowed = false;
  234184. stop (false);
  234185. updateDetailsFromDevice();
  234186. callbacksAllowed = true;
  234187. }
  234188. }
  234189. CoreAudioInternal* getRelatedDevice() const
  234190. {
  234191. UInt32 size = 0;
  234192. ScopedPointer <CoreAudioInternal> result;
  234193. AudioObjectPropertyAddress pa;
  234194. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  234195. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234196. pa.mElement = kAudioObjectPropertyElementMaster;
  234197. if (deviceID != 0
  234198. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234199. && size > 0)
  234200. {
  234201. HeapBlock <AudioDeviceID> devs;
  234202. devs.calloc (size, 1);
  234203. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234204. {
  234205. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234206. {
  234207. if (devs[i] != deviceID && devs[i] != 0)
  234208. {
  234209. result = new CoreAudioInternal (devs[i]);
  234210. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234211. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234212. if (thisIsInput != otherIsInput
  234213. || (inChanNames.size() + outChanNames.size() == 0)
  234214. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234215. break;
  234216. result = 0;
  234217. }
  234218. }
  234219. }
  234220. }
  234221. return result.release();
  234222. }
  234223. juce_UseDebuggingNewOperator
  234224. int inputLatency, outputLatency;
  234225. BigInteger activeInputChans, activeOutputChans;
  234226. StringArray inChanNames, outChanNames;
  234227. Array <double> sampleRates;
  234228. Array <int> bufferSizes;
  234229. AudioIODeviceCallback* callback;
  234230. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234231. AudioDeviceIOProcID audioProcID;
  234232. #endif
  234233. ScopedPointer<CoreAudioInternal> inputDevice;
  234234. bool isSlaveDevice;
  234235. private:
  234236. CriticalSection callbackLock;
  234237. AudioDeviceID deviceID;
  234238. bool started;
  234239. double sampleRate;
  234240. int bufferSize;
  234241. HeapBlock <float> audioBuffer;
  234242. int numInputChans, numOutputChans;
  234243. bool callbacksAllowed;
  234244. struct CallbackDetailsForChannel
  234245. {
  234246. int streamNum;
  234247. int dataOffsetSamples;
  234248. int dataStrideSamples;
  234249. };
  234250. int numInputChannelInfos, numOutputChannelInfos;
  234251. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234252. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234253. CoreAudioInternal (const CoreAudioInternal&);
  234254. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234255. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234256. const AudioTimeStamp* /*inNow*/,
  234257. const AudioBufferList* inInputData,
  234258. const AudioTimeStamp* /*inInputTime*/,
  234259. AudioBufferList* outOutputData,
  234260. const AudioTimeStamp* /*inOutputTime*/,
  234261. void* device)
  234262. {
  234263. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234264. return noErr;
  234265. }
  234266. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234267. {
  234268. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234269. switch (pa->mSelector)
  234270. {
  234271. case kAudioDevicePropertyBufferSize:
  234272. case kAudioDevicePropertyBufferFrameSize:
  234273. case kAudioDevicePropertyNominalSampleRate:
  234274. case kAudioDevicePropertyStreamFormat:
  234275. case kAudioDevicePropertyDeviceIsAlive:
  234276. intern->deviceDetailsChanged();
  234277. break;
  234278. case kAudioDevicePropertyBufferSizeRange:
  234279. case kAudioDevicePropertyVolumeScalar:
  234280. case kAudioDevicePropertyMute:
  234281. case kAudioDevicePropertyPlayThru:
  234282. case kAudioDevicePropertyDataSource:
  234283. case kAudioDevicePropertyDeviceIsRunning:
  234284. break;
  234285. }
  234286. return noErr;
  234287. }
  234288. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234289. {
  234290. AudioObjectPropertyAddress pa;
  234291. pa.mSelector = kAudioDevicePropertyDataSources;
  234292. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234293. pa.mElement = kAudioObjectPropertyElementMaster;
  234294. UInt32 size = 0;
  234295. if (deviceID != 0
  234296. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234297. {
  234298. types.calloc (size, 1);
  234299. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234300. return size / (int) sizeof (OSType);
  234301. }
  234302. return 0;
  234303. }
  234304. };
  234305. class CoreAudioIODevice : public AudioIODevice
  234306. {
  234307. public:
  234308. CoreAudioIODevice (const String& deviceName,
  234309. AudioDeviceID inputDeviceId,
  234310. const int inputIndex_,
  234311. AudioDeviceID outputDeviceId,
  234312. const int outputIndex_)
  234313. : AudioIODevice (deviceName, "CoreAudio"),
  234314. inputIndex (inputIndex_),
  234315. outputIndex (outputIndex_),
  234316. isOpen_ (false),
  234317. isStarted (false)
  234318. {
  234319. CoreAudioInternal* device = 0;
  234320. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234321. {
  234322. jassert (inputDeviceId != 0);
  234323. device = new CoreAudioInternal (inputDeviceId);
  234324. }
  234325. else
  234326. {
  234327. device = new CoreAudioInternal (outputDeviceId);
  234328. if (inputDeviceId != 0)
  234329. {
  234330. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234331. device->inputDevice = secondDevice;
  234332. secondDevice->isSlaveDevice = true;
  234333. }
  234334. }
  234335. internal = device;
  234336. AudioObjectPropertyAddress pa;
  234337. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234338. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234339. pa.mElement = kAudioObjectPropertyElementWildcard;
  234340. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234341. }
  234342. ~CoreAudioIODevice()
  234343. {
  234344. AudioObjectPropertyAddress pa;
  234345. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234346. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234347. pa.mElement = kAudioObjectPropertyElementWildcard;
  234348. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234349. }
  234350. const StringArray getOutputChannelNames()
  234351. {
  234352. return internal->outChanNames;
  234353. }
  234354. const StringArray getInputChannelNames()
  234355. {
  234356. if (internal->inputDevice != 0)
  234357. return internal->inputDevice->inChanNames;
  234358. else
  234359. return internal->inChanNames;
  234360. }
  234361. int getNumSampleRates()
  234362. {
  234363. return internal->sampleRates.size();
  234364. }
  234365. double getSampleRate (int index)
  234366. {
  234367. return internal->sampleRates [index];
  234368. }
  234369. int getNumBufferSizesAvailable()
  234370. {
  234371. return internal->bufferSizes.size();
  234372. }
  234373. int getBufferSizeSamples (int index)
  234374. {
  234375. return internal->bufferSizes [index];
  234376. }
  234377. int getDefaultBufferSize()
  234378. {
  234379. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234380. if (getBufferSizeSamples(i) >= 512)
  234381. return getBufferSizeSamples(i);
  234382. return 512;
  234383. }
  234384. const String open (const BigInteger& inputChannels,
  234385. const BigInteger& outputChannels,
  234386. double sampleRate,
  234387. int bufferSizeSamples)
  234388. {
  234389. isOpen_ = true;
  234390. if (bufferSizeSamples <= 0)
  234391. bufferSizeSamples = getDefaultBufferSize();
  234392. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234393. isOpen_ = lastError.isEmpty();
  234394. return lastError;
  234395. }
  234396. void close()
  234397. {
  234398. isOpen_ = false;
  234399. internal->stop (false);
  234400. }
  234401. bool isOpen()
  234402. {
  234403. return isOpen_;
  234404. }
  234405. int getCurrentBufferSizeSamples()
  234406. {
  234407. return internal != 0 ? internal->getBufferSize() : 512;
  234408. }
  234409. double getCurrentSampleRate()
  234410. {
  234411. return internal != 0 ? internal->getSampleRate() : 0;
  234412. }
  234413. int getCurrentBitDepth()
  234414. {
  234415. return 32; // no way to find out, so just assume it's high..
  234416. }
  234417. const BigInteger getActiveOutputChannels() const
  234418. {
  234419. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234420. }
  234421. const BigInteger getActiveInputChannels() const
  234422. {
  234423. BigInteger chans;
  234424. if (internal != 0)
  234425. {
  234426. chans = internal->activeInputChans;
  234427. if (internal->inputDevice != 0)
  234428. chans |= internal->inputDevice->activeInputChans;
  234429. }
  234430. return chans;
  234431. }
  234432. int getOutputLatencyInSamples()
  234433. {
  234434. if (internal == 0)
  234435. return 0;
  234436. // this seems like a good guess at getting the latency right - comparing
  234437. // this with a round-trip measurement, it gets it to within a few millisecs
  234438. // for the built-in mac soundcard
  234439. return internal->outputLatency + internal->getBufferSize() * 2;
  234440. }
  234441. int getInputLatencyInSamples()
  234442. {
  234443. if (internal == 0)
  234444. return 0;
  234445. return internal->inputLatency + internal->getBufferSize() * 2;
  234446. }
  234447. void start (AudioIODeviceCallback* callback)
  234448. {
  234449. if (internal != 0 && ! isStarted)
  234450. {
  234451. if (callback != 0)
  234452. callback->audioDeviceAboutToStart (this);
  234453. isStarted = true;
  234454. internal->start (callback);
  234455. }
  234456. }
  234457. void stop()
  234458. {
  234459. if (isStarted && internal != 0)
  234460. {
  234461. AudioIODeviceCallback* const lastCallback = internal->callback;
  234462. isStarted = false;
  234463. internal->stop (true);
  234464. if (lastCallback != 0)
  234465. lastCallback->audioDeviceStopped();
  234466. }
  234467. }
  234468. bool isPlaying()
  234469. {
  234470. if (internal->callback == 0)
  234471. isStarted = false;
  234472. return isStarted;
  234473. }
  234474. const String getLastError()
  234475. {
  234476. return lastError;
  234477. }
  234478. int inputIndex, outputIndex;
  234479. juce_UseDebuggingNewOperator
  234480. private:
  234481. ScopedPointer<CoreAudioInternal> internal;
  234482. bool isOpen_, isStarted;
  234483. String lastError;
  234484. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234485. {
  234486. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234487. switch (pa->mSelector)
  234488. {
  234489. case kAudioHardwarePropertyDevices:
  234490. intern->deviceDetailsChanged();
  234491. break;
  234492. case kAudioHardwarePropertyDefaultOutputDevice:
  234493. case kAudioHardwarePropertyDefaultInputDevice:
  234494. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234495. break;
  234496. }
  234497. return noErr;
  234498. }
  234499. CoreAudioIODevice (const CoreAudioIODevice&);
  234500. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234501. };
  234502. class CoreAudioIODeviceType : public AudioIODeviceType
  234503. {
  234504. public:
  234505. CoreAudioIODeviceType()
  234506. : AudioIODeviceType ("CoreAudio"),
  234507. hasScanned (false)
  234508. {
  234509. }
  234510. ~CoreAudioIODeviceType()
  234511. {
  234512. }
  234513. void scanForDevices()
  234514. {
  234515. hasScanned = true;
  234516. inputDeviceNames.clear();
  234517. outputDeviceNames.clear();
  234518. inputIds.clear();
  234519. outputIds.clear();
  234520. UInt32 size;
  234521. AudioObjectPropertyAddress pa;
  234522. pa.mSelector = kAudioHardwarePropertyDevices;
  234523. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234524. pa.mElement = kAudioObjectPropertyElementMaster;
  234525. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234526. {
  234527. HeapBlock <AudioDeviceID> devs;
  234528. devs.calloc (size, 1);
  234529. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234530. {
  234531. static bool alreadyLogged = false;
  234532. const int num = size / (int) sizeof (AudioDeviceID);
  234533. for (int i = 0; i < num; ++i)
  234534. {
  234535. char name [1024];
  234536. size = sizeof (name);
  234537. pa.mSelector = kAudioDevicePropertyDeviceName;
  234538. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234539. {
  234540. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234541. if (! alreadyLogged)
  234542. log ("CoreAudio device: " + nameString);
  234543. const int numIns = getNumChannels (devs[i], true);
  234544. const int numOuts = getNumChannels (devs[i], false);
  234545. if (numIns > 0)
  234546. {
  234547. inputDeviceNames.add (nameString);
  234548. inputIds.add (devs[i]);
  234549. }
  234550. if (numOuts > 0)
  234551. {
  234552. outputDeviceNames.add (nameString);
  234553. outputIds.add (devs[i]);
  234554. }
  234555. }
  234556. }
  234557. alreadyLogged = true;
  234558. }
  234559. }
  234560. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234561. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234562. }
  234563. const StringArray getDeviceNames (bool wantInputNames) const
  234564. {
  234565. jassert (hasScanned); // need to call scanForDevices() before doing this
  234566. if (wantInputNames)
  234567. return inputDeviceNames;
  234568. else
  234569. return outputDeviceNames;
  234570. }
  234571. int getDefaultDeviceIndex (bool forInput) const
  234572. {
  234573. jassert (hasScanned); // need to call scanForDevices() before doing this
  234574. AudioDeviceID deviceID;
  234575. UInt32 size = sizeof (deviceID);
  234576. // if they're asking for any input channels at all, use the default input, so we
  234577. // get the built-in mic rather than the built-in output with no inputs..
  234578. AudioObjectPropertyAddress pa;
  234579. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234580. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234581. pa.mElement = kAudioObjectPropertyElementMaster;
  234582. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234583. {
  234584. if (forInput)
  234585. {
  234586. for (int i = inputIds.size(); --i >= 0;)
  234587. if (inputIds[i] == deviceID)
  234588. return i;
  234589. }
  234590. else
  234591. {
  234592. for (int i = outputIds.size(); --i >= 0;)
  234593. if (outputIds[i] == deviceID)
  234594. return i;
  234595. }
  234596. }
  234597. return 0;
  234598. }
  234599. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234600. {
  234601. jassert (hasScanned); // need to call scanForDevices() before doing this
  234602. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234603. if (d == 0)
  234604. return -1;
  234605. return asInput ? d->inputIndex
  234606. : d->outputIndex;
  234607. }
  234608. bool hasSeparateInputsAndOutputs() const { return true; }
  234609. AudioIODevice* createDevice (const String& outputDeviceName,
  234610. const String& inputDeviceName)
  234611. {
  234612. jassert (hasScanned); // need to call scanForDevices() before doing this
  234613. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234614. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234615. String deviceName (outputDeviceName);
  234616. if (deviceName.isEmpty())
  234617. deviceName = inputDeviceName;
  234618. if (index >= 0)
  234619. return new CoreAudioIODevice (deviceName,
  234620. inputIds [inputIndex],
  234621. inputIndex,
  234622. outputIds [outputIndex],
  234623. outputIndex);
  234624. return 0;
  234625. }
  234626. juce_UseDebuggingNewOperator
  234627. private:
  234628. StringArray inputDeviceNames, outputDeviceNames;
  234629. Array <AudioDeviceID> inputIds, outputIds;
  234630. bool hasScanned;
  234631. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234632. {
  234633. int total = 0;
  234634. UInt32 size;
  234635. AudioObjectPropertyAddress pa;
  234636. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234637. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234638. pa.mElement = kAudioObjectPropertyElementMaster;
  234639. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234640. {
  234641. HeapBlock <AudioBufferList> bufList;
  234642. bufList.calloc (size, 1);
  234643. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234644. {
  234645. const int numStreams = bufList->mNumberBuffers;
  234646. for (int i = 0; i < numStreams; ++i)
  234647. {
  234648. const AudioBuffer& b = bufList->mBuffers[i];
  234649. total += b.mNumberChannels;
  234650. }
  234651. }
  234652. }
  234653. return total;
  234654. }
  234655. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234656. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234657. };
  234658. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234659. {
  234660. return new CoreAudioIODeviceType();
  234661. }
  234662. #undef log
  234663. #endif
  234664. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234665. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234666. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234667. // compiled on its own).
  234668. #if JUCE_INCLUDED_FILE
  234669. #if JUCE_MAC
  234670. #undef log
  234671. #define log(a) Logger::writeToLog(a)
  234672. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234673. {
  234674. if (err == noErr)
  234675. return true;
  234676. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234677. jassertfalse;
  234678. return false;
  234679. }
  234680. #undef OK
  234681. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234682. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234683. {
  234684. String result;
  234685. CFStringRef str = 0;
  234686. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234687. if (str != 0)
  234688. {
  234689. result = PlatformUtilities::cfStringToJuceString (str);
  234690. CFRelease (str);
  234691. str = 0;
  234692. }
  234693. MIDIEntityRef entity = 0;
  234694. MIDIEndpointGetEntity (endpoint, &entity);
  234695. if (entity == 0)
  234696. return result; // probably virtual
  234697. if (result.isEmpty())
  234698. {
  234699. // endpoint name has zero length - try the entity
  234700. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234701. if (str != 0)
  234702. {
  234703. result += PlatformUtilities::cfStringToJuceString (str);
  234704. CFRelease (str);
  234705. str = 0;
  234706. }
  234707. }
  234708. // now consider the device's name
  234709. MIDIDeviceRef device = 0;
  234710. MIDIEntityGetDevice (entity, &device);
  234711. if (device == 0)
  234712. return result;
  234713. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234714. if (str != 0)
  234715. {
  234716. const String s (PlatformUtilities::cfStringToJuceString (str));
  234717. CFRelease (str);
  234718. // if an external device has only one entity, throw away
  234719. // the endpoint name and just use the device name
  234720. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234721. {
  234722. result = s;
  234723. }
  234724. else if (! result.startsWithIgnoreCase (s))
  234725. {
  234726. // prepend the device name to the entity name
  234727. result = (s + " " + result).trimEnd();
  234728. }
  234729. }
  234730. return result;
  234731. }
  234732. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234733. {
  234734. String result;
  234735. // Does the endpoint have connections?
  234736. CFDataRef connections = 0;
  234737. int numConnections = 0;
  234738. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234739. if (connections != 0)
  234740. {
  234741. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234742. if (numConnections > 0)
  234743. {
  234744. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234745. for (int i = 0; i < numConnections; ++i, ++pid)
  234746. {
  234747. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234748. MIDIObjectRef connObject;
  234749. MIDIObjectType connObjectType;
  234750. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234751. if (err == noErr)
  234752. {
  234753. String s;
  234754. if (connObjectType == kMIDIObjectType_ExternalSource
  234755. || connObjectType == kMIDIObjectType_ExternalDestination)
  234756. {
  234757. // Connected to an external device's endpoint (10.3 and later).
  234758. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234759. }
  234760. else
  234761. {
  234762. // Connected to an external device (10.2) (or something else, catch-all)
  234763. CFStringRef str = 0;
  234764. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234765. if (str != 0)
  234766. {
  234767. s = PlatformUtilities::cfStringToJuceString (str);
  234768. CFRelease (str);
  234769. }
  234770. }
  234771. if (s.isNotEmpty())
  234772. {
  234773. if (result.isNotEmpty())
  234774. result += ", ";
  234775. result += s;
  234776. }
  234777. }
  234778. }
  234779. }
  234780. CFRelease (connections);
  234781. }
  234782. if (result.isNotEmpty())
  234783. return result;
  234784. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234785. return getEndpointName (endpoint, false);
  234786. }
  234787. const StringArray MidiOutput::getDevices()
  234788. {
  234789. StringArray s;
  234790. const ItemCount num = MIDIGetNumberOfDestinations();
  234791. for (ItemCount i = 0; i < num; ++i)
  234792. {
  234793. MIDIEndpointRef dest = MIDIGetDestination (i);
  234794. if (dest != 0)
  234795. {
  234796. String name (getConnectedEndpointName (dest));
  234797. if (name.isEmpty())
  234798. name = "<error>";
  234799. s.add (name);
  234800. }
  234801. else
  234802. {
  234803. s.add ("<error>");
  234804. }
  234805. }
  234806. return s;
  234807. }
  234808. int MidiOutput::getDefaultDeviceIndex()
  234809. {
  234810. return 0;
  234811. }
  234812. static MIDIClientRef globalMidiClient;
  234813. static bool hasGlobalClientBeenCreated = false;
  234814. static bool makeSureClientExists()
  234815. {
  234816. if (! hasGlobalClientBeenCreated)
  234817. {
  234818. String name ("JUCE");
  234819. if (JUCEApplication::getInstance() != 0)
  234820. name = JUCEApplication::getInstance()->getApplicationName();
  234821. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  234822. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  234823. CFRelease (appName);
  234824. }
  234825. return hasGlobalClientBeenCreated;
  234826. }
  234827. class MidiPortAndEndpoint
  234828. {
  234829. public:
  234830. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  234831. : port (port_), endPoint (endPoint_)
  234832. {
  234833. }
  234834. ~MidiPortAndEndpoint()
  234835. {
  234836. if (port != 0)
  234837. MIDIPortDispose (port);
  234838. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  234839. MIDIEndpointDispose (endPoint);
  234840. }
  234841. MIDIPortRef port;
  234842. MIDIEndpointRef endPoint;
  234843. };
  234844. MidiOutput* MidiOutput::openDevice (int index)
  234845. {
  234846. MidiOutput* mo = 0;
  234847. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  234848. {
  234849. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  234850. CFStringRef pname;
  234851. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234852. {
  234853. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  234854. if (makeSureClientExists())
  234855. {
  234856. MIDIPortRef port;
  234857. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  234858. {
  234859. mo = new MidiOutput();
  234860. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  234861. }
  234862. }
  234863. CFRelease (pname);
  234864. }
  234865. }
  234866. return mo;
  234867. }
  234868. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  234869. {
  234870. MidiOutput* mo = 0;
  234871. if (makeSureClientExists())
  234872. {
  234873. MIDIEndpointRef endPoint;
  234874. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  234875. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  234876. {
  234877. mo = new MidiOutput();
  234878. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  234879. }
  234880. CFRelease (name);
  234881. }
  234882. return mo;
  234883. }
  234884. MidiOutput::~MidiOutput()
  234885. {
  234886. delete (MidiPortAndEndpoint*) internal;
  234887. }
  234888. void MidiOutput::reset()
  234889. {
  234890. }
  234891. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234892. {
  234893. return false;
  234894. }
  234895. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234896. {
  234897. }
  234898. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234899. {
  234900. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  234901. if (message.isSysEx())
  234902. {
  234903. const int maxPacketSize = 256;
  234904. int pos = 0, bytesLeft = message.getRawDataSize();
  234905. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  234906. HeapBlock <MIDIPacketList> packets;
  234907. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  234908. packets->numPackets = numPackets;
  234909. MIDIPacket* p = packets->packet;
  234910. for (int i = 0; i < numPackets; ++i)
  234911. {
  234912. p->timeStamp = 0;
  234913. p->length = jmin (maxPacketSize, bytesLeft);
  234914. memcpy (p->data, message.getRawData() + pos, p->length);
  234915. pos += p->length;
  234916. bytesLeft -= p->length;
  234917. p = MIDIPacketNext (p);
  234918. }
  234919. if (mpe->port != 0)
  234920. MIDISend (mpe->port, mpe->endPoint, packets);
  234921. else
  234922. MIDIReceived (mpe->endPoint, packets);
  234923. }
  234924. else
  234925. {
  234926. MIDIPacketList packets;
  234927. packets.numPackets = 1;
  234928. packets.packet[0].timeStamp = 0;
  234929. packets.packet[0].length = message.getRawDataSize();
  234930. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  234931. if (mpe->port != 0)
  234932. MIDISend (mpe->port, mpe->endPoint, &packets);
  234933. else
  234934. MIDIReceived (mpe->endPoint, &packets);
  234935. }
  234936. }
  234937. const StringArray MidiInput::getDevices()
  234938. {
  234939. StringArray s;
  234940. const ItemCount num = MIDIGetNumberOfSources();
  234941. for (ItemCount i = 0; i < num; ++i)
  234942. {
  234943. MIDIEndpointRef source = MIDIGetSource (i);
  234944. if (source != 0)
  234945. {
  234946. String name (getConnectedEndpointName (source));
  234947. if (name.isEmpty())
  234948. name = "<error>";
  234949. s.add (name);
  234950. }
  234951. else
  234952. {
  234953. s.add ("<error>");
  234954. }
  234955. }
  234956. return s;
  234957. }
  234958. int MidiInput::getDefaultDeviceIndex()
  234959. {
  234960. return 0;
  234961. }
  234962. struct MidiPortAndCallback
  234963. {
  234964. MidiInput* input;
  234965. MidiPortAndEndpoint* portAndEndpoint;
  234966. MidiInputCallback* callback;
  234967. MemoryBlock pendingData;
  234968. int pendingBytes;
  234969. double pendingDataTime;
  234970. bool active;
  234971. void processSysex (const uint8*& d, int& size, const double time)
  234972. {
  234973. if (*d == 0xf0)
  234974. {
  234975. pendingBytes = 0;
  234976. pendingDataTime = time;
  234977. }
  234978. pendingData.ensureSize (pendingBytes + size, false);
  234979. uint8* totalMessage = (uint8*) pendingData.getData();
  234980. uint8* dest = totalMessage + pendingBytes;
  234981. while (size > 0)
  234982. {
  234983. if (pendingBytes > 0 && *d >= 0x80)
  234984. {
  234985. if (*d >= 0xfa || *d == 0xf8)
  234986. {
  234987. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  234988. ++d;
  234989. --size;
  234990. }
  234991. else
  234992. {
  234993. if (*d == 0xf7)
  234994. {
  234995. *dest++ = *d++;
  234996. pendingBytes++;
  234997. --size;
  234998. }
  234999. break;
  235000. }
  235001. }
  235002. else
  235003. {
  235004. *dest++ = *d++;
  235005. pendingBytes++;
  235006. --size;
  235007. }
  235008. }
  235009. if (totalMessage [pendingBytes - 1] == 0xf7)
  235010. {
  235011. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  235012. pendingBytes = 0;
  235013. }
  235014. else
  235015. {
  235016. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  235017. }
  235018. }
  235019. };
  235020. namespace CoreMidiCallbacks
  235021. {
  235022. static CriticalSection callbackLock;
  235023. static Array<void*> activeCallbacks;
  235024. }
  235025. static void midiInputProc (const MIDIPacketList* pktlist,
  235026. void* readProcRefCon,
  235027. void* /*srcConnRefCon*/)
  235028. {
  235029. double time = Time::getMillisecondCounterHiRes() * 0.001;
  235030. const double originalTime = time;
  235031. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  235032. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235033. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  235034. {
  235035. const MIDIPacket* packet = &pktlist->packet[0];
  235036. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235037. {
  235038. const uint8* d = (const uint8*) (packet->data);
  235039. int size = packet->length;
  235040. while (size > 0)
  235041. {
  235042. time = originalTime;
  235043. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  235044. {
  235045. mpc->processSysex (d, size, time);
  235046. }
  235047. else
  235048. {
  235049. int used = 0;
  235050. const MidiMessage m (d, size, used, 0, time);
  235051. if (used <= 0)
  235052. {
  235053. jassertfalse; // malformed midi message
  235054. break;
  235055. }
  235056. else
  235057. {
  235058. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  235059. }
  235060. size -= used;
  235061. d += used;
  235062. }
  235063. }
  235064. packet = MIDIPacketNext (packet);
  235065. }
  235066. }
  235067. }
  235068. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235069. {
  235070. MidiInput* mi = 0;
  235071. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  235072. {
  235073. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235074. if (endPoint != 0)
  235075. {
  235076. CFStringRef pname;
  235077. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235078. {
  235079. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  235080. if (makeSureClientExists())
  235081. {
  235082. MIDIPortRef port;
  235083. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235084. mpc->active = false;
  235085. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  235086. {
  235087. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  235088. {
  235089. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235090. mpc->callback = callback;
  235091. mpc->pendingBytes = 0;
  235092. mpc->pendingData.ensureSize (128);
  235093. mi = new MidiInput (getDevices() [index]);
  235094. mpc->input = mi;
  235095. mi->internal = mpc;
  235096. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235097. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235098. }
  235099. else
  235100. {
  235101. OK (MIDIPortDispose (port));
  235102. }
  235103. }
  235104. }
  235105. }
  235106. CFRelease (pname);
  235107. }
  235108. }
  235109. return mi;
  235110. }
  235111. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235112. {
  235113. MidiInput* mi = 0;
  235114. if (makeSureClientExists())
  235115. {
  235116. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235117. mpc->active = false;
  235118. MIDIEndpointRef endPoint;
  235119. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235120. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  235121. {
  235122. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235123. mpc->callback = callback;
  235124. mpc->pendingBytes = 0;
  235125. mpc->pendingData.ensureSize (128);
  235126. mi = new MidiInput (deviceName);
  235127. mpc->input = mi;
  235128. mi->internal = mpc;
  235129. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235130. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235131. }
  235132. CFRelease (name);
  235133. }
  235134. return mi;
  235135. }
  235136. MidiInput::MidiInput (const String& name_)
  235137. : name (name_)
  235138. {
  235139. }
  235140. MidiInput::~MidiInput()
  235141. {
  235142. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  235143. mpc->active = false;
  235144. {
  235145. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235146. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  235147. }
  235148. if (mpc->portAndEndpoint->port != 0)
  235149. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  235150. delete mpc->portAndEndpoint;
  235151. delete mpc;
  235152. }
  235153. void MidiInput::start()
  235154. {
  235155. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235156. ((MidiPortAndCallback*) internal)->active = true;
  235157. }
  235158. void MidiInput::stop()
  235159. {
  235160. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235161. ((MidiPortAndCallback*) internal)->active = false;
  235162. }
  235163. #undef log
  235164. #else
  235165. MidiOutput::~MidiOutput()
  235166. {
  235167. }
  235168. void MidiOutput::reset()
  235169. {
  235170. }
  235171. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235172. {
  235173. return false;
  235174. }
  235175. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235176. {
  235177. }
  235178. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235179. {
  235180. }
  235181. const StringArray MidiOutput::getDevices()
  235182. {
  235183. return StringArray();
  235184. }
  235185. MidiOutput* MidiOutput::openDevice (int index)
  235186. {
  235187. return 0;
  235188. }
  235189. const StringArray MidiInput::getDevices()
  235190. {
  235191. return StringArray();
  235192. }
  235193. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235194. {
  235195. return 0;
  235196. }
  235197. #endif
  235198. #endif
  235199. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235200. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235201. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235202. // compiled on its own).
  235203. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235204. #if ! JUCE_QUICKTIME
  235205. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235206. #endif
  235207. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235208. class QTCameraDeviceInteral;
  235209. END_JUCE_NAMESPACE
  235210. @interface QTCaptureCallbackDelegate : NSObject
  235211. {
  235212. @public
  235213. CameraDevice* owner;
  235214. QTCameraDeviceInteral* internal;
  235215. int64 firstPresentationTime;
  235216. int64 averageTimeOffset;
  235217. }
  235218. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235219. - (void) dealloc;
  235220. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235221. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235222. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235223. fromConnection: (QTCaptureConnection*) connection;
  235224. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235225. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235226. fromConnection: (QTCaptureConnection*) connection;
  235227. @end
  235228. BEGIN_JUCE_NAMESPACE
  235229. class QTCameraDeviceInteral
  235230. {
  235231. public:
  235232. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235233. {
  235234. const ScopedAutoReleasePool pool;
  235235. session = [[QTCaptureSession alloc] init];
  235236. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235237. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235238. input = 0;
  235239. audioInput = 0;
  235240. audioDevice = 0;
  235241. fileOutput = 0;
  235242. imageOutput = 0;
  235243. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235244. internalDev: this];
  235245. NSError* err = 0;
  235246. [device retain];
  235247. [device open: &err];
  235248. if (err == 0)
  235249. {
  235250. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235251. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235252. [session addInput: input error: &err];
  235253. if (err == 0)
  235254. {
  235255. resetFile();
  235256. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235257. [imageOutput setDelegate: callbackDelegate];
  235258. if (err == 0)
  235259. {
  235260. [session startRunning];
  235261. return;
  235262. }
  235263. }
  235264. }
  235265. openingError = nsStringToJuce ([err description]);
  235266. DBG (openingError);
  235267. }
  235268. ~QTCameraDeviceInteral()
  235269. {
  235270. [session stopRunning];
  235271. [session removeOutput: imageOutput];
  235272. [session release];
  235273. [input release];
  235274. [device release];
  235275. [audioDevice release];
  235276. [audioInput release];
  235277. [fileOutput release];
  235278. [imageOutput release];
  235279. [callbackDelegate release];
  235280. }
  235281. void resetFile()
  235282. {
  235283. [fileOutput recordToOutputFileURL: nil];
  235284. [session removeOutput: fileOutput];
  235285. [fileOutput release];
  235286. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235287. [session removeInput: audioInput];
  235288. [audioInput release];
  235289. audioInput = 0;
  235290. [audioDevice release];
  235291. audioDevice = 0;
  235292. [fileOutput setDelegate: callbackDelegate];
  235293. }
  235294. void addDefaultAudioInput()
  235295. {
  235296. NSError* err = nil;
  235297. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235298. if ([audioDevice open: &err])
  235299. [audioDevice retain];
  235300. else
  235301. audioDevice = nil;
  235302. if (audioDevice != 0)
  235303. {
  235304. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235305. [session addInput: audioInput error: &err];
  235306. }
  235307. }
  235308. void addListener (CameraImageListener* listenerToAdd)
  235309. {
  235310. const ScopedLock sl (listenerLock);
  235311. if (listeners.size() == 0)
  235312. [session addOutput: imageOutput error: nil];
  235313. listeners.addIfNotAlreadyThere (listenerToAdd);
  235314. }
  235315. void removeListener (CameraImageListener* listenerToRemove)
  235316. {
  235317. const ScopedLock sl (listenerLock);
  235318. listeners.removeValue (listenerToRemove);
  235319. if (listeners.size() == 0)
  235320. [session removeOutput: imageOutput];
  235321. }
  235322. void callListeners (CIImage* frame, int w, int h)
  235323. {
  235324. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235325. Image image (cgImage);
  235326. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235327. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235328. CGContextFlush (cgImage->context);
  235329. const ScopedLock sl (listenerLock);
  235330. for (int i = listeners.size(); --i >= 0;)
  235331. {
  235332. CameraImageListener* const l = listeners[i];
  235333. if (l != 0)
  235334. l->imageReceived (image);
  235335. }
  235336. }
  235337. QTCaptureDevice* device;
  235338. QTCaptureDeviceInput* input;
  235339. QTCaptureDevice* audioDevice;
  235340. QTCaptureDeviceInput* audioInput;
  235341. QTCaptureSession* session;
  235342. QTCaptureMovieFileOutput* fileOutput;
  235343. QTCaptureDecompressedVideoOutput* imageOutput;
  235344. QTCaptureCallbackDelegate* callbackDelegate;
  235345. String openingError;
  235346. Array<CameraImageListener*> listeners;
  235347. CriticalSection listenerLock;
  235348. };
  235349. END_JUCE_NAMESPACE
  235350. @implementation QTCaptureCallbackDelegate
  235351. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235352. internalDev: (QTCameraDeviceInteral*) d
  235353. {
  235354. [super init];
  235355. owner = owner_;
  235356. internal = d;
  235357. firstPresentationTime = 0;
  235358. averageTimeOffset = 0;
  235359. return self;
  235360. }
  235361. - (void) dealloc
  235362. {
  235363. [super dealloc];
  235364. }
  235365. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235366. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235367. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235368. fromConnection: (QTCaptureConnection*) connection
  235369. {
  235370. if (internal->listeners.size() > 0)
  235371. {
  235372. const ScopedAutoReleasePool pool;
  235373. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235374. CVPixelBufferGetWidth (videoFrame),
  235375. CVPixelBufferGetHeight (videoFrame));
  235376. }
  235377. }
  235378. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235379. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235380. fromConnection: (QTCaptureConnection*) connection
  235381. {
  235382. const Time now (Time::getCurrentTime());
  235383. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235384. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235385. #else
  235386. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235387. #endif
  235388. int64 presentationTime = (hosttime != nil)
  235389. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235390. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235391. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235392. if (firstPresentationTime == 0)
  235393. {
  235394. firstPresentationTime = presentationTime;
  235395. averageTimeOffset = timeDiff;
  235396. }
  235397. else
  235398. {
  235399. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235400. }
  235401. }
  235402. @end
  235403. BEGIN_JUCE_NAMESPACE
  235404. class QTCaptureViewerComp : public NSViewComponent
  235405. {
  235406. public:
  235407. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235408. {
  235409. const ScopedAutoReleasePool pool;
  235410. captureView = [[QTCaptureView alloc] init];
  235411. [captureView setCaptureSession: internal->session];
  235412. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235413. setView (captureView);
  235414. }
  235415. ~QTCaptureViewerComp()
  235416. {
  235417. setView (0);
  235418. [captureView setCaptureSession: nil];
  235419. [captureView release];
  235420. }
  235421. QTCaptureView* captureView;
  235422. };
  235423. CameraDevice::CameraDevice (const String& name_, int index)
  235424. : name (name_)
  235425. {
  235426. isRecording = false;
  235427. internal = new QTCameraDeviceInteral (this, index);
  235428. }
  235429. CameraDevice::~CameraDevice()
  235430. {
  235431. stopRecording();
  235432. delete static_cast <QTCameraDeviceInteral*> (internal);
  235433. internal = 0;
  235434. }
  235435. Component* CameraDevice::createViewerComponent()
  235436. {
  235437. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235438. }
  235439. const String CameraDevice::getFileExtension()
  235440. {
  235441. return ".mov";
  235442. }
  235443. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235444. {
  235445. stopRecording();
  235446. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235447. d->callbackDelegate->firstPresentationTime = 0;
  235448. file.deleteFile();
  235449. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235450. // out wrong, so we'll put some audio in there too..,
  235451. d->addDefaultAudioInput();
  235452. [d->session addOutput: d->fileOutput error: nil];
  235453. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235454. for (;;)
  235455. {
  235456. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235457. if (connection == 0)
  235458. break;
  235459. QTCompressionOptions* options = 0;
  235460. NSString* mediaType = [connection mediaType];
  235461. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235462. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235463. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235464. : @"QTCompressionOptions240SizeH264Video"];
  235465. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235466. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235467. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235468. }
  235469. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235470. isRecording = true;
  235471. }
  235472. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235473. {
  235474. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235475. if (d->callbackDelegate->firstPresentationTime != 0)
  235476. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235477. return Time();
  235478. }
  235479. void CameraDevice::stopRecording()
  235480. {
  235481. if (isRecording)
  235482. {
  235483. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235484. isRecording = false;
  235485. }
  235486. }
  235487. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  235488. {
  235489. if (listenerToAdd != 0)
  235490. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235491. }
  235492. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  235493. {
  235494. if (listenerToRemove != 0)
  235495. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235496. }
  235497. const StringArray CameraDevice::getAvailableDevices()
  235498. {
  235499. const ScopedAutoReleasePool pool;
  235500. StringArray results;
  235501. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235502. for (int i = 0; i < (int) [devs count]; ++i)
  235503. {
  235504. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235505. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235506. }
  235507. return results;
  235508. }
  235509. CameraDevice* CameraDevice::openDevice (int index,
  235510. int minWidth, int minHeight,
  235511. int maxWidth, int maxHeight)
  235512. {
  235513. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235514. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235515. return d.release();
  235516. return 0;
  235517. }
  235518. #endif
  235519. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235520. #endif
  235521. #endif
  235522. END_JUCE_NAMESPACE
  235523. #endif
  235524. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235525. #endif
  235526. #endif